@formancy/report-runtime 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":["refused","extreme"],"sources":["../src/document.ts","../src/input.ts","../src/values.ts","../src/data-errors.ts","../src/data.ts","../src/parameters.ts","../src/decimal.ts","../src/format.ts","../src/sort-group.ts","../src/evaluate.ts","../src/resolve-errors.ts","../src/render-context.ts","../src/images.ts","../src/inlines.ts","../src/styles.ts","../src/lower-table.ts","../src/lower.ts","../src/report-check.ts","../src/totals.ts","../src/resolve.ts"],"sourcesContent":["/**\n * The resolved document: a report after the runtime has read its data,\n * evaluated its expressions and conditions, grouped, sorted, totalled and\n * formatted it, with nothing left to decide but where each line falls on a\n * page. The runtime lowers a report definition to it, and\n * `@formancy/report-render-pdf` draws it\n * ([0005](../../../docs/decisions/0005-pdfmake-renders-reports-behind-one-adapter.md)).\n *\n * It names no engine and holds no engine's options. It is plain data, every\n * part of it serialisable but an image's bytes, which are a `Uint8Array`.\n * Every length is in PDF points. Every value is already the string that\n * prints: an exact number stays a string all the way to the page, and an\n * engine never formats, rounds or converts one.\n *\n * It holds everything version 0 of the definition can print: the columns,\n * sections, rule weights and colours, fonts and colours, image fits and\n * group headers across a table that\n * [0007](../../../docs/decisions/0007-a-report-definition-is-its-own-versioned-document.md)\n * found the renderer trial's document without. Its vocabularies -- font\n * tokens, alignments, fits, page sizes, colours -- are report-spec's own\n * types, so the definition and the document cannot name different ones. An\n * absent style property is the renderer's default, as report-spec's print\n * styles say.\n *\n * Where a block may stand -- a table or a page break never inside columns or\n * a keep-together block, page fields only in the page regions -- is the\n * definition's to validate and the renderer's to refuse. These types do not\n * hold it.\n */\nimport type { Alignment, AssetMediaType, Border, FontFamily, ImageFit, Margins, Orientation, PageSizeName, Width } from '@formancy/report-spec'\n\n/**\n * A run of text, or a number only the engine knows when it lays out the\n * page, which prints only in the page header and footer. A run in bold\n * inside a paragraph that is not was the trial's; version 0 of the\n * definition sets weight per paragraph.\n */\nexport type Inline = { readonly text: string; readonly bold?: boolean } | { readonly field: 'pageNumber' } | { readonly field: 'pageCount' }\n\n/**\n * How text prints: report-spec's `PrintStyle`, resolved. The runtime lays\n * each conditional style that held over the base one, a later rule's\n * property winning, and hands the engine the result; an engine never merges\n * styles itself.\n */\nexport interface TextStyle {\n /** A font token, never a font's name: the renderer maps each to a font it embeds. */\n readonly font?: FontFamily\n /** Points. */\n readonly size?: number\n readonly bold?: boolean\n readonly italic?: boolean\n /** Lower-case `#rrggbb`. */\n readonly color?: string\n readonly align?: Alignment\n}\n\n/** Text that wraps at the width it is given. A word wider than that width still prints whole, broken across lines. */\nexport interface Paragraph {\n readonly kind: 'paragraph'\n readonly runs: readonly Inline[]\n readonly style?: TextStyle\n /** Never the last thing on a page when something follows it: a heading moves with what it heads. */\n readonly keepWithNext?: boolean\n}\n\nexport interface TableColumn {\n /** Points, or `'fill'` for an equal share of the width the fixed columns leave. */\n readonly width: Width\n /** How each cell in the column is aligned, unless the cell's style says otherwise. */\n readonly align: Alignment\n}\n\n/**\n * One row of a table, its cells in column order, each aligned to the top of\n * the row, so that a row's first line holds its first cell.\n *\n * A `groupHeader` is never the last row on a page: it moves to the next page\n * with the row it heads. A `detail` row may be taller than a page; the engine\n * then continues it on the next one, or refuses with `content-too-large`, and\n * never clips it.\n */\nexport interface TableRow {\n readonly kind: 'detail' | 'groupHeader' | 'groupFooter' | 'total'\n /** One per column; exactly one when the row runs `across` the table. */\n readonly cells: readonly string[]\n /**\n * The row is one cell across every column: a group header, which version\n * 0 prints as one line across the table rather than in its first column.\n */\n readonly across?: true\n /** Every cell's style; absent, the renderer's for a row of its kind. */\n readonly style?: TextStyle\n /**\n * A cell's own style, one entry per cell, `null` where the cell has the\n * row's. A cell's own is its whole style, the row's already laid under it\n * by the runtime, never merged again by the engine: a column's print\n * style, or one of its conditional styles that held for this row.\n */\n readonly cellStyles?: readonly (TextStyle | null)[]\n}\n\nexport interface Table {\n readonly kind: 'table'\n readonly id: string\n readonly columns: readonly TableColumn[]\n /** The one header row, repeated at the top of every page the table spans. */\n readonly header: readonly string[]\n /** The header row's style; absent, the renderer's. */\n readonly headerStyle?: TextStyle\n readonly rows: readonly TableRow[]\n /** Printed under the header, in place of detail rows, when there are none. Group and total rows still print. */\n readonly emptyText: string\n}\n\n/**\n * The most bytes one image asset may have: 20 MB, the renderer trial's\n * limit, the plan's \"enforced limits\" made a number to test. The runtime\n * refuses an answer past it before copying it, and the renderer before\n * decoding it, from this one constant.\n */\nexport const MAX_ASSET_BYTES = 20 * 1024 * 1024\n\n/**\n * An approved asset's bytes, already fetched by the host: an engine never\n * resolves an address. Every image that draws the same asset shares one\n * object, which an engine embeds once.\n */\nexport interface ImageAsset {\n readonly id: string\n readonly mediaType: AssetMediaType\n readonly bytes: Uint8Array\n}\n\n/**\n * An image in a box of fixed size, which the layout reserves whole whatever\n * the image holds. `contain` draws all of the image at its own proportions,\n * as large as the box allows; `cover` fills the box at the image's\n * proportions and crops what falls outside it. Either way the image is\n * centred in its box, as CSS's `object-fit` centres one by default, and\n * nothing of it is drawn outside the box. For an image of the box's own\n * proportions the two are the same drawing. Bytes the engine cannot decode\n * are refused as `invalid-asset`, naming the asset.\n */\nexport interface Image {\n readonly kind: 'image'\n readonly asset: ImageAsset\n readonly width: number\n readonly height: number\n readonly fit: ImageFit\n}\n\n/** A horizontal line across the width it is given: the printable area's, or its column's. */\nexport interface Rule {\n readonly kind: 'rule'\n /** Points. */\n readonly thickness: number\n /** Lower-case `#rrggbb`. */\n readonly color?: string\n}\n\n/** A box of fixed size: filled, outlined, both, or neither, when it is only space. */\nexport interface Rectangle {\n readonly kind: 'rectangle'\n readonly width: number\n readonly height: number\n /** Lower-case `#rrggbb`. */\n readonly fill?: string\n /** The outline's colour, lower-case `#rrggbb`, drawn at the renderer's weight. */\n readonly stroke?: string\n}\n\nexport interface Spacer {\n readonly kind: 'spacer'\n readonly height: number\n}\n\n/** Starts a new page. */\nexport interface PageBreak {\n readonly kind: 'pageBreak'\n}\n\n/**\n * Blocks that are printed on one page, such as a report's summary. When they\n * do not fit in what is left of the page they move whole to the next one;\n * when they are taller than a whole page the engine refuses with\n * `content-too-large` rather than splitting them.\n */\nexport interface KeepTogether {\n readonly kind: 'keepTogether'\n readonly blocks: readonly Block[]\n}\n\n/** One column of a columns block, as distinct from a table's column. */\nexport interface ColumnSlot {\n /** Points, or `'fill'` for an equal share of the width the fixed columns leave. */\n readonly width: Width\n readonly blocks: readonly Block[]\n}\n\n/**\n * Two to four columns side by side, each laying its blocks out down its own\n * width, with no gap between them but what their widths leave. The block is\n * as tall as its tallest column. When it does not fit on what is left of the\n * page, the engine continues its columns on the next page or refuses with\n * `content-too-large`, and never clips them.\n */\nexport interface Columns {\n readonly kind: 'columns'\n readonly columns: readonly ColumnSlot[]\n}\n\n/**\n * Blocks in a frame: the border drawn around them, the fill behind them, and\n * the padding between the border and them. A section adds no layout rule:\n * its blocks flow as though they stood in its place, across pages too, and\n * the frame is drawn around the part on each page. Without a border, a fill\n * or padding it is its blocks and nothing more.\n */\nexport interface Section {\n readonly kind: 'section'\n readonly blocks: readonly Block[]\n readonly border?: Border\n /** Lower-case `#rrggbb`. */\n readonly fill?: string\n /** Points, on every side. */\n readonly padding?: number\n}\n\nexport type Block = Paragraph | Table | Image | Rule | Rectangle | Spacer | PageBreak | KeepTogether | Columns | Section\n\nexport interface PageSetup {\n readonly size: PageSizeName\n readonly orientation: Orientation\n /**\n * From each edge of the paper to the printable area. Everything prints\n * inside it: the page header at its top, the page footer at its bottom, and\n * the body between them.\n */\n readonly margins: Margins\n}\n\nexport interface ResolvedDocument {\n readonly info: {\n readonly title: string\n /** An ISO instant, fixed by the caller, so that the same document renders to the same PDF. */\n readonly creationDate: string\n }\n readonly page: PageSetup\n /** Repeated on every page, at the top of the printable area. */\n readonly pageHeader: readonly Block[]\n /** Repeated on every page, at the bottom of the printable area. */\n readonly pageFooter: readonly Block[]\n /**\n * What prints once, in order. A definition's report header is simply the\n * start of the body, and its summary the end: each prints once, before or\n * after everything else, so neither needs a block kind of its own. A\n * summary that must stay on one page is a keep-together block.\n */\n readonly body: readonly Block[]\n}\n\nexport const REFUSAL_CODES = ['too-many-pages', 'content-too-large', 'invalid-asset', 'cancelled', 'unsupported'] as const\nexport type RefusalCode = (typeof REFUSAL_CODES)[number]\n\n/**\n * Why an engine produced no PDF. An engine refuses rather than truncates: a\n * report that cannot be printed whole is not printed, and the caller is told\n * what stopped it. `subject` names the asset, table or block concerned, when\n * the refusal is about one.\n */\nexport class RenderRefusal extends Error {\n readonly code: RefusalCode\n readonly subject: string | undefined\n\n constructor(code: RefusalCode, message: string, subject?: string) {\n super(message)\n this.name = 'RenderRefusal'\n this.code = code\n this.subject = subject\n }\n}\n","/**\n * Reading the data a host hands over, once, without running any of it.\n *\n * Datasets and parameters are untrusted input, even from the host's own\n * provider. A JSON-parsed object is plain data, but a host may hand over\n * anything JavaScript can hold: a getter that answers differently each time\n * it is asked, a proxy whose traps throw, a sparse array. So every object\n * and list is read through its property descriptors into a copy, as\n * report-spec reads a report: a getter is refused unrun, an exception from a\n * trap becomes a refusal, and what is checked afterwards is the copy, which\n * cannot change under the check.\n */\n\n/** Why a container could not be read at all. */\nexport type ContainerCode = 'wrong-type' | 'not-data' | 'too-many'\n\n/** A property of a record that could not be read, with the key it has when it has a string one. */\nexport interface PropertyProblem {\n readonly key?: string\n readonly message: string\n}\n\nexport type RecordRead =\n | { readonly ok: true; readonly entries: ReadonlyMap<string, unknown>; readonly problems: readonly PropertyProblem[] }\n | { readonly ok: false; readonly code: Exclude<ContainerCode, 'too-many'>; readonly message: string }\n\n/** An item of a list that could not be read, by its index. */\nexport interface ItemProblem {\n readonly index: number\n readonly message: string\n}\n\n/** Stands in a read list where an item could not be read; its problem says why. */\nexport const UNREADABLE: unique symbol = Symbol('unreadable')\n\nexport type ListRead =\n | { readonly ok: true; readonly items: readonly unknown[]; readonly problems: readonly ItemProblem[] }\n | { readonly ok: false; readonly code: ContainerCode; readonly message: string }\n\nconst ACCESSOR = 'a getter or setter is not data, and is not run'\n\n/** Whether `value` is a plain object: made by a literal, JSON.parse or Object.create(null), not a class instance, an array or a Map. */\nfunction isPlainObject(value: unknown): value is object {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false\n const prototype: unknown = Object.getPrototypeOf(value)\n return prototype === Object.prototype || prototype === null\n}\n\n/**\n * A plain object's own enumerable string-keyed data properties, each read\n * once, in the object's own order. A property that is not data -- a getter,\n * a symbol key, a hidden property -- is a problem of the record and left\n * out; anything else about the object refuses it whole.\n */\nexport function readRecord(value: unknown): RecordRead {\n try {\n if (!isPlainObject(value)) return { ok: false, code: 'wrong-type', message: 'expected an object of named values' }\n const entries = new Map<string, unknown>()\n const problems: PropertyProblem[] = []\n let symbols = false\n for (const key of Reflect.ownKeys(value)) {\n if (typeof key === 'symbol') {\n symbols = true\n continue\n }\n const descriptor = Object.getOwnPropertyDescriptor(value, key) as PropertyDescriptor\n if (!('value' in descriptor)) problems.push({ key, message: ACCESSOR })\n else if (descriptor.enumerable !== true) problems.push({ key, message: 'a property that is not enumerable is not data' })\n else entries.set(key, descriptor.value)\n }\n if (symbols) problems.push({ message: 'a property named by a symbol is not data' })\n return { ok: true, entries, problems }\n } catch {\n return { ok: false, code: 'not-data', message: 'an object that throws when read is not data' }\n }\n}\n\n/**\n * A list's items, each read once, after its length is checked against\n * `max`: a list longer than that is refused before any item is read. A hole\n * or a getter is a problem at its index, and `UNREADABLE` stands in its\n * place.\n */\nexport function readList(value: unknown, max: number): ListRead {\n try {\n if (!Array.isArray(value)) return { ok: false, code: 'wrong-type', message: 'expected a list' }\n // A proxy describes its length as it likes: an object whose valueOf\n // answers the bound one number and the loop another, or Infinity. Only a\n // whole number is a length, and it is compared and looped to as read.\n const length: unknown = (Object.getOwnPropertyDescriptor(value, 'length') as PropertyDescriptor).value\n if (typeof length !== 'number' || !Number.isSafeInteger(length) || length < 0) return { ok: false, code: 'not-data', message: 'a list whose length is not a whole number is not data' }\n if (length > max) return { ok: false, code: 'too-many', message: `a list of ${length} items, more than the ${max} allowed` }\n const items: unknown[] = []\n const problems: ItemProblem[] = []\n for (let index = 0; index < length; index++) {\n const descriptor = Object.getOwnPropertyDescriptor(value, index)\n if (descriptor !== undefined && 'value' in descriptor) {\n items.push(descriptor.value)\n continue\n }\n items.push(UNREADABLE)\n problems.push({ index, message: descriptor === undefined ? 'a hole in a list is not data' : ACCESSOR })\n }\n return { ok: true, items, problems }\n } catch {\n return { ok: false, code: 'not-data', message: 'a list that throws when read is not data' }\n }\n}\n","/**\n * One value read as the type a dataset field or a parameter declares, and\n * held as the runtime computes with it.\n *\n * Exact values travel as strings with their type and are never converted\n * through a JavaScript number (0007; formancy.ai-data 0008). So:\n * - an integer is a string of its digits, or a JSON number only where a\n * number is still exact, below 2^53; it is held as a `bigint`;\n * - a decimal is only ever the string of its exact digits, held as\n * `@formancy/expressions`' `Decimal` with its scale;\n * - a date and a local date-time have no zone and are held as their ISO\n * strings, which sort in calendar order;\n * - an instant has a zone, and is held in UTC, so that two spellings of one\n * moment are one value;\n * - an image is an approved asset's id and digest, never an address.\n *\n * Each type has one spelling of each value, the one report-spec writes a\n * parameter default in. Its patterns are restated here because report-spec\n * does not export them; `values.test.ts` puts candidates to both, so the two\n * cannot drift apart unnoticed. A refusal says what was expected and never\n * repeats what was found: the data is the customer's.\n */\nimport { DEFAULT_VALUE_LIMITS, Decimal, decimalFromString } from '@formancy/expressions'\nimport { isIdentifier, MAX_SCALE } from '@formancy/report-spec'\nimport type { FieldType } from '@formancy/report-spec'\nimport { readRecord } from './input.js'\n\n/**\n * The longest string a value may be, in UTF-16 code units. Not chosen: it is\n * the longest string `@formancy/expressions` lets an expression be handed\n * (`DEFAULT_VALUE_LIMITS.maxStringLength`), so every string the data check\n * accepts is one an expression can read, and a longer one is refused where\n * the check can name its field rather than when an expression first reads\n * it.\n */\nexport const MAX_STRING_LENGTH = DEFAULT_VALUE_LIMITS.maxStringLength\n\nexport const VALUE_ERROR_CODES = [\n /** A value of another JavaScript type than the field's: a number for a string, a bigint, a Date. */\n 'wrong-type',\n 'string-too-long',\n /** A string with half a surrogate pair, which is not text and would print as something nobody wrote. */\n 'ill-formed-string',\n /** Not an integer's one spelling, or a number with a fraction. */\n 'invalid-integer',\n /** A JSON number past 2^53, which has already lost digits. */\n 'unsafe-integer',\n /** A decimal as a JSON number, which has already lost digits. */\n 'decimal-as-number',\n 'invalid-decimal',\n /** A decimal with more places than its field declares, or than a decimal holds. */\n 'decimal-scale',\n 'invalid-date',\n 'invalid-datetime',\n 'invalid-instant',\n 'invalid-image',\n] as const\nexport type ValueErrorCode = (typeof VALUE_ERROR_CODES)[number]\n\n/** An image field's value: an approved asset the host resolves to bytes by its id, pinned by its digest. */\nexport interface ImageValue {\n /** An identifier, as report-spec writes an asset's id. */\n readonly asset: string\n /** `sha256:` and 64 lower-case hex digits. */\n readonly digest: string\n}\n\n/** What a value of each field type is held as once read. */\nexport interface FieldValues {\n readonly string: string\n readonly integer: bigint\n readonly decimal: Decimal\n readonly boolean: boolean\n /** `YYYY-MM-DD`. */\n readonly date: string\n /** `YYYY-MM-DDTHH:mm:ss`, and a fraction of a second without trailing zeros when it has one. */\n readonly datetime: string\n /** As a date-time, in UTC, with a final `Z`. */\n readonly instant: string\n readonly image: ImageValue\n}\n\n/** A value of any field type, read. Null is not one: whether a field may be null is its contract's, and checked before its type. */\nexport type CheckedValue = FieldValues[FieldType]\n\nexport type ValueRead<T> = { readonly ok: true; readonly value: T } | { readonly ok: false; readonly code: ValueErrorCode; readonly message: string }\n\nfunction refused(code: ValueErrorCode, message: string): { readonly ok: false; readonly code: ValueErrorCode; readonly message: string } {\n return { ok: false, code, message }\n}\n\n/** What `raw` is, for a message: its JavaScript type, never its content. */\nfunction kindOf(raw: unknown): string {\n if (raw === null) return 'null'\n if (Array.isArray(raw)) return 'a list'\n if (raw instanceof Date) return 'a Date'\n if (raw instanceof Decimal) return 'a Decimal'\n const type = typeof raw\n return type === 'object' ? 'an object' : `a ${type}`\n}\n\nfunction wrongType(expected: string, raw: unknown): { readonly ok: false; readonly code: ValueErrorCode; readonly message: string } {\n return refused('wrong-type', `expected ${expected}, found ${kindOf(raw)}`)\n}\n\n/** An exact integer: no sign but '-', no leading zero, no '-0' (report-spec's `INTEGER`). */\nconst INTEGER = /^(?:0|-?[1-9]\\d*)$/\n\n/** An exact decimal: an integer, optionally a point and at least one digit; no negative zero (report-spec's `DECIMAL`). */\nconst DECIMAL = /^(?:-?[1-9]\\d*(?:\\.\\d+)?|0(?:\\.\\d+)?|-0\\.\\d*[1-9]\\d*)$/\n\n/** An asset's content digest: SHA-256, lower-case hex (report-spec's `DIGEST`). */\nconst DIGEST = /^sha256:[0-9a-f]{64}$/\n\n/** Half a surrogate pair: a high one not followed by a low one, or a low one not preceded by a high one. */\nconst LONE_SURROGATE = /[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/\n\nconst DATE = /^(\\d{4})-(\\d{2})-(\\d{2})$/\nconst DATETIME = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d{1,9}))?$/\n/** An ISO 8601 date-time with its zone, as `@formancy/expressions` binds a timestamp: seconds optional, a fraction to the nanosecond. */\nconst INSTANT = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2})(?::(\\d{2})(?:\\.(\\d{1,9}))?)?(?:Z|([+-])(\\d{2}):(\\d{2}))$/\n\n/**\n * Whether year, month and day name a day on the proleptic Gregorian\n * calendar from the year 1: 2024-02-29 does, 2026-02-29 does not, and no day\n * of the year 0000 does, which Intl shows as the year 1 without its era\n * (report-spec's `isCalendarDate`).\n */\nfunction isCalendarDay(year: number, month: number, day: number): boolean {\n if (year < 1 || month < 1 || month > 12 || day < 1) return false\n const leap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0\n const days = month === 2 ? (leap ? 29 : 28) : [4, 6, 9, 11].includes(month) ? 30 : 31\n return day <= days\n}\n\n/** Whether hours, minutes and seconds name a time on a clock that has no leap second, as Date has none. */\nfunction isClockTime(hour: number, minute: number, second: number): boolean {\n return hour <= 23 && minute <= 59 && second <= 59\n}\n\n/**\n * `fraction` without trailing zeros, with its point, or nothing when nothing\n * is left. A loop rather than /0+$/: the instant pattern bounds the fraction\n * to nine digits, but an anchored repetition is quadratic on many zeros\n * before a non-zero (CodeQL's js/polynomial-redos), and this needs no bound\n * to stay linear.\n */\nfunction fractionOf(fraction: string | undefined): string {\n if (fraction === undefined) return ''\n let end = fraction.length\n while (end > 0 && fraction[end - 1] === '0') end -= 1\n return end === 0 ? '' : `.${fraction.slice(0, end)}`\n}\n\nfunction readString(raw: unknown): ValueRead<string> {\n if (typeof raw !== 'string') return wrongType('a string', raw)\n if (raw.length > MAX_STRING_LENGTH) return refused('string-too-long', `a string of ${raw.length} characters, more than the ${MAX_STRING_LENGTH} a value may have`)\n if (LONE_SURROGATE.test(raw)) return refused('ill-formed-string', 'a string with half a surrogate pair is not text, and would print a character nobody wrote')\n return { ok: true, value: raw }\n}\n\nfunction readInteger(raw: unknown): ValueRead<bigint> {\n if (typeof raw === 'string') {\n if (raw.length <= MAX_STRING_LENGTH && INTEGER.test(raw)) return { ok: true, value: BigInt(raw) }\n return refused('invalid-integer', 'an integer is written as its digits, with \"-\" for a negative one, no leading zero and no \"-0\"')\n }\n if (typeof raw === 'number') {\n if (Number.isSafeInteger(raw)) return { ok: true, value: BigInt(raw) }\n if (Number.isInteger(raw)) return refused('unsafe-integer', 'a number past 2^53 has already lost digits; send the integer as a string of its digits')\n return refused('invalid-integer', 'expected a whole number')\n }\n return wrongType('an integer, written as a string of its digits', raw)\n}\n\nfunction readDecimal(raw: unknown, scale: number | undefined): ValueRead<Decimal> {\n if (typeof raw === 'number') return refused('decimal-as-number', 'a decimal is sent as a string of its exact digits, never as a number: floats lose digits')\n if (typeof raw !== 'string') return wrongType('a decimal, written as a string of its exact digits', raw)\n if (raw.length > MAX_STRING_LENGTH || !DECIMAL.test(raw)) {\n return refused('invalid-decimal', 'a decimal is written as its digits, with \".\" before any places, \"-\" for a negative one, no leading zero and no \"-0\"')\n }\n const places = raw.length - raw.indexOf('.') - 1\n const allowed = scale ?? MAX_SCALE\n if (raw.includes('.') && places > allowed) {\n const whose = scale === undefined ? 'a decimal holds' : 'the field declares'\n return refused('decimal-scale', `a decimal with ${places} places, more than the ${allowed} ${whose}; rounding it here would print another number than the source holds`)\n }\n return { ok: true, value: decimalFromString(raw) }\n}\n\nfunction readBoolean(raw: unknown): ValueRead<boolean> {\n return typeof raw === 'boolean' ? { ok: true, value: raw } : wrongType('true or false', raw)\n}\n\nfunction readDate(raw: unknown): ValueRead<string> {\n if (typeof raw !== 'string') return wrongType('a date, written YYYY-MM-DD', raw)\n const match = DATE.exec(raw)\n if (match !== null && isCalendarDay(Number(match[1]), Number(match[2]), Number(match[3]))) return { ok: true, value: raw }\n return refused('invalid-date', 'a date is a day on the calendar, written YYYY-MM-DD')\n}\n\nfunction readDatetime(raw: unknown): ValueRead<string> {\n if (typeof raw !== 'string') return wrongType('a date and time, written YYYY-MM-DDTHH:mm:ss', raw)\n const match = DATETIME.exec(raw)\n const [year, month, day, hour, minute, second] = match === null ? [] : match.slice(1, 7).map(Number)\n if (match === null || !isCalendarDay(year as number, month as number, day as number) || !isClockTime(hour as number, minute as number, second as number)) {\n return refused('invalid-datetime', 'a date and time without a zone is written YYYY-MM-DDTHH:mm:ss, with a fraction of a second of up to nine digits if it has one')\n }\n return { ok: true, value: `${raw.slice(0, 19)}${fractionOf(match[7])}` }\n}\n\nconst pad = (value: number, width: number): string => String(value).padStart(width, '0')\n\n/**\n * `text`, an ISO 8601 date-time with its zone, as the moment it names in\n * UTC: `YYYY-MM-DDTHH:mm:ssZ`, with the fraction of a second it has, less\n * trailing zeros. Undefined when it is not one, or the moment falls outside\n * the years 0001 to 9999 in UTC: past them a year has no four-digit\n * spelling, and Intl shows the year 0 as the year 1.\n *\n * What an expression gives back for a timestamp is RFC 3339 in UTC, so this\n * also makes an expression's instant comparable with the data's.\n */\nexport function canonicalInstant(text: string): string | undefined {\n const match = INSTANT.exec(text)\n if (match === null) return undefined\n const [year, month, day, hour, minute, second = 0] = match.slice(1, 7).map((part) => (part === undefined ? undefined : Number(part))) as number[]\n const offsetHours = match[9] === undefined ? 0 : Number(match[9])\n const offsetMinutes = match[10] === undefined ? 0 : Number(match[10])\n if (!isCalendarDay(year as number, month as number, day as number) || !isClockTime(hour as number, minute as number, second) || offsetHours > 23 || offsetMinutes > 59) return undefined\n // Date.UTC reads the years 0 to 99 as 1900 to 1999; setUTCFullYear does not.\n const moment = new Date(0)\n moment.setUTCFullYear(year as number, (month as number) - 1, day as number)\n moment.setUTCHours(hour as number, minute as number, second, 0)\n const offset = (match[8] === '-' ? -1 : 1) * (offsetHours * 60 + offsetMinutes)\n moment.setTime(moment.getTime() - offset * 60_000)\n const utcYear = moment.getUTCFullYear()\n if (utcYear < 1 || utcYear > 9999) return undefined\n const date = `${pad(utcYear, 4)}-${pad(moment.getUTCMonth() + 1, 2)}-${pad(moment.getUTCDate(), 2)}`\n const time = `${pad(moment.getUTCHours(), 2)}:${pad(moment.getUTCMinutes(), 2)}:${pad(moment.getUTCSeconds(), 2)}`\n return `${date}T${time}${fractionOf(match[7])}Z`\n}\n\nfunction readInstant(raw: unknown): ValueRead<string> {\n if (typeof raw !== 'string') return wrongType('an instant, written as an ISO 8601 date-time with its zone', raw)\n const value = canonicalInstant(raw)\n if (value !== undefined) return { ok: true, value }\n return refused('invalid-instant', 'an instant is an ISO 8601 date-time with its zone, Z or an offset such as +01:00, between the years 0001 and 9999 in UTC')\n}\n\nconst IMAGE_SHAPE = 'an image is an approved asset, { \"asset\": its id, \"digest\": \"sha256:\" and 64 lower-case hex digits }, never an address'\n\nfunction readImage(raw: unknown): ValueRead<ImageValue> {\n const read = readRecord(raw)\n if (!read.ok || read.problems.length > 0) return refused('invalid-image', IMAGE_SHAPE)\n const { entries } = read\n const asset = entries.get('asset')\n const digest = entries.get('digest')\n if (entries.size !== 2 || !isIdentifier(asset) || typeof digest !== 'string' || !DIGEST.test(digest)) return refused('invalid-image', IMAGE_SHAPE)\n return { ok: true, value: Object.freeze({ asset, digest }) }\n}\n\n/**\n * `raw` read as a value of `type`, or why it is not one. `scale` is a\n * decimal field's declared scale: a decimal with more places is refused.\n * Null is refused as every type's wrong type; the caller decides first\n * whether the field may hold it.\n */\nexport function readValue<T extends FieldType>(type: T, raw: unknown, scale?: number): ValueRead<FieldValues[T]> {\n const read = READERS[type] as (raw: unknown, scale: number | undefined) => ValueRead<FieldValues[T]>\n return read(raw, scale)\n}\n\nconst READERS: { readonly [T in FieldType]: (raw: unknown, scale: number | undefined) => ValueRead<FieldValues[T]> } = {\n string: readString,\n integer: readInteger,\n decimal: readDecimal,\n boolean: readBoolean,\n date: readDate,\n datetime: readDatetime,\n instant: readInstant,\n image: readImage,\n}\n","/**\n * What the runtime can say is wrong with the data and parameters it is\n * given, as stable codes, and the bounded list one check collects.\n *\n * A code is for a program and the message for a person. An error's path is\n * a JSON Pointer into what was given -- `/detail/17/amount` -- and neither\n * the path nor the message ever holds a value from it: the data is the\n * customer's, and an error is the kind of thing that ends up in a log.\n */\nimport { MAX_ERRORS, MAX_KEY_LENGTH } from '@formancy/report-spec'\nimport { VALUE_ERROR_CODES } from './values.js'\n\nexport const DATA_ERROR_CODES = [\n ...VALUE_ERROR_CODES,\n /** Something JavaScript can hold and JSON cannot: a getter, a hole, a symbol key, an object that throws when read. */\n 'not-data',\n /** A part of the data envelope the runtime does not know. */\n 'unknown-property',\n /** A dataset the report declares and the data lacks. */\n 'missing-dataset',\n /** Data for a dataset the report does not declare. */\n 'undeclared-dataset',\n /** A field the contract declares and a record lacks, which is not the same as null. */\n 'missing-field',\n /** Null where the contract or the parameter does not allow it. */\n 'unexpected-null',\n /** A field the contract does not declare: a report never carries what it does not print. */\n 'undeclared-field',\n /** More detail rows than `MAX_DETAIL_ROWS`. */\n 'too-many-rows',\n /** Data the provider says is incomplete, in a final render. */\n 'incomplete',\n /** A captured count other than the rows given, or more than the cap. */\n 'completeness-mismatch',\n 'invalid-completeness',\n 'invalid-consistency',\n /** A required parameter with no value and no default. */\n 'missing-parameter',\n /** A value for a parameter the report does not declare. */\n 'undeclared-parameter',\n /** More errors were found than are listed. */\n 'too-many-errors',\n] as const\nexport type DataErrorCode = (typeof DATA_ERROR_CODES)[number]\n\nexport interface DataError {\n /** A JSON Pointer into the data or the parameter values: `/detail/17/amount`, `/from`. */\n readonly path: string\n readonly code: DataErrorCode\n /** For a person: what was expected, never what was found. */\n readonly message: string\n}\n\n/**\n * Errors listed per check: as many as report-spec lists for a report, for\n * the same reasons. Past it, one `too-many-errors` entry says the list was\n * cut short, and the check stops reading.\n */\nexport const MAX_DATA_ERRORS = MAX_ERRORS\n\n/** The errors one check has found, bounded. */\nexport class DataFindings {\n readonly #errors: DataError[] = []\n #overflowed = false\n\n report(path: string, code: DataErrorCode, message: string): void {\n if (this.#errors.length < MAX_DATA_ERRORS) this.#errors.push({ path, code, message })\n else this.#overflowed = true\n }\n\n /** Whether the list is cut short: once it is, nothing more is worth reading. */\n get full(): boolean {\n return this.#overflowed\n }\n\n get empty(): boolean {\n return this.#errors.length === 0\n }\n\n /** The errors in the order found, and a last one when more were found than listed. */\n errors(): DataError[] {\n const errors = [...this.#errors]\n if (this.#overflowed) errors.push({ path: '', code: 'too-many-errors', message: `more than ${MAX_DATA_ERRORS} errors were found; the first ${MAX_DATA_ERRORS} are listed` })\n return errors\n }\n}\n\n/** `path` extended by one key or index, escaped as RFC 6901 says. */\nexport function at(path: string, key: string | number): string {\n if (typeof key === 'number') return `${path}/${key}`\n return `${path}/${key.replaceAll('~', '~0').replaceAll('/', '~1')}`\n}\n\n/** Whether `key` is longer than any id the format allows: such a key is never one the report declares, and never goes into a path or a message. */\nexport function isLongKey(key: string): boolean {\n return key.length > MAX_KEY_LENGTH\n}\n\n/** The path to `key` in the object at `path`; the object's own path for a long key. */\nexport function keyAt(path: string, key: string): string {\n return isLongKey(key) ? path : at(path, key)\n}\n","/**\n * The data a report is rendered from, and the check that admits it.\n *\n * A host hands over one envelope (plan 13.2): one header record and one\n * primary detail list for version 0, with what the provider says about\n * them -- how many rows it captured against what cap, and how consistent\n * the capture is. `checkData` holds every value to the report's dataset\n * contracts before anything reads it, and refuses rather than repairs:\n *\n * - **Types are the contract's.** Each value is read as its field's type\n * (`values.ts`), exact numbers as strings and never through a JavaScript\n * number, and held as the runtime computes with it.\n * - **Null is not missing.** Null is a value where the contract allows it,\n * and prints as nothing. A field the data lacks altogether is an error in\n * a final render, never an empty cell (0007); a preview, which may run on\n * a sample, warns once per field and leaves it missing.\n * - **Data minimisation.** A field, or a dataset, the report does not\n * declare is refused: a report never carries what it does not print, so\n * nothing it was not written to read rides along into a render, a cache\n * or a log.\n * - **No silent truncation.** A final render prints every row or none: data\n * the provider calls incomplete is refused, and so is a captured count\n * that disagrees with the rows given.\n * - **Bounded.** The rows and every string are bounded before they are\n * read, and so is the error list; once it is full, nothing more is read.\n *\n * What is held afterwards is a frozen copy, read once from the host's\n * objects, which no later change to them reaches.\n */\nimport { MAX_KEY_LENGTH } from '@formancy/report-spec'\nimport type { DatasetContract, DatasetRole, ReportDefinition } from '@formancy/report-spec'\nimport { at, DataFindings, isLongKey, keyAt } from './data-errors.js'\nimport type { DataError, DataErrorCode } from './data-errors.js'\nimport { readList, readRecord, UNREADABLE } from './input.js'\nimport type { ContainerCode } from './input.js'\nimport { readValue } from './values.js'\nimport type { CheckedValue } from './values.js'\n\n/**\n * How consistent the provider's capture is (plan 13.2): captured by the\n * host, read in one database snapshot, or explicitly neither -- the label\n * Formancy Data 0.1.0's records carry, read at different moments.\n */\nexport const CONSISTENCY_MODES = ['host-captured', 'transaction-snapshot', 'best-effort'] as const\nexport type Consistency = (typeof CONSISTENCY_MODES)[number]\n\n/** A final render prints the report; a preview shows an author a sample while they work, and says what it lacks. */\nexport const DATA_MODES = ['final', 'preview'] as const\nexport type DataMode = (typeof DATA_MODES)[number]\n\n/**\n * Detail rows in one render. Chosen, not derived: a report is read by a\n * person, and at the renderer trial's 48 rows a page (`docs/renderer-trial.md`,\n * 15 October 2026) this is over 2,000 pages, which pdfmake took more than 35\n * seconds to lay out at the 1,829 ms per hundred pages measured there. The\n * PDF's page bound refuses most such reports first; this bounds the\n * runtime's own work -- checking, sorting, totalling -- before a page is\n * laid out. At the bound, checking rows of the test sample report's nine\n * fields took a median of 1.5 seconds, and ordering them by site and SKU 0.5\n * (five warm runs under vitest, Node 24.21, an Intel i9-10900K, 15 October\n * 2026).\n */\nexport const MAX_DETAIL_ROWS = 100_000\n\n/** What the provider says about the rows it handed over. */\nexport interface Completeness {\n /** False when the provider stopped before the end: at its cap, or sampling. */\n readonly complete: boolean\n /** How many detail rows it captured: exactly the rows given. */\n readonly captured: number\n /** The most rows it would capture, when it has a cap. */\n readonly cap?: number\n}\n\n/** The envelope a host renders a report from. Untrusted: `checkData` reads it as data, whatever its type says. */\nexport interface ReportData {\n /** The header dataset's one record, by field id. */\n readonly header?: Readonly<Record<string, unknown>>\n /** The detail dataset's rows, in the provider's order. */\n readonly detail?: readonly Readonly<Record<string, unknown>>[]\n readonly completeness: Completeness\n readonly consistency: Consistency\n}\n\n/**\n * One record, checked: each declared field's value as its type holds it, or\n * null. A field a preview's data lacks is absent, not null. The record has\n * no prototype, so a field named `constructor` is the record's own or\n * absent, never inherited.\n */\nexport type CheckedRecord = { readonly [field: string]: CheckedValue | null }\n\nexport interface CheckedData {\n readonly mode: DataMode\n /** The header record; absent when the report declares no header dataset. */\n readonly header?: CheckedRecord\n /** The detail rows, in the provider's order; empty when the report declares no detail dataset. */\n readonly detail: readonly CheckedRecord[]\n readonly completeness: Completeness\n readonly consistency: Consistency\n}\n\nexport type DataCheck =\n | { readonly ok: true; readonly data: CheckedData; /** What a preview lacks; always empty in a final render, which refuses it. */ readonly warnings: readonly DataError[] }\n | { readonly ok: false; readonly errors: readonly DataError[] }\n\nexport interface DataCheckOptions {\n readonly mode: DataMode\n}\n\nconst ENVELOPE: readonly string[] = ['header', 'detail', 'completeness', 'consistency']\nconst COMPLETENESS: readonly string[] = ['complete', 'captured', 'cap']\n\nconst MINIMISATION = 'a report never carries what it does not print, so data it does not read is refused rather than carried along'\n\n/** What one check carries through: its errors, its warnings, and its mode. */\ninterface Check {\n readonly errors: DataFindings\n readonly warnings: DataError[]\n readonly final: boolean\n}\n\n/** A container's code as a data error's: a list too long is a dataset with too many rows. */\nconst CONTAINER: { readonly [C in ContainerCode]: DataErrorCode } = { 'wrong-type': 'wrong-type', 'not-data': 'not-data', 'too-many': 'too-many-rows' }\n\n/** Reports what a record holds that is not data, by key; returns those keys. */\nfunction reportProblems(c: Check, path: string, problems: readonly { readonly key?: string; readonly message: string }[]): ReadonlySet<string> {\n const keys = new Set<string>()\n for (const problem of problems) {\n if (problem.key !== undefined) keys.add(problem.key)\n c.errors.report(problem.key === undefined ? path : keyAt(path, problem.key), 'not-data', problem.message)\n }\n return keys\n}\n\n/** How many records lacked a field, and where it was first missed. */\ninterface Missing {\n first: string\n count: number\n}\n\n/** One record held to `contract`, or undefined when it cannot be read at all. Fields it lacks are tallied in `missing`. */\nfunction checkRecord(c: Check, contract: DatasetContract, declared: ReadonlySet<string>, raw: unknown, path: string, missing: Map<string, Missing>): CheckedRecord | undefined {\n const read = readRecord(raw)\n if (!read.ok) {\n c.errors.report(path, read.code, read.message)\n return undefined\n }\n const unreadable = reportProblems(c, path, read.problems)\n const record = Object.create(null) as Record<string, CheckedValue | null>\n for (const field of contract.fields) {\n const where = at(path, field.id)\n if (unreadable.has(field.id)) continue\n if (!read.entries.has(field.id)) {\n const tally = missing.get(field.id)\n if (c.final) c.errors.report(where, 'missing-field', `${field.id}: the contract declares this field and the data lacks it; a missing field is not null, and a final render refuses it`)\n else if (tally === undefined) missing.set(field.id, { first: where, count: 1 })\n else tally.count++\n continue\n }\n const value = read.entries.get(field.id)\n if (value === null) {\n if (field.nullable) record[field.id] = null\n else c.errors.report(where, 'unexpected-null', `${field.id}: the contract says this field is never null`)\n continue\n }\n const checked = readValue(field.type, value, field.scale)\n if (checked.ok) record[field.id] = checked.value\n else c.errors.report(where, checked.code, `${field.id}: ${checked.message}`)\n }\n for (const key of read.entries.keys()) {\n if (declared.has(key)) continue\n const what = isLongKey(key) ? `a property name longer than ${MAX_KEY_LENGTH} characters, which no field has` : 'the contract declares no such field'\n c.errors.report(keyAt(path, key), 'undeclared-field', `${what}; ${MINIMISATION}`)\n }\n return Object.freeze(record)\n}\n\n/** A warning for each field a preview's records lacked, once per field. */\nfunction warnMissing(c: Check, missing: ReadonlyMap<string, Missing>, records: number, role: DatasetRole): void {\n for (const [field, { first, count }] of missing) {\n const where = role === 'header' ? 'the header record' : `${count} of ${records} rows`\n c.warnings.push({ path: first, code: 'missing-field', message: `${field}: missing from ${where}; a final render refuses data without it` })\n }\n}\n\n/** The report does not declare `role`, and the data holds it. */\nfunction undeclaredDataset(c: Check, role: DatasetRole): void {\n c.errors.report(`/${role}`, 'undeclared-dataset', `the report declares no ${role} dataset; ${MINIMISATION}`)\n}\n\n/** The report declares `role`, and the data lacks it: an error in a final render, a warning in a preview. */\nfunction missingDataset(c: Check, role: DatasetRole): void {\n const message = `the report declares a ${role} dataset and the data has none`\n if (c.final) c.errors.report(`/${role}`, 'missing-dataset', message)\n else c.warnings.push({ path: `/${role}`, code: 'missing-dataset', message: `${message}; every field of it is missing` })\n}\n\nconst EMPTY: CheckedRecord = Object.freeze(Object.create(null) as CheckedRecord)\n\nfunction checkHeader(c: Check, contract: DatasetContract | undefined, entries: ReadonlyMap<string, unknown>): CheckedRecord | undefined {\n const present = entries.has('header')\n if (contract === undefined) {\n if (present) undeclaredDataset(c, 'header')\n return undefined\n }\n if (!present) {\n missingDataset(c, 'header')\n return EMPTY\n }\n const missing = new Map<string, Missing>()\n const record = checkRecord(c, contract, new Set(contract.fields.map(({ id }) => id)), entries.get('header'), '/header', missing)\n warnMissing(c, missing, 1, 'header')\n return record\n}\n\n/** The detail rows checked, and how many were given when that could be counted. */\nfunction checkDetail(c: Check, contract: DatasetContract | undefined, entries: ReadonlyMap<string, unknown>): { readonly rows: CheckedRecord[]; readonly given: number | undefined } {\n const present = entries.has('detail')\n if (contract === undefined || !present) {\n if (contract === undefined && present) undeclaredDataset(c, 'detail')\n if (contract !== undefined) missingDataset(c, 'detail')\n return { rows: [], given: contract === undefined && !present ? 0 : undefined }\n }\n const list = readList(entries.get('detail'), MAX_DETAIL_ROWS)\n if (!list.ok) {\n const message = list.code === 'too-many' ? `${list.message}: a render reads at most ${MAX_DETAIL_ROWS} detail rows` : list.message\n c.errors.report('/detail', CONTAINER[list.code], message)\n return { rows: [], given: undefined }\n }\n const unreadable = new Map(list.problems.map(({ index, message }) => [index, message]))\n const declared = new Set(contract.fields.map(({ id }) => id))\n const missing = new Map<string, Missing>()\n const rows: CheckedRecord[] = []\n for (const [index, item] of list.items.entries()) {\n if (c.errors.full) break\n if (item === UNREADABLE) {\n c.errors.report(at('/detail', index), 'not-data', unreadable.get(index) as string)\n continue\n }\n const record = checkRecord(c, contract, declared, item, at('/detail', index), missing)\n if (record !== undefined) rows.push(record)\n }\n warnMissing(c, missing, list.items.length, 'detail')\n return { rows, given: list.items.length }\n}\n\nconst isCount = (value: unknown): value is number => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0\n\nfunction checkCompleteness(c: Check, raw: unknown, given: number | undefined): Completeness | undefined {\n const read = readRecord(raw)\n const shape = 'completeness is { \"complete\": true or false, \"captured\": the rows given, \"cap\": the most rows the provider would capture, if it has a cap }'\n if (!read.ok) {\n c.errors.report('/completeness', 'invalid-completeness', shape)\n return undefined\n }\n reportProblems(c, '/completeness', read.problems)\n for (const key of read.entries.keys()) {\n if (!COMPLETENESS.includes(key)) c.errors.report(keyAt('/completeness', key), 'invalid-completeness', `${shape}; nothing else`)\n }\n const { complete, captured, cap } = Object.fromEntries(COMPLETENESS.map((key) => [key, read.entries.get(key)]))\n const valid = typeof complete === 'boolean' && isCount(captured) && (cap === undefined || isCount(cap))\n if (typeof complete !== 'boolean') c.errors.report('/completeness/complete', 'invalid-completeness', 'complete is true or false')\n if (!isCount(captured)) c.errors.report('/completeness/captured', 'invalid-completeness', 'captured is a count of rows: a whole number, 0 or more')\n if (cap !== undefined && !isCount(cap)) c.errors.report('/completeness/cap', 'invalid-completeness', 'cap is a count of rows: a whole number, 0 or more')\n if (!valid) return undefined\n if (given !== undefined && captured !== given) {\n c.errors.report('/completeness/captured', 'completeness-mismatch', `the provider says it captured ${captured} rows and gave ${given}; rows lost or added on the way are never papered over`)\n }\n if (cap !== undefined && captured > cap) c.errors.report('/completeness/cap', 'completeness-mismatch', `the provider says it captured ${captured} rows, more than its cap of ${cap}`)\n if (!complete) {\n const message = 'the provider says the data is incomplete'\n if (c.final) c.errors.report('/completeness/complete', 'incomplete', `${message}; a final render prints every row or none, and never a silently truncated report`)\n else c.warnings.push({ path: '/completeness/complete', code: 'incomplete', message: `${message}; this preview shows only what was captured` })\n }\n return Object.freeze({ complete, captured, ...(cap === undefined ? {} : { cap }) })\n}\n\nfunction checkConsistency(c: Check, raw: unknown): Consistency | undefined {\n if (CONSISTENCY_MODES.includes(raw as Consistency)) return raw as Consistency\n c.errors.report('/consistency', 'invalid-consistency', `consistency is one of ${CONSISTENCY_MODES.map((mode) => `\"${mode}\"`).join(', ')}`)\n return undefined\n}\n\n/**\n * `data` held to `report`'s dataset contracts, or every reason it is\n * refused, up to `MAX_DATA_ERRORS`. `report` is one the validator accepts.\n * Any mode but `preview` is held as final: the stricter of the two.\n */\nexport function checkData(report: ReportDefinition, data: ReportData, options: DataCheckOptions): DataCheck {\n const c: Check = { errors: new DataFindings(), warnings: [], final: options.mode !== 'preview' }\n const top = readRecord(data)\n if (!top.ok) return { ok: false, errors: [{ path: '', code: top.code, message: top.message }] }\n reportProblems(c, '', top.problems)\n for (const key of top.entries.keys()) {\n if (!ENVELOPE.includes(key)) c.errors.report(keyAt('', key), 'unknown-property', `the data holds ${ENVELOPE.join(', ')}, and nothing the runtime does not know`)\n }\n const header = checkHeader(c, report.datasets.header, top.entries)\n const detail = checkDetail(c, report.datasets.detail, top.entries)\n const completeness = checkCompleteness(c, top.entries.get('completeness'), detail.given)\n const consistency = checkConsistency(c, top.entries.get('consistency'))\n if (!c.errors.empty || completeness === undefined || consistency === undefined) return { ok: false, errors: c.errors.errors() }\n const checked: CheckedData = {\n mode: c.final ? 'final' : 'preview',\n ...(header === undefined ? {} : { header }),\n detail: Object.freeze(detail.rows),\n completeness,\n consistency,\n }\n return { ok: true, data: Object.freeze(checked), warnings: c.warnings }\n}\n","/**\n * The values a person supplies before rendering, held to the report's\n * parameters.\n *\n * A parameter is read by exactly the rules a dataset field of its type is\n * (`values.ts`), so `params.copies` is an integer however it reached the\n * report: from a parameter form, an API call or a default. Then:\n *\n * - **Defaults apply** to a parameter left out. A default is written as the\n * format writes it -- an exact string, or a boolean -- and read by the\n * same rules as a value.\n * - **Required is enforced.** A required parameter with neither a value nor\n * a default is refused.\n * - **Null only where there may be none.** A parameter that is neither\n * required nor defaulted may be null; any other is never null when an\n * expression reads it (0009), so null for it is refused, not read as its\n * default.\n * - **Nothing undeclared.** A value for a parameter the report does not\n * declare is refused.\n *\n * The values are checked again here even when a parameter form checked\n * them already (plan 12.4): what reaches a render is decided by the\n * runtime, never by the browser that sent it.\n */\nimport { MAX_KEY_LENGTH } from '@formancy/report-spec'\nimport type { ParameterDef, ReportDefinition } from '@formancy/report-spec'\nimport { at, DataFindings, isLongKey, keyAt } from './data-errors.js'\nimport type { DataError } from './data-errors.js'\nimport { readRecord } from './input.js'\nimport { readValue } from './values.js'\nimport type { CheckedValue } from './values.js'\n\n/** The parameters' values by id, each read as its type or null. It has no prototype, so a parameter named `constructor` is its own value. */\nexport type CheckedParameters = { readonly [parameter: string]: CheckedValue | null }\n\nexport type ParameterCheck = { readonly ok: true; readonly values: CheckedParameters } | { readonly ok: false; readonly errors: readonly DataError[] }\n\n/** The value `parameter` takes when nobody supplied one; undefined when it must be supplied. */\nfunction absent(errors: DataFindings, parameter: ParameterDef, path: string): CheckedValue | null | undefined {\n if (parameter.default !== undefined) {\n const read = readValue(parameter.type, parameter.default)\n if (read.ok) return read.value\n errors.report(path, read.code, `${parameter.id}: its default is not a ${parameter.type}: ${read.message}`)\n return undefined\n }\n if (!parameter.required) return null\n errors.report(path, 'missing-parameter', `${parameter.id}: the report requires this parameter, and it has no value and no default`)\n return undefined\n}\n\n/**\n * `values` held to `report`'s parameters, with defaults applied, or every\n * reason they are refused. `report` is one the validator accepts. A path is\n * a JSON Pointer into `values`: `/copies`.\n */\nexport function checkParameters(report: ReportDefinition, values: Readonly<Record<string, unknown>>): ParameterCheck {\n const errors = new DataFindings()\n const read = readRecord(values)\n if (!read.ok) return { ok: false, errors: [{ path: '', code: read.code, message: `parameters are ${read.message}` }] }\n const unreadable = new Set<string>()\n for (const problem of read.problems) {\n if (problem.key !== undefined) unreadable.add(problem.key)\n errors.report(problem.key === undefined ? '' : keyAt('', problem.key), 'not-data', problem.message)\n }\n const checked = Object.create(null) as Record<string, CheckedValue | null>\n for (const parameter of report.parameters) {\n const path = at('', parameter.id)\n if (unreadable.has(parameter.id)) continue\n if (!read.entries.has(parameter.id)) {\n const value = absent(errors, parameter, path)\n if (value !== undefined) checked[parameter.id] = value\n continue\n }\n const raw = read.entries.get(parameter.id)\n if (raw === null) {\n if (!parameter.required && parameter.default === undefined) checked[parameter.id] = null\n else {\n const why = parameter.default === undefined ? 'the report requires it' : 'it has a default; leave it out to use the default'\n errors.report(path, 'unexpected-null', `${parameter.id}: never null, because ${why}`)\n }\n continue\n }\n const value = readValue(parameter.type, raw)\n if (value.ok) checked[parameter.id] = value.value\n else errors.report(path, value.code, `${parameter.id}: ${value.message}`)\n }\n const declared = new Set(report.parameters.map(({ id }) => id))\n for (const key of read.entries.keys()) {\n if (declared.has(key)) continue\n const what = isLongKey(key) ? `a name longer than ${MAX_KEY_LENGTH} characters, which no parameter has` : 'the report declares no such parameter'\n errors.report(keyAt('', key), 'undeclared-parameter', `${what}; a report reads nothing it was not written to read`)\n }\n if (!errors.empty) return { ok: false, errors: errors.errors() }\n return { ok: true, values: Object.freeze(checked) }\n}\n","/**\n * Exact totals and declared rounding, over `@formancy/expressions`'\n * `Decimal`: a value as an integer of units at a scale, so that nothing here\n * ever passes through a JavaScript number.\n *\n * Totals are decided once, here (0007): a sum is exact at the largest scale\n * it meets, a minimum or maximum compares by value, and an average is the\n * exact quotient rounded once, by the rule the aggregate declares. Rounding\n * follows report-spec's `Rounding`: to a multiple of `increment` when one is\n * given -- 0.05 for Swiss cash rounding -- and otherwise to `scale` places,\n * ties going by `mode` either way, and the result at exactly `scale` places.\n *\n * Upstream's own `roundDecimal` rounds half away from zero to a number of\n * places and nothing else; a declared rounding also has half to even and an\n * increment, so it is worked here, on integers, once for every case.\n * `decimal.test.ts` holds it against a reference written independently.\n */\nimport { addDecimal, compareDecimal, Decimal, decimalFromString } from '@formancy/expressions'\nimport type { Rounding, RoundingMode } from '@formancy/report-spec'\n\n/**\n * `numerator / denominator` (denominator more than 0) rounded to a whole\n * number, ties by `mode`. Division truncates towards zero; what it left\n * decides whether to step away from zero.\n */\nfunction roundQuotient(numerator: bigint, denominator: bigint, mode: RoundingMode): bigint {\n const quotient = numerator / denominator\n const remainder = numerator % denominator\n const twice = 2n * (remainder < 0n ? -remainder : remainder)\n if (twice < denominator) return quotient\n const away = numerator < 0n ? quotient - 1n : quotient + 1n\n if (twice > denominator) return away\n return mode === 'half-away-from-zero' || quotient % 2n !== 0n ? away : quotient\n}\n\n/** The step a rounding rounds to: its increment, or one unit at its scale. Throws for a step report-spec refuses. */\nfunction stepOf(rounding: Rounding): Decimal {\n if (rounding.increment === undefined) return new Decimal(1n, rounding.scale)\n const step = decimalFromString(rounding.increment)\n if (step.units <= 0n || step.scale > rounding.scale) {\n throw new RangeError(`an increment is more than 0 and has no more places than the ${rounding.scale} its rounding keeps`)\n }\n return step\n}\n\n/** The exact quotient `numerator / denominator` rounded as `rounding` declares. */\nfunction roundRatio(numerator: bigint, denominator: bigint, rounding: Rounding): Decimal {\n const step = stepOf(rounding)\n const steps = roundQuotient(numerator * 10n ** BigInt(step.scale), denominator * step.units, rounding.mode)\n return new Decimal(steps * step.units * 10n ** BigInt(rounding.scale - step.scale), rounding.scale)\n}\n\n/**\n * `value` rounded as `rounding` declares, at exactly its scale. A negative\n * value that rounds to nothing is zero, never minus zero. Throws a\n * RangeError for an increment report-spec refuses: of zero or less, or with\n * more places than the scale.\n */\nexport function roundDecimalAs(value: Decimal, rounding: Rounding): Decimal {\n return roundRatio(value.units, 10n ** BigInt(value.scale), rounding)\n}\n\n/** The exact sum, at the largest scale among the values; 0 over none (0007). */\nexport function sumDecimals(values: Iterable<Decimal>): Decimal {\n let total = new Decimal(0n, 0)\n for (const value of values) total = addDecimal(total, value)\n return total\n}\n\n/** The value `keep` prefers over each other, compared by value; the first of equals is kept, as written. */\nfunction extreme(values: Iterable<Decimal>, keep: (order: -1 | 0 | 1) => boolean): Decimal | null {\n let found: Decimal | null = null\n for (const value of values) if (found === null || keep(compareDecimal(value, found))) found = value\n return found\n}\n\n/** The least value, as written; null over none (0007). */\nexport function minDecimal(values: Iterable<Decimal>): Decimal | null {\n return extreme(values, (order) => order < 0)\n}\n\n/** The greatest value, as written; null over none (0007). */\nexport function maxDecimal(values: Iterable<Decimal>): Decimal | null {\n return extreme(values, (order) => order > 0)\n}\n\n/**\n * The exact average, rounded once as `rounding` declares: the exact sum\n * over the count, never a quotient rounded and then rounded again. Null\n * over no values (0007).\n */\nexport function averageDecimals(values: Iterable<Decimal>, rounding: Rounding): Decimal | null {\n let count = 0n\n let total = new Decimal(0n, 0)\n for (const value of values) {\n total = addDecimal(total, value)\n count++\n }\n return count === 0n ? null : roundRatio(total.units, count * 10n ** BigInt(total.scale), rounding)\n}\n","/**\n * A value as the text a report prints, for the report's locale: report-spec's\n * number, currency, date and text formats, through Intl.\n *\n * - **Exact to the last digit.** A number reaches Intl as the string of its\n * digits, already rounded here to exactly the places it prints, half away\n * from zero as a person rounds by hand. An ES2023 engine formats such a\n * string exactly, and `format.test.ts` holds that it does; Intl is never\n * handed a double and never rounds. Up to a bound: ECMA-402 reads a\n * string whose double would be infinite as infinity, and prints '∞'. A\n * number with more than `MAX_FORMATTED_DIGITS` integer digits is refused\n * instead; printed without a format, it prints whole.\n * - **The locale's conventions.** Grouping, separators, currency symbols,\n * month names and case are the locale's, as the engine's ICU has them.\n * ICU versions can differ -- which mark Swiss German groups digits with is\n * one such difference, and `format.test.ts` reads it from the engine -- so\n * the same report can print differently on two engines. That is the cost\n * of not carrying a locale database here.\n * - **Dates have no zone.** A date, and a date and time without a zone, are\n * formatted in UTC from their own fields, so 2026-01-01 is the first of\n * January wherever the report renders. Only an instant is shown in a zone,\n * and that zone is the host's to name: the machine's is never used.\n * - **Nothing is guessed.** A locale or zone the engine lacks is refused\n * rather than replaced by a default, and a format that cannot show a value\n * is an error rather than a blank.\n *\n * Null prints as nothing (0007), under every format.\n */\nimport { Decimal, decimalToString } from '@formancy/expressions'\nimport type { CurrencyFormat, CurrencySource, DateStyle, FieldType, Format, NumberFormat, TextTransform } from '@formancy/report-spec'\nimport type { CheckedRecord } from './data.js'\nimport { roundDecimalAs } from './decimal.js'\nimport type { CheckedParameters } from './parameters.js'\nimport { readValue } from './values.js'\nimport type { FieldValues } from './values.js'\n\n/** The types a value printed can have: every field type but an image, which is drawn. */\nexport type PrintableType = Exclude<FieldType, 'image'>\n\n/** A value with its type, as the runtime holds it (`values.ts`). */\nexport type TypedValue = { readonly [T in PrintableType]: { readonly type: T; readonly value: FieldValues[T] } }[PrintableType]\n\nexport const FORMAT_ERROR_CODES = [\n /** A locale the engine's Intl does not have, which it would silently replace with the host's. */\n 'unsupported-locale',\n /** A time zone the engine's Intl does not know. */\n 'unsupported-time-zone',\n /** A format that cannot show the value it is given: a number format over text, a date format over a number. */\n 'format-type-mismatch',\n /** An amount whose currency field or parameter has no value. */\n 'no-currency',\n /** A currency that is not an ISO 4217 code in capitals. */\n 'invalid-currency',\n /** A number with more integer digits than `MAX_FORMATTED_DIGITS`, which Intl would print as '∞'. */\n 'number-too-large',\n] as const\n\n/**\n * The most integer digits a number or currency format prints: 308. A double\n * holds up to about 1.8 × 10^308, and ECMA-402's ToIntlMathematicalValue\n * reads a string whose double would be infinite as infinity, so every\n * number of 308 digits or fewer prints exactly and one of 309 may not.\n */\nexport const MAX_FORMATTED_DIGITS = 308\nexport type FormatErrorCode = (typeof FORMAT_ERROR_CODES)[number]\n\nexport type Formatted = { readonly ok: true; readonly text: string } | { readonly ok: false; readonly code: FormatErrorCode; readonly message: string }\n\n/** What a render is formatted for: the report's locale, and the zone its instants are shown in. */\nexport interface FormatContext {\n /** A BCP 47 tag, as a report's `locale` is. */\n readonly locale: string\n /** An IANA time zone, such as `Europe/Zurich`, named by the host. */\n readonly timeZone: string\n}\n\n/** Where a currency format finds a currency read from a field or a parameter. */\nexport interface CurrencyScope {\n readonly params?: CheckedParameters\n readonly header?: CheckedRecord\n /** The current detail row, in a table's cells. */\n readonly row?: CheckedRecord\n}\n\nexport interface Formatter {\n readonly locale: string\n readonly timeZone: string\n /** `value` as `format` shows it, or as it prints plainly without one. */\n format(value: TypedValue | null, format: Format | undefined, scope?: CurrencyScope): Formatted\n}\n\nfunction refused(code: FormatErrorCode, message: string): Formatted {\n return { ok: false, code, message }\n}\n\n/**\n * A value printed with no format: as the format writes it. Exact digits\n * with their scale, ISO dates, an instant in UTC; nothing is interpreted.\n */\nexport function plainText(value: TypedValue | null): string {\n if (value === null) return ''\n if (value.type === 'integer' || value.type === 'boolean') return String(value.value)\n if (value.type === 'decimal') return decimalToString(value.value)\n return value.value\n}\n\n/**\n * Whether the engine has `locale`, in its number and date formats and its\n * collation, by the lookup a tag like `de-CH` falls back from region to\n * language with. A tag it cannot read is not one it has.\n */\nexport function supportedLocale(locale: string): boolean {\n try {\n const options = { localeMatcher: 'lookup' } as const\n return (\n Intl.NumberFormat.supportedLocalesOf([locale], options).length === 1 &&\n Intl.DateTimeFormat.supportedLocalesOf([locale], options).length === 1 &&\n Intl.Collator.supportedLocalesOf([locale], options).length === 1\n )\n } catch {\n return false\n }\n}\n\n/** Whether Intl knows `timeZone`. */\nfunction knownTimeZone(timeZone: string): boolean {\n try {\n new Intl.DateTimeFormat('en', { timeZone })\n return true\n } catch {\n return false\n }\n}\n\n/** The time a date-and-time format shows with each date style: no seconds for short, seconds otherwise; never the zone's name, which a local time does not have. */\nconst TIME_STYLE: { readonly [S in DateStyle]: 'short' | 'medium' } = { short: 'short', medium: 'medium', long: 'medium' }\n\n/** A moment to show: when, whether it has a time of day, and whether it is shown in the render's zone or, having none, in UTC. */\ninterface Moment {\n readonly epochMs: number\n readonly time: boolean\n readonly zoned: boolean\n}\n\n/** Epoch milliseconds of a calendar date and time in UTC; Date.UTC would read the years 0 to 99 as 1900 to 1999. */\nfunction utc(year: number, month: number, day: number, hour = 0, minute = 0, second = 0): number {\n const moment = new Date(0)\n moment.setUTCFullYear(year, month - 1, day)\n moment.setUTCHours(hour, minute, second, 0)\n return moment.getTime()\n}\n\n/** The numbers in `text`, a date or a date and time `readValue` accepted, in order. */\nconst fieldsOf = (text: string): number[] => (text.match(/\\d+/g) as RegExpMatchArray).map(Number)\n\n/** `value` as a `type` spells it: a value of that type, or a string an expression gave that spells one, as `readValue` holds it. */\nfunction spelledAs(value: TypedValue, type: 'date' | 'datetime' | 'instant'): string | undefined {\n if (value.type === type) return value.value as string\n if (value.type !== 'string') return undefined\n const read = readValue(type, value.value)\n return read.ok ? read.value : undefined\n}\n\n/** The moment a value spells: a date, a date and time, or an instant, by its type or, for a string an expression gave, by its syntax. */\nfunction momentOf(value: TypedValue): Moment | undefined {\n const date = spelledAs(value, 'date')\n if (date !== undefined) {\n const [year, month, day] = fieldsOf(date) as [number, number, number]\n return { epochMs: utc(year, month, day), time: false, zoned: false }\n }\n const local = spelledAs(value, 'datetime')\n if (local !== undefined) {\n const [year, month, day, hour, minute, second] = fieldsOf(local) as [number, number, number, number, number, number]\n return { epochMs: utc(year, month, day, hour, minute, second), time: true, zoned: false }\n }\n const instant = spelledAs(value, 'instant')\n return instant === undefined ? undefined : { epochMs: new Date(instant).getTime(), time: true, zoned: true }\n}\n\n/** The exact number a value holds, or undefined when it holds none. */\nfunction exactNumber(value: TypedValue): Decimal | undefined {\n if (value.type === 'integer') return new Decimal(value.value, 0)\n return value.type === 'decimal' ? value.value : undefined\n}\n\n/** The currency code an amount is in, from the format, a field or a parameter, or why there is none. */\nfunction currencyOf(source: CurrencySource, scope: CurrencyScope | undefined): string | Formatted {\n if (source.kind === 'code') return source.code\n const [name, raw] =\n source.kind === 'parameter'\n ? [`parameter ${source.parameter}`, scope?.params?.[source.parameter]]\n : [`field ${source.field.field}`, (source.field.dataset === 'header' ? scope?.header : scope?.row)?.[source.field.field]]\n if (raw === null || raw === undefined) return refused('no-currency', `the amount's currency, ${name}, has no value, and an amount without one reads as some other currency`)\n if (typeof raw === 'string' && /^[A-Z]{3}$/.test(raw)) return raw\n return refused('invalid-currency', `the amount's currency, ${name}, is not an ISO 4217 code in capitals, such as CHF`)\n}\n\n/** The Intl formatter `cache` keeps for `options`, made by `make` the first time they are asked for: a table formats a column with one. */\nfunction kept<T>(cache: Map<string, T>, options: object, make: () => T): T {\n const key = JSON.stringify(options)\n const found = cache.get(key)\n if (found !== undefined) return found\n const made = make()\n cache.set(key, made)\n return made\n}\n\n/** A formatter for one locale and time zone, which builds each Intl formatter it needs once and keeps it. */\nclass LocaleFormatter implements Formatter {\n readonly locale: string\n readonly timeZone: string\n readonly #numbers = new Map<string, Intl.NumberFormat>()\n readonly #dates = new Map<string, Intl.DateTimeFormat>()\n\n constructor(context: FormatContext) {\n this.locale = context.locale\n this.timeZone = context.timeZone\n }\n\n format(value: TypedValue | null, format: Format | undefined, scope?: CurrencyScope): Formatted {\n if (value === null) return { ok: true, text: '' }\n if (format === undefined) return { ok: true, text: plainText(value) }\n switch (format.kind) {\n case 'text':\n return { ok: true, text: this.#transformed(plainText(value), format.transform) }\n case 'date':\n return this.#date(value, format.style)\n default:\n return this.#number(value, format, scope)\n }\n }\n\n #transformed(text: string, transform: TextTransform | undefined): string {\n if (transform === 'upper') return text.toLocaleUpperCase(this.locale)\n return transform === 'lower' ? text.toLocaleLowerCase(this.locale) : text\n }\n\n #number(value: TypedValue, format: NumberFormat | CurrencyFormat, scope: CurrencyScope | undefined): Formatted {\n const exact = exactNumber(value)\n if (exact === undefined) return refused('format-type-mismatch', `a ${format.kind} format shows integers and decimals, and this value is a ${value.type}`)\n const currency = format.kind === 'currency' ? currencyOf(format.currency, scope) : undefined\n if (typeof currency === 'object') return currency\n const rounded = decimalToString(roundDecimalAs(exact, { scale: format.scale, mode: 'half-away-from-zero' })) as Intl.StringNumericLiteral\n if (rounded.replace(/^-/, '').split('.')[0]!.length > MAX_FORMATTED_DIGITS) {\n return refused('number-too-large', `a number of more than ${MAX_FORMATTED_DIGITS} digits, which Intl would print as infinity; printed without a format, it prints whole`)\n }\n const options: Intl.NumberFormatOptions = {\n minimumFractionDigits: format.scale,\n maximumFractionDigits: format.scale,\n ...(currency === undefined ? { useGrouping: format.kind === 'number' && !format.grouping ? false : 'auto' } : { style: 'currency', currency }),\n }\n return { ok: true, text: kept(this.#numbers, options, () => new Intl.NumberFormat(this.locale, options)).format(rounded) }\n }\n\n #date(value: TypedValue, style: DateStyle): Formatted {\n const moment = momentOf(value)\n if (moment === undefined) return refused('format-type-mismatch', `a date format shows dates, dates and times, and instants, and this value is a ${value.type} that spells none`)\n const options: Intl.DateTimeFormatOptions = {\n dateStyle: style,\n ...(moment.time ? { timeStyle: TIME_STYLE[style] } : {}),\n timeZone: moment.zoned ? this.timeZone : 'UTC',\n }\n return { ok: true, text: kept(this.#dates, options, () => new Intl.DateTimeFormat(this.locale, options)).format(moment.epochMs) }\n }\n}\n\n/** A formatter for `context`, or why its locale or time zone is refused. */\nexport function createFormatter(context: FormatContext): { readonly ok: true; readonly formatter: Formatter } | { readonly ok: false; readonly code: FormatErrorCode; readonly message: string } {\n if (!supportedLocale(context.locale)) {\n return { ok: false, code: 'unsupported-locale', message: \"the engine's Intl does not have this locale, and would print the host's instead\" }\n }\n if (!knownTimeZone(context.timeZone)) return { ok: false, code: 'unsupported-time-zone', message: \"the engine's Intl does not know this time zone\" }\n return { ok: true, formatter: new LocaleFormatter(context) }\n}\n","/**\n * The order of a table's rows and its groups, decided once, here (0007).\n *\n * Rows are ordered by the group's key first, in its direction, then by each\n * sort key, each compared as its type: decimals by value, integers as\n * BigInt, dates and times in calendar order, text as the report's language\n * sorts it, false before true. Nulls -- and a field a preview lacks -- go\n * last whichever way a key runs, so an empty cell never lands among the\n * values. Rows whose keys are all equal keep the provider's order: the\n * row's index is the last key, so the comparator is a total order and the\n * result rests on it alone. `Array.prototype.sort` has been stable since\n * ES2019, which by itself keeps that order too, so no test can tell the two\n * apart; the index is there so that nothing depends on the algorithm.\n *\n * Text the collator holds equal but spelled differently -- é composed and\n * decomposed -- is ordered by code unit after the collator, so that rows\n * with identical keys always stand together and a group never splits around\n * another spelling. Collation is the engine's ICU's, and differs between\n * ICU versions as formatting does.\n */\nimport { compareDecimal } from '@formancy/expressions'\nimport type { Decimal } from '@formancy/expressions'\nimport type { ReportDefinition, SortDirection, TableComponent } from '@formancy/report-spec'\nimport type { CheckedRecord } from './data.js'\nimport type { PrintableType } from './format.js'\nimport type { CheckedValue } from './values.js'\n\n/** One key rows are ordered by: a detail field, its type, and its direction. */\nexport interface OrderKey {\n readonly field: string\n readonly type: PrintableType\n readonly direction: SortDirection\n}\n\n/** A detail row in its place: the record, and its index in the order the provider gave the rows. */\nexport interface OrderedRow {\n readonly index: number\n readonly record: CheckedRecord\n}\n\n/** One group: its key, as its first row spells it, or null; then its rows, in order. */\nexport interface RowGroup {\n readonly key: CheckedValue | null\n readonly rows: readonly OrderedRow[]\n}\n\n/** A table's rows in order and, when it groups, its groups in order. */\nexport interface OrderedTable {\n readonly rows: readonly OrderedRow[]\n readonly groups?: readonly RowGroup[]\n}\n\n/** A value made comparable with `<` -- or, for text, with the collator -- for one key column. */\ntype Comparable = string | bigint | boolean\n\n/**\n * A date and time with its fraction of a second at nine digits, without a\n * zone: held without trailing zeros, '10:00:00.5' and '10:00:00' differ in\n * length, and as they stand '10:00:00.5Z' sorts before '10:00:00Z'.\n */\nexport function fixedWidth(value: string): string {\n const local = value.endsWith('Z') ? value.slice(0, -1) : value\n return `${local.slice(0, 19)}.${local.slice(20).padEnd(9, '0')}`\n}\n\n/** The values of `key` in every row, made comparable once; null for a null or missing one. */\nfunction column(rows: readonly CheckedRecord[], key: OrderKey): (Comparable | null)[] {\n const values = rows.map((record) => record[key.field] ?? null)\n switch (key.type) {\n case 'decimal': {\n // Every decimal of the column at one scale, so each comparison is one of integers.\n const decimals = values as (Decimal | null)[]\n const scale = Math.max(0, ...decimals.map((value) => value?.scale ?? 0))\n return decimals.map((value) => (value === null ? null : value.units * 10n ** BigInt(scale - value.scale)))\n }\n case 'datetime':\n case 'instant':\n return (values as (string | null)[]).map((value) => (value === null ? null : fixedWidth(value)))\n default:\n return values as (Comparable | null)[]\n }\n}\n\n/** -1, 0 or 1 for two values of one comparable column. */\nfunction compared(type: PrintableType, a: Comparable, b: Comparable, collator: Intl.Collator): number {\n if (type === 'string') {\n const order = collator.compare(a as string, b as string)\n if (order !== 0) return order\n }\n return a < b ? -1 : a > b ? 1 : 0\n}\n\n/**\n * `rows` in the order `keys` give, each key applied only among rows the keys\n * before it hold equal, with text compared as `locale` sorts it -- a locale\n * `supportedLocale` accepts. Ties keep the provider's order.\n */\nexport function orderRows(rows: readonly CheckedRecord[], keys: readonly OrderKey[], locale: string): OrderedRow[] {\n const collator = new Intl.Collator(locale, { usage: 'sort' })\n const columns = keys.map((key) => column(rows, key))\n const order = rows.map((_, index) => index)\n order.sort((left, right) => {\n for (const [at, key] of keys.entries()) {\n const values = columns[at] as (Comparable | null)[]\n const [a, b] = [values[left] as Comparable | null, values[right] as Comparable | null]\n if (a === null || b === null) {\n if (a !== b) return a === null ? 1 : -1\n continue\n }\n const found = compared(key.type, a, b, collator)\n if (found !== 0) return key.direction === 'asc' ? found : -found\n }\n return left - right\n })\n return order.map((index) => Object.freeze({ index, record: rows[index] as CheckedRecord }))\n}\n\n/** Whether two group keys are one: decimals by value, everything else as held, and null with null. */\nfunction sameKey(type: PrintableType, a: CheckedValue | null, b: CheckedValue | null): boolean {\n if (a === null || b === null) return a === b\n return type === 'decimal' ? compareDecimal(a as Decimal, b as Decimal) === 0 : a === b\n}\n\n/**\n * Rows already in order, as consecutive groups of equal keys: the groups in\n * the order of their rows, each keyed by its first row's value. A missing\n * value groups with null.\n */\nexport function groupRows(rows: readonly OrderedRow[], by: { readonly field: string; readonly type: PrintableType }): RowGroup[] {\n const groups: { key: CheckedValue | null; rows: OrderedRow[] }[] = []\n for (const row of rows) {\n const value = row.record[by.field] ?? null\n const last = groups.at(-1)\n if (last !== undefined && sameKey(by.type, last.key, value)) last.rows.push(row)\n else groups.push({ key: value, rows: [row] })\n }\n return groups.map((group) => Object.freeze({ key: group.key, rows: Object.freeze(group.rows) }))\n}\n\n/**\n * The keys `table` orders its rows by: its group's key first, then its sort\n * keys (0007), each typed by the report's detail contract. Throws a\n * RangeError for a key on a field that has no order -- an image, or one the\n * contract lacks -- which report-spec refuses.\n */\nexport function orderKeys(report: ReportDefinition, table: TableComponent): OrderKey[] {\n const types = new Map((report.datasets.detail?.fields ?? []).map(({ id, type }) => [id, type]))\n const typed = (field: string, direction: SortDirection): OrderKey => {\n const type = types.get(field)\n if (type === undefined || type === 'image') throw new RangeError(`detail field ${field} has no order to sort or group by`)\n return { field, type, direction }\n }\n const group = table.group === undefined ? [] : [typed(table.group.by.field, table.group.direction)]\n return [...group, ...(table.sort ?? []).map(({ field, direction }) => typed(field.field, direction))]\n}\n\n/** `detail` -- the report's checked detail rows -- in `table`'s order, and in its groups when it has one. */\nexport function orderTable(report: ReportDefinition, table: TableComponent, detail: readonly CheckedRecord[]): OrderedTable {\n const keys = orderKeys(report, table)\n const rows = orderRows(detail, keys, report.locale)\n if (table.group === undefined) return { rows }\n return { rows, groups: groupRows(rows, keys[0] as OrderKey) }\n}\n","/**\n * A report's expressions, compiled once and evaluated against checked data,\n * within a budget, each failure an error that says where.\n *\n * - **One compilation.** `@formancy/report-core`'s `compileReport` compiles\n * every expression where it stands, and the editor's diagnostics come\n * from the same function (0009). A report its diagnostics give an error\n * for is refused before anything is evaluated, so the runtime never runs\n * what the editor refuses. Each expression is compiled once per render,\n * never once per row -- twice, in fact, since `diagnose` does not hand\n * back the compilation it made.\n * - **One binding.** Each program's values are made by report-core's\n * `expressionValues`: an integer as a BigInt, a decimal as a `Decimal`,\n * an instant as a moment, a date as its ISO string. A value missing, or of\n * another type, fails the evaluation, naming the member and never quoting\n * the value.\n * - **Nothing differs between renders.** The diagnostics refuse `now()`,\n * `today()` and `random()`; the capabilities an evaluation is handed are\n * fixed besides, so that one reached anyway would answer the same in every\n * render.\n * - **Bounded.** Each evaluation has a budget of steps, and a render has one\n * for all its evaluations together. Past either, the evaluation is refused.\n * - **A failure is an error, never a blank.** It names the component, the\n * table column or the aggregate, and the detail row, and gives upstream's\n * code for what went wrong, never upstream's message, which can quote the\n * values it was computing with.\n *\n * What an expression gives is handed back typed as the runtime holds values:\n * an integer as a BigInt, an instant in UTC. A list or a map, which has no\n * text, is refused. A double never arrives: the diagnostics refuse every\n * double literal, every `double()` and every `/` before anything is\n * evaluated (report-core's `exactness.ts`), since upstream hands an integer\n * and a double back alike, as a JavaScript number, and `int()` of a double\n * would otherwise print as an exact integer. A number that is not a safe\n * integer is still refused here, rather than printed.\n */\nimport { DEFAULT_BUDGET, Decimal, evaluate, fixedCapabilities } from '@formancy/expressions'\nimport type { Capabilities, ExpressionValue } from '@formancy/expressions'\nimport { compileReport, diagnose, expressionValues } from '@formancy/report-core'\nimport type { CompiledExpression, Diagnostic, ExpressionValues, ReportCompilation } from '@formancy/report-core'\nimport type { ReportDefinition } from '@formancy/report-spec'\nimport type { TypedValue } from './format.js'\nimport { canonicalInstant } from './values.js'\n\n/**\n * Steps one evaluation may take: upstream's default for a formancy form's\n * expression (`DEFAULT_BUDGET`). A report expression reads single values, so\n * the only way to spend many steps is a comprehension over a list literal;\n * the deepest the structural limits allow, 64 by 64, measured 8,385 steps,\n * and `evaluate.test.ts` holds that it fits while one reading three values\n * in each turn (28,865 steps) does not.\n */\nexport const EXPRESSION_STEP_BUDGET = DEFAULT_BUDGET.maxSteps\n\n/**\n * Steps every evaluation of one render may take together, each charged its\n * steps and one more for itself. Measured as a render spends them, through\n * `condition()` with each evaluation's binding included, on 15 October\n * 2026, on an Intel i9-10900K under Node 24.21 with `@formancy/expressions`\n * 0.5.0: ten million steps of `row.urgent` took 10.0 seconds (1.00\n * microseconds a step) and of `row.amount * dec(\"1.081\") > dec(\"10\")` 13.0\n * (1.30). An earlier measurement, of upstream's `evaluate` alone, had put\n * that budget at 8.5 seconds and missed the binding. So the budget is five\n * million: about 5 to 6.5 seconds of evaluation on that machine, against\n * the plan's investigation target of ten seconds in all for a hundred-page\n * report. A report of `MAX_DETAIL_ROWS` rows evaluating ten one-read\n * expressions per row spends 2,000,000.\n */\nexport const RENDER_STEP_BUDGET = 5_000_000\n\n/**\n * What `now()`, `today()` and `random()` would give: nothing a report may\n * read (0009), fixed so that one reached anyway gives the same answer in\n * every render.\n */\nexport const CAPABILITIES: Capabilities = fixedCapabilities({ nowMs: 0, today: '1970-01-01', random: 0 })\n\nexport const EVALUATION_ERROR_CODES = [\n /** A path at which the report has no compiled expression: the caller's defect. */\n 'unknown-expression',\n /** A member the expression reads has no value: a field a preview's data lacks, or a total not yet computed. */\n 'missing-value',\n /** A value of another type than its member's, which the data check admits none of. */\n 'unbound-value',\n /** Upstream refused the evaluation: a division by zero, an overflow, a result too large to hand back. */\n 'expression-failed',\n /** The evaluation took more than `EXPRESSION_STEP_BUDGET` steps. */\n 'expression-budget',\n /** The render has spent `RENDER_STEP_BUDGET` steps. */\n 'render-budget',\n /** A number that is not a safe integer: a double, which the diagnostics refuse before anything is evaluated. */\n 'inexact-value',\n /** A list, a map or anything else without text. */\n 'unprintable-value',\n /** A condition that gave something other than a boolean. */\n 'not-a-condition',\n] as const\nexport type EvaluationErrorCode = (typeof EVALUATION_ERROR_CODES)[number]\n\n/** Why an evaluation gave no value, and where. */\nexport interface EvaluationError {\n readonly code: EvaluationErrorCode\n /** For a person: where and what, never a value. */\n readonly message: string\n /** The JSON Pointer to the expression's `cel` in the report. */\n readonly path: string\n readonly componentId?: string\n readonly columnId?: string\n /** The aggregate whose expression this is, for one read from each row. */\n readonly aggregateId?: string\n /** The detail row's index in the data, when the expression read one. */\n readonly row?: number\n}\n\nexport type Evaluation = { readonly ok: true; readonly value: TypedValue | null } | { readonly ok: false; readonly error: EvaluationError }\n\nexport type ConditionEvaluation = { readonly ok: true; readonly value: boolean } | { readonly ok: false; readonly error: EvaluationError }\n\nexport interface ReportExpressions {\n /** What compiled: the programs by path, the members, and the order aggregates are computed in. */\n readonly compilation: ReportCompilation\n /** Steps this render has spent, each evaluation charged its steps and one more. */\n readonly spent: number\n /** The expression at `path` evaluated over `values`; `row` is the detail row's index, for an error to name. */\n evaluate(path: string, values: ExpressionValues, row?: number): Evaluation\n /** The condition at `path` -- a `visibleWhen` or a style rule's `when` -- evaluated over `values`. */\n condition(path: string, values: ExpressionValues, row?: number): ConditionEvaluation\n}\n\nexport type ExpressionsPreparation = { readonly ok: true; readonly expressions: ReportExpressions } | { readonly ok: false; readonly diagnostics: readonly Diagnostic[] }\n\n/** The typed value an expression's result is, or why it is not one. Exported for its test alone. */\nexport function typed(result: ExpressionValue, resultType: string): TypedValue | null | { readonly code: EvaluationErrorCode; readonly what: string } {\n if (result === null) return null\n if (result instanceof Decimal) return { type: 'decimal', value: result }\n switch (typeof result) {\n case 'boolean':\n return { type: 'boolean', value: result }\n case 'string': {\n const instant = resultType === 'timestamp' ? canonicalInstant(result) : undefined\n return instant === undefined ? { type: 'string', value: result } : { type: 'instant', value: instant }\n }\n case 'number':\n // Upstream hands an integer back as a number, and refuses one it cannot hold exactly.\n if (Number.isSafeInteger(result)) return { type: 'integer', value: BigInt(result) }\n return { code: 'inexact-value', what: 'the expression gives a double, which is not exact; dec() keeps a number exact' }\n default:\n return { code: 'unprintable-value', what: 'the expression gives a list or a map, which has no text' }\n }\n}\n\n/** One render's evaluations of a report's expressions. */\nclass Evaluator implements ReportExpressions {\n readonly compilation: ReportCompilation\n readonly #aggregates: readonly string[]\n #spent = 0\n\n constructor(report: ReportDefinition, compilation: ReportCompilation) {\n this.compilation = compilation\n this.#aggregates = report.aggregates.map(({ id }) => id)\n }\n\n get spent(): number {\n return this.#spent\n }\n\n evaluate(path: string, values: ExpressionValues, row?: number): Evaluation {\n const compiled = this.compilation.expressions.get(path)\n if (compiled === undefined) return { ok: false, error: { code: 'unknown-expression', message: `the report has no expression at ${path}`, path } }\n const fail = (code: EvaluationErrorCode, what: string): Evaluation => ({ ok: false, error: this.#error(compiled, code, what, row) })\n for (const read of compiled.reads) {\n const scope = values[read.name]\n if (scope === undefined || !Object.hasOwn(scope, read.member)) return fail('missing-value', `${read.name}.${read.member} has no value: it is missing, which is not null`)\n }\n let bound: Record<string, unknown>\n try {\n bound = expressionValues(compiled, values)\n } catch (error) {\n // report-core's refusal names the member and its type, and never quotes the value.\n return fail('unbound-value', (error as TypeError).message)\n }\n if (this.#spent >= RENDER_STEP_BUDGET) return fail('render-budget', `the render has spent its budget of ${RENDER_STEP_BUDGET} steps`)\n const maxSteps = Math.min(EXPRESSION_STEP_BUDGET, RENDER_STEP_BUDGET - this.#spent - 1)\n const outcome = evaluate(compiled.program, bound, { capabilities: CAPABILITIES, budget: { maxSteps } })\n if (!outcome.ok) {\n const exhausted = outcome.error.kind === 'budget'\n this.#spent += (exhausted ? maxSteps : 0) + 1\n if (!exhausted) return fail('expression-failed', `the expression failed (${outcome.error.code})`)\n if (maxSteps < EXPRESSION_STEP_BUDGET) return fail('render-budget', `the render has spent its budget of ${RENDER_STEP_BUDGET} steps`)\n return fail('expression-budget', `the expression took more than its budget of ${EXPRESSION_STEP_BUDGET} steps`)\n }\n this.#spent += outcome.steps + 1\n const value = typed(outcome.value, compiled.program.resultType)\n return value !== null && 'code' in value ? fail(value.code, value.what) : { ok: true, value }\n }\n\n condition(path: string, values: ExpressionValues, row?: number): ConditionEvaluation {\n const outcome = this.evaluate(path, values, row)\n if (!outcome.ok) return outcome\n if (outcome.value?.type === 'boolean') return { ok: true, value: outcome.value.value }\n const compiled = this.compilation.expressions.get(path) as CompiledExpression\n return { ok: false, error: this.#error(compiled, 'not-a-condition', 'a condition gives true or false, and this expression gives something else', row) }\n }\n\n /** An error about `compiled`, naming where it stands and the row it read. */\n #error(compiled: CompiledExpression, code: EvaluationErrorCode, what: string, row: number | undefined): EvaluationError {\n const { site } = compiled\n const aggregateId = site.path.startsWith('/aggregates/') ? this.#aggregates[Number(site.path.split('/')[2])] : undefined\n const place = [\n site.componentId === undefined ? undefined : `component ${site.componentId}`,\n site.columnId === undefined ? undefined : `column ${site.columnId}`,\n aggregateId === undefined ? undefined : `aggregate ${aggregateId}`,\n row === undefined ? undefined : `detail row ${row}`,\n ].filter((part) => part !== undefined)\n return {\n code,\n message: `${place.join(', ')}: ${what}`,\n path: site.path,\n ...(site.componentId === undefined ? {} : { componentId: site.componentId }),\n ...(site.columnId === undefined ? {} : { columnId: site.columnId }),\n ...(aggregateId === undefined ? {} : { aggregateId }),\n ...(row === undefined ? {} : { row }),\n }\n }\n}\n\n/**\n * `report`'s expressions compiled for one render, or the diagnostics that\n * refuse it: every error `diagnose` gives, which the editor shows too.\n * `report` is one the validator accepts. The evaluations of one render\n * share one budget, so a render prepares its own.\n */\nexport function prepareExpressions(report: ReportDefinition): ExpressionsPreparation {\n const errors = diagnose(report).filter(({ severity }) => severity === 'error')\n if (errors.length > 0) return { ok: false, diagnostics: errors }\n return { ok: true, expressions: new Evaluator(report, compileReport(report)) }\n}\n","/**\n * Why a report did not resolve, as one list a caller reads whatever stage\n * found the problem: the report itself, its expressions, the parameters, the\n * data, the options, an evaluation, a format, an image or a total.\n *\n * Each stage keeps the codes it already has -- report-spec's for structure,\n * report-core's diagnostics for expressions, the data check's for data and\n * parameters, the evaluator's and the formatter's -- so a code means one\n * thing wherever it appears. `stage` says which list a code is from. Like\n * every error the runtime gives, none holds a value from the data.\n */\nimport type { Diagnostic, DiagnosticCode } from '@formancy/report-core'\nimport type { ReportError, ReportErrorCode } from '@formancy/report-spec'\nimport type { DataError, DataErrorCode } from './data-errors.js'\nimport { MAX_DATA_ERRORS } from './data-errors.js'\nimport type { EvaluationError, EvaluationErrorCode } from './evaluate.js'\nimport type { FormatErrorCode } from './format.js'\n\n/** What lowering a report can find wrong besides what each earlier stage finds. */\nexport const RESOLVE_ERROR_CODES = [\n /** A creation date that is not an ISO 8601 instant with its zone. */\n 'invalid-creation-date',\n /** An image whose bytes the host does not have, or a report with images and no way to fetch them. */\n 'missing-asset',\n /** Bytes for an image that are not a `Uint8Array`, or of another media type than the asset declares or a report may draw. */\n 'invalid-asset',\n /** The host's image lookup threw. */\n 'asset-lookup-failed',\n /** A declared rounding on a total that is not a decimal: an integer, a date or an instant has no places to round. */\n 'rounding-not-decimal',\n /** A total over values that cannot be totalled together: a sum of text, a minimum of a number and a date. */\n 'aggregate-value-type',\n /** More errors were found than are listed. */\n 'too-many-errors',\n] as const\nexport type ResolveErrorCode = (typeof RESOLVE_ERROR_CODES)[number]\n\n/** Where in the report an error is, when it is in a component, a table column or a row. */\ninterface Place {\n readonly componentId?: string\n readonly columnId?: string\n /** The detail row's index in the data as the provider gave it. */\n readonly row?: number\n}\n\n/** One error, from the stage that found it, with that stage's code. Its path is a JSON Pointer into what the stage read: the report, the data, the parameters, or '' for the options. */\nexport type RuntimeError =\n | ({ readonly stage: 'report'; readonly code: ReportErrorCode; readonly path: string; readonly message: string } & Place)\n | ({ readonly stage: 'expressions'; readonly code: DiagnosticCode; readonly path: string; readonly message: string } & Place)\n | { readonly stage: 'parameters' | 'data'; readonly code: DataErrorCode; readonly path: string; readonly message: string }\n | ({ readonly stage: 'evaluation'; readonly code: EvaluationErrorCode; readonly path: string; readonly message: string; readonly aggregateId?: string } & Place)\n | ({ readonly stage: 'format'; readonly code: FormatErrorCode; readonly path: string; readonly message: string } & Place)\n | ({ readonly stage: 'resolve'; readonly code: ResolveErrorCode; readonly path: string; readonly message: string } & Place)\n\nexport type RuntimeStage = RuntimeError['stage']\n\n/** The optional parts of a place, written only when present, as exactOptionalPropertyTypes asks. */\nexport function placed(place: { readonly componentId?: string | undefined; readonly columnId?: string | undefined; readonly row?: number | undefined }): Place {\n return {\n ...(place.componentId === undefined ? {} : { componentId: place.componentId }),\n ...(place.columnId === undefined ? {} : { columnId: place.columnId }),\n ...(place.row === undefined ? {} : { row: place.row }),\n }\n}\n\nexport function fromReport(error: ReportError): RuntimeError {\n return { stage: 'report', code: error.code, path: error.path, message: error.message, ...placed(error) }\n}\n\nexport function fromDiagnostic(diagnostic: Diagnostic): RuntimeError {\n return { stage: 'expressions', code: diagnostic.code, path: diagnostic.path, message: diagnostic.message, ...placed(diagnostic) }\n}\n\nexport function fromData(stage: 'parameters' | 'data', error: DataError): RuntimeError {\n return { stage, code: error.code, path: error.path, message: error.message }\n}\n\nexport function fromEvaluation(error: EvaluationError): RuntimeError {\n return {\n stage: 'evaluation',\n code: error.code,\n path: error.path,\n message: error.message,\n ...placed(error),\n ...(error.aggregateId === undefined ? {} : { aggregateId: error.aggregateId }),\n }\n}\n\n/**\n * The errors and warnings one resolution collects. Errors are bounded as the\n * data check bounds its own: past `MAX_DATA_ERRORS`, one `too-many-errors`\n * says the list was cut short, and `full` tells a long loop to stop. A\n * warning is said once per path: a preview that lacks a field a thousand\n * rows read warns once for it.\n */\nexport class Problems {\n readonly #errors: RuntimeError[] = []\n readonly #warnings = new Map<string, RuntimeError>()\n #overflowed = false\n\n error(error: RuntimeError): void {\n if (this.#errors.length < MAX_DATA_ERRORS) this.#errors.push(error)\n else this.#overflowed = true\n }\n\n warn(warning: RuntimeError): void {\n const key = `${warning.stage} ${warning.code} ${warning.path}`\n if (!this.#warnings.has(key)) this.#warnings.set(key, warning)\n }\n\n /** Whether the error list is cut short: nothing more is worth computing. */\n get full(): boolean {\n return this.#overflowed\n }\n\n get failed(): boolean {\n return this.#errors.length > 0\n }\n\n errors(): RuntimeError[] {\n const errors = [...this.#errors]\n if (this.#overflowed) errors.push({ stage: 'resolve', code: 'too-many-errors', path: '', message: `more than ${MAX_DATA_ERRORS} errors were found; the first ${MAX_DATA_ERRORS} are listed` })\n return errors\n }\n\n warnings(): RuntimeError[] {\n return [...this.#warnings.values()]\n }\n}\n","/**\n * What one resolution knows while it lowers a report, and the three scopes\n * a value is read in (0007): the report, a group of rows, one detail row.\n *\n * A scope is the values an expression is handed -- `params`, `header`,\n * `totals`, and `group` or `row` where there is one -- and where a currency\n * format finds a currency. Every expression is evaluated through `valueOf`\n * or `holds`, so an evaluation that fails is an error in one place, and a\n * preview that lacks a field degrades in one place: what reads it prints\n * nothing, and a condition over it does not hold, each said once as a\n * warning. In a final render a missing field never gets this far: the data\n * check refuses it.\n */\nimport type { ExpressionValues } from '@formancy/report-core'\nimport type { FieldRef, FieldType, ParameterType, ReportDefinition } from '@formancy/report-spec'\nimport type { CheckedData, CheckedRecord } from './data.js'\nimport type { TextStyle } from './document.js'\nimport type { ReportExpressions } from './evaluate.js'\nimport type { CurrencyScope, Formatter, TypedValue } from './format.js'\nimport type { CheckedParameters } from './parameters.js'\nimport { fromEvaluation } from './resolve-errors.js'\nimport type { Problems } from './resolve-errors.js'\nimport type { OrderedRow, RowGroup } from './sort-group.js'\nimport type { ImageValue } from './values.js'\n\n/** An approved asset, named as report-spec names one: by id, pinned by digest. */\nexport interface ImageRef {\n readonly asset: string\n readonly digest: string\n}\n\n/** What the host holds for an approved asset: its bytes, already fetched, and their media type. */\nexport interface ImageBytes {\n readonly mediaType: string\n readonly bytes: Uint8Array\n}\n\n/**\n * The host's lookup of an approved asset's bytes by its id and digest, or\n * undefined when it has none. Never an address: the runtime fetches nothing.\n */\nexport type ImageResolver = (ref: ImageRef) => ImageBytes | undefined\n\n/** Each aggregate's value over some rows, by id: a typed value, or null where it has none. */\nexport type AggregateValues = ReadonlyMap<string, TypedValue | null>\n\n/** The totals of one render: each aggregate over every row, and the same over any group of them. */\nexport interface Totals {\n readonly report: AggregateValues\n over(rows: readonly OrderedRow[]): AggregateValues\n}\n\n/** One resolution's inputs, checked, and what it collects. */\nexport interface Render {\n /** The copy validation read. */\n readonly report: ReportDefinition\n readonly expressions: ReportExpressions\n readonly formatter: Formatter\n readonly params: CheckedParameters\n readonly data: CheckedData\n readonly problems: Problems\n readonly preview: boolean\n readonly images: ImageResolver | undefined\n /** Each print style, by id, as the document's style. */\n readonly styles: ReadonlyMap<string, TextStyle>\n readonly totals: Totals\n}\n\n/** Where a value is read: what its expressions are handed, where its currency comes from, and what an error there names. */\nexport interface Scope {\n readonly values: ExpressionValues\n readonly currency: CurrencyScope\n /** The current group's aggregates, in a group's header and footer. */\n readonly group?: AggregateValues\n /** The record a detail field is read from: the current row, or a group's first row, whose key every row of the group shares. */\n readonly record?: CheckedRecord\n /** The current row's index in the data as the provider gave it, for an error to name. */\n readonly row?: number\n}\n\n/** Each aggregate's value as an expression is handed it: the typed value's own, or null. */\nfunction raw(values: AggregateValues): Record<string, unknown> {\n return Object.fromEntries([...values].map(([id, value]) => [id, value === null ? null : value.value]))\n}\n\n/** The header record, or none when the report declares no header dataset. */\nfunction headerOf(render: Pick<Render, 'data'>): CheckedRecord {\n return render.data.header ?? {}\n}\n\nexport function reportScope(render: Pick<Render, 'params' | 'data'>, totals: AggregateValues): Scope {\n const header = headerOf(render)\n return { values: { params: render.params, header, totals: raw(totals) }, currency: { params: render.params, header } }\n}\n\n/**\n * A group's header and footer: the report's values, and the group's\n * aggregates and key as `group`. `by` is the field grouped by; where a\n * preview's rows lack it the key is missing, as the field is, not null.\n */\nexport function groupScope(render: Render, group: RowGroup, aggregates: AggregateValues, by: string): Scope {\n const record = (group.rows[0] as OrderedRow).record\n const header = headerOf(render)\n const key = Object.hasOwn(record, by) ? { key: group.key } : {}\n return {\n values: { params: render.params, header, totals: raw(render.totals.report), group: { ...raw(aggregates), ...key } },\n currency: { params: render.params, header, row: record },\n group: aggregates,\n record,\n }\n}\n\n/** One detail row: the report's values, and the row's as `row`. */\nexport function rowScope(render: Pick<Render, 'params' | 'data'>, totals: AggregateValues, row: OrderedRow): Scope {\n const header = headerOf(render)\n return {\n values: { params: render.params, header, totals: raw(totals), row: row.record },\n currency: { params: render.params, header, row: row.record },\n record: row.record,\n row: row.index,\n }\n}\n\n/** A failed evaluation: an error, or in a preview a value the data lacks, which is a warning. Returns whether it was only a warning. */\nfunction failed(render: Pick<Render, 'problems' | 'preview'>, outcome: { readonly error: Parameters<typeof fromEvaluation>[0] }): boolean {\n if (render.preview && outcome.error.code === 'missing-value') {\n // Said once for the expression, naming the first row, not once per row: the data check has already said which field is missing.\n const error = fromEvaluation(outcome.error)\n render.problems.warn({ ...error, message: `${error.message}; this preview prints nothing for it` })\n return true\n }\n render.problems.error(fromEvaluation(outcome.error))\n return false\n}\n\n/** The value of the expression whose `cel` is at `path`, read in `scope`; null for none, undefined when it failed and the failure is recorded. */\nexport function valueOf(render: Pick<Render, 'expressions' | 'problems' | 'preview'>, scope: Scope, path: string): TypedValue | null | undefined {\n const outcome = render.expressions.evaluate(path, scope.values, scope.row)\n if (outcome.ok) return outcome.value\n return failed(render, outcome) ? null : undefined\n}\n\n/** Whether the condition whose `cel` is at `path` holds in `scope`; undefined when it failed and the failure is recorded as an error. */\nexport function holds(render: Pick<Render, 'expressions' | 'problems' | 'preview'>, scope: Scope, path: string): boolean | undefined {\n const outcome = render.expressions.condition(path, scope.values, scope.row)\n if (outcome.ok) return outcome.value\n return failed(render, outcome) ? false : undefined\n}\n\n/** The type the report's contract gives `ref`'s field; the validator has checked that it declares one. */\nexport function fieldType(report: ReportDefinition, ref: FieldRef): FieldType {\n return report.datasets[ref.dataset]?.fields.find(({ id }) => id === ref.field)?.type as FieldType\n}\n\nexport function parameterType(report: ReportDefinition, parameter: string): ParameterType {\n return report.parameters.find(({ id }) => id === parameter)?.type as ParameterType\n}\n\n/**\n * The value of `ref`, typed by its contract: a header field's from the\n * header, a detail field's from `record`. Null where it is null, and where\n * a preview's data lacks it, which the data check has already warned of. An\n * image field is drawn, never printed (0007), and reads as null here.\n */\nexport function fieldValue(render: Pick<Render, 'report' | 'data'>, record: CheckedRecord | undefined, ref: FieldRef): TypedValue | null {\n const value = (ref.dataset === 'header' ? render.data.header : record)?.[ref.field] ?? null\n const type = fieldType(render.report, ref)\n if (value === null || type === 'image') return null\n return { type, value } as TypedValue\n}\n\n/** An image field's value in the header: an approved asset, or null when there is none to draw. */\nexport function imageValue(render: Pick<Render, 'data'>, ref: FieldRef): ImageValue | null {\n return (render.data.header?.[ref.field] as ImageValue | null | undefined) ?? null\n}\n","/**\n * An image component lowered to the bytes it draws.\n *\n * An image shows an asset the template pins, or an image field of the\n * header dataset (0007). Either way it names an approved asset by its id\n * and digest, and the host's lookup hands over the bytes: the runtime never\n * follows an address and fetches nothing. What comes back is checked here --\n * bytes, and a media type a report may draw, the one the template declares\n * for its own asset -- and copied, so that nothing the host changes\n * afterwards reaches the document. Whether the bytes are a picture is the\n * renderer's to say (`invalid-asset`).\n *\n * The lookup is trusted to return the bytes the digest pins: the runtime has\n * no hash function of its own, being free of Node and of the DOM, and does\n * not check them against it.\n *\n * An image field with no value draws nothing, and its box is kept as space,\n * so that what follows it stands where it would with a picture: null prints\n * as nothing (0007), and nothing moves.\n *\n * Each approved asset is asked for once per render, and every image that\n * draws it shares the one copy, so that a logo on every page header, or a\n * photo drawn by forty components, is held and embedded once. An answer\n * past `MAX_ASSET_BYTES` is refused before it is copied.\n */\nimport { ASSET_MEDIA_TYPES } from '@formancy/report-spec'\nimport type { AssetMediaType, ImageComponent } from '@formancy/report-spec'\nimport { MAX_ASSET_BYTES } from './document.js'\nimport type { Image, ImageAsset, Spacer } from './document.js'\nimport { imageValue } from './render-context.js'\nimport type { ImageBytes, ImageRef, Render } from './render-context.js'\nimport type { ResolveErrorCode } from './resolve-errors.js'\n\n/** Why an asset's bytes could not be had: the code, and what to say after the component's id. */\ninterface Refusal {\n readonly code: ResolveErrorCode\n readonly message: string\n}\n\n/** What the host handed over, if it is bytes of a media type a report draws, within the limit: copied. A string says why it is not. */\nfunction checkedBytes(found: unknown, declared: AssetMediaType | undefined): { readonly mediaType: AssetMediaType; readonly bytes: Uint8Array } | string {\n const media = `is not bytes of ${declared === undefined ? ASSET_MEDIA_TYPES.join(' or ') : declared}`\n if (typeof found !== 'object' || found === null) return media\n const { mediaType, bytes } = found as Partial<ImageBytes>\n if (!(bytes instanceof Uint8Array) || !ASSET_MEDIA_TYPES.includes(mediaType as AssetMediaType)) return media\n if (declared !== undefined && mediaType !== declared) return media\n if (bytes.length > MAX_ASSET_BYTES) return `is ${bytes.length} bytes; an asset may have ${MAX_ASSET_BYTES} (20 MB)`\n return { mediaType: mediaType as AssetMediaType, bytes: new Uint8Array(bytes) }\n}\n\n/** The bytes of `ref`, asked of the host and checked, or why they could not be had. */\nfunction fetched(render: Render, ref: ImageRef, declared: AssetMediaType | undefined): ImageAsset | Refusal {\n if (render.images === undefined) return { code: 'missing-asset', message: 'the report draws an image, and the host gave no way to fetch approved assets' }\n let found: unknown\n let bytes: ReturnType<typeof checkedBytes>\n try {\n // The answer is read inside the guard too: a getter on it is the host's code, and may throw.\n found = render.images(ref)\n bytes = checkedBytes(found, declared)\n } catch {\n return { code: 'asset-lookup-failed', message: `fetching the approved asset ${ref.asset} failed` }\n }\n if (found === undefined) return { code: 'missing-asset', message: `the host has no bytes for the approved asset ${ref.asset} at its digest` }\n if (typeof bytes === 'string') return { code: 'invalid-asset', message: `the host's answer for the approved asset ${ref.asset} ${bytes}` }\n return { id: ref.asset, ...bytes }\n}\n\n/** Each render's assets, by id, digest and the type declared for them: asked for once, and shared. */\nconst ASSETS = new WeakMap<Render, Map<string, ImageAsset | Refusal>>()\n\nfunction assetOf(render: Render, ref: ImageRef, declared: AssetMediaType | undefined): ImageAsset | Refusal {\n const cache = ASSETS.get(render) ?? new Map<string, ImageAsset | Refusal>()\n ASSETS.set(render, cache)\n const key = JSON.stringify([ref.asset, ref.digest, declared ?? null])\n const known = cache.get(key)\n if (known !== undefined) return known\n const asset = fetched(render, ref, declared)\n cache.set(key, asset)\n return asset\n}\n\n/** `component`, at `path`, as the image it draws, the space it keeps when its field is null, or undefined when its bytes could not be had, which is recorded. */\nexport function imageBlock(render: Render, component: ImageComponent, path: string): Image | Spacer | undefined {\n const { source } = component\n let ref: ImageRef\n let declared: AssetMediaType | undefined\n if (source.kind === 'asset') {\n // report-spec refuses an image of an asset the report does not declare.\n const asset = render.report.assets.find(({ id }) => id === source.asset) as { readonly id: string; readonly mediaType: AssetMediaType; readonly digest: string }\n ref = { asset: asset.id, digest: asset.digest }\n declared = asset.mediaType\n } else {\n const value = imageValue(render, source.field)\n if (value === null) return { kind: 'spacer', height: component.height }\n ref = { asset: value.asset, digest: value.digest }\n }\n const asset = assetOf(render, ref, declared)\n if ('code' in asset) {\n render.problems.error({ stage: 'resolve', code: asset.code, path: `${path}/source`, message: `component ${component.id}: ${asset.message}`, componentId: component.id })\n return undefined\n }\n return { kind: 'image', asset, width: component.width, height: component.height, fit: component.fit }\n}\n","/**\n * A run of a report -- literal, bound, computed, totalled or a page counter\n * -- lowered to the text it prints, formatted for the report's locale.\n *\n * The one place each kind of inline gets its value: a field from the header\n * or the current record, a parameter from the checked parameters, an\n * expression from its evaluation in the scope it stands in, an aggregate\n * from the report's totals or the current group's. Every value is formatted\n * by `format.ts` with the inline's format, or printed plainly without one,\n * and null prints as nothing (0007). A page counter stays a field the\n * engine fills in, since only it knows the pages.\n */\nimport type { Inline as ReportInline } from '@formancy/report-spec'\nimport type { Inline } from './document.js'\nimport type { TypedValue } from './format.js'\nimport { fieldValue, parameterType, valueOf } from './render-context.js'\nimport type { Render, Scope } from './render-context.js'\nimport { placed } from './resolve-errors.js'\n\n/** What an error names besides the inline's path: the component, and in a table the column. */\nexport interface Owner {\n readonly componentId?: string\n readonly columnId?: string\n}\n\n/** The value `inline` prints, read in `scope`; undefined when its evaluation failed, which is recorded. */\nfunction valueAt(render: Render, scope: Scope, inline: Exclude<ReportInline, { kind: 'text' | 'pageNumber' | 'pageCount' }>, path: string): TypedValue | null | undefined {\n switch (inline.kind) {\n case 'field':\n return fieldValue(render, scope.record, inline.field)\n case 'parameter': {\n const value = render.params[inline.parameter] ?? null\n return value === null ? null : ({ type: parameterType(render.report, inline.parameter), value } as TypedValue)\n }\n case 'expression':\n return valueOf(render, scope, `${path}/expression/cel`)\n case 'aggregate':\n // report-spec allows a group's aggregate only where there is a group.\n return (inline.over === 'group' ? scope.group : render.totals.report)?.get(inline.aggregate) ?? null\n }\n}\n\n/** `inline`, at `path` in the report, as the run it prints in `scope`; undefined when it could not be, which is recorded. */\nexport function runOf(render: Render, scope: Scope, inline: ReportInline, path: string, owner: Owner): Inline | undefined {\n if (inline.kind === 'text') return { text: inline.text }\n if (inline.kind === 'pageNumber' || inline.kind === 'pageCount') return { field: inline.kind }\n const value = valueAt(render, scope, inline, path)\n if (value === undefined) return undefined\n const formatted = render.formatter.format(value, inline.format, scope.currency)\n if (formatted.ok) return { text: formatted.text }\n const where = [owner.componentId && `component ${owner.componentId}`, owner.columnId && `column ${owner.columnId}`, scope.row !== undefined && `detail row ${scope.row}`].filter(Boolean).join(', ')\n render.problems.error({ stage: 'format', code: formatted.code, path, message: `${where}: ${formatted.message}`, ...placed({ ...owner, row: scope.row }) })\n return undefined\n}\n\n/** The text of runs that hold no page counter: what a table cell or a group header prints. */\nexport function textOfRuns(runs: readonly Inline[]): string {\n return runs.map((run) => ('text' in run ? run.text : '')).join('')\n}\n","/**\n * Print styles resolved to the one style each piece of text prints in.\n *\n * report-spec's styles are tokens (0007); here they are laid over each other\n * once, and the document carries the result, so an engine never merges\n * styles (`TextStyle`). The order, each later one's property winning:\n *\n * 1. what the component stands in passes down: a section's, a columns\n * block's or a keep-together block's style is the base of the text\n * inside it;\n * 2. the component's own `style`;\n * 3. each of its `styleWhen` rules that holds, in order.\n *\n * In a table, the table's resolved style is the base of every row: the\n * header's `headerStyle`, a group header's, a footer row's own, and each\n * column's style and rules over a detail cell. An image, a line, a\n * rectangle, a spacer and a page break print no text; a style on one is\n * read for its rules' conditions, and changes nothing.\n */\nimport type { PrintStyle, StyleRule } from '@formancy/report-spec'\nimport type { TextStyle } from './document.js'\nimport { holds } from './render-context.js'\nimport type { Render, Scope } from './render-context.js'\n\n/** Each print style as the document's: the same tokens without the id. */\nexport function documentStyles(styles: readonly PrintStyle[]): ReadonlyMap<string, TextStyle> {\n return new Map(styles.map(({ id, ...style }) => [id, style]))\n}\n\n/** `styles` laid over each other, a later one's property winning; undefined when none sets anything. */\nexport function layered(...styles: readonly (TextStyle | undefined)[]): TextStyle | undefined {\n const merged: TextStyle = Object.assign({}, ...styles.filter((style) => style !== undefined)) as TextStyle\n return Object.keys(merged).length === 0 ? undefined : merged\n}\n\n/**\n * `base`, then the print style `style` names, then each rule at\n * `<path>/<index>` whose condition holds in `scope`. Undefined when nothing\n * sets anything, or when a condition failed, which is recorded.\n */\nexport function styled(render: Render, scope: Scope, base: TextStyle | undefined, style: string | undefined, rules: readonly StyleRule[] | undefined, path: string): TextStyle | undefined {\n const held: TextStyle[] = []\n for (const [index, rule] of (rules ?? []).entries()) {\n if (holds(render, scope, `${path}/${index}/when/cel`) === true) held.push(render.styles.get(rule.style) as TextStyle)\n }\n return layered(base, style === undefined ? undefined : render.styles.get(style), ...held)\n}\n","/**\n * The table over the detail dataset, lowered to the rows it prints.\n *\n * Its rows are ordered and grouped by `sort-group.ts` (0007): the group's\n * key first, then the sort keys, ties in the provider's order. Then, in\n * that order:\n *\n * - for each group, one line across the table read in the group's scope,\n * its rows, and its footer rows, whose aggregates are the group's;\n * - the totals rows, whose aggregates are over every row;\n * - with no detail rows, the table's empty text in their place, and its\n * totals still printed: a count and a sum of nothing are 0.\n *\n * A column whose condition does not hold is left out, read once per report:\n * its header, every cell under it and its footer cells, and the fill columns\n * share its width. A table every column of which is hidden prints nothing.\n * Each detail cell is read in its row's scope, its column's style rules too;\n * every other row has one style.\n */\nimport type { TableColumn as ReportColumn, TableComponent, TableFooterRow } from '@formancy/report-spec'\nimport type { Table, TableRow, TextStyle } from './document.js'\nimport { runOf, textOfRuns } from './inlines.js'\nimport { groupScope, holds, reportScope, rowScope } from './render-context.js'\nimport type { Render, Scope } from './render-context.js'\nimport { orderTable } from './sort-group.js'\nimport type { OrderedRow } from './sort-group.js'\nimport { layered, styled } from './styles.js'\n\n/** A column that prints, and where it stands in the report's list of the table's columns. */\ninterface Shown {\n readonly column: ReportColumn\n readonly index: number\n}\n\n/** What every row of one table is read with. */\ninterface Lowering {\n readonly render: Render\n readonly table: TableComponent\n readonly path: string\n readonly shown: readonly Shown[]\n /** The table's own style, laid under every row's. */\n readonly base: TextStyle | undefined\n}\n\n/** `style` as a row's: the table's under the named print style; absent when neither sets anything. */\nfunction rowStyle(lowering: Lowering, style: string | undefined): { readonly style?: TextStyle } {\n const resolved = layered(lowering.base, style === undefined ? undefined : lowering.render.styles.get(style))\n return resolved === undefined ? {} : { style: resolved }\n}\n\n/** One detail row: each shown column's value and own style, read in the row's scope. */\nfunction detailRow(lowering: Lowering, row: OrderedRow): TableRow {\n const { render, table, path } = lowering\n const scope = rowScope(render, render.totals.report, row)\n const cells = lowering.shown.map(({ column, index }) => {\n const run = runOf(render, scope, column.value, `${path}/columns/${index}/value`, { componentId: table.id, columnId: column.id })\n return run === undefined ? '' : textOfRuns([run])\n })\n const own = lowering.shown.map(({ column, index }) => styled(render, scope, undefined, column.style, column.styleWhen, `${path}/columns/${index}/styleWhen`))\n const cellStyles = own.some((style) => style !== undefined) ? { cellStyles: own.map((style) => (style === undefined ? null : (layered(lowering.base, style) as TextStyle))) } : {}\n return { kind: 'detail', cells, ...(lowering.base === undefined ? {} : { style: lowering.base }), ...cellStyles }\n}\n\n/** Footer rows read in `scope`: under a group, or under the table. A shown column without a cell in a row prints nothing there. */\nfunction footerRows(lowering: Lowering, rows: readonly TableFooterRow[] | undefined, at: string, kind: 'groupFooter' | 'total', scope: Scope): TableRow[] {\n const { render, table } = lowering\n return (rows ?? []).map((row, rowIndex) => {\n const cells = lowering.shown.map(({ column }) => {\n const cellIndex = row.cells.findIndex((cell) => cell.column === column.id)\n const cell = row.cells[cellIndex]\n if (cell === undefined) return ''\n const run = runOf(render, scope, cell.value, `${at}/${rowIndex}/cells/${cellIndex}/value`, { componentId: table.id, columnId: column.id })\n return run === undefined ? '' : textOfRuns([run])\n })\n return { kind, cells, ...rowStyle(lowering, row.style) }\n })\n}\n\n/** The rows of a table that groups: per group, its header line, its rows and its footer. */\nfunction groupedRows(lowering: Lowering, groups: NonNullable<ReturnType<typeof orderTable>['groups']>): TableRow[] {\n const { render, table, path } = lowering\n const group = table.group as NonNullable<TableComponent['group']>\n const rows: TableRow[] = []\n for (const each of groups) {\n if (render.problems.full) break\n const scope = groupScope(render, each, render.totals.over(each.rows), group.by.field)\n const runs = group.header.map((inline, index) => runOf(render, scope, inline, `${path}/group/header/${index}`, { componentId: table.id }))\n rows.push({ kind: 'groupHeader', cells: [textOfRuns(runs.filter((run) => run !== undefined))], across: true, ...rowStyle(lowering, group.headerStyle) })\n for (const row of each.rows) rows.push(detailRow(lowering, row))\n rows.push(...footerRows(lowering, group.footer, `${path}/group/footer`, 'groupFooter', scope))\n }\n return rows\n}\n\n/**\n * `table`, at `path`, as the document's table, `base` its own resolved\n * style; undefined when every column is hidden. A value that could not be\n * read prints nothing here, and is recorded as an error, so the report is\n * refused.\n */\nexport function tableBlock(render: Render, table: TableComponent, path: string, base: TextStyle | undefined): Table | undefined {\n const scope = reportScope(render, render.totals.report)\n const shown = table.columns\n .map((column, index) => ({ column, index }))\n .filter(({ column, index }) => column.visibleWhen === undefined || holds(render, scope, `${path}/columns/${index}/visibleWhen/cel`) === true)\n if (shown.length === 0) return undefined\n const lowering: Lowering = { render, table, path, shown, base }\n const ordered = orderTable(render.report, table, render.data.detail)\n const rows: TableRow[] = []\n if (ordered.groups !== undefined) rows.push(...groupedRows(lowering, ordered.groups))\n else {\n for (const row of ordered.rows) {\n if (render.problems.full) break\n rows.push(detailRow(lowering, row))\n }\n }\n rows.push(...footerRows(lowering, table.totals, `${path}/totals`, 'total', scope))\n const headerStyle = layered(base, table.headerStyle === undefined ? undefined : render.styles.get(table.headerStyle))\n return {\n kind: 'table',\n id: table.id,\n columns: shown.map(({ column }) => ({ width: column.width, align: column.align })),\n header: shown.map(({ column }) => column.header),\n ...(headerStyle === undefined ? {} : { headerStyle }),\n rows,\n emptyText: table.emptyText,\n }\n}\n","/**\n * A report's components lowered to the document's blocks, region by region.\n *\n * Every component is read in the report's scope: its condition first, and a\n * component whose condition does not hold prints nothing, nor does anything\n * inside it. Then its style (`styles.ts`), and then what it is. A kind maps\n * to a block through a table over every kind, so a kind added to the format\n * without a way down does not compile.\n *\n * The report header is the start of the body and the summary its end, so\n * the document has three regions: the page header and footer, repeated on\n * every page, and the body.\n */\nimport type { Component, ComponentKind, RegionName } from '@formancy/report-spec'\nimport type { Block, TextStyle } from './document.js'\nimport { imageBlock } from './images.js'\nimport { runOf } from './inlines.js'\nimport { tableBlock } from './lower-table.js'\nimport { holds, reportScope } from './render-context.js'\nimport type { Render, Scope } from './render-context.js'\nimport { styled } from './styles.js'\n\n/** The document's regions, lowered. */\nexport interface LoweredRegions {\n readonly pageHeader: readonly Block[]\n readonly pageFooter: readonly Block[]\n readonly body: readonly Block[]\n}\n\n/** What one component is lowered with: where it is, the report scope, and its resolved style. */\ninterface At {\n readonly render: Render\n readonly scope: Scope\n readonly path: string\n readonly style: TextStyle | undefined\n}\n\ntype Lowerer<K extends ComponentKind> = (component: Extract<Component, { kind: K }>, at: At) => Block | undefined\n\n/** `value` under `key` when it is defined: the document writes only what is set. */\nconst optional = <K extends string, V>(key: K, value: V | undefined): { [P in K]?: V } => (value === undefined ? {} : ({ [key]: value } as { [P in K]: V }))\n\nconst LOWER: { readonly [K in ComponentKind]: Lowerer<K> } = {\n text: (text, { render, scope, path, style }) => {\n const runs = text.content.flatMap((inline, index) => runOf(render, scope, inline, `${path}/content/${index}`, { componentId: text.id }) ?? [])\n return { kind: 'paragraph', runs, ...optional('style', style), ...(text.keepWithNext === true ? { keepWithNext: true } : {}) }\n },\n image: (image, { render, path }) => imageBlock(render, image, path),\n line: (line) => ({ kind: 'rule', thickness: line.thickness, ...optional('color', line.color) }),\n rectangle: (rectangle) => ({ kind: 'rectangle', width: rectangle.width, height: rectangle.height, ...optional('fill', rectangle.fill), ...optional('stroke', rectangle.stroke) }),\n spacer: (spacer) => ({ kind: 'spacer', height: spacer.height }),\n columns: (columns, { render, path, style }) => ({\n kind: 'columns',\n columns: columns.columns.map((slot, index) => ({ width: slot.width, blocks: blocksOf(render, slot.components, `${path}/columns/${index}/components`, style) })),\n }),\n section: (section, { render, path, style }) => ({\n kind: 'section',\n blocks: blocksOf(render, section.components, `${path}/components`, style),\n ...optional('border', section.border),\n ...optional('fill', section.fill),\n ...optional('padding', section.padding),\n }),\n table: (table, { render, path, style }) => tableBlock(render, table, path, style),\n pageBreak: () => ({ kind: 'pageBreak' }),\n keepTogether: (kept, { render, path, style }) => ({ kind: 'keepTogether', blocks: blocksOf(render, kept.components, `${path}/components`, style) }),\n}\n\n/** `component`, at `path`, as the block it prints; undefined when it prints nothing, or could not be lowered, which is recorded. */\nfunction blockOf(render: Render, component: Component, path: string, inherited: TextStyle | undefined): Block | undefined {\n const scope = reportScope(render, render.totals.report)\n if (component.visibleWhen !== undefined && holds(render, scope, `${path}/visibleWhen/cel`) !== true) return undefined\n const style = styled(render, scope, inherited, component.style, component.styleWhen, `${path}/styleWhen`)\n return (LOWER[component.kind] as Lowerer<ComponentKind>)(component as never, { render, scope, path, style })\n}\n\n/** The components of the list at `path`, in order, as the blocks they print. */\nfunction blocksOf(render: Render, components: readonly Component[], path: string, inherited: TextStyle | undefined): Block[] {\n return components.flatMap((component, index) => blockOf(render, component, `${path}/${index}`, inherited) ?? [])\n}\n\nfunction region(render: Render, name: RegionName): Block[] {\n return blocksOf(render, render.report.regions[name], `/regions/${name}`, undefined)\n}\n\n/** Every region of `render`'s report, lowered: the report header, body and summary as the one body. */\nexport function lowerRegions(render: Render): LoweredRegions {\n return {\n pageHeader: region(render, 'pageHeader'),\n pageFooter: region(render, 'pageFooter'),\n body: [...region(render, 'reportHeader'), ...region(render, 'body'), ...region(render, 'summary')],\n }\n}\n","/**\n * Whether a report can be rendered at all, before any data is read: the\n * first two levels of plan 15, structure and bindings.\n *\n * A report reaches the runtime as untrusted input, whatever its type says --\n * parsed from storage, posted by a browser. So it is validated again here,\n * with report-spec's `validateReport`, and what the runtime goes on to read\n * is the copy validation made, which no later change to the caller's object\n * reaches. Then its expressions are compiled with report-core, and a report\n * the editor's diagnostics give an error for is refused (0009): the runtime\n * never renders what the editor refuses.\n */\nimport type { ReportDefinition } from '@formancy/report-spec'\nimport { validateReport } from '@formancy/report-spec'\nimport { prepareExpressions } from './evaluate.js'\nimport type { ReportExpressions } from './evaluate.js'\nimport { fromDiagnostic, fromReport } from './resolve-errors.js'\nimport type { RuntimeError } from './resolve-errors.js'\n\nexport type ReportCheck =\n | { readonly ok: true; /** The copy validation read. */ readonly report: ReportDefinition; readonly expressions: ReportExpressions }\n | { readonly ok: false; readonly errors: readonly RuntimeError[] }\n\n/**\n * `report` validated and its expressions compiled for one render, or every\n * reason it is refused: each structural error, or, for a report that is\n * structurally valid, each diagnostic of severity error.\n */\nexport function checkReport(report: unknown): ReportCheck {\n const validation = validateReport(report)\n if (!validation.valid) return { ok: false, errors: validation.errors.map(fromReport) }\n const prepared = prepareExpressions(validation.report)\n if (!prepared.ok) return { ok: false, errors: prepared.diagnostics.map(fromDiagnostic) }\n return { ok: true, report: validation.report, expressions: prepared.expressions }\n}\n","/**\n * The report's aggregates, computed exactly, once, here (0007): over every\n * detail row for `totals`, and over a group's rows for `group`.\n *\n * - **In report-core's order.** An aggregate's expression may read another\n * aggregate's total, so each is computed after every one it reads, in the\n * order `compileReport` gives (0009); an aggregate that could never be\n * computed has already refused the report.\n * - **Each row read once.** What an aggregate reads from a row is read once\n * per render, with the report's totals, and kept by the row's index; a\n * group's aggregate is the same function over its rows' values. So a\n * group's subtotal and the report's total are totals of the same values,\n * and the subtotals of a sum that declares no rounding add up to the\n * total. A declared rounding is applied to each group's exact sum and to\n * the report's, once each, so rounded subtotals need not add up to the\n * rounded total: two groups of 0.02, rounded to 0.05, print 0.00 and 0.00\n * over 0.05.\n * - **Exact, and of one kind.** Integers as BigInt, decimals as `Decimal`,\n * through `decimal.ts`; nothing passes through a JavaScript number. A\n * total report-core compiled as a decimal is a decimal, its 0 too, and so\n * is one whose kind the compiler could not tell (`dyn`) once it declares a\n * rounding or meets a decimal; a group's total is of the report total's\n * kind, so an expression reading `group.<id>` meets one type.\n * - **Nulls are skipped**, and so is a value a preview's data lacks. Over no\n * values a count and a sum are 0 and the rest null (0007).\n * - **Declared rounding is applied once**, to the exact result: an average\n * always declares one, and a sum, a minimum or a maximum of decimals may.\n * A rounding on a total that is an integer or a moment is refused, never\n * ignored.\n */\nimport { compareDecimal, Decimal } from '@formancy/expressions'\nimport type { AggregateDef, Rounding } from '@formancy/report-spec'\nimport { averageDecimals, roundDecimalAs, sumDecimals } from './decimal.js'\nimport type { TypedValue } from './format.js'\nimport { fieldValue, rowScope, valueOf } from './render-context.js'\nimport type { AggregateValues, Render, Totals } from './render-context.js'\nimport type { ResolveErrorCode } from './resolve-errors.js'\nimport type { OrderedRow } from './sort-group.js'\nimport { fixedWidth } from './sort-group.js'\n\n/** Why a total has no value: its code and what to say. */\ninterface Refusal {\n readonly code: ResolveErrorCode\n readonly message: string\n}\n\ntype Total = TypedValue | null | Refusal\n\nconst isRefusal = (value: Total): value is Refusal => value !== null && 'code' in value\n\nconst integer = (value: bigint): TypedValue => ({ type: 'integer', value })\nconst decimal = (value: Decimal): TypedValue => ({ type: 'decimal', value })\nconst asDecimal = (value: TypedValue): Decimal => (value.type === 'integer' ? new Decimal(value.value, 0) : (value.value as Decimal))\n\n/** How one aggregate is totalled: its definition, whether its numbers are decimals whatever they hold, and the text order. */\ninterface Totalling {\n readonly aggregate: AggregateDef\n readonly decimals: boolean\n readonly collator: Intl.Collator\n}\n\n/** Values as numbers of one kind: integers while every one is and decimals are not asked for, else decimals; undefined when one is not a number. */\nfunction numbers(values: readonly TypedValue[], decimals: boolean): { readonly integers: readonly bigint[] } | { readonly decimals: readonly Decimal[] } | undefined {\n if (!decimals && values.every((value) => value.type === 'integer')) return { integers: values.map((value) => value.value as bigint) }\n if (!values.every((value) => value.type === 'integer' || value.type === 'decimal')) return undefined\n return { decimals: values.map(asDecimal) }\n}\n\nconst NOT_NUMBERS: Refusal = { code: 'aggregate-value-type', message: 'totals integers and decimals, and a value it read is neither' }\n\nfunction sum(values: readonly TypedValue[], decimals: boolean): Total {\n const read = numbers(values, decimals)\n if (read === undefined) return NOT_NUMBERS\n return 'integers' in read ? integer(read.integers.reduce((total, value) => total + value, 0n)) : decimal(sumDecimals(read.decimals))\n}\n\nfunction average(values: readonly TypedValue[], rounding: Rounding): Total {\n const read = numbers(values, true) as { readonly decimals: readonly Decimal[] } | undefined\n if (read === undefined) return NOT_NUMBERS\n const result = averageDecimals(read.decimals, rounding)\n return result === null ? null : decimal(result)\n}\n\nconst ordered = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0)\n\n/** -1, 0 or 1 for two values of one kind: numbers by value, text as the report's language sorts it, dates as days, moments in time order. */\nfunction comparator(values: readonly TypedValue[], collator: Intl.Collator): ((a: TypedValue, b: TypedValue) => number) | undefined {\n const types = new Set(values.map(({ type }) => type))\n if ([...types].every((type) => type === 'integer' || type === 'decimal')) return (a, b) => compareDecimal(asDecimal(a), asDecimal(b))\n const only = types.size === 1 ? [...types][0] : undefined\n if (only === 'string') return (a, b) => collator.compare(a.value as string, b.value as string)\n if (only === 'date') return (a, b) => ordered(a.value as string, b.value as string)\n if (only === 'datetime' || only === 'instant') return (a, b) => ordered(fixedWidth(a.value as string), fixedWidth(b.value as string))\n return undefined\n}\n\n/** The least (`sign` -1) or greatest (1) value, the first of equals as written; null over none. */\nfunction extreme(values: readonly TypedValue[], sign: -1 | 1, totalling: Totalling): Total {\n const compare = comparator(values, totalling.collator)\n if (compare === undefined) return { code: 'aggregate-value-type', message: 'takes the least or greatest of values of one kind, and the values it read are of several' }\n const found = values.reduce<TypedValue | null>((kept, value) => (kept === null || Math.sign(compare(value, kept)) === sign ? value : kept), null)\n return found?.type === 'integer' && totalling.decimals ? decimal(asDecimal(found)) : found\n}\n\n/** `total` rounded as `rounding` declares: a decimal at the rounding's scale. */\nfunction rounded(total: Total, rounding: Rounding | undefined): Total {\n if (rounding === undefined || total === null || isRefusal(total)) return total\n if (total.type === 'decimal') return decimal(roundDecimalAs(total.value, rounding))\n return { code: 'rounding-not-decimal', message: `declares a rounding, and its total is ${total.type === 'integer' ? 'an integer' : `a ${total.type}`}, which has no places to round` }\n}\n\n/** The aggregate over the values read from some rows -- each null or typed -- or over `rows` rows when it reads nothing. */\nfunction reduce(totalling: Totalling, read: readonly (TypedValue | null)[] | undefined, rows: number): Total {\n const { aggregate, decimals } = totalling\n const values = (read ?? []).filter((value): value is TypedValue => value !== null)\n switch (aggregate.fn) {\n case 'count':\n return integer(BigInt(read === undefined ? rows : values.length))\n case 'avg':\n // report-spec requires an average to declare its rounding.\n return values.length === 0 ? null : average(values, aggregate.rounding as Rounding)\n case 'sum':\n return rounded(sum(values, decimals), aggregate.rounding)\n case 'min':\n return rounded(extreme(values, -1, totalling), aggregate.rounding)\n case 'max':\n return rounded(extreme(values, 1, totalling), aggregate.rounding)\n }\n}\n\n/**\n * Every aggregate of `render`'s report, over its detail rows and, through\n * `over`, over any of them; or undefined when one could not be computed,\n * each reason recorded. `render` has every input but the totals.\n */\nexport function computeTotals(render: Omit<Render, 'totals'>): Totals | undefined {\n const { report, expressions, data, problems } = render\n const collator = new Intl.Collator(report.locale, { usage: 'sort' })\n const rows: readonly OrderedRow[] = data.detail.map((record, index) => ({ index, record }))\n const read = new Map<string, readonly (TypedValue | null)[]>()\n const totals = new Map<string, TypedValue | null>()\n const totallings = new Map<string, Totalling>()\n const refuse = (index: number, refusal: Refusal): void => {\n problems.error({ stage: 'resolve', code: refusal.code, path: `/aggregates/${index}`, message: `aggregate ${report.aggregates[index]?.id} ${refusal.message}` })\n }\n let computed = true\n\n for (const id of expressions.compilation.aggregateOrder) {\n const index = report.aggregates.findIndex((aggregate) => aggregate.id === id)\n const aggregate = report.aggregates[index] as AggregateDef\n const compiled = expressions.compilation.members.totals.get(id)?.type\n const decimals = compiled === 'decimal' || (compiled === 'dyn' && aggregate.rounding !== undefined)\n const of = aggregate.of\n if (of !== undefined) {\n const path = `/aggregates/${index}/of/expression/cel`\n const values = rows.map((row) => (of.kind === 'field' ? fieldValue(render, row.record, of.field) : valueOf(render, rowScope(render, totals, row), path)))\n if (values.some((value) => value === undefined)) {\n computed = false\n continue\n }\n read.set(id, values as (TypedValue | null)[])\n }\n const totalling: Totalling = { aggregate, decimals, collator }\n const total = reduce(totalling, read.get(id), rows.length)\n if (isRefusal(total)) {\n computed = false\n refuse(index, total)\n continue\n }\n totals.set(id, total)\n // A group's total is of its report total's kind: one that met a decimal is a decimal in every group.\n totallings.set(id, total?.type === 'decimal' ? { ...totalling, decimals: true } : totalling)\n }\n if (!computed) return undefined\n\n return {\n report: totals,\n over(group: readonly OrderedRow[]): AggregateValues {\n const values = new Map<string, TypedValue | null>()\n for (const aggregate of report.aggregates) {\n const each = read.get(aggregate.id)\n // Never refused: a group's values are some of those the report's\n // total took, of the kinds it took, totalled as the same kind and\n // rounded as it was. Every refusal `reduce` has is about the kinds\n // of values, and a share of values has no kind the whole lacks.\n values.set(aggregate.id, reduce(totallings.get(aggregate.id) as Totalling, each && group.map((row) => each[row.index] as TypedValue | null), group.length) as TypedValue | null)\n }\n return values\n },\n }\n}\n","/**\n * A report resolved against its data: the renderer-neutral document it\n * prints, and the manifest that says what it was printed from (plan 14).\n *\n * The composition of the runtime's stages, each decided in its own module:\n *\n * 1. the report, validated again and its expressions compiled; one the\n * editor's diagnostics give an error for is refused (`report-check.ts`);\n * 2. the options, the parameters and the data, each checked, and every\n * error of the three listed together (`parameters.ts`, `data.ts`);\n * 3. the aggregates, exactly, over every row (`totals.ts`);\n * 4. the regions, lowered component by component (`lower.ts`), tables row\n * by row (`lower-table.ts`), images through the host's lookup\n * (`images.ts`).\n *\n * It refuses rather than prints a wrong report: any error at any stage, and\n * the result is the errors, never a partial document. A preview may run on\n * data the provider calls incomplete or that lacks a field; it says so in\n * the manifest and in its warnings, and its every page carries\n * `PREVIEW_LABEL`, so that a preview printed or passed on is never taken for\n * the report. A final render refuses such data.\n */\nimport { decimalToString } from '@formancy/expressions'\nimport type { Decimal } from '@formancy/expressions'\nimport { reportHash } from '@formancy/report-spec'\nimport type { ReportDefinition } from '@formancy/report-spec'\nimport { checkData } from './data.js'\nimport type { Completeness, Consistency, DataMode, ReportData } from './data.js'\nimport type { Paragraph, ResolvedDocument } from './document.js'\nimport { createFormatter } from './format.js'\nimport { lowerRegions } from './lower.js'\nimport { checkParameters } from './parameters.js'\nimport type { CheckedParameters } from './parameters.js'\nimport type { ImageResolver } from './render-context.js'\nimport { checkReport } from './report-check.js'\nimport { fromData, Problems } from './resolve-errors.js'\nimport type { RuntimeError } from './resolve-errors.js'\nimport { documentStyles } from './styles.js'\nimport { computeTotals } from './totals.js'\nimport { canonicalInstant } from './values.js'\n\nexport interface ResolveOptions {\n /** A final render prints the report; a preview shows a sample and says what it lacks. */\n readonly mode: DataMode\n /** The values a person supplied, by parameter id; defaults apply to those left out. */\n readonly parameters?: Readonly<Record<string, unknown>>\n /** The host's lookup of approved assets' bytes; a report that draws an image is refused without one. */\n readonly images?: ImageResolver\n /** An ISO 8601 instant with its zone, fixed by the caller, so that the same inputs print the same PDF. */\n readonly creationDate: string\n /** The IANA zone instants are shown in, named by the host: UTC when absent, never the machine's. */\n readonly timeZone?: string\n}\n\n/** What a document was resolved from, to keep beside the PDF (plan 14). Nothing in it is the data's. */\nexport interface RenderManifest {\n /** report-spec's hash of the report as validated. */\n readonly reportHash: string\n readonly reportSpecVersion: ReportDefinition['reportSpecVersion']\n readonly locale: string\n readonly timeZone: string\n readonly mode: DataMode\n readonly consistency: Consistency\n readonly completeness: Completeness\n /** Each parameter's value as the format writes one -- an exact number or a date as a string, a boolean -- or null. */\n readonly parameters: Readonly<Record<string, string | boolean | null>>\n}\n\nexport type Resolution =\n | { readonly ok: true; readonly document: ResolvedDocument; readonly manifest: RenderManifest; /** What a preview lacks; empty in a final render, which refuses it. */ readonly warnings: readonly RuntimeError[] }\n | { readonly ok: false; readonly errors: readonly RuntimeError[] }\n\n/** What every page of a preview that lacks data says, at the top of its page header. */\nexport const PREVIEW_LABEL = 'Preview of incomplete data: not a final report'\n\nconst LABEL: Paragraph = { kind: 'paragraph', runs: [{ text: PREVIEW_LABEL }], style: { size: 8, bold: true, color: '#b00020' } }\n\n/** Each parameter's value as the format writes one. */\nfunction writtenParameters(values: CheckedParameters): Record<string, string | boolean | null> {\n return Object.fromEntries(\n Object.entries(values).map(([id, value]) => {\n if (value === null || typeof value === 'boolean' || typeof value === 'string') return [id, value]\n if (typeof value === 'bigint') return [id, String(value)]\n // A parameter is never an image (report-spec), so what is left is a decimal.\n return [id, decimalToString(value as Decimal)]\n }),\n )\n}\n\n/**\n * `report` resolved against `data`: the document to render and its\n * manifest, or every reason it is refused, up to a bound. Nothing is read\n * from `report`, `data` or the parameters but through the checks, and\n * nothing in the result is shared with them.\n */\nexport function resolveReport(report: ReportDefinition, data: ReportData, options: ResolveOptions): Resolution {\n const checked = checkReport(report)\n if (!checked.ok) return { ok: false, errors: checked.errors }\n const valid = checked.report\n const timeZone = options.timeZone ?? 'UTC'\n const errors: RuntimeError[] = []\n const creationDate = canonicalInstant(String(options.creationDate))\n if (creationDate === undefined) errors.push({ stage: 'resolve', code: 'invalid-creation-date', path: '', message: 'the creation date is an ISO 8601 instant with its zone' })\n const formatter = createFormatter({ locale: valid.locale, timeZone })\n if (!formatter.ok) errors.push({ stage: 'format', code: formatter.code, path: formatter.code === 'unsupported-locale' ? '/locale' : '', message: formatter.message })\n const parameters = checkParameters(valid, options.parameters ?? {})\n if (!parameters.ok) errors.push(...parameters.errors.map((error) => fromData('parameters', error)))\n const checkedData = checkData(valid, data, { mode: options.mode })\n if (!checkedData.ok) errors.push(...checkedData.errors.map((error) => fromData('data', error)))\n if (errors.length > 0 || creationDate === undefined || !formatter.ok || !parameters.ok || !checkedData.ok) return { ok: false, errors }\n\n const problems = new Problems()\n for (const warning of checkedData.warnings) problems.warn(fromData('data', warning))\n const preview = checkedData.data.mode === 'preview'\n const inputs = {\n report: valid,\n expressions: checked.expressions,\n formatter: formatter.formatter,\n params: parameters.values,\n data: checkedData.data,\n problems,\n preview,\n images: options.images,\n styles: documentStyles(valid.styles),\n }\n const totals = computeTotals(inputs)\n if (totals === undefined) return { ok: false, errors: problems.errors() }\n const regions = lowerRegions({ ...inputs, totals })\n if (problems.failed) return { ok: false, errors: problems.errors() }\n\n const { completeness, consistency } = checkedData.data\n const warnings = problems.warnings()\n const labelled = preview && (!completeness.complete || warnings.length > 0)\n const document: ResolvedDocument = {\n info: { title: valid.title, creationDate },\n page: valid.page,\n pageHeader: labelled ? [LABEL, ...regions.pageHeader] : regions.pageHeader,\n pageFooter: regions.pageFooter,\n body: regions.body,\n }\n const manifest: RenderManifest = {\n reportHash: reportHash(valid),\n reportSpecVersion: valid.reportSpecVersion,\n locale: valid.locale,\n timeZone,\n mode: checkedData.data.mode,\n consistency,\n completeness,\n parameters: writtenParameters(parameters.values),\n }\n return { ok: true, document, manifest, warnings }\n}\n"],"mappings":";;;;;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,MAAM;GACzB,QAAQ,MAAM;GACd;GACA,MAAM,YAAY,KAAK;GACvB;GACA;GACA,YAAY,kBAAkB,WAAW,MAAM;EAEb;EAAG;CAAS;AAClD"}
1
+ {"version":3,"file":"index.mjs","names":["MAX_QR_BILL_ADDITIONAL_INFORMATION","refuse","qrBillPageBreak","QR_BILL_CURRENCIES","checkQrBillAmount","EPC_MAX_BYTES","epcCaptionBreak","epcLeastVersion","EPC_MAX_VERSION","refused","MAX_SCALE","extreme","kept","headerOf","invoiceNames","sum","refuse","text","optional","amount","optional","refuse","checked","refuse","address","party","FACTUR_X_PROFILES","XRECHNUNG","FACTUR_X","FONT_FACE_KEYS","isFontMediaType","MAX_FONT_BYTES","readFont","ADDRESS_PARTS","refuse","checked","amount","checkQrBillAmount","MAX_SVG_BYTES","MAX_ASSET_BYTES"],"sources":["../src/document.ts","../src/qr-symbol.ts","../src/bill-check.ts","../src/slip-print.ts","../src/epc-symbol.ts","../src/input.ts","../src/values.ts","../src/data-errors.ts","../src/languages.ts","../src/source.ts","../src/data.ts","../src/parameters.ts","../src/decimal.ts","../src/format.ts","../src/sort-group.ts","../src/chart-ticks.ts","../src/resolve-errors.ts","../src/render-context.ts","../src/totals.ts","../src/lower-chart.ts","../src/evaluate.ts","../src/page-label.ts","../src/e-invoice-copy.ts","../src/xml.ts","../src/cii-parties.ts","../src/cii.ts","../src/e-invoice-totals.ts","../src/inlines.ts","../src/e-invoice-lines.ts","../src/e-invoice-terms.ts","../src/lower-e-invoice.ts","../src/lower-fonts.ts","../src/e-invoice-payable.ts","../src/qr-bill.ts","../src/lower-payment-part.ts","../src/images.ts","../src/lower-epc-qr-code.ts","../src/styles.ts","../src/lower-table.ts","../src/lower.ts","../src/report-check.ts","../src/resolve.ts"],"sourcesContent":["/**\n * The resolved document: a report after the runtime has read its data,\n * evaluated its expressions and conditions, grouped, sorted, totalled and\n * formatted it, with nothing left to decide but where each line falls on a\n * page. The runtime lowers a report definition to it;\n * `@formancy/report-render-pdf` draws it\n * ([0005](../../../docs/decisions/0005-pdfmake-renders-reports-behind-one-adapter.md)),\n * and `@formancy/report-render-docx` writes it as a Word file\n * ([0068](../../../docs/decisions/0068-a-report-is-written-as-a-word-file-by-a-writer-of-its-own-and-what-belongs-to-its-pdf-is-refused.md)).\n *\n * It names no engine and holds no engine's options. It is plain data, every\n * part of it serialisable but an image's bytes, which are a `Uint8Array`.\n * Every length is in PDF points. Every value is already the string that\n * prints: an exact number stays a string all the way to the page, and an\n * engine never formats, rounds or converts one.\n *\n * It holds everything version 0 of the definition can print: the columns,\n * sections, rule weights and colours, fonts and colours, image fits and\n * group headers across a table that\n * [0007](../../../docs/decisions/0007-a-report-definition-is-its-own-versioned-document.md)\n * found the renderer trial's document without. Its vocabularies -- font\n * tokens, alignments, fits, page sizes, colours -- are report-spec's own\n * types, so the definition and the document cannot name different ones. An\n * absent style property is the renderer's default, as report-spec's print\n * styles say.\n *\n * Where a block may stand -- a table or a page break never inside columns or\n * a keep-together block, page fields only in the page regions -- is the\n * definition's to validate and the renderer's to refuse. These types do not\n * hold it.\n */\nimport type {\n Alignment,\n AssetMediaType,\n BaselineShift,\n Border,\n EpcCaption,\n FacturXProfileTerms,\n FontFamily,\n ImageFit,\n Margins,\n Orientation,\n PageSizeName,\n QrBillCurrency,\n QrErrorCorrection,\n Width,\n XRechnungTerms,\n XRechnungVersion,\n} from '@formancy/report-spec'\nimport type { Chart } from './chart-document.js'\n\n/**\n * A run of text, or a number only the engine knows when it lays out the\n * page, which prints only in the page header and footer. A run in bold\n * inside a paragraph that is not was the trial's; version 0 of the\n * definition sets weight per paragraph.\n *\n * A run of text may be set below or above the line, `baseline`, as its\n * source run was (0061): absent, it stands on the line, and the runtime\n * writes the key only where the report set one. A page counter takes none.\n * What such a run prints as is `SHIFTED_SIZE` and `SHIFTED_RISE`.\n */\nexport type Inline =\n { readonly text: string; readonly bold?: boolean; readonly baseline?: BaselineShift } | { readonly field: 'pageNumber' } | { readonly field: 'pageCount' }\n\n/**\n * A run set below or above the line prints at this fraction of its\n * paragraph's size, in the paragraph's face (0061). It is pdfmake 0.3.11's\n * own figure (`TextInlines.js`), stated here as the document's, for any\n * engine: the renderer counts such a run's line at it (`bound.ts`), the\n * corpus reads a run at it as one of its line (`lines.ts`), and a PDF that\n * draws another fails there.\n */\nexport const SHIFTED_SIZE = 0.58\n\n/**\n * How far such a run's baseline is moved from its line's, as a fraction of\n * its paragraph's size, up positive: 0.75 of the reduced size up for a run\n * set above the line, 0.35 of it down for one below, 0.435 and 0.203 of the\n * paragraph's size. pdfmake 0.3.11's own figures (`Renderer.js`'s\n * `offsetText`), as `SHIFTED_SIZE` is. The move itself takes no room in\n * the line: what room a line makes for such a run, below or above it, is\n * the engine's.\n */\nexport const SHIFTED_RISE: Readonly<Record<BaselineShift, number>> = { superscript: 0.75 * SHIFTED_SIZE, subscript: -0.35 * SHIFTED_SIZE }\n\n/**\n * How text prints: report-spec's `PrintStyle`, resolved. The runtime lays\n * each conditional style that held over the base one, a later rule's\n * property winning, and hands the engine the result; an engine never merges\n * styles itself.\n */\nexport interface TextStyle {\n /** A font token, never a font's name: the renderer maps each to a font it embeds. */\n readonly font?: FontFamily\n /** Points. */\n readonly size?: number\n readonly bold?: boolean\n readonly italic?: boolean\n /** Lower-case `#rrggbb`. */\n readonly color?: string\n readonly align?: Alignment\n}\n\n/** Text that wraps at the width it is given. A word wider than that width still prints whole, broken across lines. */\nexport interface Paragraph {\n readonly kind: 'paragraph'\n readonly runs: readonly Inline[]\n readonly style?: TextStyle\n /** Never the last thing on a page when something follows it: a heading moves with what it heads. */\n readonly keepWithNext?: boolean\n}\n\nexport interface TableColumn {\n /** Points, or `'fill'` for an equal share of the width the fixed columns leave. */\n readonly width: Width\n /** How each cell in the column is aligned, unless the cell's style says otherwise. */\n readonly align: Alignment\n}\n\n/**\n * One row of a table, its cells in column order, each aligned to the top of\n * the row, so that a row's first line holds its first cell.\n *\n * A `groupHeader` is never the last row on a page: it moves to the next page\n * with the row it heads, or with as many of its group's first rows as it\n * keeps (`keepWithRows`). A `detail` row may be taller than a page; the\n * engine then continues it on the next one, or refuses with\n * `content-too-large`, and never clips it.\n */\nexport interface TableRow {\n readonly kind: 'detail' | 'groupHeader' | 'groupFooter' | 'total'\n /** One per column; exactly one when the row runs `across` the table. */\n readonly cells: readonly string[]\n /**\n * The row is one cell across every column: a group header, which version\n * 0 prints as one line across the table rather than in its first column.\n */\n readonly across?: true\n /** Every cell's style; absent, the renderer's for a row of its kind. */\n readonly style?: TextStyle\n /**\n * A cell's own style, one entry per cell, `null` where the cell has the\n * row's. A cell's own is its whole style, the row's already laid under it\n * by the runtime, never merged again by the engine: a column's print\n * style, or one of its conditional styles that held for this row.\n */\n readonly cellStyles?: readonly (TextStyle | null)[]\n /**\n * On a `groupHeader` alone: how many of its group's first rows it stands\n * on its page with, from 2 to `MAX_KEEP_WITH_ROWS` and never more than\n * the detail rows under it -- the count its group states, or the group's\n * rows where it has fewer (0059). Absent, it is kept with its first row.\n * An engine keeps it with as many of them as fit on a page under the\n * repeated header, and with its first row where no more do.\n */\n readonly keepWithRows?: number\n}\n\nexport interface Table {\n readonly kind: 'table'\n readonly id: string\n readonly columns: readonly TableColumn[]\n /**\n * The one header row, repeated at the top of every page the table spans;\n * absent where every column the table shows is titled with nothing, or\n * with white space alone: the table then has no header row, and prints\n * no band of nothing above its rows on any page (0078).\n */\n readonly header?: readonly string[]\n /** The header row's style; absent, the renderer's, and absent with the header. */\n readonly headerStyle?: TextStyle\n readonly rows: readonly TableRow[]\n /** Printed under the header, in place of detail rows, when there are none. Group and total rows still print. */\n readonly emptyText: string\n}\n\n/**\n * An approved asset's bytes, already fetched by the host: an engine never\n * resolves an address. Every image that draws the same asset shares one\n * object, which an engine embeds once for a PNG or a JPEG, and draws again\n * wherever an SVG prints (0030).\n */\nexport interface ImageAsset {\n readonly id: string\n readonly mediaType: AssetMediaType\n readonly bytes: Uint8Array\n}\n\n/**\n * An image in a box of fixed size, which the layout reserves whole whatever\n * the image holds. `contain` draws all of the image at its own proportions,\n * as large as the box allows; `cover` fills the box at the image's\n * proportions and crops what falls outside it. Either way the image is\n * centred in its box, as CSS's `object-fit` centres one by default, and\n * nothing of it is drawn outside the box. For an image of the box's own\n * proportions the two are the same drawing. Bytes the engine cannot decode\n * are refused as `invalid-asset`, naming the asset.\n */\nexport interface Image {\n readonly kind: 'image'\n readonly asset: ImageAsset\n readonly width: number\n readonly height: number\n readonly fit: ImageFit\n}\n\n/**\n * A QR code (ISO/IEC 18004): `text`, encoded as UTF-8 at the error\n * correction level asked for, drawn dark on white in a square `size` points\n * a side, whose quiet zone of four modules lies inside that square. `text`\n * is what the component's content prints, formatted as a paragraph's runs\n * are; it never holds a page number or count, which report-spec refuses in\n * a QR code. In a final render it holds every value its content reads and\n * is never empty: the runtime refuses a run whose value is null, and\n * content that prints nothing, as `no-qr-value` and `empty-qr-code`. In a\n * preview it is what the content resolves to, a value that is null as\n * nothing, and it can be empty, which an engine draws as a symbol of no\n * data. Which version of the symbol holds the text, and so how large a\n * module is, is the engine's to work out: text no version holds at the\n * level, or modules too small to print, are refused as `content-too-large`,\n * naming the code by `id`, never drawn as a code that does not scan.\n */\nexport interface QrCode {\n readonly kind: 'qrCode'\n /** The component's id, which a refusal names as its subject. */\n readonly id: string\n readonly text: string\n /** Points: the side of the square, quiet zone included. */\n readonly size: number\n readonly errorCorrection: QrErrorCorrection\n}\n\n/**\n * An EPC QR code (EPC069-12 v3.1): the code a SEPA credit transfer is\n * initiated from, drawn dark on white in a square `size` points a side.\n * `payload` is its text, every element resolved and held to the EPC's\n * rules (report-spec's `epc-payload.ts`): the engine encodes it as UTF-8\n * at level M, in a symbol of version 13 at most (EPC069-12 2.1), and\n * formats, checks and changes nothing of it. A payload no such symbol\n * holds, or modules too small to print, are refused as\n * `content-too-large`, naming the code by `id`, never drawn at another\n * level or in a larger version, which a bank's app need not read.\n *\n * Without a caption the code is drawn as a QR code is, its quiet zone of\n * four modules inside its square. With one, Austria's frame and the words\n * \"Zahlen mit Code\" are drawn inside the square too (PSA v3.0 5), as\n * report-spec's `epc-print.ts` lays them out and bounds the modules'\n * width; the engine, which knows the version, refuses a code whose\n * modules are outside those bounds.\n */\nexport interface EpcQrCode {\n readonly kind: 'epcQrCode'\n /** The component's id, which a refusal names as its subject. */\n readonly id: string\n /** The EPC's elements in EPC069-12 2.2's order, each on its own line, separated by a line feed and not ended by one: at most 331 bytes in UTF-8. */\n readonly payload: string\n /** Points: the side of the square, the quiet zone, and the frame and caption when there are any, inside it. */\n readonly size: number\n /** Austria's frame and caption; absent, the code is drawn alone. */\n readonly caption?: EpcCaption\n}\n\n/** A horizontal line across the width it is given: the printable area's, or its column's. */\nexport interface Rule {\n readonly kind: 'rule'\n /** Points. */\n readonly thickness: number\n /** Lower-case `#rrggbb`. */\n readonly color?: string\n}\n\n/** A box of fixed size: filled, outlined, both, or neither, when it is only space. */\nexport interface Rectangle {\n readonly kind: 'rectangle'\n readonly width: number\n readonly height: number\n /** Lower-case `#rrggbb`. */\n readonly fill?: string\n /** The outline's colour, lower-case `#rrggbb`, drawn at the renderer's weight. */\n readonly stroke?: string\n}\n\nexport interface Spacer {\n readonly kind: 'spacer'\n readonly height: number\n}\n\n/** Starts a new page. */\nexport interface PageBreak {\n readonly kind: 'pageBreak'\n}\n\n/**\n * Blocks that are printed on one page, such as a report's summary. When they\n * do not fit in what is left of the page they move whole to the next one;\n * when they are taller than a whole page the engine refuses with\n * `content-too-large` rather than splitting them.\n */\nexport interface KeepTogether {\n readonly kind: 'keepTogether'\n readonly blocks: readonly Block[]\n}\n\n/** One column of a columns block, as distinct from a table's column. */\nexport interface ColumnSlot {\n /** Points, or `'fill'` for an equal share of the width the fixed columns leave. */\n readonly width: Width\n readonly blocks: readonly Block[]\n}\n\n/**\n * Two to four columns side by side, each laying its blocks out down its own\n * width, with no gap between them but what their widths leave. The block is\n * as tall as its tallest column. When it does not fit on what is left of the\n * page, the engine continues its columns on the next page or refuses with\n * `content-too-large`, and never clips them.\n */\nexport interface Columns {\n readonly kind: 'columns'\n readonly columns: readonly ColumnSlot[]\n}\n\n/**\n * Blocks in a frame: the border drawn around them, the fill behind them, and\n * the padding between the border and them. A section adds no layout rule:\n * its blocks flow as though they stood in its place, across pages too, and\n * the frame is drawn around the part on each page. Without a border, a fill\n * or padding it is its blocks and nothing more.\n */\nexport interface Section {\n readonly kind: 'section'\n readonly blocks: readonly Block[]\n readonly border?: Border\n /** Lower-case `#rrggbb`. */\n readonly fill?: string\n /** Points, on every side. */\n readonly padding?: number\n}\n\n/** Every block a region holds; a chart's types are `chart-document.ts`'s. */\nexport type Block = Paragraph | Table | Image | QrCode | EpcQrCode | Chart | Rule | Rectangle | Spacer | PageBreak | KeepTogether | Columns | Section\n\nexport interface PageSetup {\n readonly size: PageSizeName\n readonly orientation: Orientation\n /**\n * From each edge of the paper to the printable area. Everything prints\n * inside it: the page header at its top, the page footer at its bottom, and\n * the body between them.\n */\n readonly margins: Margins\n}\n\n/**\n * The headings a QR-bill's slip prints, in its language: SIX's own words\n * (IG Annex C), which \"must not be changed\".\n */\nexport interface QrBillHeadings {\n readonly paymentPart: string\n readonly receipt: string\n /** \"Account / Payable to\". */\n readonly account: string\n readonly reference: string\n readonly additionalInformation: string\n /** \"Payable by\", or, for a bill without a debtor, \"Payable by (name/address)\" over the blank field. */\n readonly payableBy: string\n readonly currency: string\n readonly amount: string\n readonly acceptancePoint: string\n /** \"Separate before paying in\": the instruction above the line a PDF's slip is cut along. */\n readonly separate: string\n}\n\n/**\n * A Swiss QR-bill: its receipt and its payment part, 210 by 105 mm across\n * the foot of an A4 page, the report's last (report-spec's `QR_BILL_SIZE`).\n * Where it falls, and a page of its own when the body leaves no room for\n * it, is the engine's to lay out.\n *\n * Everything in it is resolved and checked by SIX's rules (report-spec's\n * `qr-bill.ts`): `payload` is the Swiss QR Code's text, which the engine\n * encodes at level M, and every other text is what the slip prints, exactly\n * as it prints, the values grouped as SIX groups them. An engine formats,\n * groups, translates and checks nothing of it; it draws the headings, the\n * values, the blank fields where a value is null, the code and the cross.\n * The engine draws the receipt's texts from the same values, but for\n * `additionalInformation`, which a receipt never prints (IG 3.6).\n */\nexport interface QrBill {\n readonly kind: 'swissQrBill'\n /** The Swiss QR Code's elements in IG Table 8's order, each on its own line, separated by a line feed and not ended by one: at most 997 characters. */\n readonly payload: string\n readonly headings: QrBillHeadings\n /** The IBAN in blocks of four: \"CH44 3199 9123 0008 8901 2\". */\n readonly account: string\n /** The creditor's address, line by line: the name, the street and building number, the postal code and town. */\n readonly creditor: readonly string[]\n /** The QR reference or creditor reference in SIX's blocks, or null for a bill without one. */\n readonly reference: string | null\n /** The message, then the billing information, each that is there, on a line of its own; empty prints no heading. */\n readonly additionalInformation: readonly string[]\n /** The debtor's address, line by line; null prints the blank field for the payer to write in. */\n readonly debtor: readonly string[] | null\n readonly currency: QrBillCurrency\n /** The amount with a space between thousands and two decimals: \"1 949.75\"; null prints the blank field for the payer to write in. */\n readonly amount: string | null\n}\n\n/**\n * The e-invoice a PDF carries: its XML, which the runtime wrote from the\n * very values the page prints (0027), and what the renderer embeds it as\n * [S] -- the file's name, its `/AFRelationship` and the XMP's\n * `fx:ConformanceLevel`. The values are report-spec's `FACTUR_X` and\n * `FACTUR_X_PROFILES`, handed on so an engine reads the one decision; one\n * an engine does not know it refuses as `unsupported`, never embedded\n * under another name. Only a final render writes one: a preview is not the\n * invoice. An engine encodes the XML as UTF-8 and changes nothing of it.\n */\nexport interface FacturXFile {\n readonly kind: 'facturX'\n /** The CII XML, with its declaration: the invoice itself. */\n readonly xml: string\n /** The embedded file's name: `factur-x.xml`. */\n readonly fileName: string\n readonly relationship: FacturXProfileTerms['relationship']\n /** `EN 16931`. */\n readonly conformanceLevel: string\n}\n\n/**\n * An XRechnung (0038): its XML, the invoice itself, which a host takes from\n * the resolved document and sends -- to a portal, by email or over Peppol,\n * as its buyer asks -- and which no PDF embeds; and what it is, its syntax,\n * the specification identifier it opens with (BT-24) and the XRechnung\n * version that names, report-spec's `XRECHNUNG`. An engine draws the page\n * as a plain PDF labelled on every page as the copy, and refuses a file of\n * another syntax, guideline or version as `unsupported`.\n */\nexport interface XRechnungFile {\n readonly kind: 'xrechnung'\n /** The CII XML, with its declaration: the invoice itself. */\n readonly xml: string\n readonly syntax: XRechnungTerms['syntax']\n /** BT-24, as the XML holds it. */\n readonly guideline: string\n readonly version: XRechnungVersion\n}\n\n/** The e-invoice of a final render, by its kind: a Factur-X file a PDF/A-3b embeds, or an XRechnung's XML a host sends. */\nexport type EInvoiceFile = FacturXFile | XRechnungFile\n\n/**\n * One face of a host's font, resolved to the bytes the renderer embeds\n * (0043): its asset id, for a refusal to name; the digest the report\n * pinned, which the renderer names the embedded face by and caches its\n * glyphs under; and the bytes the host's lookup handed over, which\n * report-spec's `readFont` has read. Never a media type -- every face is a\n * TrueType font.\n */\nexport interface FontAsset {\n readonly id: string\n /** `sha256:` and 64 lower-case hex digits: the digest the report pinned the face by. */\n readonly digest: string\n readonly bytes: Uint8Array\n}\n\n/** The faces of one font token a report maps: `normal` always, the rest where the report prints text in them, each resolved to its bytes. */\nexport interface ResolvedFaces {\n readonly normal: FontAsset\n readonly bold?: FontAsset\n readonly italic?: FontAsset\n readonly boldItalic?: FontAsset\n}\n\n/** The faces each font token a report maps prints in; a token left out prints in the renderer's own face. */\nexport type ResolvedFonts = { readonly [F in FontFamily]?: ResolvedFaces }\n\nexport interface ResolvedDocument {\n readonly info: {\n readonly title: string\n /** An ISO instant, fixed by the caller, so that the same document renders to the same PDF. */\n readonly creationDate: string\n }\n readonly page: PageSetup\n /**\n * Page 1's own header, which page 1 prints at the top of the printable\n * area in the page header's place (0060); an empty list is none, and page\n * 1's body then starts at the top margin. Absent, page 1 prints the page\n * header, as every page does. It holds no page field: report-spec refuses\n * one in it, and the renderer draws it before the pages are counted.\n */\n readonly firstPageHeader?: readonly Block[]\n /** Repeated at the top of the printable area on every page, or on every page but the first where the document has `firstPageHeader`. */\n readonly pageHeader: readonly Block[]\n /** Repeated on every page, at the bottom of the printable area. */\n readonly pageFooter: readonly Block[]\n /**\n * What prints once, in order. A definition's report header is simply the\n * start of the body, and its summary the end: each prints once, before or\n * after everything else, so neither needs a block kind of its own. A\n * summary that must stay on one page is a keep-together block.\n */\n readonly body: readonly Block[]\n /** The slip the report is paid by, at the foot of its last page; absent, it has none. Never a block: it stands at a place SIX fixes, outside the printable area. */\n readonly paymentPart?: QrBill\n /** The e-invoice the PDF embeds, in a final render of a report that is one; absent, the PDF carries none. */\n readonly eInvoice?: EInvoiceFile\n /** The host fonts each font token prints in, resolved to their bytes; absent, every token prints in the renderer's own face (0043). */\n readonly fonts?: ResolvedFonts\n}\n\nexport const REFUSAL_CODES = ['too-many-pages', 'content-too-large', 'invalid-asset', 'cancelled', 'unsupported'] as const\nexport type RefusalCode = (typeof REFUSAL_CODES)[number]\n\n/**\n * Why an engine produced no file: the PDF renderer no PDF, the Word writer\n * no Word file (0068). An engine refuses rather than truncates: a report\n * that cannot be printed, or written, whole is not, and the caller is told\n * what stopped it. `subject` names the asset, table or block concerned, when\n * the refusal is about one.\n */\nexport class RenderRefusal extends Error {\n readonly code: RefusalCode\n readonly subject: string | undefined\n\n constructor(code: RefusalCode, message: string, subject?: string) {\n super(message)\n this.name = 'RenderRefusal'\n this.code = code\n this.subject = subject\n }\n}\n","import { utf8Length } from '@formancy/report-spec'\nimport { encode } from 'uqr'\nimport { RenderRefusal, type QrCode } from './document.js'\n\n/**\n * A QR code's symbol (ISO/IEC 18004), and what refuses one: decided here\n * once, below every engine, so that the PDF renderer and the Word writer\n * draw one symbol of a code and refuse the same codes in the same words\n * (0074). An engine draws the symbol it is handed, and decides nothing of\n * it.\n *\n * uqr encodes the text as UTF-8 in byte mode -- or as digits or\n * upper-case alphanumerics, when that is all it holds -- in the smallest\n * version that holds it at the level asked, and never raises the level to\n * fill a version. An engine encodes a code once, when it checks the\n * document, and draws that symbol, so that what is refused and what is\n * drawn are one decision (0020).\n *\n * The square a code stands in is its `size`, its quiet zone inside it:\n * four modules on every side, white, the symbol between them, so a\n * module is the size over the symbol's modules and eight.\n */\n\n/** ISO/IEC 18004's quiet zone: four modules of white on every side of the symbol. */\nexport const QR_QUIET_ZONE = 4\n\n/**\n * The smallest module drawn: 0.4 mm, 1.13 pt. ISO/IEC 18004 leaves the\n * module's size to the application; SIX's Swiss Implementation Guidelines\n * for the QR-bill, version 2.3, section 6.3, require at least 0.4 mm when\n * printing, and that is taken here as what a printer prints and a phone's\n * camera reads reliably. A square too small for its text at that module is\n * refused, naming the size it needs, never drawn finer. It is a borrowed\n * minimum: the same guidelines draw their largest code finer (0020).\n */\nexport const QR_MIN_MODULE = (0.4 * 72) / 25.4\n\n/**\n * The most characters any QR code holds: 7089 digits, version 40 at level\n * L (ISO/IEC 18004, table 7). A character is a code point, as a reader\n * counts one: an emoji is one, though JavaScript holds it in two code\n * units. Longer text fits no version in any mode, and is refused before it\n * is encoded, which takes time and memory with the length of the text;\n * within it, the encoder decides by the bytes the text takes.\n */\nexport const QR_MAX_CHARACTERS = 7089\n\nconst LEVELS: ReadonlySet<unknown> = new Set(['L', 'M', 'Q', 'H'])\n\n/** A code's symbol, without its quiet zone: rows of modules, `true` for dark, as many rows as modules in each. */\nexport interface QrSymbol {\n readonly modules: readonly (readonly boolean[])[]\n}\n\n/** The version `symbol` is, from its modules a side (ISO/IEC 18004: 4 a version and 17). */\nexport function qrSymbolVersion(symbol: QrSymbol): number {\n return (symbol.modules.length - 17) / 4\n}\n\n/** A code point as Unicode writes it: U+5C71. */\nconst codePoint = (point: number): string => `U+${point.toString(16).toUpperCase().padStart(4, '0')}`\n\n/** The lone half of a surrogate pair `text` holds, as a refusal names it, or undefined: with the u flag, a pair is one character and only a lone half is a surrogate. */\nexport function loneSurrogate(text: string): string | undefined {\n const lone = /\\p{Cs}/u.exec(text)?.[0]\n return lone === undefined ? undefined : codePoint(lone.charCodeAt(0))\n}\n\n/** How many code points `text` holds, counted without building them into an array. */\nfunction codePoints(text: string): number {\n let count = 0\n for (const _ of text) count++\n return count\n}\n\n/**\n * Refuses a code's square that is no size, as `unsupported`, or wider\n * than the `width` it stands at, as `content-too-large`: a code is a\n * square that stands where an image may. How tall a page's body is, is an\n * engine's to know, and to refuse a square by.\n */\nexport function refuseSquare(what: string, id: string, size: number, width: number): void {\n if (!(size > 0 && Number.isFinite(size))) throw new RenderRefusal('unsupported', `${what} is drawn ${size} pt a side`, id)\n if (size > width) throw new RenderRefusal('content-too-large', `${what} is ${size} pt wide; it stands ${width.toFixed(2)} pt wide`, id)\n}\n\n/**\n * `code`'s symbol where it stands `width` points wide, or the refusal\n * that says why it is not drawn: a square of no size, a level or text no\n * encoder can draw, as `unsupported`; a square wider than where it\n * stands, text no version holds, or a square too small for the version\n * that holds it, as `content-too-large`. Each names the code by its id.\n */\nexport function qrSymbol(code: QrCode, width: number): QrSymbol {\n const { id, text, size, errorCorrection } = code\n refuseSquare(`the QR code ${id}`, id, size, width)\n if (!LEVELS.has(errorCorrection))\n throw new RenderRefusal(\n 'unsupported',\n `the QR code ${id} asks for the error correction level '${String(errorCorrection)}'; the levels are L, M, Q and H`,\n id,\n )\n if (typeof text !== 'string') throw new RenderRefusal('unsupported', `the QR code ${id} encodes something that is not text`, id)\n const lone = loneSurrogate(text)\n if (lone !== undefined)\n throw new RenderRefusal('unsupported', `the QR code ${id} holds ${lone}, half of a surrogate pair without the other, which has no UTF-8`, id)\n // No text has more code points than code units, so they are counted only past the cap.\n const characters = text.length > QR_MAX_CHARACTERS ? codePoints(text) : text.length\n if (characters > QR_MAX_CHARACTERS)\n throw new RenderRefusal('content-too-large', `the QR code ${id} holds ${characters} characters; no QR code holds more than ${QR_MAX_CHARACTERS}`, id)\n const modules = encoded(text, errorCorrection, id)\n refuseFineModules({ modules }, size, `the QR code ${id}`, 'its text', id)\n return { modules }\n}\n\n/**\n * Refuses `symbol` drawn in a square of `size` with its quiet zone when its\n * modules would be finer than 0.4 mm, naming the square `holds` needs:\n * the floor every code drawn with a quiet zone is held to (0020).\n */\nexport function refuseFineModules(symbol: QrSymbol, size: number, what: string, holds: string, id: string): void {\n const count = symbol.modules.length + 2 * QR_QUIET_ZONE\n const smallest = count * QR_MIN_MODULE\n if (size < smallest) {\n throw new RenderRefusal(\n 'content-too-large',\n `${what} is ${size} pt a side, which makes the ${count} modules across its symbol and quiet zone ${(size / count).toFixed(2)} pt each; the smallest module is 0.4 mm (${QR_MIN_MODULE.toFixed(2)} pt), so ${holds} needs a square of at least ${(Math.ceil(smallest * 100) / 100).toFixed(2)} pt`,\n id,\n )\n }\n}\n\n/** Whether `error` is what uqr 0.1.3 says of text no version holds, and says of nothing else. */\nexport function tooLong(error: unknown): boolean {\n return error instanceof RangeError && error.message === 'Data too long'\n}\n\n/** The symbol uqr encodes, without its quiet zone; refused when no version holds the text. */\nfunction encoded(text: string, level: QrCode['errorCorrection'], id: string): boolean[][] {\n try {\n return encode(text, { ecc: level, border: 0, boostEcc: false }).data\n } catch (error) {\n if (!tooLong(error)) throw error\n throw new RenderRefusal('content-too-large', `the QR code ${id} holds ${utf8Length(text)} bytes of text, more than a QR code at level ${level} holds`, id)\n }\n}\n\n/**\n * The most characters a Swiss QR Code holds, its line feeds included: 997\n * (IG 6.2), which is what version 25 holds at level M in byte mode. A\n * payload of more is refused before it is encoded.\n */\nexport const SWISS_QR_MAX_CHARACTERS = 997\n\n/** The largest version SIX allows (IG 6.2): 117 modules a side. */\nconst SWISS_MAX_VERSION = 25\n\n/**\n * A QR-bill's Swiss QR Code (IG 6), or the refusal that says why it is not\n * drawn: its payload as UTF-8 at level M (6.1), in the smallest version that\n * holds it (6.4), and never past version 25 (6.2). A payload of more than\n * 997 characters is refused unencoded; one whose UTF-8 is more than version\n * 25 holds, once the encoder finds none does. Every refusal names the\n * payment part, and none quotes the payload: it holds names and accounts.\n *\n * SIX prints the code at 46 mm whatever its version, so a module is 46 mm\n * over the symbol's modules, 0.393 mm at version 25: finer than the 0.4 mm\n * a `qrCode` is held to, which is SIX's own figure for print (6.3). SIX's\n * size is drawn, not the floor (0020's generic minimum does not apply).\n */\nexport function swissSymbol(payload: unknown): QrSymbol {\n const refuse = (code: 'unsupported' | 'content-too-large', what: string): RenderRefusal =>\n new RenderRefusal(code, `the payment part's Swiss QR Code ${what}`, 'paymentPart')\n if (typeof payload !== 'string') throw refuse('unsupported', 'holds something that is not text')\n const lone = loneSurrogate(payload)\n if (lone !== undefined) throw refuse('unsupported', `holds ${lone}, half of a surrogate pair without the other, which has no UTF-8`)\n const characters = payload.length > SWISS_QR_MAX_CHARACTERS ? codePoints(payload) : payload.length\n if (characters > SWISS_QR_MAX_CHARACTERS) throw refuse('content-too-large', `holds ${characters} characters; SIX allows ${SWISS_QR_MAX_CHARACTERS}`)\n try {\n return { modules: encode(payload, { ecc: 'M', border: 0, boostEcc: false, maxVersion: SWISS_MAX_VERSION }).data }\n } catch (error) {\n if (!tooLong(error)) throw error\n throw refuse(\n 'content-too-large',\n `holds ${utf8Length(payload)} bytes, more than version ${SWISS_MAX_VERSION} holds at level M, the largest code SIX allows`,\n )\n }\n}\n","import { checkQrBillAmount, MAX_QR_BILL_ADDITIONAL_INFORMATION, QR_BILL_CURRENCIES, qrBillPageBreak } from '@formancy/report-spec'\nimport { RenderRefusal, type PageSetup, type QrBill, type QrBillHeadings } from './document.js'\nimport { swissSymbol, type QrSymbol } from './qr-symbol.js'\n\n/**\n * What refuses a QR-bill's payment part before an engine lays its slip\n * out, and its Swiss QR Code, encoded once: decided here, below every\n * engine, so that the PDF renderer and the Word writer refuse the same\n * bills in the same words and draw one symbol of a bill's code (0075, as\n * 0074 did for a code).\n *\n * The runtime hands an engine a bill SIX's rules have accepted, every\n * text as the slip prints it (`QrBill`); an engine formats nothing, and\n * decides none of SIX's rules again. What is refused here is what no\n * engine draws whole, or would draw as some other slip: a kind of payment\n * part nobody knows, a page the slip has no place on, text that is not\n * text, an amount or currency SIX does not print, more lines than a slip\n * prints, a value longer than any SIX allows, and a code larger than SIX\n * allows (`swissSymbol`). Where one of those is SIX's rule -- the page,\n * the currencies, the amounts, the longest value -- it is report-spec's,\n * so that what the editor accepts and what an engine draws cannot part.\n *\n * One thing is an engine's to say, since only it knows the face it\n * draws in: whether that face draws a text (`BillUndrawn`). Every\n * refusal names the payment part and the field, and none quotes a value:\n * a bill holds names, addresses and accounts.\n */\n\n/** The two faces a slip prints in: its values, and its titles and headings. */\nexport type BillFace = 'normal' | 'bold'\n\n/** A bill an engine draws, and its code's symbol. */\nexport interface CheckedBill {\n readonly bill: QrBill\n readonly symbol: QrSymbol\n}\n\n/**\n * What an engine says of a text its face does not draw whole: the rest of\n * the sentence that begins with the field's name -- \"prints U+5C71, which\n * ...\" -- or undefined where it draws every character of it.\n */\nexport type BillUndrawn = (text: string, face: BillFace) => string | undefined\n\n/** The longest value a slip prints: a line of the additional information, which the message and the billing information share (IG Table 8). An address line is shorter. */\nconst MAX_VALUE = MAX_QR_BILL_ADDITIONAL_INFORMATION\n\n/** An amount as the slip prints it: a space between thousands, a point and two decimals (IG 3.5.3). Which amounts a bill pays is report-spec's `checkQrBillAmount`. */\nconst AMOUNT = /^\\d{1,3}(?: \\d{3})*\\.\\d{2}$/\n\n/** The lines an address prints: its name, its street and building number, its postal code and town (IG 3.5.4). */\nconst ADDRESS_LINES = 3\n\n/** The message and the billing information, each on its line. */\nconst ADDITIONAL_LINES = 2\n\nfunction refuse(what: string): RenderRefusal {\n return new RenderRefusal('unsupported', `the payment part's ${what}`, 'paymentPart')\n}\n\n/**\n * Refuses `page` for a slip by report-spec's rule, the one the editor\n * refuses it by (`qrBillPageBreak`): a page that is not A4 in portrait,\n * which has no foot the slip spans, and one whose top margin, with `above`\n * printed under it, reaches into the slip, which no layout can undo.\n */\nexport function refuseBillPage(page: PageSetup, above = 0): void {\n const broken = qrBillPageBreak(page, above)\n if (broken !== undefined) throw new RenderRefusal(broken.field === 'page' ? 'unsupported' : 'content-too-large', broken.rule, 'paymentPart')\n}\n\n/** Refuses what no engine draws of `bill` on `page`, the top margin alone before anything above the slip is measured, and encodes its code. */\nexport function checkQrBill(bill: QrBill, page: PageSetup, undrawn: BillUndrawn): CheckedBill {\n const { kind } = bill as { readonly kind?: unknown }\n if (kind !== 'swissQrBill') throw new RenderRefusal('unsupported', `the payment part is a '${String(kind)}', which a report does not know`, 'paymentPart')\n refuseBillPage(page)\n const text = (value: unknown, what: string, face: BillFace): void => {\n if (typeof value !== 'string') throw refuse(`${what} holds something that is not text`)\n if (value.length > MAX_VALUE) throw refuse(`${what} holds a value longer than any SIX allows, ${MAX_VALUE} characters`)\n const missing = undrawn(value, face)\n if (missing !== undefined) throw refuse(`${what} ${missing}`)\n }\n const lines = (value: unknown, what: string, most: number, least: number): void => {\n if (!Array.isArray(value)) throw refuse(`${what} is not lines of text`)\n if (value.length > most || value.length < least) throw refuse(`${what} has the wrong number of lines: a slip prints ${least} to ${most}`)\n for (const line of value) text(line, what, 'normal')\n }\n const headings = (bill.headings ?? {}) as Partial<Record<keyof QrBillHeadings, unknown>>\n for (const [key, face] of Object.entries(BILL_HEADING_FACES) as [keyof QrBillHeadings, BillFace][]) text(headings[key], `heading '${key}'`, face)\n text(bill.account, 'account', 'normal')\n lines(bill.creditor, \"creditor's address\", ADDRESS_LINES, 2)\n if (bill.reference !== null) text(bill.reference, 'reference', 'normal')\n lines(bill.additionalInformation, 'additional information', ADDITIONAL_LINES, 0)\n if (bill.debtor !== null) lines(bill.debtor, \"debtor's address\", ADDRESS_LINES, 2)\n if (!(QR_BILL_CURRENCIES as readonly unknown[]).includes(bill.currency)) throw refuse(`currency is not one SIX allows: ${QR_BILL_CURRENCIES.join(' or ')}`)\n text(bill.currency, 'currency', 'normal')\n if (bill.amount !== null) {\n if (typeof bill.amount !== 'string' || !AMOUNT.test(bill.amount))\n throw refuse('amount is not written as the slip prints one: its thousands apart and two decimals')\n const paid = checkQrBillAmount(bill.amount.replaceAll(' ', ''))\n if (!paid.ok) throw refuse(`amount ${paid.rule}`)\n text(bill.amount, 'amount', 'normal')\n }\n return { bill, symbol: swissSymbol(bill.payload) }\n}\n\n/**\n * The face each heading of a slip prints in, which an engine's glyphs\n * and widths are held to: `separate` regular, the rest bold. A table\n * over every heading, so that one added to the document's\n * `QrBillHeadings` without its face does not compile, rather than going\n * unchecked.\n */\nexport const BILL_HEADING_FACES: { readonly [K in keyof QrBillHeadings]-?: BillFace } = {\n paymentPart: 'bold',\n receipt: 'bold',\n account: 'bold',\n reference: 'bold',\n additionalInformation: 'bold',\n payableBy: 'bold',\n currency: 'bold',\n amount: 'bold',\n acceptancePoint: 'bold',\n separate: 'normal',\n}\n","import type { QrBill } from './document.js'\n\n/**\n * Where SIX puts each part of a QR-bill's slip, the receipt and the\n * payment part, and at what size: stated here once, below every engine,\n * so that the PDF renderer and the Word writer lay one slip out (0075).\n * An engine draws by these, in its own way, and decides none of them.\n * Nothing here formats a value: the runtime hands every text as it\n * prints (`QrBill`).\n *\n * The numbers are SIX's: \"IG\" is the Swiss Implementation Guidelines for\n * the QR-bill, version 2.4, and \"SG\" its Style Guide, version 1.1, whose\n * page 6 gives every section's place and size in millimetres, page 7 the\n * blank fields', and page 15 the sizes and line spacing. What neither gives\n * is taken from manuelbl's SwissQRBill generator, which matches SG 7 drawn\n * to scale: where the blank amount fields stand, and 2 pt between a\n * debtor's heading and its field.\n *\n * Positions are in points from the slip's top left. The slip is\n * report-spec's `QR_BILL_SIZE`, 210 by 105 mm.\n */\n\n/** Millimetres in points. */\nconst mm = (value: number): number => (value * 72) / 25.4\n\n/** The receipt is 62 mm wide, and the payment part starts there (IG 3.3). */\nexport const SLIP_RECEIPT_WIDTH = mm(62)\n\n/**\n * \"Separate before paying in\", above the line along the slip's top, outside\n * the payment part, which a slip may print instead of a scissors symbol\n * (IG 3.7, SG 4): 8 pt, the payment part's heading size, centred over the\n * slip, its baseline 3 pt above the line. SIX gives neither.\n */\nexport const SLIP_INSTRUCTION = { size: 8, gap: 3 } as const\n\n/** The lines the slip is cut along (IG 3.7): solid, half a point. SIX gives no weight. */\nexport const SLIP_SEPARATION = 0.5\n\n/** A blank field's corner marks: 3 mm arms, 0.75 pt (IG 3.5.3, SG 7). */\nexport const SLIP_CORNER = { arm: mm(3), weight: 0.75 } as const\n\n/** Between a debtor's heading's line and its blank field. */\nexport const SLIP_FIELD_GAP = 2\n\n/** The titles, \"Receipt\" and \"Payment part\": 11 pt bold (IG 3.5.1, 3.6.1). */\nexport const SLIP_TITLE = 11\n\n/** A part's text: headings bold and 2 pt smaller than their values, every line `pitch` below the one before (IG 3.4, SG 15). */\nexport interface SlipLettering {\n readonly heading: number\n readonly value: number\n readonly pitch: number\n}\n\n/** A part of the slip: where each of its sections starts, and the room its information has. */\nexport interface SlipPart {\n readonly name: string\n readonly lettering: SlipLettering\n /** Where its title stands, and which heading it prints: \"Receipt\" or \"Payment part\". */\n readonly title: { readonly x: number; readonly top: number; readonly heading: 'receipt' | 'paymentPart' }\n /** Whether it prints the additional information: the payment part does, the receipt never (IG 3.6.2). */\n readonly additionalInformation: boolean\n readonly information: { readonly x: number; readonly top: number; readonly width: number; readonly height: number; readonly millimetres: number }\n /** The amount section: its headings' top, and how far the amount stands in from the currency. */\n readonly amount: { readonly x: number; readonly top: number; readonly indent: number; readonly pitch: number }\n /** The blank amount field: its box, and whether its top is the amount's line rather than the section's. */\n readonly amountField: { readonly x: number; readonly width: number; readonly height: number; readonly onAmountLine: boolean }\n readonly debtorField: { readonly width: number; readonly height: number }\n}\n\n/** The receipt, 62 by 105 mm (SG 6): 5 mm margins, its title, 56 mm of information, 14 of amount, 18 of acceptance point. */\nexport const SLIP_RECEIPT: SlipPart = {\n name: 'the receipt',\n lettering: { heading: 6, value: 8, pitch: 9 },\n title: { x: mm(5), top: mm(5), heading: 'receipt' },\n additionalInformation: false,\n information: { x: mm(5), top: mm(12), width: mm(52), height: mm(56), millimetres: 56 },\n // A receipt's amount is 8 pt on 11 pt (SG 15), 12 mm in (SG 7).\n amount: { x: mm(5), top: mm(68), indent: mm(12), pitch: 11 },\n // 30 by 10 mm, right-aligned to the receipt's text, at the section's top.\n amountField: { x: mm(27), width: mm(30), height: mm(10), onAmountLine: false },\n debtorField: { width: mm(52), height: mm(20) },\n}\n\n/** The payment part, 148 by 105 mm (SG 6): the code's 46 mm and the amount's 22 mm beside 87 by 85 mm of information. */\nexport const SLIP_PAYMENT_PART: SlipPart = {\n name: 'the payment part',\n lettering: { heading: 8, value: 10, pitch: 11 },\n title: { x: SLIP_RECEIPT_WIDTH + mm(5), top: mm(5), heading: 'paymentPart' },\n additionalInformation: true,\n information: { x: SLIP_RECEIPT_WIDTH + mm(56), top: mm(5), width: mm(87), height: mm(85), millimetres: 85 },\n // The payment part's amount is 10 pt on 13 pt (SG 15), 15 mm in (SG 7).\n amount: { x: SLIP_RECEIPT_WIDTH + mm(5), top: mm(68), indent: mm(15), pitch: 13 },\n // 40 by 15 mm, its right edge at the information section's left, its top where the amount would stand.\n amountField: { x: SLIP_RECEIPT_WIDTH + mm(16), width: mm(40), height: mm(15), onAmountLine: true },\n debtorField: { width: mm(65), height: mm(25) },\n}\n\n/** The Swiss QR Code's place: 5 mm in, below the title section and 5 mm of quiet zone (IG 3.5.2, SG 6). */\nexport const SLIP_CODE = { x: SLIP_RECEIPT_WIDTH + mm(5), top: mm(17) } as const\n\n/** The acceptance point, right-aligned to the receipt's text at the top of its section (IG 3.6.4, SG 6). */\nexport const SLIP_ACCEPTANCE = { right: mm(57), top: mm(82) } as const\n\n/** A block of a part's information: a heading over its values, or over a blank field for the payer's hand. */\nexport type SlipBlock = { readonly heading: string; readonly values: readonly string[] } | { readonly heading: string; readonly field: SlipPart['debtorField'] }\n\n/** The blocks a part's information holds, in SIX's order (IG 3.5.4, 3.6.2): the additional information in the payment part alone. */\nexport function slipBlocks(bill: QrBill, part: SlipPart): SlipBlock[] {\n const { headings } = bill\n return [\n { heading: headings.account, values: [bill.account, ...bill.creditor] },\n ...(bill.reference === null ? [] : [{ heading: headings.reference, values: [bill.reference] }]),\n ...(part.additionalInformation && bill.additionalInformation.length > 0\n ? [{ heading: headings.additionalInformation, values: bill.additionalInformation }]\n : []),\n bill.debtor === null ? { heading: headings.payableBy, field: part.debtorField } : { heading: headings.payableBy, values: bill.debtor },\n ]\n}\n\n/** A Swiss QR Code's side, without a quiet zone, whatever its version (IG 6.4): its modules are this over theirs. */\nexport const SWISS_CODE_SIZE = mm(46)\n\n/**\n * The Swiss cross over the code's centre (IG 6.4.2), in millimetres: SIX's\n * logo, as schoero's generator draws it, is a white square of 7 mm, a black\n * square of 6 mm on it, and a white cross on that, its arms 7/6 mm wide and\n * 35/9 mm from end to end. manuelbl's draws the same black square and cross\n * on modules it clears, rather than on a white square.\n */\nexport const SWISS_CROSS = { white: 7, black: 6, arm: 7 / 6, span: 35 / 9 } as const\n","import { EPC_MAX_BYTES, EPC_MAX_VERSION, epcCaptionBreak, epcLeastVersion, utf8Length } from '@formancy/report-spec'\nimport { encode } from 'uqr'\nimport { RenderRefusal, type EpcQrCode } from './document.js'\nimport { loneSurrogate, qrSymbolVersion, refuseFineModules, refuseSquare, tooLong, type QrSymbol } from './qr-symbol.js'\n\n/**\n * An EPC QR code's symbol (EPC069-12 v3.1), and what refuses one: decided\n * here once, below every engine, as a QR code's is (`qr-symbol.ts`, 0074).\n * Its payload as UTF-8 at level M, in a symbol of version 13 at most,\n * which an engine encodes once, when it checks the document.\n *\n * Without a caption it is a QR code's symbol, in a square with a quiet\n * zone of four modules inside it, held to the 0.4 mm floor. With\n * Austria's caption it is the PSA's (PSA v3.0 5), by report-spec's\n * `epc-print.ts`, the one place those rules are decided: modules of 15 to\n * 20 mil, and a symbol as tall as the caption beside it. In a square the\n * author sized, the version that just holds a payload may have modules\n * over 20 mil: the symbol is the least version that prints there\n * (`epcLeastVersion`), a larger symbol of the same payload at the same\n * level.\n *\n * Every refusal names the code by its id, and none quotes the payload: it\n * holds a name and an account.\n */\n\n/**\n * `code`'s symbol where it stands `width` points wide, or the refusal\n * that says why it is not drawn: a square of no size, a caption no engine\n * knows, or a payload that is not text, as `unsupported`; a square wider\n * than where it stands, a payload past 331 bytes, refused unencoded when\n * it is longer than that in characters, or modules the square cannot\n * print, as `content-too-large`.\n */\nexport function epcSymbol(code: EpcQrCode, width: number): QrSymbol {\n const { id, payload, size, caption } = code\n const what = `the EPC QR code ${id}`\n refuseSquare(what, id, size, width)\n if (caption !== undefined && caption !== 'zahlenMitCode')\n throw new RenderRefusal('unsupported', `${what} asks for the caption '${String(caption)}', which a report does not know`, id)\n if (typeof payload !== 'string') throw new RenderRefusal('unsupported', `${what} holds something that is not text`, id)\n const lone = loneSurrogate(payload)\n if (lone !== undefined) throw new RenderRefusal('unsupported', `${what} holds ${lone}, half of a surrogate pair without the other, which has no UTF-8`, id)\n // No character is fewer bytes than code units, so a payload longer than the limit in code units is longer in bytes, and is refused without being encoded.\n if (payload.length > EPC_MAX_BYTES) throw new RenderRefusal('content-too-large', `${what} holds more than the ${EPC_MAX_BYTES} bytes the EPC allows`, id)\n const square = caption === undefined ? undefined : epcCaptionBreak(size)\n if (square !== undefined) throw new RenderRefusal('content-too-large', `${what} cannot be printed as the PSA prints it: ${square}`, id)\n // A size the caption's rules take has a least version (report-spec's epc-print.test.ts holds every one).\n const least = epcLeastVersion(size, caption) as number\n let symbol: QrSymbol\n try {\n symbol = { modules: encode(payload, { ecc: 'M', border: 0, boostEcc: false, minVersion: least, maxVersion: EPC_MAX_VERSION }).data }\n } catch (error) {\n if (!tooLong(error)) throw error\n throw new RenderRefusal(\n 'content-too-large',\n `${what} holds ${utf8Length(payload)} bytes, more than version ${EPC_MAX_VERSION} holds at level M, the largest code the EPC allows`,\n id,\n )\n }\n if (caption === undefined) {\n refuseFineModules(symbol, size, what, 'its payload', id)\n return symbol\n }\n const version = epcCaptionBreak(size, qrSymbolVersion(symbol))\n if (version !== undefined) throw new RenderRefusal('content-too-large', `${what} cannot be printed as the PSA prints it: ${version}`, id)\n return symbol\n}\n","/**\n * Reading the data a host hands over, once, without running any of it.\n *\n * Datasets and parameters are untrusted input, even from the host's own\n * provider. A JSON-parsed object is plain data, but a host may hand over\n * anything JavaScript can hold: a getter that answers differently each time\n * it is asked, a proxy whose traps throw, a sparse array. So every object\n * and list is read through its property descriptors into a copy, as\n * report-spec reads a report: a getter is refused unrun, an exception from a\n * trap becomes a refusal, and what is checked afterwards is the copy, which\n * cannot change under the check.\n */\n\n/** Why a container could not be read at all. */\nexport type ContainerCode = 'wrong-type' | 'not-data' | 'too-many'\n\n/** A property of a record that could not be read, with the key it has when it has a string one. */\nexport interface PropertyProblem {\n readonly key?: string\n readonly message: string\n}\n\nexport type RecordRead =\n | { readonly ok: true; readonly entries: ReadonlyMap<string, unknown>; readonly problems: readonly PropertyProblem[] }\n | { readonly ok: false; readonly code: Exclude<ContainerCode, 'too-many'>; readonly message: string }\n\n/** An item of a list that could not be read, by its index. */\nexport interface ItemProblem {\n readonly index: number\n readonly message: string\n}\n\n/** Stands in a read list where an item could not be read; its problem says why. */\nexport const UNREADABLE: unique symbol = Symbol('unreadable')\n\nexport type ListRead =\n | { readonly ok: true; readonly items: readonly unknown[]; readonly problems: readonly ItemProblem[] }\n | { readonly ok: false; readonly code: ContainerCode; readonly message: string }\n\nconst ACCESSOR = 'a getter or setter is not data, and is not run'\n\n/** Whether `value` is a plain object: made by a literal, JSON.parse or Object.create(null), not a class instance, an array or a Map. */\nfunction isPlainObject(value: unknown): value is object {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false\n const prototype: unknown = Object.getPrototypeOf(value)\n return prototype === Object.prototype || prototype === null\n}\n\n/**\n * A plain object's own enumerable string-keyed data properties, each read\n * once, in the object's own order. A property that is not data -- a getter,\n * a symbol key, a hidden property -- is a problem of the record and left\n * out; anything else about the object refuses it whole.\n */\nexport function readRecord(value: unknown): RecordRead {\n try {\n if (!isPlainObject(value)) return { ok: false, code: 'wrong-type', message: 'expected an object of named values' }\n const entries = new Map<string, unknown>()\n const problems: PropertyProblem[] = []\n let symbols = false\n for (const key of Reflect.ownKeys(value)) {\n if (typeof key === 'symbol') {\n symbols = true\n continue\n }\n const descriptor = Object.getOwnPropertyDescriptor(value, key) as PropertyDescriptor\n if (!('value' in descriptor)) problems.push({ key, message: ACCESSOR })\n else if (descriptor.enumerable !== true) problems.push({ key, message: 'a property that is not enumerable is not data' })\n else entries.set(key, descriptor.value)\n }\n if (symbols) problems.push({ message: 'a property named by a symbol is not data' })\n return { ok: true, entries, problems }\n } catch {\n return { ok: false, code: 'not-data', message: 'an object that throws when read is not data' }\n }\n}\n\n/**\n * A list's items, each read once, after its length is checked against\n * `max`: a list longer than that is refused before any item is read. A hole\n * or a getter is a problem at its index, and `UNREADABLE` stands in its\n * place.\n */\nexport function readList(value: unknown, max: number): ListRead {\n try {\n if (!Array.isArray(value)) return { ok: false, code: 'wrong-type', message: 'expected a list' }\n // A proxy describes its length as it likes: an object whose valueOf\n // answers the bound one number and the loop another, or Infinity. Only a\n // whole number is a length, and it is compared and looped to as read.\n const length: unknown = (Object.getOwnPropertyDescriptor(value, 'length') as PropertyDescriptor).value\n if (typeof length !== 'number' || !Number.isSafeInteger(length) || length < 0)\n return { ok: false, code: 'not-data', message: 'a list whose length is not a whole number is not data' }\n if (length > max) return { ok: false, code: 'too-many', message: `a list of ${length} items, more than the ${max} allowed` }\n const items: unknown[] = []\n const problems: ItemProblem[] = []\n for (let index = 0; index < length; index++) {\n const descriptor = Object.getOwnPropertyDescriptor(value, index)\n if (descriptor !== undefined && 'value' in descriptor) {\n items.push(descriptor.value)\n continue\n }\n items.push(UNREADABLE)\n problems.push({ index, message: descriptor === undefined ? 'a hole in a list is not data' : ACCESSOR })\n }\n return { ok: true, items, problems }\n } catch {\n return { ok: false, code: 'not-data', message: 'a list that throws when read is not data' }\n }\n}\n","/**\n * One value read as the type a dataset field or a parameter declares, and\n * held as the runtime computes with it.\n *\n * Exact values travel as strings with their type and are never converted\n * through a JavaScript number (0007; formancy.ai-data 0008). So:\n * - an integer is a string of its digits, or a JSON number only where a\n * number is still exact, below 2^53; it is held as a `bigint`;\n * - a decimal is only ever the string of its exact digits, held as\n * `@formancy/expressions`' `Decimal` with its scale;\n * - a date and a local date-time have no zone and are held as their ISO\n * strings, which sort in calendar order;\n * - an instant has a zone, and is held in UTC, so that two spellings of one\n * moment are one value;\n * - an image is an approved asset's id and digest, never an address.\n *\n * Each type has one spelling of each value, the one report-spec writes a\n * parameter default in. Its patterns are restated here because report-spec\n * does not export them; `values.test.ts` puts candidates to both, so the two\n * cannot drift apart unnoticed. A refusal says what was expected and never\n * repeats what was found: the data is the customer's.\n */\nimport { DEFAULT_VALUE_LIMITS, Decimal, decimalFromString } from '@formancy/expressions'\nimport { isIdentifier, MAX_SCALE } from '@formancy/report-spec'\nimport type { FieldType } from '@formancy/report-spec'\nimport { readRecord } from './input.js'\n\n/**\n * The longest string a value may be, in UTF-16 code units. Not chosen: it is\n * the longest string `@formancy/expressions` lets an expression be handed\n * (`DEFAULT_VALUE_LIMITS.maxStringLength`), so every string the data check\n * accepts is one an expression can read, and a longer one is refused where\n * the check can name its field rather than when an expression first reads\n * it.\n */\nexport const MAX_STRING_LENGTH = DEFAULT_VALUE_LIMITS.maxStringLength\n\nexport const VALUE_ERROR_CODES = [\n /** A value of another JavaScript type than the field's: a number for a string, a bigint, a Date. */\n 'wrong-type',\n 'string-too-long',\n /** A string with half a surrogate pair, which is not text and would print as something nobody wrote. */\n 'ill-formed-string',\n /** Not an integer's one spelling, or a number with a fraction. */\n 'invalid-integer',\n /** A JSON number past 2^53, which has already lost digits. */\n 'unsafe-integer',\n /** A decimal as a JSON number, which has already lost digits. */\n 'decimal-as-number',\n 'invalid-decimal',\n /** A decimal with more places than its field declares, or than a decimal holds. */\n 'decimal-scale',\n 'invalid-date',\n 'invalid-datetime',\n 'invalid-instant',\n 'invalid-image',\n] as const\nexport type ValueErrorCode = (typeof VALUE_ERROR_CODES)[number]\n\n/** An image field's value: an approved asset the host resolves to bytes by its id, pinned by its digest. */\nexport interface ImageValue {\n /** An identifier, as report-spec writes an asset's id. */\n readonly asset: string\n /** `sha256:` and 64 lower-case hex digits. */\n readonly digest: string\n}\n\n/** What a value of each field type is held as once read. */\nexport interface FieldValues {\n readonly string: string\n readonly integer: bigint\n readonly decimal: Decimal\n readonly boolean: boolean\n /** `YYYY-MM-DD`. */\n readonly date: string\n /** `YYYY-MM-DDTHH:mm:ss`, and a fraction of a second without trailing zeros when it has one. */\n readonly datetime: string\n /** As a date-time, in UTC, with a final `Z`. */\n readonly instant: string\n readonly image: ImageValue\n}\n\n/** A value of any field type, read. Null is not one: whether a field may be null is its contract's, and checked before its type. */\nexport type CheckedValue = FieldValues[FieldType]\n\nexport type ValueRead<T> = { readonly ok: true; readonly value: T } | { readonly ok: false; readonly code: ValueErrorCode; readonly message: string }\n\nfunction refused(code: ValueErrorCode, message: string): { readonly ok: false; readonly code: ValueErrorCode; readonly message: string } {\n return { ok: false, code, message }\n}\n\n/** What `raw` is, for a message: its JavaScript type, never its content. */\nfunction kindOf(raw: unknown): string {\n if (raw === null) return 'null'\n if (Array.isArray(raw)) return 'a list'\n if (raw instanceof Date) return 'a Date'\n if (raw instanceof Decimal) return 'a Decimal'\n const type = typeof raw\n return type === 'object' ? 'an object' : `a ${type}`\n}\n\nfunction wrongType(expected: string, raw: unknown): { readonly ok: false; readonly code: ValueErrorCode; readonly message: string } {\n return refused('wrong-type', `expected ${expected}, found ${kindOf(raw)}`)\n}\n\n/** An exact integer: no sign but '-', no leading zero, no '-0' (report-spec's `INTEGER`). */\nconst INTEGER = /^(?:0|-?[1-9]\\d*)$/\n\n/** An exact decimal: an integer, optionally a point and at least one digit; no negative zero (report-spec's `DECIMAL`). */\nconst DECIMAL = /^(?:-?[1-9]\\d*(?:\\.\\d+)?|0(?:\\.\\d+)?|-0\\.0*[1-9]\\d*)$/\n\n/** An asset's content digest: SHA-256, lower-case hex (report-spec's `DIGEST`). */\nconst DIGEST = /^sha256:[0-9a-f]{64}$/\n\n/** Half a surrogate pair: a high one not followed by a low one, or a low one not preceded by a high one. */\nconst LONE_SURROGATE = /[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/\n\nconst DATE = /^(\\d{4})-(\\d{2})-(\\d{2})$/\nconst DATETIME = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d{1,9}))?$/\n/** An ISO 8601 date-time with its zone, as `@formancy/expressions` binds a timestamp: seconds optional, a fraction to the nanosecond. */\nconst INSTANT = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2})(?::(\\d{2})(?:\\.(\\d{1,9}))?)?(?:Z|([+-])(\\d{2}):(\\d{2}))$/\n\n/**\n * Whether year, month and day name a day on the proleptic Gregorian\n * calendar from the year 1: 2024-02-29 does, 2026-02-29 does not, and no day\n * of the year 0000 does, which Intl shows as the year 1 without its era\n * (report-spec's `isCalendarDate`).\n */\nfunction isCalendarDay(year: number, month: number, day: number): boolean {\n if (year < 1 || month < 1 || month > 12 || day < 1) return false\n const leap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0\n const days = month === 2 ? (leap ? 29 : 28) : [4, 6, 9, 11].includes(month) ? 30 : 31\n return day <= days\n}\n\n/** Whether hours, minutes and seconds name a time on a clock that has no leap second, as Date has none. */\nfunction isClockTime(hour: number, minute: number, second: number): boolean {\n return hour <= 23 && minute <= 59 && second <= 59\n}\n\n/**\n * `fraction` without trailing zeros, with its point, or nothing when nothing\n * is left. A loop rather than /0+$/: the instant pattern bounds the fraction\n * to nine digits, but an anchored repetition is quadratic on many zeros\n * before a non-zero (CodeQL's js/polynomial-redos), and this needs no bound\n * to stay linear.\n */\nfunction fractionOf(fraction: string | undefined): string {\n if (fraction === undefined) return ''\n let end = fraction.length\n while (end > 0 && fraction[end - 1] === '0') end -= 1\n return end === 0 ? '' : `.${fraction.slice(0, end)}`\n}\n\nfunction readString(raw: unknown): ValueRead<string> {\n if (typeof raw !== 'string') return wrongType('a string', raw)\n if (raw.length > MAX_STRING_LENGTH)\n return refused('string-too-long', `a string of ${raw.length} characters, more than the ${MAX_STRING_LENGTH} a value may have`)\n if (LONE_SURROGATE.test(raw)) return refused('ill-formed-string', 'a string with half a surrogate pair is not text, and would print a character nobody wrote')\n return { ok: true, value: raw }\n}\n\nfunction readInteger(raw: unknown): ValueRead<bigint> {\n if (typeof raw === 'string') {\n if (raw.length <= MAX_STRING_LENGTH && INTEGER.test(raw)) return { ok: true, value: BigInt(raw) }\n return refused('invalid-integer', 'an integer is written as its digits, with \"-\" for a negative one, no leading zero and no \"-0\"')\n }\n if (typeof raw === 'number') {\n if (Number.isSafeInteger(raw)) return { ok: true, value: BigInt(raw) }\n if (Number.isInteger(raw)) return refused('unsafe-integer', 'a number past 2^53 has already lost digits; send the integer as a string of its digits')\n return refused('invalid-integer', 'expected a whole number')\n }\n return wrongType('an integer, written as a string of its digits', raw)\n}\n\nfunction readDecimal(raw: unknown, scale: number | undefined): ValueRead<Decimal> {\n if (typeof raw === 'number') return refused('decimal-as-number', 'a decimal is sent as a string of its exact digits, never as a number: floats lose digits')\n if (typeof raw !== 'string') return wrongType('a decimal, written as a string of its exact digits', raw)\n if (raw.length > MAX_STRING_LENGTH || !DECIMAL.test(raw)) {\n return refused('invalid-decimal', 'a decimal is written as its digits, with \".\" before any places, \"-\" for a negative one, no leading zero and no \"-0\"')\n }\n const places = raw.length - raw.indexOf('.') - 1\n const allowed = scale ?? MAX_SCALE\n if (raw.includes('.') && places > allowed) {\n const whose = scale === undefined ? 'a decimal holds' : 'the field declares'\n return refused(\n 'decimal-scale',\n `a decimal with ${places} places, more than the ${allowed} ${whose}; rounding it here would print another number than the source holds`,\n )\n }\n return { ok: true, value: decimalFromString(raw) }\n}\n\nfunction readBoolean(raw: unknown): ValueRead<boolean> {\n return typeof raw === 'boolean' ? { ok: true, value: raw } : wrongType('true or false', raw)\n}\n\nfunction readDate(raw: unknown): ValueRead<string> {\n if (typeof raw !== 'string') return wrongType('a date, written YYYY-MM-DD', raw)\n const match = DATE.exec(raw)\n if (match !== null && isCalendarDay(Number(match[1]), Number(match[2]), Number(match[3]))) return { ok: true, value: raw }\n return refused('invalid-date', 'a date is a day on the calendar, written YYYY-MM-DD')\n}\n\nfunction readDatetime(raw: unknown): ValueRead<string> {\n if (typeof raw !== 'string') return wrongType('a date and time, written YYYY-MM-DDTHH:mm:ss', raw)\n const match = DATETIME.exec(raw)\n const [year, month, day, hour, minute, second] = match === null ? [] : match.slice(1, 7).map(Number)\n if (match === null || !isCalendarDay(year as number, month as number, day as number) || !isClockTime(hour as number, minute as number, second as number)) {\n return refused(\n 'invalid-datetime',\n 'a date and time without a zone is written YYYY-MM-DDTHH:mm:ss, with a fraction of a second of up to nine digits if it has one',\n )\n }\n return { ok: true, value: `${raw.slice(0, 19)}${fractionOf(match[7])}` }\n}\n\nconst pad = (value: number, width: number): string => String(value).padStart(width, '0')\n\n/**\n * `text`, an ISO 8601 date-time with its zone, as the moment it names in\n * UTC: `YYYY-MM-DDTHH:mm:ssZ`, with the fraction of a second it has, less\n * trailing zeros. Undefined when it is not one, or the moment falls outside\n * the years 0001 to 9999 in UTC: past them a year has no four-digit\n * spelling, and Intl shows the year 0 as the year 1.\n *\n * What an expression gives back for a timestamp is RFC 3339 in UTC, so this\n * also makes an expression's instant comparable with the data's.\n */\nexport function canonicalInstant(text: string): string | undefined {\n const match = INSTANT.exec(text)\n if (match === null) return undefined\n const [year, month, day, hour, minute, second = 0] = match.slice(1, 7).map((part) => (part === undefined ? undefined : Number(part))) as [\n number,\n number,\n number,\n number,\n number,\n number | undefined,\n ]\n const offsetHours = match[9] === undefined ? 0 : Number(match[9])\n const offsetMinutes = match[10] === undefined ? 0 : Number(match[10])\n if (!isCalendarDay(year, month, day) || !isClockTime(hour, minute, second) || offsetHours > 23 || offsetMinutes > 59) return undefined\n // Date.UTC reads the years 0 to 99 as 1900 to 1999; setUTCFullYear does not.\n const moment = new Date(0)\n moment.setUTCFullYear(year, month - 1, day)\n moment.setUTCHours(hour, minute, second, 0)\n const offset = (match[8] === '-' ? -1 : 1) * (offsetHours * 60 + offsetMinutes)\n moment.setTime(moment.getTime() - offset * 60_000)\n const utcYear = moment.getUTCFullYear()\n if (utcYear < 1 || utcYear > 9999) return undefined\n const date = `${pad(utcYear, 4)}-${pad(moment.getUTCMonth() + 1, 2)}-${pad(moment.getUTCDate(), 2)}`\n const time = `${pad(moment.getUTCHours(), 2)}:${pad(moment.getUTCMinutes(), 2)}:${pad(moment.getUTCSeconds(), 2)}`\n return `${date}T${time}${fractionOf(match[7])}Z`\n}\n\nfunction readInstant(raw: unknown): ValueRead<string> {\n if (typeof raw !== 'string') return wrongType('an instant, written as an ISO 8601 date-time with its zone', raw)\n const value = canonicalInstant(raw)\n if (value !== undefined) return { ok: true, value }\n return refused('invalid-instant', 'an instant is an ISO 8601 date-time with its zone, Z or an offset such as +01:00, between the years 0001 and 9999 in UTC')\n}\n\nconst IMAGE_SHAPE = 'an image is an approved asset, { \"asset\": its id, \"digest\": \"sha256:\" and 64 lower-case hex digits }, never an address'\n\nfunction readImage(raw: unknown): ValueRead<ImageValue> {\n const read = readRecord(raw)\n if (!read.ok || read.problems.length > 0) return refused('invalid-image', IMAGE_SHAPE)\n const { entries } = read\n const asset = entries.get('asset')\n const digest = entries.get('digest')\n if (entries.size !== 2 || !isIdentifier(asset) || typeof digest !== 'string' || !DIGEST.test(digest)) return refused('invalid-image', IMAGE_SHAPE)\n return { ok: true, value: Object.freeze({ asset, digest }) }\n}\n\n/**\n * `raw` read as a value of `type`, or why it is not one. `scale` is a\n * decimal field's declared scale: a decimal with more places is refused.\n * Null is refused as every type's wrong type; the caller decides first\n * whether the field may hold it.\n */\nexport function readValue<T extends FieldType>(type: T, raw: unknown, scale?: number): ValueRead<FieldValues[T]> {\n const read = READERS[type] as (raw: unknown, scale: number | undefined) => ValueRead<FieldValues[T]>\n return read(raw, scale)\n}\n\nconst READERS: { readonly [T in FieldType]: (raw: unknown, scale: number | undefined) => ValueRead<FieldValues[T]> } = {\n string: readString,\n integer: readInteger,\n decimal: readDecimal,\n boolean: readBoolean,\n date: readDate,\n datetime: readDatetime,\n instant: readInstant,\n image: readImage,\n}\n","/**\n * What the runtime can say is wrong with the data and parameters it is\n * given, as stable codes, and the bounded list one check collects.\n *\n * A code is for a program and the message for a person. An error's path is\n * a JSON Pointer into what was given -- `/detail/17/amount` -- and neither\n * the path nor the message ever holds a value from it: the data is the\n * customer's, and an error is the kind of thing that ends up in a log.\n */\nimport { MAX_ERRORS, MAX_KEY_LENGTH } from '@formancy/report-spec'\nimport { VALUE_ERROR_CODES } from './values.js'\n\nexport const DATA_ERROR_CODES = [\n ...VALUE_ERROR_CODES,\n /** Something JavaScript can hold and JSON cannot: a getter, a hole, a symbol key, an object that throws when read. */\n 'not-data',\n /** A part of the data envelope the runtime does not know. */\n 'unknown-property',\n /** A dataset the report declares and the data lacks. */\n 'missing-dataset',\n /** Data for a dataset the report does not declare. */\n 'undeclared-dataset',\n /** A field the contract declares and a record lacks, which is not the same as null. */\n 'missing-field',\n /** Null where the contract or the parameter does not allow it. */\n 'unexpected-null',\n /** A field the contract does not declare: a report never carries what it does not print. */\n 'undeclared-field',\n /** More detail rows than `MAX_DETAIL_ROWS`. */\n 'too-many-rows',\n /** Data the provider says is incomplete, in a final render. */\n 'incomplete',\n /** A captured count other than the rows given, or more than the cap. */\n 'completeness-mismatch',\n 'invalid-completeness',\n 'invalid-consistency',\n /** A source past the syntax of identifiers or its shape's keys, naming a provider the runtime does not know, or past its bounds (0041). */\n 'invalid-source',\n /** A formancy form's data whose labels were read in another locale than the one the render prints in, a source that names none read in the report's own (0063). */\n 'labels-locale-differs',\n /** A required parameter with no value and no default. */\n 'missing-parameter',\n /** A value for a parameter the report does not declare. */\n 'undeclared-parameter',\n /** More errors were found than are listed. */\n 'too-many-errors',\n] as const\nexport type DataErrorCode = (typeof DATA_ERROR_CODES)[number]\n\nexport interface DataError {\n /** A JSON Pointer into the data or the parameter values: `/detail/17/amount`, `/from`. */\n readonly path: string\n readonly code: DataErrorCode\n /** For a person: what was expected, never what was found. */\n readonly message: string\n}\n\n/**\n * Errors listed per check: as many as report-spec lists for a report, for\n * the same reasons. Past it, one `too-many-errors` entry says the list was\n * cut short, and the check stops reading.\n */\nexport const MAX_DATA_ERRORS = MAX_ERRORS\n\n/** The errors one check has found, bounded. */\nexport class DataFindings {\n readonly #errors: DataError[] = []\n #overflowed = false\n\n report(path: string, code: DataErrorCode, message: string): void {\n if (this.#errors.length < MAX_DATA_ERRORS) this.#errors.push({ path, code, message })\n else this.#overflowed = true\n }\n\n /** Whether the list is cut short: once it is, nothing more is worth reading. */\n get full(): boolean {\n return this.#overflowed\n }\n\n get empty(): boolean {\n return this.#errors.length === 0\n }\n\n /** The errors in the order found, and a last one when more were found than listed. */\n errors(): DataError[] {\n const errors = [...this.#errors]\n if (this.#overflowed)\n errors.push({ path: '', code: 'too-many-errors', message: `more than ${MAX_DATA_ERRORS} errors were found; the first ${MAX_DATA_ERRORS} are listed` })\n return errors\n }\n}\n\n/** `path` extended by one key or index, escaped as RFC 6901 says. */\nexport function at(path: string, key: string | number): string {\n if (typeof key === 'number') return `${path}/${key}`\n return `${path}/${key.replaceAll('~', '~0').replaceAll('/', '~1')}`\n}\n\n/** Whether `key` is longer than any id the format allows: such a key is never one the report declares, and never goes into a path or a message. */\nexport function isLongKey(key: string): boolean {\n return key.length > MAX_KEY_LENGTH\n}\n\n/** The path to `key` in the object at `path`; the object's own path for a long key. */\nexport function keyAt(path: string, key: string): string {\n return isLongKey(key) ? path : at(path, key)\n}\n","/**\n * The language a render prints in (0063): the locale it names, held to\n * those the report is written in, the errors that refuse a render in it,\n * and a formancy form's labels held to it.\n *\n * - **A declared locale, exactly.** A render names the report's own\n * locale or one its translations declare, and nothing near either:\n * fr-FR is not fr-CH, and fr is neither. A render that names none\n * prints in the report's own, as every render did before. report-spec's\n * `renderLocale` decides it, the rule report-forms holds a read to.\n * - **An error refuses its own language.** Of the editor's diagnostics,\n * an error that names no language refuses every render, and one that\n * names a language a render in it alone: a report whose French lacks a\n * word prints in its own language, and in every other that is whole.\n * - **The report in that language.** What a render prints is report-spec's\n * `reportIn`: its words, the expressions that print words, its locale\n * and its slip's language the render's, and no translations, so that\n * every stage after this one reads a report in one language, as every\n * report was before, with no language step of its own.\n * - **Labels read in it.** Form data names the locale its labels were read\n * in where it is not the report's own; data that names none was read in\n * the report's own. Labels read in another locale than the render's are\n * refused, never printed in a language it does not name.\n */\nimport type { Diagnostic } from '@formancy/report-core'\nimport { declaredLocales, renderLocale } from '@formancy/report-spec'\nimport type { ReportDefinition } from '@formancy/report-spec'\nimport type { DataFindings } from './data-errors.js'\nimport type { RuntimeError } from './resolve-errors.js'\nimport type { DataSource } from './source.js'\n\nexport type LocaleChoice = { readonly ok: true; readonly locale: string } | { readonly ok: false; readonly error: RuntimeError }\n\n/**\n * The locale a render of `report` prints in -- `requested`, or the\n * report's own where nothing is requested -- or the error that refuses\n * it: `undeclared-locale`, at the options, naming the locales the report\n * is written in. `requested` is the host's, whatever its type says.\n */\nexport function printLocale(report: ReportDefinition, requested: unknown): LocaleChoice {\n const choice =\n requested === undefined || typeof requested === 'string'\n ? renderLocale(report, requested)\n : { ok: false as const, message: `a render names its locale as a tag; this report is written in ${declaredLocales(report).join(', ')}` }\n return choice.ok ? choice : { ok: false, error: { stage: 'resolve', code: 'undeclared-locale', path: '', message: choice.message } }\n}\n\n/** Whether `diagnostic` refuses a render in `locale`: an error that names no language refuses every render, one that names a language a render in it alone. */\nexport const refuses = (diagnostic: Diagnostic, locale: string): boolean =>\n diagnostic.severity === 'error' && (diagnostic.language === undefined || diagnostic.language === locale)\n\n/** Where `locale`, one `report` is written in, stands in it: the report's own at `/locale`, a translation's at the translation that declares it. */\nexport function localePath(report: ReportDefinition, locale: string): string {\n const index = (report.translations ?? []).findIndex((translation) => translation.locale === locale)\n return index === -1 ? '/locale' : `/translations/${index}/locale`\n}\n\n/**\n * Reports form data whose labels were read in another locale than\n * `printed`, the one the render prints in: a source that names none was\n * read in `own`, the report's own. Data of no form, or of Formancy Data,\n * holds no label of a form's.\n */\nexport function checkLabels(errors: DataFindings, source: DataSource | undefined, own: string, printed: string): void {\n if (source?.provider !== 'formancy-form' || (source.locale ?? own) === printed) return\n const read = source.locale === undefined ? \"the report's own locale\" : 'another locale'\n errors.report(\n source.locale === undefined ? '/source' : '/source/locale',\n 'labels-locale-differs',\n `the form's labels were read in ${read}, and this render prints in ${printed}: read them again in ${printed}, or render in the locale they were read in, since labels are never printed in a language the render does not name`,\n )\n}\n","/**\n * Where a report's data came from, as its provider names it, and the check\n * that admits it (0041). The render's manifest carries it, so that a PDF\n * kept for years can be traced to what collected its data: plan 13.2's\n * identity and provenance, as far as identifiers say them.\n *\n * - **A formancy form**: each submission the data was read from, with the\n * form's id and the `schemaHash` of the version that collected it -- one\n * for a report of one submission, one a row for a report of many,\n * whatever versions they answered. The form's id is a submission's too,\n * since formancy lets a new version change it. And the locale a\n * choice's labels were read in, where it is not the report's own (0063).\n * - **Formancy Data**: the published form each dataset was read from. Never\n * a record's token, which spells the record's key (formancy.ai-data\n * 0012), and a key can be the customer's own data.\n *\n * A source names identifiers and nothing else. It is held to their syntax,\n * bounded in count and length, and refused rather than cut short; a key\n * its shape does not name is refused by its container's path, since the\n * key may be the answer, and a provider the runtime does not know is\n * refused, never read as one it does. The syntax keeps out a space, an\n * `@`, a `/`, a `:`, a letter beyond ASCII and anything past 128\n * characters; it cannot tell a single word, a personal number or a digest\n * of an answer from an identifier, which 0041 says is its cost. Whether a\n * source is true -- that the host read what it names -- is the provider's\n * statement, as its completeness is; the runtime holds its form.\n *\n * As `data.ts` does, the check reports every problem and returns what it\n * read; `checkData` refuses the data when any was reported, so what a\n * render keeps is a source read whole.\n */\nimport { isFormId, isLocale, isSchemaHash } from '@formancy/report-spec'\nimport type { DatasetRole, Datasets } from '@formancy/report-spec'\nimport { at } from './data-errors.js'\nimport type { DataErrorCode, DataFindings } from './data-errors.js'\nimport { readList, readRecord, UNREADABLE } from './input.js'\nimport type { ContainerCode, PropertyProblem } from './input.js'\n\n/** Who handed the data over: a formancy form's submissions, or Formancy Data's forms. */\nexport const SOURCE_PROVIDERS = ['formancy-form', 'formancy-data'] as const\nexport type SourceProvider = (typeof SOURCE_PROVIDERS)[number]\n\n/** One submission the data was read from, and the version of the form that collected it. */\nexport interface FormSubmission {\n /** The submission's id, as the host that keeps it names it; formancy's server makes a UUID. */\n readonly id: string\n /** The form's id, as the version that collected the submission writes it: a version may change it. */\n readonly form: string\n /** `schemaHash` of the exact form version the submission answered: 64 lower-case hex digits. */\n readonly formHash: string\n}\n\n/** Data read from a formancy form's submissions. */\nexport interface FormSource {\n readonly provider: 'formancy-form'\n /** Each submission the data was read from, once, in the order the provider read them; at least one. */\n readonly submissions: readonly FormSubmission[]\n /**\n * The locale a choice's labels were read in, where it is not the\n * report's own, written as a report writes its locale; absent where\n * they were read in the report's own (0063). A render refuses labels\n * read in another locale than its own.\n */\n readonly locale?: string\n}\n\n/** Data read from Formancy Data: the published form each of the report's datasets was read from, by its id. */\nexport interface FormancyDataSource {\n readonly provider: 'formancy-data'\n readonly forms: { readonly [R in DatasetRole]?: string }\n}\n\n/** Where a report's data came from. Data a host captured itself may name none. */\nexport type DataSource = FormSource | FormancyDataSource\n\nconst ROLES: readonly DatasetRole[] = ['header', 'detail']\n\n/** The characters a form's id and a submission's may hold, as a refusal says them. */\nconst ID_SYNTAX = \"letters, digits, '.', '_' and '-', starting with a letter or a digit, at most 128 characters\"\n\n/**\n * A submission's id. The same characters as a form's id, by choice and not\n * by rule: report-spec's `FORM_ID` is formancy's syntax for a form, which\n * formancy may change, and a submission's id is the host's, which formancy's\n * server makes as a UUID. A UUID, a ULID or a number fits, and so does a\n * single word or a personal number, which a syntax cannot tell from an id.\n */\nconst SUBMISSION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/\n\n/**\n * Whether `value` is a submission's id as a source names one: what the form\n * bridge holds an id to before it reads a submission, so that the two\n * cannot read an id differently (0042).\n */\nexport function isSubmissionId(value: unknown): value is string {\n return typeof value === 'string' && SUBMISSION_ID.test(value)\n}\n\n/** What `isSubmissionId` accepts, in the words a refusal says it: the form bridge says them when it refuses an id, so the two cannot describe one rule two ways. */\nexport const SUBMISSION_ID_SYNTAX = ID_SYNTAX\n\nconst FORM_ID = `a form's id as formancy writes one: ${ID_SYNTAX}`\nconst NOTHING_ELSE = 'and nothing else: a source names identifiers, and no answer rides into the manifest a PDF is kept with'\nconst SUBMISSION = 'a submission is { \"id\": its id, \"form\": the form\\'s id, \"formHash\": the schemaHash of the version that collected it }'\n\n/** What each provider's source names besides its provider. */\nconst NAMES: { readonly [P in SourceProvider]: readonly string[] } = { 'formancy-form': ['submissions', 'locale'], 'formancy-data': ['forms'] }\n\n/** What each provider's source names, as a refusal says it. */\nconst SHAPES: { readonly [P in SourceProvider]: string } = {\n 'formancy-form': \"a formancy-form source names submissions, and the locale its labels were read in where that is not the report's own\",\n 'formancy-data': 'a formancy-data source names forms',\n}\n\n/** A container that could not be read, as a source's error: what is not data stays `not-data`. */\nconst container = (code: ContainerCode): DataErrorCode => (code === 'not-data' ? 'not-data' : 'invalid-source')\n\n/**\n * Reports a record's properties that are not data: a key of `known` where\n * it stands, any other by the record's own path, since a key the shape\n * does not name may be the answer. Returns the known keys reported.\n */\nfunction notData(errors: DataFindings, path: string, problems: readonly PropertyProblem[], known: readonly string[]): ReadonlySet<string> {\n const keys = new Set<string>()\n for (const { key, message } of problems) {\n const named = key !== undefined && known.includes(key)\n if (named) keys.add(key)\n errors.report(named ? at(path, key) : path, 'not-data', message)\n }\n return keys\n}\n\n/** Refuses, once and by the record's own path, the keys of `entries` that `known` does not hold. */\nfunction onlyKnown(errors: DataFindings, path: string, entries: ReadonlyMap<string, unknown>, known: readonly string[], shape: string): void {\n if ([...entries.keys()].some((key) => !known.includes(key))) errors.report(path, 'invalid-source', `${shape}, ${NOTHING_ELSE}`)\n}\n\n/** One submission, or undefined when it cannot be read at all; `seen` holds the ids read before it. */\nfunction readSubmission(errors: DataFindings, raw: unknown, path: string, seen: Set<string>): FormSubmission | undefined {\n const read = readRecord(raw)\n if (!read.ok) {\n errors.report(path, container(read.code), SUBMISSION)\n return undefined\n }\n const known = ['id', 'form', 'formHash']\n const unreadable = notData(errors, path, read.problems, known)\n onlyKnown(errors, path, read.entries, known, SUBMISSION)\n const [id, form, formHash] = known.map((key) => read.entries.get(key))\n if (!unreadable.has('id')) {\n if (!isSubmissionId(id)) {\n errors.report(at(path, 'id'), 'invalid-source', `a submission's id: ${ID_SYNTAX}; never a name, an address or an answer`)\n } else if (seen.has(id)) {\n errors.report(at(path, 'id'), 'invalid-source', 'a source names each submission once, and an earlier entry names this one')\n } else seen.add(id)\n }\n if (!unreadable.has('form') && !isFormId(form)) errors.report(at(path, 'form'), 'invalid-source', `the form the submission answered: ${FORM_ID}`)\n if (!unreadable.has('formHash') && !isSchemaHash(formHash)) {\n errors.report(at(path, 'formHash'), 'invalid-source', 'the schemaHash of the form version that collected the submission: 64 lower-case hex digits')\n }\n return Object.freeze({ id: id as string, form: form as string, formHash: formHash as string })\n}\n\n/** A formancy form's source: each submission, read after the bound is checked. */\nfunction readFormSource(errors: DataFindings, entries: ReadonlyMap<string, unknown>, max: number): FormSource | undefined {\n const list = readList(entries.get('submissions'), max)\n if (!list.ok) {\n const message =\n list.code === 'too-many'\n ? `${list.message}: a source names no more submissions than the data gives detail rows, or one where it gives none, since a report of one submission reads its repeater's rows and a report of many one a row`\n : 'submissions is a list of { \"id\", \"form\", \"formHash\" }, one for each submission the data was read from'\n errors.report('/source/submissions', container(list.code), message)\n return undefined\n }\n if (list.items.length === 0) errors.report('/source/submissions', 'invalid-source', 'a form source names at least one submission the data was read from')\n const unreadable = new Map(list.problems.map(({ index, message }) => [index, message]))\n const seen = new Set<string>()\n const submissions: FormSubmission[] = []\n for (const [index, item] of list.items.entries()) {\n if (errors.full) break\n const path = at('/source/submissions', index)\n if (item === UNREADABLE) {\n errors.report(path, 'not-data', unreadable.get(index) as string)\n continue\n }\n const submission = readSubmission(errors, item, path, seen)\n if (submission !== undefined) submissions.push(submission)\n }\n const locale = entries.get('locale')\n // A locale refused is said once, here, and is not compared with the render's as well.\n if (entries.has('locale') && !isLocale(locale))\n errors.report('/source/locale', 'invalid-source', \"the locale the form's labels were read in, as a report writes its locale: a BCP 47 tag such as fr-CH\")\n return Object.freeze({ provider: 'formancy-form', submissions: Object.freeze(submissions), ...(isLocale(locale) ? { locale } : {}) })\n}\n\n/** Formancy Data's source: a form for each dataset the report declares, for no other, and at least one. */\nfunction readDataSource(errors: DataFindings, entries: ReadonlyMap<string, unknown>, datasets: Datasets): FormancyDataSource | undefined {\n const read = readRecord(entries.get('forms'))\n if (!read.ok) {\n errors.report('/source/forms', container(read.code), 'forms is { \"header\", \"detail\" }: the published form each dataset the report declares was read from')\n return undefined\n }\n const unreadable = notData(errors, '/source/forms', read.problems, ROLES)\n if (read.entries.size === 0 && read.problems.length === 0) {\n errors.report(\n '/source/forms',\n 'invalid-source',\n 'a Formancy Data source names the form each dataset was read from, and data read from no form names no source',\n )\n return undefined\n }\n onlyKnown(errors, '/source/forms', read.entries, ROLES, 'forms is keyed by the datasets a report declares, header and detail')\n for (const role of ROLES) {\n if (unreadable.has(role)) continue\n const declared = datasets[role] !== undefined\n if (!read.entries.has(role)) {\n if (declared) errors.report('/source/forms', 'invalid-source', `the report declares a ${role} dataset, and the source names no form it was read from`)\n } else if (!declared) errors.report(at('/source/forms', role), 'invalid-source', `the report declares no ${role} dataset, so none was read from a form`)\n else if (!isFormId(read.entries.get(role)))\n errors.report(at('/source/forms', role), 'invalid-source', `the published form the ${role} dataset was read from: ${FORM_ID}`)\n }\n // In the datasets' order, whatever the host's: one source, one spelling.\n const forms = Object.fromEntries(ROLES.filter((role) => read.entries.has(role)).map((role) => [role, read.entries.get(role) as string]))\n return Object.freeze({ provider: 'formancy-data', forms: Object.freeze(forms) })\n}\n\n/**\n * The source `raw` names, held to its provider's shape and to `datasets`,\n * as a frozen copy, with every problem reported to `errors`; undefined when\n * it cannot be read at all. No more than `maxSubmissions` submissions are\n * read, and a list past it is refused before any of its items is.\n */\nexport function checkSource(errors: DataFindings, raw: unknown, datasets: Datasets, maxSubmissions: number): DataSource | undefined {\n const shape = `a source is { \"provider\": one of ${SOURCE_PROVIDERS.map((provider) => `\"${provider}\"`).join(', ')}, and what that provider names }`\n const read = readRecord(raw)\n if (!read.ok) {\n errors.report('/source', container(read.code), shape)\n return undefined\n }\n const unreadable = notData(errors, '/source', read.problems, ['provider', ...new Set(Object.values(NAMES).flat())])\n if (unreadable.has('provider')) return undefined\n const provider = SOURCE_PROVIDERS.find((each) => each === read.entries.get('provider'))\n if (provider === undefined) {\n errors.report('/source/provider', 'invalid-source', shape)\n return undefined\n }\n const names = NAMES[provider]\n onlyKnown(errors, '/source', read.entries, ['provider', ...names], SHAPES[provider])\n // What is not data was said where it stands, and is not said again as missing.\n if (names.some((name) => unreadable.has(name))) return undefined\n return provider === 'formancy-form' ? readFormSource(errors, read.entries, maxSubmissions) : readDataSource(errors, read.entries, datasets)\n}\n","/**\n * The data a report is rendered from, and the check that admits it.\n *\n * A host hands over one envelope (plan 13.2): one header record and one\n * primary detail list for version 0, with what the provider says about\n * them -- how many rows it captured against what cap, and how consistent\n * the capture is. `checkData` holds every value to the report's dataset\n * contracts before anything reads it, and refuses rather than repairs:\n *\n * - **Types are the contract's.** Each value is read as its field's type\n * (`values.ts`), exact numbers as strings and never through a JavaScript\n * number, and held as the runtime computes with it.\n * - **Null is not missing.** Null is a value where the contract allows it,\n * and prints as nothing. A field the data lacks altogether is an error in\n * a final render, never an empty cell (0007); a preview, which may run on\n * a sample, warns once per field and leaves it missing.\n * - **Data minimisation.** A field, or a dataset, the report does not\n * declare is refused: a report never carries what it does not print, so\n * nothing it was not written to read rides along into a render, a cache\n * or a log.\n * - **No silent truncation.** A final render prints every row or none: data\n * the provider calls incomplete is refused, and so is a captured count\n * that disagrees with the rows given.\n * - **Bounded.** The rows and every string are bounded before they are\n * read, and so is the error list; once it is full, nothing more is read.\n * - **Its source, by the syntax of identifiers.** Where the provider names\n * where the data came from -- a formancy form's submissions and their\n * versions, or Formancy Data's forms -- it is held to `source.ts`'s\n * rules, no more submissions than the rows given, and the render's\n * manifest carries it (0041). A formancy form's labels were read in the\n * locale the report prints in, or are refused (0063).\n *\n * What is held afterwards is a frozen copy, read once from the host's\n * objects, which no later change to them reaches.\n */\nimport { MAX_KEY_LENGTH } from '@formancy/report-spec'\nimport type { DatasetContract, DatasetRole, ReportDefinition } from '@formancy/report-spec'\nimport { at, DataFindings, isLongKey, keyAt } from './data-errors.js'\nimport type { DataError, DataErrorCode } from './data-errors.js'\nimport { readList, readRecord, UNREADABLE } from './input.js'\nimport type { ContainerCode } from './input.js'\nimport { checkLabels } from './languages.js'\nimport { checkSource } from './source.js'\nimport type { DataSource } from './source.js'\nimport { readValue } from './values.js'\nimport type { CheckedValue } from './values.js'\n\n/**\n * How consistent the provider's capture is (plan 13.2): captured by the\n * host, read in one database snapshot, or explicitly neither -- the label\n * Formancy Data 0.1.0's records carry, read at different moments.\n */\nexport const CONSISTENCY_MODES = ['host-captured', 'transaction-snapshot', 'best-effort'] as const\nexport type Consistency = (typeof CONSISTENCY_MODES)[number]\n\n/** A final render prints the report; a preview shows an author a sample while they work, and says what it lacks. */\nexport const DATA_MODES = ['final', 'preview'] as const\nexport type DataMode = (typeof DATA_MODES)[number]\n\n/**\n * Detail rows in one render. Chosen, not derived: a report is read by a\n * person, and at the renderer trial's 48 rows a page (`docs/renderer-trial.md`,\n * 15 October 2026) this is over 2,000 pages, which pdfmake took more than 35\n * seconds to lay out at the 1,829 ms per hundred pages measured there. The\n * PDF's page bound refuses most such reports first; this bounds the\n * runtime's own work -- checking, sorting, totalling -- before a page is\n * laid out. At the bound, checking rows of the test sample report's nine\n * fields took a median of 1.5 seconds, and ordering them by site and SKU 0.5\n * (five warm runs under vitest, Node 24.21, an Intel i9-10900K, 15 October\n * 2026).\n */\nexport const MAX_DETAIL_ROWS = 100_000\n\n/** What the provider says about the rows it handed over. */\nexport interface Completeness {\n /** False when the provider stopped before the end: at its cap, or sampling. */\n readonly complete: boolean\n /** How many detail rows it captured: exactly the rows given. */\n readonly captured: number\n /** The most rows it would capture, when it has a cap. */\n readonly cap?: number\n}\n\n/** The envelope a host renders a report from. Untrusted: `checkData` reads it as data, whatever its type says. */\nexport interface ReportData {\n /** The header dataset's one record, by field id. */\n readonly header?: Readonly<Record<string, unknown>>\n /** The detail dataset's rows, in the provider's order. */\n readonly detail?: readonly Readonly<Record<string, unknown>>[]\n readonly completeness: Completeness\n readonly consistency: Consistency\n /** Where the data came from, held to the syntax of identifiers (0041); absent where the provider names none. */\n readonly source?: DataSource\n}\n\n/**\n * One record, checked: each declared field's value as its type holds it, or\n * null. A field a preview's data lacks is absent, not null. The record has\n * no prototype, so a field named `constructor` is the record's own or\n * absent, never inherited.\n */\nexport type CheckedRecord = { readonly [field: string]: CheckedValue | null }\n\nexport interface CheckedData {\n readonly mode: DataMode\n /** The header record; absent when the report declares no header dataset. */\n readonly header?: CheckedRecord\n /** The detail rows, in the provider's order; empty when the report declares no detail dataset. */\n readonly detail: readonly CheckedRecord[]\n readonly completeness: Completeness\n readonly consistency: Consistency\n /** The source the data named, as a frozen copy; absent where it named none. */\n readonly source?: DataSource\n}\n\nexport type DataCheck =\n | {\n readonly ok: true\n readonly data: CheckedData\n /** What a preview lacks; always empty in a final render, which refuses it. */ readonly warnings: readonly DataError[]\n }\n | { readonly ok: false; readonly errors: readonly DataError[] }\n\nexport interface DataCheckOptions {\n readonly mode: DataMode\n /**\n * The locale the report's own words are written in, where `report` is\n * one written in another of its languages, as a render in a\n * translation's locale checks the report it prints (0063): form data\n * that names no locale had its labels read in it. `report.locale` when\n * absent.\n */\n readonly reportLocale?: string\n}\n\nconst ENVELOPE: readonly string[] = ['header', 'detail', 'completeness', 'consistency', 'source']\nconst COMPLETENESS: readonly string[] = ['complete', 'captured', 'cap']\n\nconst MINIMISATION = 'a report never carries what it does not print, so data it does not read is refused rather than carried along'\n\n/** What one check carries through: its errors, its warnings, and its mode. */\ninterface Check {\n readonly errors: DataFindings\n readonly warnings: DataError[]\n readonly final: boolean\n}\n\n/** A container's code as a data error's: a list too long is a dataset with too many rows. */\nconst CONTAINER: { readonly [C in ContainerCode]: DataErrorCode } = { 'wrong-type': 'wrong-type', 'not-data': 'not-data', 'too-many': 'too-many-rows' }\n\n/** Reports what a record holds that is not data, by key; returns those keys. */\nfunction reportProblems(c: Check, path: string, problems: readonly { readonly key?: string; readonly message: string }[]): ReadonlySet<string> {\n const keys = new Set<string>()\n for (const problem of problems) {\n if (problem.key !== undefined) keys.add(problem.key)\n c.errors.report(problem.key === undefined ? path : keyAt(path, problem.key), 'not-data', problem.message)\n }\n return keys\n}\n\n/** How many records lacked a field, and where it was first missed. */\ninterface Missing {\n first: string\n count: number\n}\n\n/** One record held to `contract`, or undefined when it cannot be read at all. Fields it lacks are tallied in `missing`. */\nfunction checkRecord(\n c: Check,\n contract: DatasetContract,\n declared: ReadonlySet<string>,\n raw: unknown,\n path: string,\n missing: Map<string, Missing>,\n): CheckedRecord | undefined {\n const read = readRecord(raw)\n if (!read.ok) {\n c.errors.report(path, read.code, read.message)\n return undefined\n }\n const unreadable = reportProblems(c, path, read.problems)\n const record = Object.create(null) as Record<string, CheckedValue | null>\n for (const field of contract.fields) {\n const where = at(path, field.id)\n if (unreadable.has(field.id)) continue\n if (!read.entries.has(field.id)) {\n const tally = missing.get(field.id)\n if (c.final)\n c.errors.report(\n where,\n 'missing-field',\n `${field.id}: the contract declares this field and the data lacks it; a missing field is not null, and a final render refuses it`,\n )\n else if (tally === undefined) missing.set(field.id, { first: where, count: 1 })\n else tally.count++\n continue\n }\n const value = read.entries.get(field.id)\n if (value === null) {\n if (field.nullable) record[field.id] = null\n else c.errors.report(where, 'unexpected-null', `${field.id}: the contract says this field is never null`)\n continue\n }\n const checked = readValue(field.type, value, field.scale)\n if (checked.ok) record[field.id] = checked.value\n else c.errors.report(where, checked.code, `${field.id}: ${checked.message}`)\n }\n for (const key of read.entries.keys()) {\n if (declared.has(key)) continue\n const what = isLongKey(key) ? `a property name longer than ${MAX_KEY_LENGTH} characters, which no field has` : 'the contract declares no such field'\n c.errors.report(keyAt(path, key), 'undeclared-field', `${what}; ${MINIMISATION}`)\n }\n return Object.freeze(record)\n}\n\n/** A warning for each field a preview's records lacked, once per field. */\nfunction warnMissing(c: Check, missing: ReadonlyMap<string, Missing>, records: number, role: DatasetRole): void {\n for (const [field, { first, count }] of missing) {\n const where = role === 'header' ? 'the header record' : `${count} of ${records} rows`\n c.warnings.push({ path: first, code: 'missing-field', message: `${field}: missing from ${where}; a final render refuses data without it` })\n }\n}\n\n/** The report does not declare `role`, and the data holds it. */\nfunction undeclaredDataset(c: Check, role: DatasetRole): void {\n c.errors.report(`/${role}`, 'undeclared-dataset', `the report declares no ${role} dataset; ${MINIMISATION}`)\n}\n\n/** The report declares `role`, and the data lacks it: an error in a final render, a warning in a preview. */\nfunction missingDataset(c: Check, role: DatasetRole): void {\n const message = `the report declares a ${role} dataset and the data has none`\n if (c.final) c.errors.report(`/${role}`, 'missing-dataset', message)\n else c.warnings.push({ path: `/${role}`, code: 'missing-dataset', message: `${message}; every field of it is missing` })\n}\n\nconst EMPTY: CheckedRecord = Object.freeze(Object.create(null) as CheckedRecord)\n\nfunction checkHeader(c: Check, contract: DatasetContract | undefined, entries: ReadonlyMap<string, unknown>): CheckedRecord | undefined {\n const present = entries.has('header')\n if (contract === undefined) {\n if (present) undeclaredDataset(c, 'header')\n return undefined\n }\n if (!present) {\n missingDataset(c, 'header')\n return EMPTY\n }\n const missing = new Map<string, Missing>()\n const record = checkRecord(c, contract, new Set(contract.fields.map(({ id }) => id)), entries.get('header'), '/header', missing)\n warnMissing(c, missing, 1, 'header')\n return record\n}\n\n/** The detail rows checked, and how many were given when that could be counted. */\nfunction checkDetail(\n c: Check,\n contract: DatasetContract | undefined,\n entries: ReadonlyMap<string, unknown>,\n): { readonly rows: CheckedRecord[]; readonly given: number | undefined } {\n const present = entries.has('detail')\n if (contract === undefined || !present) {\n if (contract === undefined && present) undeclaredDataset(c, 'detail')\n if (contract !== undefined) missingDataset(c, 'detail')\n return { rows: [], given: contract === undefined && !present ? 0 : undefined }\n }\n const list = readList(entries.get('detail'), MAX_DETAIL_ROWS)\n if (!list.ok) {\n const message = list.code === 'too-many' ? `${list.message}: a render reads at most ${MAX_DETAIL_ROWS} detail rows` : list.message\n c.errors.report('/detail', CONTAINER[list.code], message)\n return { rows: [], given: undefined }\n }\n const unreadable = new Map(list.problems.map(({ index, message }) => [index, message]))\n const declared = new Set(contract.fields.map(({ id }) => id))\n const missing = new Map<string, Missing>()\n const rows: CheckedRecord[] = []\n for (const [index, item] of list.items.entries()) {\n if (c.errors.full) break\n if (item === UNREADABLE) {\n c.errors.report(at('/detail', index), 'not-data', unreadable.get(index) as string)\n continue\n }\n const record = checkRecord(c, contract, declared, item, at('/detail', index), missing)\n if (record !== undefined) rows.push(record)\n }\n warnMissing(c, missing, list.items.length, 'detail')\n return { rows, given: list.items.length }\n}\n\nconst isCount = (value: unknown): value is number => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0\n\nfunction checkCompleteness(c: Check, raw: unknown, given: number | undefined): Completeness | undefined {\n const read = readRecord(raw)\n const shape = 'completeness is { \"complete\": true or false, \"captured\": the rows given, \"cap\": the most rows the provider would capture, if it has a cap }'\n if (!read.ok) {\n c.errors.report('/completeness', 'invalid-completeness', shape)\n return undefined\n }\n reportProblems(c, '/completeness', read.problems)\n for (const key of read.entries.keys()) {\n if (!COMPLETENESS.includes(key)) c.errors.report(keyAt('/completeness', key), 'invalid-completeness', `${shape}; nothing else`)\n }\n const { complete, captured, cap } = Object.fromEntries(COMPLETENESS.map((key) => [key, read.entries.get(key)]))\n const valid = typeof complete === 'boolean' && isCount(captured) && (cap === undefined || isCount(cap))\n if (typeof complete !== 'boolean') c.errors.report('/completeness/complete', 'invalid-completeness', 'complete is true or false')\n if (!isCount(captured)) c.errors.report('/completeness/captured', 'invalid-completeness', 'captured is a count of rows: a whole number, 0 or more')\n if (cap !== undefined && !isCount(cap)) c.errors.report('/completeness/cap', 'invalid-completeness', 'cap is a count of rows: a whole number, 0 or more')\n if (!valid) return undefined\n if (given !== undefined && captured !== given) {\n c.errors.report(\n '/completeness/captured',\n 'completeness-mismatch',\n `the provider says it captured ${captured} rows and gave ${given}; rows lost or added on the way are never papered over`,\n )\n }\n if (cap !== undefined && captured > cap)\n c.errors.report('/completeness/cap', 'completeness-mismatch', `the provider says it captured ${captured} rows, more than its cap of ${cap}`)\n if (!complete) {\n const message = 'the provider says the data is incomplete'\n if (c.final)\n c.errors.report('/completeness/complete', 'incomplete', `${message}; a final render prints every row or none, and never a silently truncated report`)\n else c.warnings.push({ path: '/completeness/complete', code: 'incomplete', message: `${message}; this preview shows only what was captured` })\n }\n return Object.freeze({ complete, captured, ...(cap === undefined ? {} : { cap }) })\n}\n\nfunction checkConsistency(c: Check, raw: unknown): Consistency | undefined {\n if (CONSISTENCY_MODES.includes(raw as Consistency)) return raw as Consistency\n c.errors.report('/consistency', 'invalid-consistency', `consistency is one of ${CONSISTENCY_MODES.map((mode) => `\"${mode}\"`).join(', ')}`)\n return undefined\n}\n\n/**\n * `data` held to `report`'s dataset contracts, or every reason it is\n * refused, up to `MAX_DATA_ERRORS`. `report` is one the validator accepts.\n * Any mode but `preview` is held as final: the stricter of the two.\n */\nexport function checkData(report: ReportDefinition, data: ReportData, options: DataCheckOptions): DataCheck {\n const c: Check = { errors: new DataFindings(), warnings: [], final: options.mode !== 'preview' }\n const top = readRecord(data)\n if (!top.ok) return { ok: false, errors: [{ path: '', code: top.code, message: top.message }] }\n reportProblems(c, '', top.problems)\n for (const key of top.entries.keys()) {\n if (!ENVELOPE.includes(key))\n c.errors.report(keyAt('', key), 'unknown-property', `the data holds ${ENVELOPE.join(', ')}, and nothing the runtime does not know`)\n }\n const header = checkHeader(c, report.datasets.header, top.entries)\n const detail = checkDetail(c, report.datasets.detail, top.entries)\n const completeness = checkCompleteness(c, top.entries.get('completeness'), detail.given)\n const consistency = checkConsistency(c, top.entries.get('consistency'))\n // A report of one submission reads its repeater's rows, and a report of\n // many one a row, so a source names no more submissions than the rows\n // given, or one where none are. Rows that could not be counted are their\n // own error, and the source is held to the most a render reads.\n const rows = top.entries.has('detail') ? detail.given : 0\n const submissions = rows === undefined ? MAX_DETAIL_ROWS : Math.max(1, rows)\n const source = top.entries.has('source') ? checkSource(c.errors, top.entries.get('source'), report.datasets, submissions) : undefined\n checkLabels(c.errors, source, options.reportLocale ?? report.locale, report.locale)\n if (!c.errors.empty || completeness === undefined || consistency === undefined) return { ok: false, errors: c.errors.errors() }\n const checked: CheckedData = {\n mode: c.final ? 'final' : 'preview',\n ...(header === undefined ? {} : { header }),\n detail: Object.freeze(detail.rows),\n completeness,\n consistency,\n ...(source === undefined ? {} : { source }),\n }\n return { ok: true, data: Object.freeze(checked), warnings: c.warnings }\n}\n","/**\n * The values a person supplies before rendering, held to the report's\n * parameters.\n *\n * A parameter is read by exactly the rules a dataset field of its type is\n * (`values.ts`), so `params.copies` is an integer however it reached the\n * report: from a parameter form, an API call or a default. Then:\n *\n * - **Defaults apply** to a parameter left out. A default is written as the\n * format writes it -- an exact string, or a boolean -- and read by the\n * same rules as a value.\n * - **Required is enforced.** A required parameter with neither a value nor\n * a default is refused.\n * - **Null only where there may be none.** A parameter that is neither\n * required nor defaulted may be null; any other is never null when an\n * expression reads it (0009), so null for it is refused, not read as its\n * default.\n * - **Nothing undeclared.** A value for a parameter the report does not\n * declare is refused.\n *\n * The values are checked again here even when a parameter form checked\n * them already (plan 12.4): what reaches a render is decided by the\n * runtime, never by the browser that sent it.\n */\nimport { MAX_KEY_LENGTH } from '@formancy/report-spec'\nimport type { ParameterDef, ReportDefinition } from '@formancy/report-spec'\nimport { at, DataFindings, isLongKey, keyAt } from './data-errors.js'\nimport type { DataError } from './data-errors.js'\nimport { readRecord } from './input.js'\nimport { readValue } from './values.js'\nimport type { CheckedValue } from './values.js'\n\n/** The parameters' values by id, each read as its type or null. It has no prototype, so a parameter named `constructor` is its own value. */\nexport type CheckedParameters = { readonly [parameter: string]: CheckedValue | null }\n\nexport type ParameterCheck = { readonly ok: true; readonly values: CheckedParameters } | { readonly ok: false; readonly errors: readonly DataError[] }\n\n/** The value `parameter` takes when nobody supplied one; undefined when it must be supplied. */\nfunction absent(errors: DataFindings, parameter: ParameterDef, path: string): CheckedValue | null | undefined {\n if (parameter.default !== undefined) {\n const read = readValue(parameter.type, parameter.default)\n if (read.ok) return read.value\n errors.report(path, read.code, `${parameter.id}: its default is not a ${parameter.type}: ${read.message}`)\n return undefined\n }\n if (!parameter.required) return null\n errors.report(path, 'missing-parameter', `${parameter.id}: the report requires this parameter, and it has no value and no default`)\n return undefined\n}\n\n/**\n * `values` held to `report`'s parameters, with defaults applied, or every\n * reason they are refused. `report` is one the validator accepts. A path is\n * a JSON Pointer into `values`: `/copies`.\n */\nexport function checkParameters(report: ReportDefinition, values: Readonly<Record<string, unknown>>): ParameterCheck {\n const errors = new DataFindings()\n const read = readRecord(values)\n if (!read.ok) return { ok: false, errors: [{ path: '', code: read.code, message: `parameters are ${read.message}` }] }\n const unreadable = new Set<string>()\n for (const problem of read.problems) {\n if (problem.key !== undefined) unreadable.add(problem.key)\n errors.report(problem.key === undefined ? '' : keyAt('', problem.key), 'not-data', problem.message)\n }\n const checked = Object.create(null) as Record<string, CheckedValue | null>\n for (const parameter of report.parameters) {\n const path = at('', parameter.id)\n if (unreadable.has(parameter.id)) continue\n if (!read.entries.has(parameter.id)) {\n const value = absent(errors, parameter, path)\n if (value !== undefined) checked[parameter.id] = value\n continue\n }\n const raw = read.entries.get(parameter.id)\n if (raw === null) {\n if (!parameter.required && parameter.default === undefined) checked[parameter.id] = null\n else {\n const why = parameter.default === undefined ? 'the report requires it' : 'it has a default; leave it out to use the default'\n errors.report(path, 'unexpected-null', `${parameter.id}: never null, because ${why}`)\n }\n continue\n }\n const value = readValue(parameter.type, raw)\n if (value.ok) checked[parameter.id] = value.value\n else errors.report(path, value.code, `${parameter.id}: ${value.message}`)\n }\n const declared = new Set(report.parameters.map(({ id }) => id))\n for (const key of read.entries.keys()) {\n if (declared.has(key)) continue\n const what = isLongKey(key) ? `a name longer than ${MAX_KEY_LENGTH} characters, which no parameter has` : 'the report declares no such parameter'\n errors.report(keyAt('', key), 'undeclared-parameter', `${what}; a report reads nothing it was not written to read`)\n }\n if (!errors.empty) return { ok: false, errors: errors.errors() }\n return { ok: true, values: Object.freeze(checked) }\n}\n","/**\n * Exact totals and declared rounding, over `@formancy/expressions`'\n * `Decimal`: a value as an integer of units at a scale, so that nothing here\n * ever passes through a JavaScript number.\n *\n * Totals are decided once, here (0007): a sum is exact at the largest scale\n * it meets, a minimum or maximum compares by value, and an average is the\n * exact quotient rounded once, by the rule the aggregate declares. Rounding\n * follows report-spec's `Rounding`: to a multiple of `increment` when one is\n * given -- 0.05 for Swiss cash rounding -- and otherwise to `scale` places,\n * ties going by `mode` either way, and the result at exactly `scale` places.\n *\n * Upstream's own `roundDecimal` rounds half away from zero to a number of\n * places and nothing else; a declared rounding also has half to even and an\n * increment, so it is worked here, on integers, once for every case.\n * `decimal.test.ts` holds it against a reference written independently.\n */\nimport { addDecimal, compareDecimal, Decimal, decimalFromString } from '@formancy/expressions'\nimport type { Rounding, RoundingMode } from '@formancy/report-spec'\n\n/**\n * `numerator / denominator` (denominator more than 0) rounded to a whole\n * number, ties by `mode`. Division truncates towards zero; what it left\n * decides whether to step away from zero.\n */\nfunction roundQuotient(numerator: bigint, denominator: bigint, mode: RoundingMode): bigint {\n const quotient = numerator / denominator\n const remainder = numerator % denominator\n const twice = 2n * (remainder < 0n ? -remainder : remainder)\n if (twice < denominator) return quotient\n const away = numerator < 0n ? quotient - 1n : quotient + 1n\n if (twice > denominator) return away\n return mode === 'half-away-from-zero' || quotient % 2n !== 0n ? away : quotient\n}\n\n/** The step a rounding rounds to: its increment, or one unit at its scale. Throws for a step report-spec refuses. */\nfunction stepOf(rounding: Rounding): Decimal {\n if (rounding.increment === undefined) return new Decimal(1n, rounding.scale)\n const step = decimalFromString(rounding.increment)\n if (step.units <= 0n || step.scale > rounding.scale) {\n throw new RangeError(`an increment is more than 0 and has no more places than the ${rounding.scale} its rounding keeps`)\n }\n return step\n}\n\n/** The exact quotient `numerator / denominator` rounded as `rounding` declares. */\nfunction roundRatio(numerator: bigint, denominator: bigint, rounding: Rounding): Decimal {\n const step = stepOf(rounding)\n const steps = roundQuotient(numerator * 10n ** BigInt(step.scale), denominator * step.units, rounding.mode)\n return new Decimal(steps * step.units * 10n ** BigInt(rounding.scale - step.scale), rounding.scale)\n}\n\n/** The exact ratio of two decimals rounded once as `rounding` declares: a share, never computed through a double. Throws a RangeError for a denominator of 0 or less, which `roundQuotient` does not divide by. */\nexport function ratioRounded(numerator: Decimal, denominator: Decimal, rounding: Rounding): Decimal {\n if (denominator.units <= 0n) throw new RangeError('a ratio is of a denominator more than 0')\n return roundRatio(numerator.units * 10n ** BigInt(denominator.scale), denominator.units * 10n ** BigInt(numerator.scale), rounding)\n}\n\n/**\n * `value` rounded as `rounding` declares, at exactly its scale. A negative\n * value that rounds to nothing is zero, never minus zero. Throws a\n * RangeError for an increment report-spec refuses: of zero or less, or with\n * more places than the scale.\n */\nexport function roundDecimalAs(value: Decimal, rounding: Rounding): Decimal {\n return roundRatio(value.units, 10n ** BigInt(value.scale), rounding)\n}\n\n/** The exact sum, at the largest scale among the values; 0 over none (0007). */\nexport function sumDecimals(values: Iterable<Decimal>): Decimal {\n let total = new Decimal(0n, 0)\n for (const value of values) total = addDecimal(total, value)\n return total\n}\n\n/** The value `keep` prefers over each other, compared by value; the first of equals is kept, as written. */\nfunction extreme(values: Iterable<Decimal>, keep: (order: -1 | 0 | 1) => boolean): Decimal | null {\n let found: Decimal | null = null\n for (const value of values) if (found === null || keep(compareDecimal(value, found))) found = value\n return found\n}\n\n/** The least value, as written; null over none (0007). */\nexport function minDecimal(values: Iterable<Decimal>): Decimal | null {\n return extreme(values, (order) => order < 0)\n}\n\n/** The greatest value, as written; null over none (0007). */\nexport function maxDecimal(values: Iterable<Decimal>): Decimal | null {\n return extreme(values, (order) => order > 0)\n}\n\n/**\n * The exact average, rounded once as `rounding` declares: the exact sum\n * over the count, never a quotient rounded and then rounded again. Null\n * over no values (0007).\n */\nexport function averageDecimals(values: Iterable<Decimal>, rounding: Rounding): Decimal | null {\n let count = 0n\n let total = new Decimal(0n, 0)\n for (const value of values) {\n total = addDecimal(total, value)\n count++\n }\n return count === 0n ? null : roundRatio(total.units, count * 10n ** BigInt(total.scale), rounding)\n}\n","/**\n * A value as the text a report prints, for the report's locale: report-spec's\n * number, currency, date and text formats, through Intl.\n *\n * - **Exact to the last digit.** A number reaches Intl as the string of its\n * digits, already rounded here to exactly the places it prints, half away\n * from zero as a person rounds by hand. An ES2023 engine formats such a\n * string exactly, and `format.test.ts` holds that it does; Intl is never\n * handed a double and never rounds. Up to a bound: ECMA-402 reads a\n * string whose double would be infinite as infinity, and prints '∞'. A\n * number with more than `MAX_FORMATTED_DIGITS` integer digits is refused\n * instead; printed without a format, it prints whole. `percent` is held\n * to both: a share at more places than it keeps is refused, never rounded\n * by Intl.\n * - **The locale's conventions.** Grouping, separators, currency symbols,\n * month names and case are the locale's, as the engine's ICU has them.\n * ICU versions can differ -- which mark Swiss German groups digits with is\n * one such difference, and `format.test.ts` reads it from the engine -- so\n * the same report can print differently on two engines. That is the cost\n * of not carrying a locale database here.\n * - **Dates have no zone.** A date, and a date and time without a zone, are\n * formatted in UTC from their own fields, so 2026-01-01 is the first of\n * January wherever the report renders. Only an instant is shown in a zone,\n * and that zone is the host's to name: the machine's is never used.\n * - **Nothing is guessed.** A locale or zone the engine lacks is refused\n * rather than replaced by a default, and a format that cannot show a value\n * is an error rather than a blank.\n *\n * Null prints as nothing (0007), under every format.\n */\nimport { Decimal, decimalToString } from '@formancy/expressions'\nimport type { CurrencyFormat, CurrencySource, DateStyle, FieldType, Format, NumberFormat, TextTransform } from '@formancy/report-spec'\nimport type { CheckedRecord } from './data.js'\nimport { roundDecimalAs } from './decimal.js'\nimport type { CheckedParameters } from './parameters.js'\nimport { readValue } from './values.js'\nimport type { FieldValues } from './values.js'\n\n/** The types a value printed can have: every field type but an image, which is drawn. */\nexport type PrintableType = Exclude<FieldType, 'image'>\n\n/** A value with its type, as the runtime holds it (`values.ts`). */\nexport type TypedValue = { readonly [T in PrintableType]: { readonly type: T; readonly value: FieldValues[T] } }[PrintableType]\n\nexport const FORMAT_ERROR_CODES = [\n /** A locale the engine's Intl does not have, which it would silently replace with the host's. */\n 'unsupported-locale',\n /** A time zone the engine's Intl does not know. */\n 'unsupported-time-zone',\n /** A format that cannot show the value it is given: a number format over text, a date format over a number. */\n 'format-type-mismatch',\n /** An amount whose currency field or parameter has no value. */\n 'no-currency',\n /** A currency that is not an ISO 4217 code in capitals. */\n 'invalid-currency',\n /** A number with more integer digits than `MAX_FORMATTED_DIGITS`, which Intl would print as '∞'. */\n 'number-too-large',\n /** A share handed to `percent` at more places than it keeps, which Intl would round again by its own rule. */\n 'percent-rounds-again',\n] as const\n\n/**\n * The most integer digits a number or currency format prints: 308. A double\n * holds up to about 1.8 × 10^308, and ECMA-402's ToIntlMathematicalValue\n * reads a string whose double would be infinite as infinity, so every\n * number of 308 digits or fewer prints exactly and one of 309 may not.\n */\nexport const MAX_FORMATTED_DIGITS = 308\nexport type FormatErrorCode = (typeof FORMAT_ERROR_CODES)[number]\n\nexport type Formatted = { readonly ok: true; readonly text: string } | { readonly ok: false; readonly code: FormatErrorCode; readonly message: string }\n\n/** What a render is formatted for: the report's locale, and the zone its instants are shown in. */\nexport interface FormatContext {\n /** A BCP 47 tag, as a report's `locale` is. */\n readonly locale: string\n /** An IANA time zone, such as `Europe/Zurich`, named by the host. */\n readonly timeZone: string\n}\n\n/** Where a currency format finds a currency read from a field or a parameter. */\nexport interface CurrencyScope {\n readonly params?: CheckedParameters\n readonly header?: CheckedRecord\n /** The current detail row, in a table's cells. */\n readonly row?: CheckedRecord\n}\n\nexport interface Formatter {\n readonly locale: string\n readonly timeZone: string\n /** `value` as `format` shows it, or as it prints plainly without one. */\n format(value: TypedValue | null, format: Format | undefined, scope?: CurrencyScope): Formatted\n /** `fraction` as the locale writes a percentage at `places`: 0.125 at 1 is 12.5%. The fraction is already rounded to `places + 2` places, so Intl shifts its digits and never rounds. */\n percent(fraction: Decimal, places: number): Formatted\n}\n\n/** Whether `digits`, a number as `decimalToString` writes it, has more integer digits than Intl prints: it would print them as infinity. */\nconst tooManyDigits = (digits: string): boolean => digits.replace(/^-/, '').split('.')[0]!.length > MAX_FORMATTED_DIGITS\n\n/** A count of places as a message says it: \"1 place\", \"3 places\". */\nconst placesOf = (count: number): string => `${count} ${count === 1 ? 'place' : 'places'}`\n\nfunction refused(code: FormatErrorCode, message: string): Formatted {\n return { ok: false, code, message }\n}\n\n/**\n * A value printed with no format: as the format writes it. Exact digits\n * with their scale, ISO dates, an instant in UTC; nothing is interpreted.\n */\nexport function plainText(value: TypedValue | null): string {\n if (value === null) return ''\n if (value.type === 'integer' || value.type === 'boolean') return String(value.value)\n if (value.type === 'decimal') return decimalToString(value.value)\n return value.value\n}\n\n/**\n * Whether the engine has `locale`, in its number and date formats and its\n * collation, by the lookup a tag like `de-CH` falls back from region to\n * language with. A tag it cannot read is not one it has.\n */\nexport function supportedLocale(locale: string): boolean {\n try {\n const options = { localeMatcher: 'lookup' } as const\n return (\n Intl.NumberFormat.supportedLocalesOf([locale], options).length === 1 &&\n Intl.DateTimeFormat.supportedLocalesOf([locale], options).length === 1 &&\n Intl.Collator.supportedLocalesOf([locale], options).length === 1\n )\n } catch {\n return false\n }\n}\n\n/** Whether Intl knows `timeZone`. */\nfunction knownTimeZone(timeZone: string): boolean {\n try {\n new Intl.DateTimeFormat('en', { timeZone })\n return true\n } catch {\n return false\n }\n}\n\n/** The time a date-and-time format shows with each date style: no seconds for short, seconds otherwise; never the zone's name, which a local time does not have. */\nconst TIME_STYLE: { readonly [S in DateStyle]: 'short' | 'medium' } = { short: 'short', medium: 'medium', long: 'medium' }\n\n/** A moment to show: when, whether it has a time of day, and whether it is shown in the render's zone or, having none, in UTC. */\ninterface Moment {\n readonly epochMs: number\n readonly time: boolean\n readonly zoned: boolean\n}\n\n/** Epoch milliseconds of a calendar date and time in UTC; Date.UTC would read the years 0 to 99 as 1900 to 1999. */\nfunction utc(year: number, month: number, day: number, hour = 0, minute = 0, second = 0): number {\n const moment = new Date(0)\n moment.setUTCFullYear(year, month - 1, day)\n moment.setUTCHours(hour, minute, second, 0)\n return moment.getTime()\n}\n\n/** The numbers in `text`, a date or a date and time `readValue` accepted, in order. */\nconst fieldsOf = (text: string): number[] => (text.match(/\\d+/g) as RegExpMatchArray).map(Number)\n\n/** `value` as a `type` spells it: a value of that type, or a string an expression gave that spells one, as `readValue` holds it. */\nfunction spelledAs(value: TypedValue, type: 'date' | 'datetime' | 'instant'): string | undefined {\n if (value.type === type) return value.value\n if (value.type !== 'string') return undefined\n const read = readValue(type, value.value)\n return read.ok ? read.value : undefined\n}\n\n/** The moment a value spells: a date, a date and time, or an instant, by its type or, for a string an expression gave, by its syntax. */\nfunction momentOf(value: TypedValue): Moment | undefined {\n const date = spelledAs(value, 'date')\n if (date !== undefined) {\n const [year, month, day] = fieldsOf(date) as [number, number, number]\n return { epochMs: utc(year, month, day), time: false, zoned: false }\n }\n const local = spelledAs(value, 'datetime')\n if (local !== undefined) {\n const [year, month, day, hour, minute, second] = fieldsOf(local) as [number, number, number, number, number, number]\n return { epochMs: utc(year, month, day, hour, minute, second), time: true, zoned: false }\n }\n const instant = spelledAs(value, 'instant')\n return instant === undefined ? undefined : { epochMs: new Date(instant).getTime(), time: true, zoned: true }\n}\n\n/** The exact number a value holds, or undefined when it holds none. */\nfunction exactNumber(value: TypedValue): Decimal | undefined {\n if (value.type === 'integer') return new Decimal(value.value, 0)\n return value.type === 'decimal' ? value.value : undefined\n}\n\n/** The currency code an amount is in, from the format, a field or a parameter, or why there is none. */\nfunction currencyOf(source: CurrencySource, scope: CurrencyScope | undefined): string | Formatted {\n if (source.kind === 'code') return source.code\n const [name, raw] =\n source.kind === 'parameter'\n ? [`parameter ${source.parameter}`, scope?.params?.[source.parameter]]\n : [`field ${source.field.field}`, (source.field.dataset === 'header' ? scope?.header : scope?.row)?.[source.field.field]]\n if (raw === null || raw === undefined)\n return refused('no-currency', `the amount's currency, ${name}, has no value, and an amount without one reads as some other currency`)\n if (typeof raw === 'string' && /^[A-Z]{3}$/.test(raw)) return raw\n return refused('invalid-currency', `the amount's currency, ${name}, is not an ISO 4217 code in capitals, such as CHF`)\n}\n\n/** The Intl formatter `cache` keeps for `options`, made by `make` the first time they are asked for: a table formats a column with one. */\nfunction kept<T>(cache: Map<string, T>, options: object, make: () => T): T {\n const key = JSON.stringify(options)\n const found = cache.get(key)\n if (found !== undefined) return found\n const made = make()\n cache.set(key, made)\n return made\n}\n\n/** A formatter for one locale and time zone, which builds each Intl formatter it needs once and keeps it. */\nclass LocaleFormatter implements Formatter {\n readonly locale: string\n readonly timeZone: string\n readonly #numbers = new Map<string, Intl.NumberFormat>()\n readonly #dates = new Map<string, Intl.DateTimeFormat>()\n\n constructor(context: FormatContext) {\n this.locale = context.locale\n this.timeZone = context.timeZone\n }\n\n format(value: TypedValue | null, format: Format | undefined, scope?: CurrencyScope): Formatted {\n if (value === null) return { ok: true, text: '' }\n if (format === undefined) return { ok: true, text: plainText(value) }\n switch (format.kind) {\n case 'text':\n return { ok: true, text: this.#transformed(plainText(value), format.transform) }\n case 'date':\n return this.#date(value, format.style)\n default:\n return this.#number(value, format, scope)\n }\n }\n\n percent(fraction: Decimal, places: number): Formatted {\n if (fraction.scale > places + 2) {\n return refused(\n 'percent-rounds-again',\n `a share of ${placesOf(fraction.scale)}, printed as a percentage at ${placesOf(places)}, would be rounded again by Intl; round it to ${placesOf(places + 2)} first`,\n )\n }\n const digits = decimalToString(fraction) as Intl.StringNumericLiteral\n if (tooManyDigits(digits)) {\n return refused('number-too-large', `a share of more than ${MAX_FORMATTED_DIGITS} integer digits, which Intl would print as infinity`)\n }\n const options: Intl.NumberFormatOptions = { style: 'percent', minimumFractionDigits: places, maximumFractionDigits: places }\n return { ok: true, text: kept(this.#numbers, options, () => new Intl.NumberFormat(this.locale, options)).format(digits) }\n }\n\n #transformed(text: string, transform: TextTransform | undefined): string {\n if (transform === 'upper') return text.toLocaleUpperCase(this.locale)\n return transform === 'lower' ? text.toLocaleLowerCase(this.locale) : text\n }\n\n #number(value: TypedValue, format: NumberFormat | CurrencyFormat, scope: CurrencyScope | undefined): Formatted {\n const exact = exactNumber(value)\n if (exact === undefined) return refused('format-type-mismatch', `a ${format.kind} format shows integers and decimals, and this value is a ${value.type}`)\n const currency = format.kind === 'currency' ? currencyOf(format.currency, scope) : undefined\n if (typeof currency === 'object') return currency\n const rounded = decimalToString(roundDecimalAs(exact, { scale: format.scale, mode: 'half-away-from-zero' })) as Intl.StringNumericLiteral\n if (tooManyDigits(rounded)) {\n return refused(\n 'number-too-large',\n `a number of more than ${MAX_FORMATTED_DIGITS} digits, which Intl would print as infinity; printed without a format, it prints whole`,\n )\n }\n const options: Intl.NumberFormatOptions = {\n minimumFractionDigits: format.scale,\n maximumFractionDigits: format.scale,\n ...(currency === undefined ? { useGrouping: format.kind === 'number' && !format.grouping ? false : 'auto' } : { style: 'currency', currency }),\n }\n return { ok: true, text: kept(this.#numbers, options, () => new Intl.NumberFormat(this.locale, options)).format(rounded) }\n }\n\n #date(value: TypedValue, style: DateStyle): Formatted {\n const moment = momentOf(value)\n if (moment === undefined)\n return refused('format-type-mismatch', `a date format shows dates, dates and times, and instants, and this value is a ${value.type} that spells none`)\n const options: Intl.DateTimeFormatOptions = {\n dateStyle: style,\n ...(moment.time ? { timeStyle: TIME_STYLE[style] } : {}),\n timeZone: moment.zoned ? this.timeZone : 'UTC',\n }\n return { ok: true, text: kept(this.#dates, options, () => new Intl.DateTimeFormat(this.locale, options)).format(moment.epochMs) }\n }\n}\n\n/** A formatter for `context`, or why its locale or time zone is refused. */\nexport function createFormatter(\n context: FormatContext,\n): { readonly ok: true; readonly formatter: Formatter } | { readonly ok: false; readonly code: FormatErrorCode; readonly message: string } {\n if (!supportedLocale(context.locale)) {\n return { ok: false, code: 'unsupported-locale', message: \"the engine's Intl does not have this locale, and would print the host's instead\" }\n }\n if (!knownTimeZone(context.timeZone)) return { ok: false, code: 'unsupported-time-zone', message: \"the engine's Intl does not know this time zone\" }\n return { ok: true, formatter: new LocaleFormatter(context) }\n}\n","/**\n * The order of a table's rows and its groups, decided once, here (0007).\n *\n * Rows are ordered by the group's key first, in its direction, then by each\n * sort key, each compared as its type: decimals by value, integers as\n * BigInt, dates and times in calendar order, text as the report's language\n * sorts it, false before true. Nulls -- and a field a preview lacks -- go\n * last whichever way a key runs, so an empty cell never lands among the\n * values. Rows whose keys are all equal keep the provider's order: the\n * row's index is the last key, so the comparator is a total order and the\n * result rests on it alone. `Array.prototype.sort` has been stable since\n * ES2019, which by itself keeps that order too, so no test can tell the two\n * apart; the index is there so that nothing depends on the algorithm.\n *\n * Text the collator holds equal but spelled differently -- é composed and\n * decomposed -- is ordered by code unit after the collator, so that rows\n * with identical keys always stand together and a group never splits around\n * another spelling. Collation is the engine's ICU's, and differs between\n * ICU versions as formatting does.\n */\nimport { compareDecimal } from '@formancy/expressions'\nimport type { Decimal } from '@formancy/expressions'\nimport type { ChartOrder, ReportDefinition, SortDirection, TableComponent } from '@formancy/report-spec'\nimport type { CheckedRecord } from './data.js'\nimport type { PrintableType } from './format.js'\nimport type { CheckedValue } from './values.js'\n\n/** One key rows are ordered by: a detail field, its type, and its direction. */\nexport interface OrderKey {\n readonly field: string\n readonly type: PrintableType\n readonly direction: SortDirection\n}\n\n/** A detail row in its place: the record, and its index in the order the provider gave the rows. */\nexport interface OrderedRow {\n readonly index: number\n readonly record: CheckedRecord\n}\n\n/** One group: its key, as its first row spells it, or null; then its rows, in order. */\nexport interface RowGroup {\n readonly key: CheckedValue | null\n readonly rows: readonly OrderedRow[]\n}\n\n/** A table's rows in order and, when it groups, its groups in order. */\nexport interface OrderedTable {\n readonly rows: readonly OrderedRow[]\n readonly groups?: readonly RowGroup[]\n}\n\n/** A value made comparable with `<` -- or, for text, with the collator -- for one key column. */\ntype Comparable = string | bigint | boolean\n\n/**\n * A date and time with its fraction of a second at nine digits, without a\n * zone: held without trailing zeros, '10:00:00.5' and '10:00:00' differ in\n * length, and as they stand '10:00:00.5Z' sorts before '10:00:00Z'.\n */\nexport function fixedWidth(value: string): string {\n const local = value.endsWith('Z') ? value.slice(0, -1) : value\n return `${local.slice(0, 19)}.${local.slice(20).padEnd(9, '0')}`\n}\n\n/** The values of `key` in every row, made comparable once; null for a null or missing one. */\nfunction column(rows: readonly CheckedRecord[], key: OrderKey): (Comparable | null)[] {\n const values = rows.map((record) => record[key.field] ?? null)\n switch (key.type) {\n case 'decimal': {\n // Every decimal of the column at one scale, so each comparison is one of integers.\n const decimals = values as (Decimal | null)[]\n const scale = Math.max(0, ...decimals.map((value) => value?.scale ?? 0))\n return decimals.map((value) => (value === null ? null : value.units * 10n ** BigInt(scale - value.scale)))\n }\n case 'datetime':\n case 'instant':\n return (values as (string | null)[]).map((value) => (value === null ? null : fixedWidth(value)))\n default:\n return values as (Comparable | null)[]\n }\n}\n\n/** -1, 0 or 1 for two values of one comparable column. */\nfunction compared(type: PrintableType, a: Comparable, b: Comparable, collator: Intl.Collator): number {\n if (type === 'string') {\n const order = collator.compare(a as string, b as string)\n if (order !== 0) return order\n }\n return a < b ? -1 : a > b ? 1 : 0\n}\n\n/**\n * `rows` in the order `keys` give, each key applied only among rows the keys\n * before it hold equal, with text compared as `locale` sorts it -- a locale\n * `supportedLocale` accepts. Ties keep the provider's order.\n */\nexport function orderRows(rows: readonly CheckedRecord[], keys: readonly OrderKey[], locale: string): OrderedRow[] {\n const collator = new Intl.Collator(locale, { usage: 'sort' })\n const columns = keys.map((key) => column(rows, key))\n const order = rows.map((_, index) => index)\n order.sort((left, right) => {\n for (const [at, key] of keys.entries()) {\n const values = columns[at] as (Comparable | null)[]\n const [a, b] = [values[left] as Comparable | null, values[right] as Comparable | null]\n if (a === null || b === null) {\n if (a !== b) return a === null ? 1 : -1\n continue\n }\n const found = compared(key.type, a, b, collator)\n if (found !== 0) return key.direction === 'asc' ? found : -found\n }\n return left - right\n })\n return order.map((index) => Object.freeze({ index, record: rows[index] as CheckedRecord }))\n}\n\n/** Whether two group keys are one: decimals by value, everything else as held, and null with null. */\nexport function sameKey(type: PrintableType, a: CheckedValue | null, b: CheckedValue | null): boolean {\n if (a === null || b === null) return a === b\n return type === 'decimal' ? compareDecimal(a as Decimal, b as Decimal) === 0 : a === b\n}\n\n/**\n * One value a Map can find a group key by: equal for two keys of a type\n * exactly when `sameKey` holds them one (a test holds the two to each other).\n * A decimal is normalised -- trailing zeros stripped while it has a scale (zero ends at 0),\n * so 1.0 and 1.00 meet; text, integers and booleans are\n * their own keys, which a Map compares by value; null is null.\n */\nexport function canonicalKey(type: PrintableType, value: CheckedValue | null): string | bigint | boolean | null {\n if (value === null) return null\n if (type !== 'decimal') return value as string | bigint | boolean\n let { units, scale } = value as Decimal\n while (scale > 0 && units % 10n === 0n) {\n units /= 10n\n scale -= 1\n }\n return `${units}/${scale}`\n}\n\n/**\n * Rows already in order, as consecutive groups of equal keys: the groups in\n * the order of their rows, each keyed by its first row's value. A missing\n * value groups with null.\n */\nexport function groupRows(rows: readonly OrderedRow[], by: { readonly field: string; readonly type: PrintableType }): RowGroup[] {\n const groups: { key: CheckedValue | null; rows: OrderedRow[] }[] = []\n for (const row of rows) {\n const value = row.record[by.field] ?? null\n const last = groups.at(-1)\n if (last !== undefined && sameKey(by.type, last.key, value)) last.rows.push(row)\n else groups.push({ key: value, rows: [row] })\n }\n return groups.map((group) => Object.freeze({ key: group.key, rows: Object.freeze(group.rows) }))\n}\n\n/**\n * A chart's categories, grouped as a table's rows are: sorted by the\n * category's key, nulls last, then grouped; or, in the data's order, each\n * distinct key once at its first row's place, holding every row with that\n * key in the provider's order. Rows without a category are one group.\n */\nexport function categoryGroups(\n rows: readonly CheckedRecord[],\n by: { readonly field: string; readonly type: PrintableType },\n order: ChartOrder,\n locale: string,\n): RowGroup[] {\n if (order !== 'data') return groupRows(orderRows(rows, [{ ...by, direction: order }], locale), by)\n const groups = new Map<string | bigint | boolean | null, { key: CheckedValue | null; rows: OrderedRow[] }>()\n for (const [index, record] of rows.entries()) {\n const value = record[by.field] ?? null\n const row = Object.freeze({ index, record })\n const id = canonicalKey(by.type, value)\n const found = groups.get(id)\n if (found !== undefined) found.rows.push(row)\n else groups.set(id, { key: value, rows: [row] })\n }\n return [...groups.values()].map((group) => Object.freeze({ key: group.key, rows: Object.freeze(group.rows) }))\n}\n\n/**\n * The keys `table` orders its rows by: its group's key first, then its sort\n * keys (0007), each typed by the report's detail contract. Throws a\n * RangeError for a key on a field that has no order -- an image, or one the\n * contract lacks -- which report-spec refuses.\n */\nexport function orderKeys(report: ReportDefinition, table: TableComponent): OrderKey[] {\n const types = new Map((report.datasets.detail?.fields ?? []).map(({ id, type }) => [id, type]))\n const typed = (field: string, direction: SortDirection): OrderKey => {\n const type = types.get(field)\n if (type === undefined || type === 'image') throw new RangeError(`detail field ${field} has no order to sort or group by`)\n return { field, type, direction }\n }\n const group = table.group === undefined ? [] : [typed(table.group.by.field, table.group.direction)]\n return [...group, ...(table.sort ?? []).map(({ field, direction }) => typed(field.field, direction))]\n}\n\n/** `selected`, in the data's order, as `orderRows` orders them: each the very row selected, at its index in the data, not in the selection. */\nfunction selectedInOrder(selected: readonly OrderedRow[], keys: readonly OrderKey[], locale: string): OrderedRow[] {\n const records = selected.map(({ record }) => record)\n return orderRows(records, keys, locale).map(({ index }) => selected[index] as OrderedRow)\n}\n\n/**\n * `detail` -- the report's checked detail rows -- in `table`'s order, and in\n * its groups when it has one. Given `selected`, the rows a table's\n * condition selected, in the data's order (0062), those alone, each still\n * at its index in `detail`: a total over a group reads a row's value by\n * that index, and an error names the row by it. Ties keep the data's order\n * among them.\n */\nexport function orderTable(report: ReportDefinition, table: TableComponent, detail: readonly CheckedRecord[], selected?: readonly OrderedRow[]): OrderedTable {\n const keys = orderKeys(report, table)\n const rows = selected === undefined ? orderRows(detail, keys, report.locale) : selectedInOrder(selected, keys, report.locale)\n if (table.group === undefined) return { rows }\n return { rows, groups: groupRows(rows, keys[0] as OrderKey) }\n}\n","/**\n * A chart's value axis: ticks a reader takes in at a glance, found exactly.\n *\n * The step is 1, 2 or 5 times a power of ten, the finest that covers every\n * value in at most `MAX_TICK_INTERVALS` intervals and no finer than one unit\n * of the value format's last place. Everything is BigInt division on a\n * decimal's units, never a double, so a 40-digit total ticks exactly (0010).\n */\nimport { Decimal } from '@formancy/expressions'\n\n/** Intervals an axis may hold: six labels down it, chosen as what a reader takes in at a glance. */\nexport const MAX_TICK_INTERVALS = 5\n\n/** `numerator / denominator` rounded down, denominator more than 0. */\nfunction floorDiv(numerator: bigint, denominator: bigint): bigint {\n const quotient = numerator / denominator\n return numerator % denominator < 0n ? quotient - 1n : quotient\n}\n\n/**\n * The decimal of `units` at `scale`, without trailing zeros: a tick is\n * written as its value needs, and printed at the value format's scale, to\n * which the formatter pads it back -- 11 prints as 11.00 at two places.\n */\nfunction tick(units: bigint, scale: number): Decimal {\n let kept = units\n let places = scale\n while (places > 0 && kept % 10n === 0n) {\n kept /= 10n\n places--\n }\n return new Decimal(kept, places)\n}\n\n/**\n * The ticks of an axis over `values` (non-empty, not null) at the value\n * format's `scale`, ascending, evenly spaced and holding every value; a bar\n * chart's axis, and a flat line's, hold zero as well. Zero is a tick whenever\n * the axis holds it.\n */\nexport function chartTicks(values: readonly Decimal[], chart: 'bar' | 'line', scale: number): Decimal[] {\n const common = values.reduce((most, value) => Math.max(most, value.scale), scale)\n const units = values.map((value) => value.units * 10n ** BigInt(common - value.scale))\n let lo = units.reduce((least, value) => (value < least ? value : least))\n let hi = units.reduce((most, value) => (value > most ? value : most))\n if (chart === 'bar' || lo === hi) {\n if (lo > 0n) lo = 0n\n if (hi < 0n) hi = 0n\n }\n if (lo === hi) hi = 10n ** BigInt(common)\n // floor(log10(span)), exactly.\n const e = (hi - lo).toString().length - 1 - common\n for (let k = Math.max(-scale, e - 1); ; k++) {\n for (const m of [1n, 2n, 5n]) {\n const step = m * 10n ** BigInt(k + common)\n const first = floorDiv(lo, step)\n const intervals = -floorDiv(-hi, step) - first\n if (intervals > BigInt(MAX_TICK_INTERVALS)) continue\n return Array.from({ length: Number(intervals) + 1 }, (_, i) => tick((first + BigInt(i)) * step, common))\n }\n }\n}\n","/**\n * Why a report did not resolve, as one list a caller reads whatever stage\n * found the problem: the report itself, its expressions, the parameters, the\n * data, the options, an evaluation, a format, an image or a total.\n *\n * Each stage keeps the codes it already has -- report-spec's for structure,\n * report-core's diagnostics for expressions, the data check's for data and\n * parameters, the evaluator's and the formatter's -- so a code means one\n * thing wherever it appears. `stage` says which list a code is from. Like\n * every error the runtime gives, none holds a value from the data.\n */\nimport type { Diagnostic, DiagnosticCode } from '@formancy/report-core'\nimport type { ReportError, ReportErrorCode } from '@formancy/report-spec'\nimport type { DataError, DataErrorCode } from './data-errors.js'\nimport { MAX_DATA_ERRORS } from './data-errors.js'\nimport type { EvaluationError, EvaluationErrorCode } from './evaluate.js'\nimport type { FormatErrorCode } from './format.js'\n\n/** What lowering a report can find wrong besides what each earlier stage finds. */\nexport const RESOLVE_ERROR_CODES = [\n /** A creation date that is not an ISO 8601 instant with its zone. */\n 'invalid-creation-date',\n /** A locale a render names that the report is not written in: neither its own nor one its translations declare, a near one among them (0063). */\n 'undeclared-locale',\n /** An image whose bytes the host does not have, or a report with images and no way to fetch them. */\n 'missing-asset',\n /** Bytes for an image that are not a `Uint8Array`, or of another media type than the asset declares or a report may draw. */\n 'invalid-asset',\n /** The host's image lookup threw. */\n 'asset-lookup-failed',\n /** A declared rounding on a total that is not a decimal: an integer, a date or an instant has no places to round. */\n 'rounding-not-decimal',\n /** A total over values that cannot be totalled together: a sum of text, a minimum of a number and a date. */\n 'aggregate-value-type',\n /** In a final render, a run of a QR code's content, or of a QR-bill's or an EPC QR code's text, whose value is null: the code would scan as less than its content, and nothing on the page would say so. */\n 'no-qr-value',\n /** In a final render, a QR code whose content prints nothing: a symbol of no data, which a scanner reads as no code. */\n 'empty-qr-code',\n /**\n * A QR-bill a rule of SIX's breaks once its data has resolved it: an\n * account, a reference, an address part, a message or an amount. The\n * code report-spec gives a literal that breaks it, from the same rules.\n */\n 'invalid-qr-bill',\n /**\n * An EPC QR code a rule of the EPC's breaks once its data has resolved\n * it: an IBAN, a BIC, a name, a reference, a text, an amount, or a\n * payload past its bytes. The code report-spec gives a literal that\n * breaks it, from the same rules.\n */\n 'invalid-epc-qr-code',\n /**\n * An e-invoice a rule of EN 16931's breaks once its data has resolved it\n * -- a text, a date, a line's term, a row with none -- or a payment code\n * that asks for another amount or account than it names. The code\n * report-spec gives a literal that breaks it, from the same rules.\n */\n 'invalid-e-invoice',\n /** A warning, never an error: a preview of an e-invoice, which writes no XML and is not the invoice. */\n 'e-invoice-preview',\n /**\n * A copy of an e-invoice a render does not make (0077): asked for as\n * anything but `'copy'`, of a preview, which writes no XML to be a copy\n * of, or in a language the runtime has no label in.\n */\n 'no-e-invoice-copy',\n /**\n * A chart of more categories than the runtime groups, `MAX_CHART_CATEGORIES`,\n * or a pie of more categories than its palette has colours: two slices of\n * one colour would be told apart by nothing.\n */\n 'chart-too-many-categories',\n /** A pie a category of which totals less than zero: a share of a whole is never negative. */\n 'chart-negative-share',\n /** More errors were found than are listed. */\n 'too-many-errors',\n] as const\nexport type ResolveErrorCode = (typeof RESOLVE_ERROR_CODES)[number]\n\n/** Where in the report an error is, when it is in a component, a table column or a row. */\ninterface Place {\n readonly componentId?: string\n readonly columnId?: string\n /** The detail row's index in the data as the provider gave it. */\n readonly row?: number\n}\n\n/** One error, from the stage that found it, with that stage's code. Its path is a JSON Pointer into what the stage read: the report, the data, the parameters, or '' for the options. */\nexport type RuntimeError =\n | ({ readonly stage: 'report'; readonly code: ReportErrorCode; readonly path: string; readonly message: string } & Place)\n | ({ readonly stage: 'expressions'; readonly code: DiagnosticCode; readonly path: string; readonly message: string } & Place)\n | { readonly stage: 'parameters' | 'data'; readonly code: DataErrorCode; readonly path: string; readonly message: string }\n | ({\n readonly stage: 'evaluation'\n readonly code: EvaluationErrorCode\n readonly path: string\n readonly message: string\n readonly aggregateId?: string\n } & Place)\n | ({ readonly stage: 'format'; readonly code: FormatErrorCode; readonly path: string; readonly message: string } & Place)\n | ({ readonly stage: 'resolve'; readonly code: ResolveErrorCode; readonly path: string; readonly message: string } & Place)\n\nexport type RuntimeStage = RuntimeError['stage']\n\n/** The optional parts of a place, written only when present, as exactOptionalPropertyTypes asks. */\nexport function placed(place: { readonly componentId?: string | undefined; readonly columnId?: string | undefined; readonly row?: number | undefined }): Place {\n return {\n ...(place.componentId === undefined ? {} : { componentId: place.componentId }),\n ...(place.columnId === undefined ? {} : { columnId: place.columnId }),\n ...(place.row === undefined ? {} : { row: place.row }),\n }\n}\n\n/** A type as a message says what a value is: \"a decimal\", \"an integer\". */\nexport function aType(type: string): string {\n return `${/^[aeiou]/.test(type) ? 'an' : 'a'} ${type}`\n}\n\nexport function fromReport(error: ReportError): RuntimeError {\n return { stage: 'report', code: error.code, path: error.path, message: error.message, ...placed(error) }\n}\n\nexport function fromDiagnostic(diagnostic: Diagnostic): RuntimeError {\n return { stage: 'expressions', code: diagnostic.code, path: diagnostic.path, message: diagnostic.message, ...placed(diagnostic) }\n}\n\nexport function fromData(stage: 'parameters' | 'data', error: DataError): RuntimeError {\n return { stage, code: error.code, path: error.path, message: error.message }\n}\n\nexport function fromEvaluation(error: EvaluationError): RuntimeError {\n return {\n stage: 'evaluation',\n code: error.code,\n path: error.path,\n message: error.message,\n ...placed(error),\n ...(error.aggregateId === undefined ? {} : { aggregateId: error.aggregateId }),\n }\n}\n\n/**\n * The errors and warnings one resolution collects. Errors are bounded as the\n * data check bounds its own: past `MAX_DATA_ERRORS`, one `too-many-errors`\n * says the list was cut short, and `full` tells a long loop to stop. A\n * warning is said once per path: a preview that lacks a field a thousand\n * rows read warns once for it.\n */\nexport class Problems {\n readonly #errors: RuntimeError[] = []\n readonly #warnings = new Map<string, RuntimeError>()\n #overflowed = false\n\n error(error: RuntimeError): void {\n if (this.#errors.length < MAX_DATA_ERRORS) this.#errors.push(error)\n else this.#overflowed = true\n }\n\n warn(warning: RuntimeError): void {\n const key = `${warning.stage} ${warning.code} ${warning.path}`\n if (!this.#warnings.has(key)) this.#warnings.set(key, warning)\n }\n\n /** Whether the error list is cut short: nothing more is worth computing. */\n get full(): boolean {\n return this.#overflowed\n }\n\n get failed(): boolean {\n return this.#errors.length > 0\n }\n\n errors(): RuntimeError[] {\n const errors = [...this.#errors]\n if (this.#overflowed)\n errors.push({\n stage: 'resolve',\n code: 'too-many-errors',\n path: '',\n message: `more than ${MAX_DATA_ERRORS} errors were found; the first ${MAX_DATA_ERRORS} are listed`,\n })\n return errors\n }\n\n warnings(): RuntimeError[] {\n return [...this.#warnings.values()]\n }\n}\n","/**\n * What one resolution knows while it lowers a report, and the four scopes\n * a value is read in (0007, 0062): the report, a table's total rows, a\n * group of rows, one detail row.\n *\n * A scope is the values an expression is handed -- `params`, `header`,\n * `totals`, and `table`, `group` or `row` where there is one -- and where a\n * currency format finds a currency. `totals` is every detail row's in every\n * scope; `table` is the rows one table prints, the report's totals\n * themselves under a table without a condition. Every expression is\n * evaluated through `valueOf` or `holds`, so an evaluation that fails is\n * an error in one place, and a preview that lacks a field degrades in one\n * place: what reads it prints nothing, and a condition over it does not\n * hold, each said once as a warning. In a final render a missing field\n * never gets this far: the data check refuses it.\n *\n * A code is the one place a value that prints as nothing is refused: in a\n * final render, a run whose value is null in a QR code's content or a\n * QR-bill's or an EPC QR code's text (`joinedText` in `inlines.ts`), and a\n * QR code's content that prints nothing at all. A preview encodes them as they resolve, as a\n * paragraph prints them.\n *\n * A report that is an e-invoice reads three more names wherever `totals`\n * is read -- `invoice`, `vatBasis` and `vatAmount` -- once its totals are\n * computed (`lower-e-invoice.ts`), before anything is lowered.\n */\nimport type { Decimal } from '@formancy/expressions'\nimport type { ExpressionValues } from '@formancy/report-core'\nimport type { FieldRef, FieldType, ParameterType, ReportDefinition } from '@formancy/report-spec'\nimport type { CheckedData, CheckedRecord } from './data.js'\nimport type { TextStyle } from './document.js'\nimport type { ReportExpressions } from './evaluate.js'\nimport type { CurrencyScope, Formatter, TypedValue } from './format.js'\nimport type { CheckedParameters } from './parameters.js'\nimport { fromEvaluation } from './resolve-errors.js'\nimport type { Problems } from './resolve-errors.js'\nimport type { OrderedRow, RowGroup } from './sort-group.js'\nimport type { ImageValue } from './values.js'\n\n/** An approved asset, named as report-spec names one: by id, pinned by digest. */\nexport interface ImageRef {\n readonly asset: string\n readonly digest: string\n}\n\n/** What the host holds for an approved asset: its bytes, already fetched, and their media type. */\nexport interface ImageBytes {\n readonly mediaType: string\n readonly bytes: Uint8Array\n}\n\n/**\n * The host's lookup of an approved asset's bytes by its id and digest, or\n * undefined when it has none. Never an address: the runtime fetches\n * nothing. One lookup answers for every asset a report names -- an image it\n * draws, or a font it prints in (0043) -- by the id and digest the report\n * pinned.\n */\nexport type AssetResolver = (ref: ImageRef) => ImageBytes | undefined\n\n/** @deprecated The resolver's former name, kept for a release; use `AssetResolver`, which answers for fonts too. */\nexport type ImageResolver = AssetResolver\n\n/** Each aggregate's value over some rows, by id: a typed value, or null where it has none. */\nexport type AggregateValues = ReadonlyMap<string, TypedValue | null>\n\n/** The totals of one render: each aggregate over every row, and the same over any of them -- a group's, or the rows a table selects -- each known by its index in the data. */\nexport interface Totals {\n readonly report: AggregateValues\n over(rows: readonly OrderedRow[]): AggregateValues\n}\n\n/**\n * What a render that is an e-invoice computed before it lowered anything\n * (`lower-e-invoice.ts`), for lowering to read.\n */\nexport interface InvoiceReads {\n /** What `invoice`, `vatBasis` and `vatAmount` hold. */\n readonly names: ExpressionValues\n /**\n * Each value a column that prints a term of each line gave, by the path\n * of the column's value, one for each detail row by its index in the\n * data: what the table prints, so that it prints what the XML holds.\n */\n readonly columns: ReadonlyMap<string, readonly (TypedValue | null)[]>\n /** What a payment code printed with the e-invoice may ask for: the amount due (BT-115), and the payment account (BT-84) once its rule took it, undefined where none did. */\n readonly payable: { readonly amount: Decimal; readonly account: string | undefined }\n}\n\n/** One resolution's inputs, checked, and what it collects. */\nexport interface Render {\n /** The copy validation read. */\n readonly report: ReportDefinition\n readonly expressions: ReportExpressions\n readonly formatter: Formatter\n readonly params: CheckedParameters\n readonly data: CheckedData\n readonly problems: Problems\n readonly preview: boolean\n readonly images: AssetResolver | undefined\n /** Each print style, by id, as the document's style. */\n readonly styles: ReadonlyMap<string, TextStyle>\n readonly totals: Totals\n /** What the e-invoice computed before lowering, where the report is one. */\n readonly invoice?: InvoiceReads\n}\n\n/** Where a value is read: what its expressions are handed, where its currency comes from, and what an error there names. */\nexport interface Scope {\n readonly values: ExpressionValues\n readonly currency: CurrencyScope\n /** The current table's aggregates, over the rows it prints: in its total rows, and its group's header and footer. */\n readonly table?: AggregateValues\n /** The current group's aggregates, in a group's header and footer. */\n readonly group?: AggregateValues\n /** The record a detail field is read from: the current row, or a group's first row, whose key every row of the group shares. */\n readonly record?: CheckedRecord\n /** The current row's index in the data as the provider gave it, for an error to name. */\n readonly row?: number\n}\n\n/** Each aggregate's value as an expression is handed it: the typed value's own, or null. */\nfunction raw(values: AggregateValues): Record<string, unknown> {\n return Object.fromEntries([...values].map(([id, value]) => [id, value === null ? null : value.value]))\n}\n\n/** The header record, or none when the report declares no header dataset. */\nfunction headerOf(render: Pick<Render, 'data'>): CheckedRecord {\n return render.data.header ?? {}\n}\n\n/** The e-invoice's names, read wherever `totals` is, once they are computed; none in a report that is no e-invoice. */\nfunction invoiceNames(render: Pick<Render, 'invoice'>): ExpressionValues {\n return render.invoice?.names ?? {}\n}\n\nexport function reportScope(render: Pick<Render, 'params' | 'data' | 'invoice'>, totals: AggregateValues): Scope {\n const header = headerOf(render)\n return { values: { params: render.params, header, totals: raw(totals), ...invoiceNames(render) }, currency: { params: render.params, header } }\n}\n\n/** A table's total rows: the report's values, and the table's aggregates, over the rows it prints, as `table`. */\nexport function tableScope(render: Render, table: AggregateValues): Scope {\n const scope = reportScope(render, render.totals.report)\n return { ...scope, values: { ...scope.values, table: raw(table) }, table }\n}\n\n/**\n * A group's header and footer: the table's scope, and the group's\n * aggregates and key as `group`. `by` is the field grouped by; where a\n * preview's rows lack it the key is missing, as the field is, not null.\n */\nexport function groupScope(render: Render, group: RowGroup, aggregates: AggregateValues, table: AggregateValues, by: string): Scope {\n const record = (group.rows[0] as OrderedRow).record\n const header = headerOf(render)\n const key = Object.hasOwn(record, by) ? { key: group.key } : {}\n return {\n values: {\n params: render.params,\n header,\n totals: raw(render.totals.report),\n table: raw(table),\n group: { ...raw(aggregates), ...key },\n ...invoiceNames(render),\n },\n currency: { params: render.params, header, row: record },\n table,\n group: aggregates,\n record,\n }\n}\n\n/** One detail row: the report's values, and the row's as `row`. */\nexport function rowScope(render: Pick<Render, 'params' | 'data' | 'invoice'>, totals: AggregateValues, row: OrderedRow): Scope {\n const header = headerOf(render)\n return {\n values: { params: render.params, header, totals: raw(totals), row: row.record, ...invoiceNames(render) },\n currency: { params: render.params, header, row: row.record },\n record: row.record,\n row: row.index,\n }\n}\n\n/** A failed evaluation: an error, or in a preview a value the data lacks, which is a warning. Returns whether it was only a warning. */\nfunction failed(render: Pick<Render, 'problems' | 'preview'>, outcome: { readonly error: Parameters<typeof fromEvaluation>[0] }): boolean {\n if (render.preview && outcome.error.code === 'missing-value') {\n // Said once for the expression, naming the first row, not once per row: the data check has already said which field is missing.\n const error = fromEvaluation(outcome.error)\n render.problems.warn({ ...error, message: `${error.message}; this preview prints nothing for it` })\n return true\n }\n render.problems.error(fromEvaluation(outcome.error))\n return false\n}\n\n/** The value of the expression whose `cel` is at `path`, read in `scope`; null for none, undefined when it failed and the failure is recorded. */\nexport function valueOf(render: Pick<Render, 'expressions' | 'problems' | 'preview'>, scope: Scope, path: string): TypedValue | null | undefined {\n const outcome = render.expressions.evaluate(path, scope.values, scope.row)\n if (outcome.ok) return outcome.value\n return failed(render, outcome) ? null : undefined\n}\n\n/** Whether the condition whose `cel` is at `path` holds in `scope`; undefined when it failed and the failure is recorded as an error. */\nexport function holds(render: Pick<Render, 'expressions' | 'problems' | 'preview'>, scope: Scope, path: string): boolean | undefined {\n const outcome = render.expressions.condition(path, scope.values, scope.row)\n if (outcome.ok) return outcome.value\n return failed(render, outcome) ? false : undefined\n}\n\n/** The type the report's contract gives `ref`'s field; the validator has checked that it declares one. */\nexport function fieldType(report: ReportDefinition, ref: FieldRef): FieldType {\n return report.datasets[ref.dataset]?.fields.find(({ id }) => id === ref.field)?.type as FieldType\n}\n\nexport function parameterType(report: ReportDefinition, parameter: string): ParameterType {\n return report.parameters.find(({ id }) => id === parameter)?.type as ParameterType\n}\n\n/**\n * The value of `ref`, typed by its contract: a header field's from the\n * header, a detail field's from `record`. Null where it is null, and where\n * a preview's data lacks it, which the data check has already warned of. An\n * image field is drawn, never printed (0007), and reads as null here.\n */\nexport function fieldValue(render: Pick<Render, 'report' | 'data'>, record: CheckedRecord | undefined, ref: FieldRef): TypedValue | null {\n const value = (ref.dataset === 'header' ? render.data.header : record)?.[ref.field] ?? null\n const type = fieldType(render.report, ref)\n if (value === null || type === 'image') return null\n return { type, value } as TypedValue\n}\n\n/** An image field's value in the header: an approved asset, or null when there is none to draw. */\nexport function imageValue(render: Pick<Render, 'data'>, ref: FieldRef): ImageValue | null {\n return (render.data.header?.[ref.field] as ImageValue | null | undefined) ?? null\n}\n","/**\n * The report's aggregates, computed exactly, once, here (0007): over every\n * detail row for `totals`, over a group's rows for `group`, and over the\n * rows a table's condition selects for `table` (0062).\n *\n * - **In report-core's order.** An aggregate's expression may read another\n * aggregate's total, so each is computed after every one it reads, in the\n * order `compileReport` gives (0009); an aggregate that could never be\n * computed has already refused the report.\n * - **Each row read once.** What an aggregate reads from a row is read once\n * per render, with the report's totals, and kept by the row's index; a\n * group's aggregate, and a table's, is the same function over its rows'\n * values. So a group's subtotal and the report's total are totals of the\n * same values, and the subtotals of a sum that declares no rounding add\n * up to the total. A declared rounding is applied to each group's exact\n * sum and to the report's, once each, so rounded subtotals need not add\n * up to the rounded total: two groups of 0.02, rounded to 0.05, print\n * 0.00 and 0.00 over 0.05.\n * - **Exact, and of one kind.** Integers as BigInt, decimals as `Decimal`,\n * through `decimal.ts`; nothing passes through a JavaScript number. A\n * total report-core compiled as a decimal is a decimal, its 0 too, and so\n * is one whose kind the compiler could not tell (`dyn`) once it declares a\n * rounding or meets a decimal; a group's total, and a table's, is of the\n * report total's kind, so an expression reading `group.<id>` or\n * `table.<id>` meets one type.\n * - **Nulls are skipped**, and so is a value a preview's data lacks. Over no\n * values a count and a sum are 0 and the rest null (0007).\n * - **Declared rounding is applied once**, to the exact result: an average\n * always declares one, and a sum, a minimum or a maximum of decimals may.\n * A rounding on a total that is an integer or a moment is refused, never\n * ignored.\n */\nimport { compareDecimal, Decimal } from '@formancy/expressions'\nimport type { AggregateDef, Rounding } from '@formancy/report-spec'\nimport { averageDecimals, roundDecimalAs, sumDecimals } from './decimal.js'\nimport type { TypedValue } from './format.js'\nimport { fieldValue, rowScope, valueOf } from './render-context.js'\nimport type { AggregateValues, Render, Totals } from './render-context.js'\nimport type { ResolveErrorCode } from './resolve-errors.js'\nimport type { OrderedRow } from './sort-group.js'\nimport { fixedWidth } from './sort-group.js'\n\n/** Why a total has no value: its code and what to say. */\ninterface Refusal {\n readonly code: ResolveErrorCode\n readonly message: string\n}\n\ntype Total = TypedValue | null | Refusal\n\nconst isRefusal = (value: Total): value is Refusal => value !== null && 'code' in value\n\nconst integer = (value: bigint): TypedValue => ({ type: 'integer', value })\nconst decimal = (value: Decimal): TypedValue => ({ type: 'decimal', value })\n/** A number as a decimal: an integer at no places. */\nexport const asDecimal = (value: TypedValue): Decimal => (value.type === 'integer' ? new Decimal(value.value, 0) : (value.value as Decimal))\n\n/** Values as numbers of one kind: integers while every one is and decimals are not asked for, else decimals; undefined when one is not a number. */\nfunction numbers(\n values: readonly TypedValue[],\n decimals: boolean,\n): { readonly integers: readonly bigint[] } | { readonly decimals: readonly Decimal[] } | undefined {\n if (!decimals && values.every((value) => value.type === 'integer')) return { integers: values.map((value) => value.value) }\n if (!values.every((value) => value.type === 'integer' || value.type === 'decimal')) return undefined\n return { decimals: values.map(asDecimal) }\n}\n\nconst NOT_NUMBERS: Refusal = { code: 'aggregate-value-type', message: 'totals integers and decimals, and a value it read is neither' }\n\nfunction sum(values: readonly TypedValue[], decimals: boolean): Total {\n const read = numbers(values, decimals)\n if (read === undefined) return NOT_NUMBERS\n return 'integers' in read ? integer(read.integers.reduce((total, value) => total + value, 0n)) : decimal(sumDecimals(read.decimals))\n}\n\nfunction average(values: readonly TypedValue[], rounding: Rounding): Total {\n const read = numbers(values, true) as { readonly decimals: readonly Decimal[] } | undefined\n if (read === undefined) return NOT_NUMBERS\n const result = averageDecimals(read.decimals, rounding)\n return result === null ? null : decimal(result)\n}\n\nconst ordered = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0)\n\n/**\n * -1, 0 or 1 for two values of one kind: numbers by value, text as the\n * report's language sorts it, through `collator`, dates as days, moments in\n * time order. Text met without a collator is a defect: a total handed none\n * -- a chart's series, which totals numbers alone -- would otherwise order\n * it by code unit, which no reader takes for their language's order.\n */\nfunction comparator(values: readonly TypedValue[], collator: Intl.Collator | undefined): ((a: TypedValue, b: TypedValue) => number) | undefined {\n const types = new Set(values.map(({ type }) => type))\n if ([...types].every((type) => type === 'integer' || type === 'decimal')) return (a, b) => compareDecimal(asDecimal(a), asDecimal(b))\n const only = types.size === 1 ? [...types][0] : undefined\n if (only === 'string') {\n if (collator === undefined) throw new RangeError(\"a least or greatest of text is ordered by the report's collator, and none was handed: a defect\")\n return (a, b) => collator.compare(a.value as string, b.value as string)\n }\n if (only === 'date') return (a, b) => ordered(a.value as string, b.value as string)\n if (only === 'datetime' || only === 'instant') return (a, b) => ordered(fixedWidth(a.value as string), fixedWidth(b.value as string))\n return undefined\n}\n\n/** The least (`sign` -1) or greatest (1) value, the first of equals as written; null over none. */\nfunction extreme(values: readonly TypedValue[], sign: -1 | 1, decimals: boolean, collator: Intl.Collator | undefined): Total {\n const compare = comparator(values, collator)\n if (compare === undefined)\n return { code: 'aggregate-value-type', message: 'takes the least or greatest of values of one kind, and the values it read are of several' }\n const found = values.reduce<TypedValue | null>((kept, value) => (kept === null || Math.sign(compare(value, kept)) === sign ? value : kept), null)\n return found?.type === 'integer' && decimals ? decimal(asDecimal(found)) : found\n}\n\n/** `total` rounded as `rounding` declares: a decimal at the rounding's scale. */\nfunction rounded(total: Total, rounding: Rounding | undefined): Total {\n if (rounding === undefined || total === null || isRefusal(total)) return total\n if (total.type === 'decimal') return decimal(roundDecimalAs(total.value, rounding))\n return {\n code: 'rounding-not-decimal',\n message: `declares a rounding, and its total is ${total.type === 'integer' ? 'an integer' : `a ${total.type}`}, which has no places to round`,\n }\n}\n\n/** What totalling a definition comes to: its total, or why it has none. */\nexport type TotalOutcome =\n { readonly ok: true; readonly value: TypedValue | null } | { readonly ok: false; readonly code: ResolveErrorCode; readonly message: string }\n\n/** Whether a total the compiler typed as `type` is totalled in decimals: one it typed a decimal, or could not tell and declares a rounding. */\nexport function totalsInDecimals(type: string | undefined, rounding: Rounding | undefined): boolean {\n return type === 'decimal' || (type === 'dyn' && rounding !== undefined)\n}\n\n/**\n * The aggregate over the values read from some rows -- each null or typed --\n * or over `rows` rows when it reads nothing: the one rule every total is\n * computed by, the report's, a group's and a chart's series'. `collator`\n * orders text, for a least or a greatest of it; a total of numbers needs none.\n */\nexport function totalOf(\n aggregate: AggregateDef,\n decimals: boolean,\n read: readonly (TypedValue | null)[] | undefined,\n rows: number,\n collator?: Intl.Collator,\n): TotalOutcome {\n const values = (read ?? []).filter((value): value is TypedValue => value !== null)\n let total: Total\n switch (aggregate.fn) {\n case 'count':\n total = rounded(integer(BigInt(read === undefined ? rows : values.length)), aggregate.rounding)\n break\n case 'avg':\n // report-spec requires an average to declare its rounding.\n total = values.length === 0 ? null : average(values, aggregate.rounding as Rounding)\n break\n case 'sum':\n total = rounded(sum(values, decimals), aggregate.rounding)\n break\n case 'min':\n total = rounded(extreme(values, -1, decimals, collator), aggregate.rounding)\n break\n case 'max':\n total = rounded(extreme(values, 1, decimals, collator), aggregate.rounding)\n break\n }\n return isRefusal(total) ? { ok: false, ...total } : { ok: true, value: total }\n}\n\n/**\n * Every aggregate of `render`'s report, over its detail rows and, through\n * `over`, over any of them; or undefined when one could not be computed,\n * each reason recorded. `render` has every input but the totals.\n */\nexport function computeTotals(render: Omit<Render, 'totals'>): Totals | undefined {\n const { report, expressions, data, problems } = render\n const collator = new Intl.Collator(report.locale, { usage: 'sort' })\n const rows: readonly OrderedRow[] = data.detail.map((record, index) => ({ index, record }))\n const read = new Map<string, readonly (TypedValue | null)[]>()\n const totals = new Map<string, TypedValue | null>()\n // Whether each aggregate's group totals are decimals: its report total's kind, which a group's values share.\n const inDecimals = new Map<string, boolean>()\n const refuse = (index: number, refusal: Refusal): void => {\n problems.error({\n stage: 'resolve',\n code: refusal.code,\n path: `/aggregates/${index}`,\n message: `aggregate ${report.aggregates[index]?.id} ${refusal.message}`,\n })\n }\n let computed = true\n\n for (const id of expressions.compilation.aggregateOrder) {\n const index = report.aggregates.findIndex((aggregate) => aggregate.id === id)\n const aggregate = report.aggregates[index] as AggregateDef\n const compiled = expressions.compilation.members.totals.get(id)?.type\n const decimals = totalsInDecimals(compiled, aggregate.rounding)\n const of = aggregate.of\n if (of !== undefined) {\n const path = `/aggregates/${index}/of/expression/cel`\n const values = rows.map((row) => (of.kind === 'field' ? fieldValue(render, row.record, of.field) : valueOf(render, rowScope(render, totals, row), path)))\n if (values.some((value) => value === undefined)) {\n computed = false\n continue\n }\n read.set(id, values as (TypedValue | null)[])\n }\n const outcome = totalOf(aggregate, decimals, read.get(id), rows.length, collator)\n if (!outcome.ok) {\n computed = false\n refuse(index, outcome)\n continue\n }\n const total = outcome.value\n totals.set(id, total)\n // A group's total is of its report total's kind: one that met a decimal is a decimal in every group.\n inDecimals.set(id, decimals || total?.type === 'decimal')\n }\n if (!computed) return undefined\n\n return {\n report: totals,\n over(group: readonly OrderedRow[]): AggregateValues {\n const values = new Map<string, TypedValue | null>()\n for (const aggregate of report.aggregates) {\n const each = read.get(aggregate.id)\n const grouped = totalOf(\n aggregate,\n inDecimals.get(aggregate.id) as boolean,\n each && group.map((row) => each[row.index] as TypedValue | null),\n group.length,\n collator,\n )\n // Never refused: a group's values, and a table's, are some of those\n // the report's total took, of the kinds it took, totalled as the\n // same kind and rounded as it was, and a share of values has no\n // kind the whole lacks.\n if (!grouped.ok) {\n throw new RangeError(\n `a total of some rows of aggregate ${aggregate.id} was refused as ${grouped.code} after the report's was not: a defect, refused rather than printed as nothing`,\n )\n }\n values.set(aggregate.id, grouped.value)\n }\n return values\n },\n }\n}\n","/**\n * A chart of the detail rows, lowered to the block a renderer draws: every\n * number it prints and every word, decided here, once, by the rules a\n * table's are decided by, so that a chart never disagrees with the table\n * beside it. In order:\n *\n * 1. **Its categories**, grouped where a table's rows are grouped\n * (`categoryGroups`): in the data's order, each key once at its first\n * row, or sorted, the rows without one last. More than\n * `MAX_CHART_CATEGORIES`, or a pie of more categories than its palette\n * has colours -- two slices of one colour are told apart by nothing --\n * is refused before anything is totalled.\n * 2. **Each category's label**: its key in the category's format, or for\n * the rows without one the chart's `nullLabel`. In a preview a field the\n * data lacks reads as null; with no `nullLabel` it prints nothing, the\n * data check having warned.\n * 3. **Each series' value at each category**, by `totalOf`, the one rule\n * every total is computed by, in the decimals an aggregate of the same\n * function over the same field is totalled in (report-core's\n * `seriesType`, `totalsInDecimals`), and so rounded and refused alike;\n * printed in the chart's value format, read where the report is.\n * 4. **Nothing to draw** -- no rows, a bar or a line chart with no value, a\n * pie whose values are all zero -- is the chart's title and empty text,\n * and nothing else.\n * 5. **A bar or a line chart's value axis** (`chartTicks`), each tick in the\n * value format, and a legend of its series where it has more than one.\n * 6. **A pie's slices**, a negative one refused, and a legend of its\n * categories; where it labels its values, each entry says its value and\n * its share, the exact ratio rounded once to `SHARE_PLACES` places of a\n * percentage, which `Formatter.percent` prints without rounding again.\n * The whole a share is of is the sum of the slices as they are totalled\n * and drawn -- each rounded where its series declares a rounding -- not\n * a total over every row.\n *\n * A refusal names the chart by its id and says counts, never a value, a\n * label or a category, each of which may be the data's.\n */\nimport type { Decimal } from '@formancy/expressions'\nimport { seriesType } from '@formancy/report-core'\nimport { CHART_PALETTE } from '@formancy/report-spec'\nimport type { AggregateDef, ChartComponent, ChartSeries } from '@formancy/report-spec'\nimport type { AxisChart, Chart, ChartLegendEntry, ChartSeriesValues, ChartValue, PieChart } from './chart-document.js'\nimport { chartTicks } from './chart-ticks.js'\nimport { ratioRounded, sumDecimals } from './decimal.js'\nimport type { TextStyle } from './document.js'\nimport { plainText } from './format.js'\nimport type { CurrencyScope, Formatted, PrintableType, TypedValue } from './format.js'\nimport { fieldType, fieldValue, reportScope } from './render-context.js'\nimport type { Render } from './render-context.js'\nimport type { ResolveErrorCode } from './resolve-errors.js'\nimport { categoryGroups } from './sort-group.js'\nimport type { RowGroup } from './sort-group.js'\nimport { asDecimal, totalOf, totalsInDecimals } from './totals.js'\n\n/**\n * The most categories a chart groups its rows into: 200, chosen as a bound\n * on one chart's work, totalling every series at every category. How many\n * a box draws legibly is the renderer's to say, and so is how many charts\n * a render draws together: the renderer's `MAX_CHART_DRAWING` (0058) weighs\n * a render's charts and refuses them past it.\n *\n * What the costliest of eight chart forms tried costs a render, at one\n * packing, measured on 2026-11-15 on a Mac (Apple M2) under Node 22.23.4,\n * ECharts 6.1.0, with the machine at a load average of about 5 from other\n * work: three charts to an A4 landscape page, zero margins, each as wide\n * as the page and a third of its height, eight series where it has them,\n * value labels off, and `renderPdf` run seven times to each page after a\n * warm-up. Each form is the largest `drawChart` does not refuse: a line\n * chart of 8 series and the full 200 categories, whose empty labels are no\n * word, took a median of 586 ms (549 to 849) against 4.6 ms for the same\n * page without charts; the same chart with one-letter labels, refused past\n * 123 categories, 430 ms; the most categories a bar chart draws, 186 of\n * one series, 77 ms. The bound stays, for one chart's work; how many\n * charts a render draws, and so what a page costs, is the renderer's\n * `MAX_CHART_DRAWING`, which refuses that page of three 8 × 200 lines at\n * its third chart, at 5,016 units, and admits two. The renderer's word\n * checks took under 1 ms of any page.\n */\nexport const MAX_CHART_CATEGORIES = 200\n\n/** The places of a percentage a pie's share prints at: 12.5 %. */\nexport const SHARE_PLACES = 1\n\n/** What one chart is lowered with. */\ninterface Charting {\n readonly render: Render\n readonly chart: ChartComponent\n readonly path: string\n /** Where a currency format finds its currency: the report's scope, since a chart has no current row. */\n readonly currency: CurrencyScope\n /** The colours it paints, by series (bar, line) or by category (pie). */\n readonly palette: readonly string[]\n}\n\n/** What every kind of chart holds but its legend and its marks. */\ntype Frame = Pick<Chart, 'kind' | 'id' | 'width' | 'height' | 'style' | 'title'>\n\n/** Records a refusal of the chart at `at`; undefined, for its caller to return. */\nfunction refuse(c: Charting, code: ResolveErrorCode, at: string, message: string): undefined {\n c.render.problems.error({ stage: 'resolve', code, path: at, message, componentId: c.chart.id })\n return undefined\n}\n\n/** `formatted`'s text, or undefined when the formatter refused it, which is recorded at `at`. */\nfunction said(c: Charting, formatted: Formatted, at: string): string | undefined {\n if (formatted.ok) return formatted.text\n c.render.problems.error({ stage: 'format', code: formatted.code, path: at, message: `chart ${c.chart.id}: ${formatted.message}`, componentId: c.chart.id })\n return undefined\n}\n\n/** A value as the block holds it: its exact digits, and its text in the chart's value format. */\nfunction charted(c: Charting, value: TypedValue): ChartValue | undefined {\n const text = said(c, c.render.formatter.format(value, c.chart.valueFormat, c.currency), `${c.path}/valueFormat`)\n return text === undefined ? undefined : { exact: plainText(value), text }\n}\n\n/** Each of `values` as the block holds it, null as null; undefined once one could not be printed, which is recorded, and nothing after it is tried. */\nfunction chartedAll<T extends TypedValue | null>(c: Charting, values: readonly T[]): (T extends null ? null : ChartValue)[] | undefined {\n const found: (ChartValue | null)[] = []\n for (const value of values) {\n const each = value === null ? null : charted(c, value)\n if (each === undefined) return undefined\n found.push(each)\n }\n return found as (T extends null ? null : ChartValue)[]\n}\n\n/**\n * Each category's label, in order: its key, of the category field's `type`,\n * as `categoryGroups` read it once, in the category's format; undefined\n * when one could not be printed, which is recorded.\n */\nfunction labels(c: Charting, groups: readonly RowGroup[], type: PrintableType): string[] | undefined {\n const { format, nullLabel } = c.chart.category\n const found: string[] = []\n for (const { key } of groups) {\n const typed = { type, value: key } as TypedValue\n const label = key === null ? (nullLabel ?? '') : said(c, c.render.formatter.format(typed, format, c.currency), `${c.path}/category`)\n if (label === undefined) return undefined\n found.push(label)\n }\n return found\n}\n\n/** `series` as the aggregate of its definition: the same function, over the same field, rounded as it declares. */\nfunction asAggregate(series: ChartSeries): AggregateDef {\n return {\n id: series.id,\n fn: series.fn,\n ...(series.of === undefined ? {} : { of: { kind: 'field', field: series.of } }),\n ...(series.rounding === undefined ? {} : { rounding: series.rounding }),\n }\n}\n\n/**\n * Each series' total at each category, null where it has none; undefined\n * when a series could not be totalled, which is recorded once for it. The\n * validator types every field a series reads, and report-core refuses a\n * rounding with no places to round before anything renders; one refused\n * here all the same is refused as an aggregate's is, never drawn.\n */\nfunction totals(c: Charting, groups: readonly RowGroup[]): (TypedValue | null)[][] | undefined {\n const { render, chart } = c\n let refused = false\n const found = chart.series.map((series, index) => {\n const aggregate = asAggregate(series)\n const decimals = totalsInDecimals(seriesType(render.report, series).type, series.rounding)\n const of = series.of\n const values: (TypedValue | null)[] = []\n for (const group of groups) {\n const read = of === undefined ? undefined : group.rows.map((row) => fieldValue(render, row.record, of))\n // No collator: a series takes no least or greatest of text (report-spec's validator), and a count orders nothing.\n const outcome = totalOf(aggregate, decimals, read, group.rows.length)\n if (!outcome.ok) {\n refused = true\n refuse(c, outcome.code, `${c.path}/series/${index}`, `series ${series.id} of chart ${chart.id} ${outcome.message}`)\n break\n }\n values.push(outcome.value)\n }\n return values\n })\n return refused ? undefined : found\n}\n\n/** A bar or a line chart over `values`, one list for each series; with no value at all, its empty text. */\nfunction axisChart(c: Charting, frame: Frame, categories: readonly string[], values: readonly (readonly (TypedValue | null)[])[]): AxisChart | undefined {\n const { chart } = c\n const kind = chart.chart as AxisChart['chart']\n const valueLabels = chart.valueLabels === true\n const exact = values.flat().flatMap((total) => (total === null ? [] : [asDecimal(total)]))\n if (exact.length === 0) return { ...frame, chart: kind, legend: [], empty: chart.emptyText, categories: [], series: [], ticks: [], valueLabels }\n const series: ChartSeriesValues[] = []\n for (const [index, each] of values.entries()) {\n const printed = chartedAll(c, each)\n if (printed === undefined) return undefined\n series.push({ color: c.palette[index] as string, values: printed })\n }\n const ticks = chartedAll(\n c,\n chartTicks(exact, kind, chart.valueFormat.scale).map((tick): TypedValue => ({ type: 'decimal', value: tick })),\n )\n if (ticks === undefined) return undefined\n const legend: ChartLegendEntry[] = chart.series.length > 1 ? chart.series.map(({ label }, index) => ({ text: label, color: c.palette[index] as string })) : []\n return {\n ...frame,\n chart: kind,\n ...(chart.categoryTitle === undefined ? {} : { categoryTitle: chart.categoryTitle }),\n ...(chart.valueTitle === undefined ? {} : { valueTitle: chart.valueTitle }),\n legend,\n categories,\n series,\n ticks,\n valueLabels,\n }\n}\n\n/**\n * A pie over `values`, a sum or a count at each category, which is never\n * null: a negative one refused; all zero, its empty text; otherwise a\n * slice and a legend entry for each, its share in the entry where the\n * chart labels its values.\n */\nfunction pieChart(c: Charting, frame: Frame, categories: readonly string[], values: readonly TypedValue[]): PieChart | undefined {\n const { chart, path } = c\n const exact = values.map(asDecimal)\n if (exact.some((value) => value.units < 0n)) {\n return refuse(\n c,\n 'chart-negative-share',\n `${path}/series/0`,\n `chart ${chart.id} is a pie, and a category of it totals less than nothing, which is no share of a whole`,\n )\n }\n const total = sumDecimals(exact)\n if (total.units === 0n) return { ...frame, chart: 'pie', legend: [], empty: chart.emptyText, slices: [] }\n const printed = chartedAll(c, values)\n if (printed === undefined) return undefined\n const legend: ChartLegendEntry[] = []\n for (const [index, value] of printed.entries()) {\n const label = categories[index] as string\n let text = label\n if (chart.valueLabels === true) {\n const share = ratioRounded(exact[index] as Decimal, total, { scale: SHARE_PLACES + 2, mode: 'half-away-from-zero' })\n // Never refused: a share is at exactly `SHARE_PLACES + 2` places and at most 1, which `percent` prints as written.\n // Were it, the refusal would stand at the series whose share it is: no value format prints a share.\n const percent = said(c, c.render.formatter.percent(share, SHARE_PLACES), `${path}/series/0`)\n if (percent === undefined) return undefined\n text = `${label}: ${value.text} (${percent})`\n }\n legend.push({ text, color: c.palette[index] as string })\n }\n return { ...frame, chart: 'pie', legend, slices: printed.map((value, index) => ({ color: c.palette[index] as string, value })) }\n}\n\n/**\n * `chart`, at `path`, as the block a renderer draws, `style` its words'\n * resolved style; undefined when it is refused, the reason recorded.\n */\nexport function chartBlock(render: Render, chart: ChartComponent, path: string, style: TextStyle | undefined): Chart | undefined {\n const c: Charting = { render, chart, path, currency: reportScope(render, render.totals.report).currency, palette: chart.palette ?? CHART_PALETTE }\n const by = { field: chart.category.field.field, type: fieldType(render.report, chart.category.field) as PrintableType }\n const groups = categoryGroups(render.data.detail, by, chart.category.order, render.report.locale)\n if (groups.length > MAX_CHART_CATEGORIES) {\n const message = `chart ${chart.id} groups its rows into ${groups.length} categories, and a chart groups at most ${MAX_CHART_CATEGORIES}`\n return refuse(c, 'chart-too-many-categories', `${path}/category`, message)\n }\n if (chart.chart === 'pie' && groups.length > c.palette.length) {\n const message = `chart ${chart.id} is a pie of ${groups.length} categories; a pie colours each slice apart, and its palette has ${c.palette.length} colours`\n return refuse(c, 'chart-too-many-categories', `${path}/category`, message)\n }\n const categories = labels(c, groups, by.type)\n const values = categories && totals(c, groups)\n if (categories === undefined || values === undefined) return undefined\n const frame: Frame = {\n kind: 'chart',\n id: chart.id,\n width: chart.width,\n height: chart.height,\n ...(style === undefined ? {} : { style }),\n ...(chart.title === undefined ? {} : { title: chart.title }),\n }\n return chart.chart === 'pie' ? pieChart(c, frame, categories, (values[0] ?? []) as TypedValue[]) : axisChart(c, frame, categories, values)\n}\n","/**\n * A report's expressions, compiled once and evaluated against checked data,\n * within a budget, each failure an error that says where.\n *\n * - **One compilation.** `@formancy/report-core`'s `compileReport` compiles\n * every expression where it stands, and the editor's diagnostics come\n * from the same function (0009). A report its diagnostics give an error\n * for is refused before anything is evaluated, so the runtime never runs\n * what the editor refuses. Each expression is compiled once per render,\n * never once per row -- twice, in fact, since `diagnose` does not hand\n * back the compilation it made.\n * - **One binding.** Each program's values are made by report-core's\n * `expressionValues`: an integer as a BigInt, a decimal as a `Decimal`,\n * an instant as a moment, a date as its ISO string. A value missing, or of\n * another type, fails the evaluation, naming the member and never quoting\n * the value.\n * - **Nothing differs between renders.** The diagnostics refuse `now()`,\n * `today()` and `random()`; the capabilities an evaluation is handed are\n * fixed besides, so that one reached anyway would answer the same in every\n * render.\n * - **Bounded.** Each evaluation has a budget of steps, and a render has one\n * for all its evaluations together. Past either, the evaluation is refused.\n * - **A failure is an error, never a blank.** It names the component, the\n * table column or the aggregate, and the detail row, and gives upstream's\n * code for what went wrong, never upstream's message, which can quote the\n * values it was computing with.\n *\n * What an expression gives is handed back typed as the runtime holds values:\n * an integer as a BigInt, an instant in UTC. A list or a map, which has no\n * text, is refused. A double never arrives: the diagnostics refuse every\n * double literal, every `double()` and every `/` before anything is\n * evaluated (report-core's `exactness.ts`), since upstream hands an integer\n * and a double back alike, as a JavaScript number, and `int()` of a double\n * would otherwise print as an exact integer. A number that is not a safe\n * integer is still refused here, rather than printed.\n */\nimport { DEFAULT_BUDGET, Decimal, evaluate, fixedCapabilities } from '@formancy/expressions'\nimport type { Capabilities, ExpressionValue } from '@formancy/expressions'\nimport { compileReport, diagnose, expressionValues } from '@formancy/report-core'\nimport type { CompiledExpression, Diagnostic, ExpressionValues, ReportCompilation } from '@formancy/report-core'\nimport { reportIn } from '@formancy/report-spec'\nimport type { ReportDefinition } from '@formancy/report-spec'\nimport type { TypedValue } from './format.js'\nimport { refuses } from './languages.js'\nimport { canonicalInstant } from './values.js'\n\n/**\n * Steps one evaluation may take: upstream's default for a formancy form's\n * expression (`DEFAULT_BUDGET`). A report expression reads single values, so\n * the only way to spend many steps is a comprehension over a list literal;\n * the deepest the structural limits allow, 64 by 64, measured 8,385 steps,\n * and `evaluate.test.ts` holds that it fits while one reading three values\n * in each turn (28,865 steps) does not.\n */\nexport const EXPRESSION_STEP_BUDGET = DEFAULT_BUDGET.maxSteps\n\n/**\n * Steps every evaluation of one render may take together, each charged its\n * steps and one more for itself. Measured as a render spends them, through\n * `condition()` with each evaluation's binding included, on 15 October\n * 2026, on an Intel i9-10900K under Node 24.21 with `@formancy/expressions`\n * 0.5.0: ten million steps of `row.urgent` took 10.0 seconds (1.00\n * microseconds a step) and of `row.amount * dec(\"1.081\") > dec(\"10\")` 13.0\n * (1.30). An earlier measurement, of upstream's `evaluate` alone, had put\n * that budget at 8.5 seconds and missed the binding. So the budget is five\n * million: about 5 to 6.5 seconds of evaluation on that machine, against\n * the plan's investigation target of ten seconds in all for a hundred-page\n * report. A report of `MAX_DETAIL_ROWS` rows evaluating ten one-read\n * expressions per row spends 2,000,000.\n */\nexport const RENDER_STEP_BUDGET = 5_000_000\n\n/**\n * What `now()`, `today()` and `random()` would give: nothing a report may\n * read (0009), fixed so that one reached anyway gives the same answer in\n * every render.\n */\nexport const CAPABILITIES: Capabilities = fixedCapabilities({ nowMs: 0, today: '1970-01-01', random: 0 })\n\nexport const EVALUATION_ERROR_CODES = [\n /** A path at which the report has no compiled expression: the caller's defect. */\n 'unknown-expression',\n /** A member the expression reads has no value: a field a preview's data lacks, or a total not yet computed. */\n 'missing-value',\n /** A value of another type than its member's, which the data check admits none of. */\n 'unbound-value',\n /** Upstream refused the evaluation: a division by zero, an overflow, a result too large to hand back. */\n 'expression-failed',\n /** The evaluation took more than `EXPRESSION_STEP_BUDGET` steps. */\n 'expression-budget',\n /** The render has spent `RENDER_STEP_BUDGET` steps. */\n 'render-budget',\n /** A number that is not a safe integer: a double, which the diagnostics refuse before anything is evaluated. */\n 'inexact-value',\n /** A list, a map or anything else without text. */\n 'unprintable-value',\n /** A condition that gave something other than a boolean. */\n 'not-a-condition',\n] as const\nexport type EvaluationErrorCode = (typeof EVALUATION_ERROR_CODES)[number]\n\n/** Why an evaluation gave no value, and where. */\nexport interface EvaluationError {\n readonly code: EvaluationErrorCode\n /** For a person: where and what, never a value. */\n readonly message: string\n /** The JSON Pointer to the expression's `cel` in the report. */\n readonly path: string\n readonly componentId?: string\n readonly columnId?: string\n /** The aggregate whose expression this is, for one read from each row. */\n readonly aggregateId?: string\n /** The detail row's index in the data, when the expression read one. */\n readonly row?: number\n}\n\nexport type Evaluation = { readonly ok: true; readonly value: TypedValue | null } | { readonly ok: false; readonly error: EvaluationError }\n\nexport type ConditionEvaluation = { readonly ok: true; readonly value: boolean } | { readonly ok: false; readonly error: EvaluationError }\n\nexport interface ReportExpressions {\n /** What compiled: the programs by path, the members, and the order aggregates are computed in. */\n readonly compilation: ReportCompilation\n /** Steps this render has spent, each evaluation charged its steps and one more. */\n readonly spent: number\n /** The expression at `path` evaluated over `values`; `row` is the detail row's index, for an error to name. */\n evaluate(path: string, values: ExpressionValues, row?: number): Evaluation\n /** The condition at `path` -- a `visibleWhen` or a style rule's `when` -- evaluated over `values`. */\n condition(path: string, values: ExpressionValues, row?: number): ConditionEvaluation\n}\n\nexport type ExpressionsPreparation =\n | {\n readonly ok: true\n /** The report the expressions are of: the one prepared, written in the render's locale (report-spec's `reportIn`, 0063), with no translations. */\n readonly report: ReportDefinition\n readonly expressions: ReportExpressions\n }\n | { readonly ok: false; readonly diagnostics: readonly Diagnostic[] }\n\n/** The typed value an expression's result is, or why it is not one. Exported for its test alone. */\nexport function typed(result: ExpressionValue, resultType: string): TypedValue | null | { readonly code: EvaluationErrorCode; readonly what: string } {\n if (result === null) return null\n if (result instanceof Decimal) return { type: 'decimal', value: result }\n switch (typeof result) {\n case 'boolean':\n return { type: 'boolean', value: result }\n case 'string': {\n const instant = resultType === 'timestamp' ? canonicalInstant(result) : undefined\n return instant === undefined ? { type: 'string', value: result } : { type: 'instant', value: instant }\n }\n case 'number':\n // Upstream hands an integer back as a number, and refuses one it cannot hold exactly.\n if (Number.isSafeInteger(result)) return { type: 'integer', value: BigInt(result) }\n return { code: 'inexact-value', what: 'the expression gives a double, which is not exact; dec() keeps a number exact' }\n default:\n return { code: 'unprintable-value', what: 'the expression gives a list or a map, which has no text' }\n }\n}\n\n/** One render's evaluations of a report's expressions. */\nclass Evaluator implements ReportExpressions {\n readonly compilation: ReportCompilation\n readonly #aggregates: readonly string[]\n #spent = 0\n\n constructor(report: ReportDefinition, compilation: ReportCompilation) {\n this.compilation = compilation\n this.#aggregates = report.aggregates.map(({ id }) => id)\n }\n\n get spent(): number {\n return this.#spent\n }\n\n evaluate(path: string, values: ExpressionValues, row?: number): Evaluation {\n const compiled = this.compilation.expressions.get(path)\n if (compiled === undefined) return { ok: false, error: { code: 'unknown-expression', message: `the report has no expression at ${path}`, path } }\n const fail = (code: EvaluationErrorCode, what: string): Evaluation => ({ ok: false, error: this.#error(compiled, code, what, row) })\n for (const read of compiled.reads) {\n const scope = values[read.name]\n if (scope === undefined || !Object.hasOwn(scope, read.member))\n return fail('missing-value', `${read.name}.${read.member} has no value: it is missing, which is not null`)\n }\n let bound: Record<string, unknown>\n try {\n bound = expressionValues(compiled, values)\n } catch (error) {\n // report-core's refusal names the member and its type, and never quotes the value.\n return fail('unbound-value', (error as TypeError).message)\n }\n if (this.#spent >= RENDER_STEP_BUDGET) return fail('render-budget', `the render has spent its budget of ${RENDER_STEP_BUDGET} steps`)\n const maxSteps = Math.min(EXPRESSION_STEP_BUDGET, RENDER_STEP_BUDGET - this.#spent - 1)\n const outcome = evaluate(compiled.program, bound, { capabilities: CAPABILITIES, budget: { maxSteps } })\n if (!outcome.ok) {\n const exhausted = outcome.error.kind === 'budget'\n this.#spent += (exhausted ? maxSteps : 0) + 1\n if (!exhausted) return fail('expression-failed', `the expression failed (${outcome.error.code})`)\n if (maxSteps < EXPRESSION_STEP_BUDGET) return fail('render-budget', `the render has spent its budget of ${RENDER_STEP_BUDGET} steps`)\n return fail('expression-budget', `the expression took more than its budget of ${EXPRESSION_STEP_BUDGET} steps`)\n }\n this.#spent += outcome.steps + 1\n const value = typed(outcome.value, compiled.program.resultType)\n return value !== null && 'code' in value ? fail(value.code, value.what) : { ok: true, value }\n }\n\n condition(path: string, values: ExpressionValues, row?: number): ConditionEvaluation {\n const outcome = this.evaluate(path, values, row)\n if (!outcome.ok) return outcome\n if (outcome.value?.type === 'boolean') return { ok: true, value: outcome.value.value }\n const compiled = this.compilation.expressions.get(path) as CompiledExpression\n return { ok: false, error: this.#error(compiled, 'not-a-condition', 'a condition gives true or false, and this expression gives something else', row) }\n }\n\n /** An error about `compiled`, naming where it stands and the row it read. */\n #error(compiled: CompiledExpression, code: EvaluationErrorCode, what: string, row: number | undefined): EvaluationError {\n const { site } = compiled\n const aggregateId = site.path.startsWith('/aggregates/') ? this.#aggregates[Number(site.path.split('/')[2])] : undefined\n const place = [\n // The payment part and the e-invoice stand in no component, and are named as one would be.\n site.path.startsWith('/paymentPart/') ? 'the payment part' : site.path.startsWith('/eInvoice/') ? 'the e-invoice' : undefined,\n site.componentId === undefined ? undefined : `component ${site.componentId}`,\n site.columnId === undefined ? undefined : `column ${site.columnId}`,\n aggregateId === undefined ? undefined : `aggregate ${aggregateId}`,\n row === undefined ? undefined : `detail row ${row}`,\n ].filter((part) => part !== undefined)\n return {\n code,\n message: `${place.join(', ')}: ${what}`,\n path: site.path,\n ...(site.componentId === undefined ? {} : { componentId: site.componentId }),\n ...(site.columnId === undefined ? {} : { columnId: site.columnId }),\n ...(aggregateId === undefined ? {} : { aggregateId }),\n ...(row === undefined ? {} : { row }),\n }\n }\n}\n\n/**\n * `report`'s expressions compiled for one render in `locale`, or the\n * diagnostics that refuse it: every error `diagnose` gives, which the\n * editor shows too, that names no language or names `locale` (0063). What\n * is compiled is `report` written in `locale`, which the render prints.\n * `report` is one the validator accepts, and `locale` the report's own or\n * one it declares, as `printLocale` holds it. The evaluations of one\n * render share one budget, so a render prepares its own.\n */\nexport function prepareExpressions(report: ReportDefinition, locale: string = report.locale): ExpressionsPreparation {\n const errors = diagnose(report).filter((diagnostic) => refuses(diagnostic, locale))\n if (errors.length > 0) return { ok: false, diagnostics: errors }\n const printed = reportIn(report, locale)\n return { ok: true, report: printed, expressions: new Evaluator(printed, compileReport(printed)) }\n}\n","import type { Paragraph } from './document.js'\n\n/**\n * A label, as the runtime heads every page with one -- a preview's, an\n * XRechnung's copy's (0038), a copy of an e-invoice's (0077): the text\n * alone, small, bold and red, in a paragraph of its own.\n */\nexport const label = (text: string): Paragraph => ({ kind: 'paragraph', runs: [{ text }], style: { size: 8, bold: true, color: '#b00020' } })\n\n/** `paragraph` frozen through: its runs, each run, and its style. */\nexport function frozen(paragraph: Paragraph): Paragraph {\n for (const run of paragraph.runs) Object.freeze(run)\n Object.freeze(paragraph.runs)\n Object.freeze(paragraph.style)\n return Object.freeze(paragraph)\n}\n","import type { Block, EInvoiceFile, Paragraph } from './document.js'\nimport { frozen, label } from './page-label.js'\n\n/**\n * The label of a copy of an e-invoice (0077): what every page of a final\n * render says where a host asked for the copy and not the invoice\n * (`ResolveOptions.eInvoice`). A copy is what a Word file is written of:\n * a file a person may change is no invoice, so its every page says that\n * it is a copy, that it is not the invoice, and what the invoice is --\n * the PDF that embeds its XML, of a Factur-X, or its XML, of an\n * XRechnung. It carries no XML itself.\n *\n * The words are the runtime's, in the language the render prints in\n * (0063): the label is the one thing that tells a reader what the page\n * is, and in a language the page does not speak it tells them nothing.\n * So a copy in a language no label is written in is refused, never\n * labelled in another. It says \"this document\", not \"this Word file\":\n * the copy is a resolved document, and whatever is made of it is no\n * invoice. A preview's label and an XRechnung's PDF's stay English, as\n * they were (0038).\n *\n * One decision, here: the runtime writes the label, and an engine reads\n * it with `readCopyLabel` and decides no word of it.\n */\n\n/** The languages a copy is labelled in: those the starters print in. A locale's language is its first subtag. */\nexport const E_INVOICE_COPY_LANGUAGES = ['de', 'en', 'es', 'fr', 'it', 'nl'] as const\nexport type EInvoiceCopyLanguage = (typeof E_INVOICE_COPY_LANGUAGES)[number]\n\ntype Kind = EInvoiceFile['kind']\n\n/** What every page of a copy says, by the e-invoice's kind and the render's language. */\nexport const E_INVOICE_COPY_LABELS: Readonly<Record<Kind, Readonly<Record<EInvoiceCopyLanguage, string>>>> = Object.freeze({\n facturX: Object.freeze({\n de: 'Kopie einer E-Rechnung: Die Rechnung ist das PDF, das ihr XML einbettet, und dieses Dokument ist nicht die Rechnung',\n en: 'Copy of an e-invoice: the invoice is the PDF that embeds its XML, and this document is not the invoice',\n es: 'Copia de una factura electrónica: la factura es el PDF que incorpora su XML, y este documento no es la factura',\n fr: \"Copie d'une facture électronique\\u00a0: la facture est le PDF qui intègre son XML, et ce document n'est pas la facture\",\n it: 'Copia di una fattura elettronica: la fattura è il PDF che incorpora il suo XML, e questo documento non è la fattura',\n nl: 'Kopie van een e-factuur: de factuur is de pdf waarin haar XML is ingebed, en dit document is niet de factuur',\n }),\n xrechnung: Object.freeze({\n de: 'Kopie einer XRechnung: Die Rechnung ist ihr XML, und dieses Dokument ist nicht die Rechnung',\n en: 'Copy of an XRechnung: the invoice is its XML, and this document is not the invoice',\n es: 'Copia de una XRechnung: la factura es su XML, y este documento no es la factura',\n fr: \"Copie d'une XRechnung\\u00a0: la facture est son XML, et ce document n'est pas la facture\",\n it: 'Copia di una XRechnung: la fattura è il suo XML, e questo documento non è la fattura',\n nl: 'Kopie van een XRechnung: de factuur is haar XML, en dit document is niet de factuur',\n }),\n})\n\nconst KINDS = ['facturX', 'xrechnung'] as const satisfies readonly Kind[]\n\n/** A copy's label as an engine finds it: its kind, its language, and the paragraph the runtime writes, frozen. */\ninterface Known {\n readonly kind: Kind\n readonly language: EInvoiceCopyLanguage\n readonly paragraph: Paragraph\n}\n\n/** Every label's paragraph, made once and frozen: what a document's own paragraph is held to. */\nconst PARAGRAPHS: readonly Known[] = KINDS.flatMap((kind) =>\n E_INVOICE_COPY_LANGUAGES.map((language) => ({ kind, language, paragraph: frozen(label(E_INVOICE_COPY_LABELS[kind][language])) })),\n)\n\n/**\n * The paragraph a copy of an e-invoice of `kind` is labelled with in a\n * render that prints in `locale`, as the runtime writes it; undefined\n * where no label is written in that locale's language. Frozen, and the\n * same object each time: a document carries a paragraph of its own.\n */\nexport function eInvoiceCopyParagraph(kind: Kind, locale: string): Paragraph | undefined {\n // By the list, never by a lookup that would find 'constructor' on every object.\n const language = locale.split('-')[0]!.toLowerCase()\n return PARAGRAPHS.find((each) => each.kind === kind && each.language === language)?.paragraph\n}\n\n/** The label a header opens with: of which copy, and whether it stands as the runtime writes it. */\nexport interface CopyLabel extends Known {\n /** Whether the header's paragraph is the runtime's, style and all: the words in white, at one point or light are found, and are not as written. */\n readonly asWritten: boolean\n}\n\n/**\n * The copy's label `header` opens with, or undefined where it opens with\n * none: a paragraph of one run whose text is a label's, whatever its\n * style, as a preview's label is read (0057). `asWritten` says whether\n * the paragraph is the runtime's whole -- its size, bold and its colour,\n * and nothing else -- which an engine that writes a copy holds it to:\n * the words in white say nothing to a reader. A label among other runs,\n * or below another block, heads nothing and is not found.\n */\nexport function readCopyLabel(header: readonly Block[]): CopyLabel | undefined {\n const first = header[0]\n if (first?.kind !== 'paragraph' || first.runs.length !== 1) return undefined\n const run = first.runs[0]!\n if (!('text' in run)) return undefined\n const known = PARAGRAPHS.find(({ paragraph }) => (paragraph.runs[0] as { readonly text: string }).text === run.text)\n return known === undefined ? undefined : { ...known, asWritten: samePlain(first, known.paragraph) }\n}\n\n/** Whether two values of a resolved document are the same data: equal primitives, or two arrays, or two objects that are not, of the same keys holding the same values. */\nfunction samePlain(a: unknown, b: unknown): boolean {\n if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return a === b\n if (Array.isArray(a) !== Array.isArray(b)) return false\n const [left, right] = [Object.keys(a), Object.keys(b)]\n return (\n left.length === right.length &&\n left.every((key) => right.includes(key) && samePlain((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key]))\n )\n}\n","/**\n * XML, written one way: a tree of elements serialised with the same bytes\n * for the same tree, every text escaped so that a parser gives back exactly\n * what was written. The e-invoice's CII is built as such a tree\n * (`cii.ts`), and this is the one place it becomes text.\n *\n * Exactly, to a parser: a reader that applies the schema reads an element\n * the XSD types as xs:token -- an identifier, a code -- with its white\n * space collapsed. report-spec's rules refuse such a text that holds any\n * (`token` in `en16931.ts`), so what such a reader reads is what was\n * written too.\n *\n * - **Deterministic.** `<?xml version=\"1.0\" encoding=\"UTF-8\"?>`, no byte\n * order mark, a line feed after every line, two spaces a level, an empty\n * element closed at once, attributes in the order given. Nothing reads a\n * clock or the machine.\n * - **Escaped.** In text `&`, `<` and `>`, and a carriage return as\n * `&#13;`, which a parser would otherwise read as a line feed (XML 1.0,\n * 2.11). In an attribute the double quote too, and a tab, a line feed and\n * a carriage return as references, which a parser would otherwise read\n * as spaces (3.3.3).\n * - **Never a character XML 1.0 cannot hold.** report-spec's\n * `xmlCharacterBreak` decides which: the e-invoice's rules refuse a text\n * that holds one where it is read, naming its term. One that reaches the\n * writer anyway is a defect, thrown as a RangeError, never dropped, since\n * dropping it would change what the invoice says.\n */\nimport { xmlCharacterBreak } from '@formancy/report-spec'\n\n/** An attribute: its qualified name and its value. */\nexport type XmlAttribute = readonly [name: string, value: string]\n\n/** An element: its qualified name, its attributes, and either its text or the elements it holds. */\nexport interface XmlElement {\n readonly name: string\n readonly attributes: readonly XmlAttribute[]\n readonly content: string | readonly XmlElement[]\n}\n\n/** An element holding `children`, in order; an undefined child is a term the document leaves out. */\nexport function element(name: string, children: readonly (XmlElement | undefined)[], attributes: readonly XmlAttribute[] = []): XmlElement {\n return { name, attributes, content: children.filter((child): child is XmlElement => child !== undefined) }\n}\n\n/** An element holding the text `text`. */\nexport function leaf(name: string, text: string, attributes: readonly XmlAttribute[] = []): XmlElement {\n return { name, attributes, content: text }\n}\n\n/** `text` with no character XML 1.0 cannot write; a RangeError when it holds one, which the rules refuse before. */\nfunction writable(text: string): string {\n const broken = xmlCharacterBreak(text)\n if (broken !== undefined) throw new RangeError(`a text ${broken}; the e-invoice's rules refuse it where it is read`)\n return text\n}\n\nconst TEXT = /[&<>\\r]/g\nconst ATTRIBUTE = /[&<>\"\\t\\n\\r]/g\nconst REFERENCES: { readonly [character: string]: string } = {\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n '\\t': '&#9;',\n '\\n': '&#10;',\n '\\r': '&#13;',\n}\n\nconst escaped =\n (pattern: RegExp) =>\n (text: string): string =>\n writable(text).replace(pattern, (character) => REFERENCES[character] as string)\nconst text = escaped(TEXT)\nconst attribute = escaped(ATTRIBUTE)\n\n/** `node` written into `lines`, at `depth` levels. */\nfunction write(node: XmlElement, depth: number, lines: string[]): void {\n const indent = ' '.repeat(depth)\n const open = `${indent}<${node.name}${node.attributes.map(([name, value]) => ` ${name}=\"${attribute(value)}\"`).join('')}`\n if (typeof node.content === 'string') {\n lines.push(`${open}>${text(node.content)}</${node.name}>`)\n return\n }\n if (node.content.length === 0) {\n lines.push(`${open}/>`)\n return\n }\n lines.push(`${open}>`)\n for (const child of node.content) write(child, depth + 1, lines)\n lines.push(`${indent}</${node.name}>`)\n}\n\n/** The document whose root is `root`, as UTF-8 XML text: its declaration first, a line feed after every line. */\nexport function xmlDocument(root: XmlElement): string {\n const lines = ['<?xml version=\"1.0\" encoding=\"UTF-8\"?>']\n write(root, 0, lines)\n return `${lines.join('\\n')}\\n`\n}\n","/**\n * The parties of a CII invoice and how it is paid: the seller (BG-4) and\n * the buyer (BG-7) with their addresses (BG-5, BG-8), and the payment\n * instructions (BG-16), each in the order the Factur-X EN 16931 XSD's\n * `xs:sequence` gives its elements and at the path CEN/TC 434's CII binding\n * gives each business term. `cii.ts` places them in the document.\n *\n * A trade party is `Name`, `SpecifiedLegalOrganization`,\n * `DefinedTradeContact`, `PostalTradeAddress`, `URIUniversalCommunication`\n * and `SpecifiedTaxRegistration`, in that order, the VAT identifier under\n * scheme `VA` and the seller's tax number under `FC`; a contact is\n * `PersonName`, `TelephoneUniversalCommunication` and\n * `EmailURIUniversalCommunication`; an address is `PostcodeCode`,\n * `LineOne`, `LineTwo`, `CityName`, `CountryID`. Only elements D16B\n * shares with D22B are written, since the validators run the D16B schema.\n */\nimport type { AddressTerms, ContactTerms, PartyTerms, PaymentTerms } from './e-invoice-terms.js'\nimport { element, leaf } from './xml.js'\nimport type { XmlElement } from './xml.js'\n\n/** `make` of `value` where there is one; nothing where the term is left out. */\nexport function optional(value: string | undefined, make: (value: string) => XmlElement): XmlElement | undefined {\n return value === undefined ? undefined : make(value)\n}\n\n/** BG-5 or BG-8: the post code, the lines, the city and the country (BT-38, 35, 36, 37, 40; BT-53, 50, 51, 52, 55). */\nfunction postalAddress(address: AddressTerms): XmlElement {\n return element('ram:PostalTradeAddress', [\n leaf('ram:PostcodeCode', address.postalCode),\n leaf('ram:LineOne', address.line1),\n optional(address.line2, (line) => leaf('ram:LineTwo', line)),\n leaf('ram:CityName', address.city),\n leaf('ram:CountryID', address.country),\n ])\n}\n\n/** BG-6: the contact point (BT-41), the telephone number (BT-42) and the email address (BT-43), all three, as a contact gives them; no element where the seller names none. */\nfunction tradeContact(contact: ContactTerms | undefined): XmlElement | undefined {\n if (contact === undefined) return undefined\n return element('ram:DefinedTradeContact', [\n leaf('ram:PersonName', contact.name),\n element('ram:TelephoneUniversalCommunication', [leaf('ram:CompleteNumber', contact.telephone)]),\n element('ram:EmailURIUniversalCommunication', [leaf('ram:URIID', contact.email)]),\n ])\n}\n\n/**\n * The seller or the buyer: its name (BT-27, BT-44), its legal registration\n * and its scheme (BT-30, BT-47), the seller's contact (BG-6), its address,\n * its electronic address and its scheme (BT-34, BT-49), its VAT\n * identifier (BT-31, BT-48) and, the seller's, its tax number (BT-32).\n */\nexport function tradeParty(name: 'ram:SellerTradeParty' | 'ram:BuyerTradeParty', party: PartyTerms): XmlElement {\n const registration = party.legalId\n const reached = party.electronicAddress\n return element(name, [\n leaf('ram:Name', party.name),\n registration === undefined\n ? undefined\n : element('ram:SpecifiedLegalOrganization', [\n leaf('ram:ID', registration.id, registration.scheme === undefined ? [] : [['schemeID', registration.scheme]]),\n ]),\n tradeContact(party.contact),\n postalAddress(party.address),\n reached === undefined ? undefined : element('ram:URIUniversalCommunication', [leaf('ram:URIID', reached.id, [['schemeID', reached.scheme]])]),\n optional(party.vatId, (id) => element('ram:SpecifiedTaxRegistration', [leaf('ram:ID', id, [['schemeID', 'VA']])])),\n optional(party.taxNumber, (id) => element('ram:SpecifiedTaxRegistration', [leaf('ram:ID', id, [['schemeID', 'FC']])])),\n ])\n}\n\n/**\n * BG-16: the means (BT-81), the account by its IBAN (BT-84) and its name\n * (BT-85), and the BIC of its bank (BT-86). The remittance information\n * (BT-83) is the settlement's `PaymentReference`, which `cii.ts` writes.\n */\nexport function paymentMeans(payment: PaymentTerms): XmlElement {\n return element('ram:SpecifiedTradeSettlementPaymentMeans', [\n leaf('ram:TypeCode', payment.means),\n element('ram:PayeePartyCreditorFinancialAccount', [\n leaf('ram:IBANID', payment.account),\n optional(payment.accountName, (name) => leaf('ram:AccountName', name)),\n ]),\n optional(payment.bic, (bic) => element('ram:PayeeSpecifiedCreditorFinancialInstitution', [leaf('ram:BICID', bic)])),\n ])\n}\n","/**\n * An e-invoice written as UN/CEFACT Cross Industry Invoice XML in the\n * Factur-X 1.09.2 / ZUGFeRD 2.5.2 EN 16931 profile (0027), or as an\n * XRechnung 3.0 (0038): the runtime's, as the QR-bill's payload is, since\n * the XML is the invoice's payload and the renderer decides none of it.\n * One writer for both kinds: the XML of an XRechnung is the XML of a\n * Factur-X invoice of the same terms, but for the specification\n * identifier (BT-24) it opens with, which says whose rules it follows.\n *\n * - **Its shape.** The root `rsm:CrossIndustryInvoice` with the four\n * namespaces of CEN/TC 434's binding; its context (BT-23, BT-24), its document\n * (BT-1, BT-3, BT-2) and its transaction: the lines, then the\n * agreement, the delivery and the settlement, each element in the order\n * the profile's XSD `xs:sequence` gives it, at the path CEN's binding\n * gives each business term. Only elements D16B shares with D22B are\n * written, since the validators run the D16B schema.\n * - **Dates** are `udt:DateTimeString` of format 102, YYYYMMDD.\n * - **The delivery**, which the XSD needs once, is written empty where the\n * invoice gives an invoicing period and no delivery date: it has nothing\n * else to hold. Mustang 2.26.0's Factur-X schematron warns of that empty\n * element (PEPPOL-EN16931-R008, \"still status warning\"), and KoSIT's\n * EN 16931 scenario does not, measured by hand on 17 October 2026.\n * - **Amounts** are written from their own digits with exactly two places;\n * only `TaxTotalAmount` names its currency (CII-DT-031). A quantity and\n * a net price, which CEN does not hold to two places, are written as the\n * template's columns resolved them; a rate by value, `19`, `7`, `0`.\n * - **Its order** is the template's and the table's: categories as\n * declared, lines as the table prints them. The same invoice is the same\n * bytes (`xml.ts`).\n *\n * Every value is one the rules have already held (`e-invoice-lines.ts`,\n * `e-invoice-terms.ts`) and every total one `e-invoice-totals.ts`\n * computed: nothing here decides, rounds or checks.\n */\nimport { decimalToString } from '@formancy/expressions'\nimport type { Decimal } from '@formancy/expressions'\nimport type { EInvoiceCurrency, InvoiceTypeCode } from '@formancy/report-spec'\nimport { optional, paymentMeans, tradeParty } from './cii-parties.js'\nimport type { LineTerms } from './e-invoice-lines.js'\nimport type { InvoiceTerms } from './e-invoice-terms.js'\nimport type { InvoiceTotals, VatBreakdown } from './e-invoice-totals.js'\nimport { element, leaf, xmlDocument } from './xml.js'\nimport type { XmlAttribute, XmlElement } from './xml.js'\n\n/** What the XML is written from: the specification identifier, the type and the currency, every term, the lines in the table's order, and the totals. */\nexport interface CiiInvoice {\n /** BT-24: the profile's or the XRechnung version's, as report-spec names it. */\n readonly guideline: string\n readonly type: InvoiceTypeCode\n readonly currency: EInvoiceCurrency\n readonly terms: InvoiceTerms\n readonly lines: readonly LineTerms[]\n readonly totals: InvoiceTotals\n}\n\n/** CEN/TC 434's CII namespaces, as its schematron declares them. */\nconst NAMESPACES: readonly XmlAttribute[] = [\n ['xmlns:rsm', 'urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100'],\n ['xmlns:qdt', 'urn:un:unece:uncefact:data:standard:QualifiedDataType:100'],\n ['xmlns:ram', 'urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100'],\n ['xmlns:udt', 'urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100'],\n]\n\n/** A date, YYYY-MM-DD as the runtime holds one, as CII writes it: format 102, YYYYMMDD. */\nfunction dateTime(name: string, date: string): XmlElement {\n return element(name, [leaf('udt:DateTimeString', date.replaceAll('-', ''), [['format', '102']])])\n}\n\n/** An amount, from its own digits; a RangeError for one not at the two places every total and line amount is computed at. */\nfunction amount(name: string, value: Decimal, attributes: readonly XmlAttribute[] = []): XmlElement {\n if (value.scale !== 2) throw new RangeError(`${name} is at ${value.scale} places, and an e-invoice's amounts are computed at two`)\n return leaf(name, decimalToString(value), attributes)\n}\n\n/** A tax (BT-118, BT-119; at a line BT-151, BT-152): `VAT`, its category and its rate, and its reason, basis and amount where a breakdown has them. */\nfunction tradeTax(breakdown: VatBreakdown, totals?: { readonly reason: string | undefined }): XmlElement {\n return element('ram:ApplicableTradeTax', [\n totals === undefined ? undefined : amount('ram:CalculatedAmount', breakdown.amount),\n leaf('ram:TypeCode', 'VAT'),\n optional(totals?.reason, (reason) => leaf('ram:ExemptionReason', reason)),\n totals === undefined ? undefined : amount('ram:BasisAmount', breakdown.basis),\n leaf('ram:CategoryCode', breakdown.category.code),\n leaf('ram:RateApplicablePercent', breakdown.rate),\n ])\n}\n\n/** A line (BG-25): its identifier (BT-126), its item (BT-153), its net price (BT-146), its quantity and unit (BT-129, BT-130), its tax and its net amount (BT-131). */\nfunction line(each: LineTerms, breakdown: VatBreakdown): XmlElement {\n return element('ram:IncludedSupplyChainTradeLineItem', [\n element('ram:AssociatedDocumentLineDocument', [leaf('ram:LineID', each.id)]),\n element('ram:SpecifiedTradeProduct', [leaf('ram:Name', each.name)]),\n element('ram:SpecifiedLineTradeAgreement', [element('ram:NetPriceProductTradePrice', [leaf('ram:ChargeAmount', each.netPrice)])]),\n element('ram:SpecifiedLineTradeDelivery', [leaf('ram:BilledQuantity', each.quantity, [['unitCode', each.unit]])]),\n element('ram:SpecifiedLineTradeSettlement', [\n tradeTax(breakdown),\n element('ram:SpecifiedTradeSettlementLineMonetarySummation', [amount('ram:LineTotalAmount', each.netAmount)]),\n ]),\n ])\n}\n\n/** The settlement: the remittance (BT-83), the currency (BT-5), the payment, the breakdown, the period (BG-14), the terms (BT-20, BT-9) and the totals (BG-22). */\nfunction settlement(invoice: CiiInvoice): XmlElement {\n const { terms, totals, currency } = invoice\n const period = terms.period\n return element('ram:ApplicableHeaderTradeSettlement', [\n optional(terms.payment?.remittance, (remittance) => leaf('ram:PaymentReference', remittance)),\n leaf('ram:InvoiceCurrencyCode', currency),\n terms.payment === undefined ? undefined : paymentMeans(terms.payment),\n ...totals.breakdown.map((breakdown) => tradeTax(breakdown, { reason: terms.reasons.get(breakdown.category.id) })),\n period === undefined\n ? undefined\n : element('ram:BillingSpecifiedPeriod', [\n optional(period.start, (start) => dateTime('ram:StartDateTime', start)),\n optional(period.end, (end) => dateTime('ram:EndDateTime', end)),\n ]),\n terms.terms === undefined && terms.due === undefined\n ? undefined\n : element('ram:SpecifiedTradePaymentTerms', [\n optional(terms.terms, (text) => leaf('ram:Description', text)),\n optional(terms.due, (due) => dateTime('ram:DueDateDateTime', due)),\n ]),\n element('ram:SpecifiedTradeSettlementHeaderMonetarySummation', [\n amount('ram:LineTotalAmount', totals.lineTotal),\n amount('ram:TaxBasisTotalAmount', totals.taxBasisTotal),\n amount('ram:TaxTotalAmount', totals.taxTotal, [['currencyID', currency]]),\n amount('ram:GrandTotalAmount', totals.grandTotal),\n totals.paid === null ? undefined : amount('ram:TotalPrepaidAmount', totals.paid),\n amount('ram:DuePayableAmount', totals.duePayable),\n ]),\n ])\n}\n\n/** `invoice` as CII XML, UTF-8 text with its declaration, the same bytes for the same invoice. */\nexport function ciiXml(invoice: CiiInvoice): string {\n const { terms, totals } = invoice\n const breakdowns = new Map(totals.breakdown.map((breakdown) => [breakdown.category.id, breakdown]))\n const root = element(\n 'rsm:CrossIndustryInvoice',\n [\n element('rsm:ExchangedDocumentContext', [\n optional(terms.businessProcess, (process) => element('ram:BusinessProcessSpecifiedDocumentContextParameter', [leaf('ram:ID', process)])),\n element('ram:GuidelineSpecifiedDocumentContextParameter', [leaf('ram:ID', invoice.guideline)]),\n ]),\n element('rsm:ExchangedDocument', [leaf('ram:ID', terms.number), leaf('ram:TypeCode', invoice.type), dateTime('ram:IssueDateTime', terms.issued)]),\n element('rsm:SupplyChainTradeTransaction', [\n // Every line's category has a breakdown: the totals are computed from these lines.\n ...invoice.lines.map((each) => line(each, breakdowns.get(each.category.id) as VatBreakdown)),\n element('ram:ApplicableHeaderTradeAgreement', [\n optional(terms.buyerReference, (reference) => leaf('ram:BuyerReference', reference)),\n tradeParty('ram:SellerTradeParty', terms.seller),\n tradeParty('ram:BuyerTradeParty', terms.buyer),\n ]),\n element('ram:ApplicableHeaderTradeDelivery', [\n optional(terms.delivered, (delivered) => element('ram:ActualDeliverySupplyChainEvent', [dateTime('ram:OccurrenceDateTime', delivered)])),\n ]),\n settlement(invoice),\n ]),\n ],\n NAMESPACES,\n )\n return xmlDocument(root)\n}\n","/**\n * An e-invoice's totals and VAT breakdown, computed once, here, from its\n * lines (0027): the page prints them through `invoice`, `vatBasis` and\n * `vatAmount`, and the XML is written from the very same values, so the\n * two cannot part. The rules are CEN/TC 434's CII artefacts 1.3.17's, by\n * number.\n *\n * | Value | Computed as | Rule |\n * |---|---|---|\n * | BT-131 | BT-129 × BT-146, rounded once to two places: held, not written from it | EN 16931's definition; PEPPOL-EN16931-R120 |\n * | BT-106 | Σ BT-131, each a whole number of cents | BR-CO-10 |\n * | BT-109 | BT-106: there are no allowances or charges | BR-CO-13 |\n * | BT-116 | Σ BT-131 of the category's lines | BR-S-08, BR-E-08, BR-AE-08 |\n * | BT-117 | BT-116 × BT-119 / 100, rounded once to two places, half away from zero | BR-CO-17, BR-E-09, BR-AE-09 |\n * | BT-110 | Σ BT-117 | BR-CO-14 |\n * | BT-112 | BT-109 + BT-110 | BR-CO-15 |\n * | BT-115 | BT-112 − BT-113; there is no BT-114 | BR-CO-16 |\n *\n * - **Exact.** In `@formancy/expressions`' `Decimal`, a value as an integer\n * of units at a scale; nothing passes through a JavaScript number.\n * Dividing by 100 moves the point and loses nothing, so a category's tax\n * is the exact product rounded once. CEN tests BR-CO-17 and BR-S-09\n * within one unit of the currency either way, a euro, and the exact\n * product rounded once lies inside.\n * - **Per category, once.** VAT is rounded per category, never per line:\n * an ERP that rounds each line can differ by up to half a cent a line,\n * which is said where the costs are.\n * - **Half away from zero**, as upstream's `roundDecimal` rounds and as a\n * person rounds by hand. CEN's tests round the absolute value, where half\n * away from zero and XPath's `round` agree.\n * - **A breakdown for each category a line is in**, in the order the\n * invoice declares them: BR-E-01 and BR-AE-01 refuse one for a category\n * no line has, and one invoice is one XML.\n */\nimport { addDecimal, Decimal, decimalFromString, multiplyDecimal, roundDecimal, subtractDecimal } from '@formancy/expressions'\nimport type { ExpressionValues } from '@formancy/report-core'\nimport { checkVatRate } from '@formancy/report-spec'\nimport type { EInvoice, VatCategory } from '@formancy/report-spec'\n\n/** A line as its totals read it: its net amount (BT-131) at exactly two places, and the category it is in (BT-151). */\nexport interface TotalledLine {\n readonly netAmount: Decimal\n readonly category: VatCategory\n}\n\n/** One VAT breakdown (BG-23): a category a line is in, its rate as the XML writes it, its taxable amount and its tax. */\nexport interface VatBreakdown {\n readonly category: VatCategory\n /** BT-119 by value, as report-spec's `checkVatRate` gives it: `19`, `7`, `0`. */\n readonly rate: string\n /** BT-116. */\n readonly basis: Decimal\n /** BT-117. */\n readonly amount: Decimal\n}\n\n/** The document's totals (BG-22) and its VAT breakdown (BG-23), every amount at exactly two places. */\nexport interface InvoiceTotals {\n /** BT-106. */\n readonly lineTotal: Decimal\n /** BT-109. */\n readonly taxBasisTotal: Decimal\n /** BT-110. */\n readonly taxTotal: Decimal\n /** BT-112. */\n readonly grandTotal: Decimal\n /** BT-113, or null where none was paid. */\n readonly paid: Decimal | null\n /** BT-115. */\n readonly duePayable: Decimal\n /** Each category a line is in, in the order the invoice declares them. */\n readonly breakdown: readonly VatBreakdown[]\n}\n\nconst ZERO = new Decimal(0n, 2)\n\n/** `amount`, which a defect of the caller's would have written at another scale than the two places the XML writes. */\nfunction cents(amount: Decimal, what: string): Decimal {\n if (amount.scale !== 2) throw new RangeError(`${what} is at ${amount.scale} places, and the e-invoice's lines are read at two`)\n return amount\n}\n\nconst sum = (amounts: Iterable<Decimal>): Decimal => {\n let total = ZERO\n for (const amount of amounts) total = addDecimal(total, amount)\n return total\n}\n\n/**\n * A line's net amount (BT-131) as EN 16931 makes it, which the lines'\n * reader holds each line's to: its quantity (BT-129) times its net price\n * (BT-146), each as the XML writes it, rounded once to two places, half\n * away from zero, as BT-117 is. This version writes no line allowance or\n * charge and no base quantity (BT-149), which would enter it.\n */\nexport function lineNetAmount(quantity: string, netPrice: string): Decimal {\n return roundDecimal(multiplyDecimal(decimalFromString(quantity), decimalFromString(netPrice)), 2)\n}\n\n/** BT-117 of a category of `rate` over `basis`: the exact product over 100, rounded once to two places, half away from zero. */\nfunction tax(basis: Decimal, rate: string): Decimal {\n const product = multiplyDecimal(basis, decimalFromString(rate))\n return roundDecimal(new Decimal(product.units, product.scale + 2), 2)\n}\n\n/**\n * The totals of `lines`, each in one of `categories`, as declared; `paid`\n * the amount already paid (BT-113), or null. Every amount it is handed is\n * at exactly two places, as the lines' reader writes it, and a RangeError\n * says a caller handed one that is not.\n */\nexport function invoiceTotals(categories: readonly VatCategory[], lines: readonly TotalledLine[], paid: Decimal | null): InvoiceTotals {\n const amounts = lines.map((line, index) => cents(line.netAmount, `line ${index}'s net amount`))\n const breakdown = categories.flatMap((category): VatBreakdown[] => {\n const own = lines.flatMap((line, index) => (line.category === category ? [amounts[index] as Decimal] : []))\n if (own.length === 0) return []\n const basis = sum(own)\n // report-spec's validator took the rate by this very check, so it takes it again.\n const rate = (checkVatRate(category.code, category.rate) as { readonly value: string }).value\n return [{ category, rate, basis, amount: tax(basis, category.rate) }]\n })\n const lineTotal = sum(amounts)\n const taxTotal = sum(breakdown.map(({ amount }) => amount))\n const grandTotal = addDecimal(lineTotal, taxTotal)\n const prepaid = paid === null ? null : cents(paid, 'the paid amount')\n return {\n lineTotal,\n taxBasisTotal: lineTotal,\n taxTotal,\n grandTotal,\n paid: prepaid,\n duePayable: prepaid === null ? grandTotal : subtractDecimal(grandTotal, prepaid),\n breakdown,\n }\n}\n\n/**\n * What the e-invoice's names hold, as an expression is handed them (0027,\n * beside 0009): `invoice` each document total, `paid` only where the\n * invoice declares a paid amount, as report-core binds it; `vatBasis` and\n * `vatAmount` each declared category's basis and tax by its id, null where\n * no line is in it, which prints as nothing (0007). The very values the\n * XML is written from.\n */\nexport function invoiceNames(invoice: Pick<EInvoice, 'vat' | 'paid'>, totals: InvoiceTotals): ExpressionValues {\n const of = (category: VatCategory): VatBreakdown | undefined => totals.breakdown.find((each) => each.category.id === category.id)\n return {\n invoice: {\n lineTotal: totals.lineTotal,\n taxBasisTotal: totals.taxBasisTotal,\n taxTotal: totals.taxTotal,\n grandTotal: totals.grandTotal,\n ...(invoice.paid === undefined ? {} : { paid: totals.paid }),\n duePayable: totals.duePayable,\n },\n vatBasis: Object.fromEntries(invoice.vat.map((category) => [category.id, of(category)?.basis ?? null])),\n vatAmount: Object.fromEntries(invoice.vat.map((category) => [category.id, of(category)?.amount ?? null])),\n }\n}\n","/**\n * A run of a report -- literal, bound, computed, totalled or a page counter\n * -- lowered to the text it prints, formatted for the report's locale.\n *\n * The one place each kind of inline gets its value: a field from the header\n * or the current record, a parameter from the checked parameters, an\n * expression from its evaluation in the scope it stands in, an aggregate\n * from the report's totals, the current table's or the current group's\n * (`OVER`). Every value is formatted by `format.ts` with the inline's\n * format, or printed plainly without one, and null prints as nothing\n * (0007). A page counter stays a field the engine fills in, since only it\n * knows the pages.\n *\n * A QR code's content, and each text of a QR-bill or an EPC QR code, is\n * read run by run as a paragraph's is, and joined into the one text the\n * code encodes (`joinedText`), where a value that prints as nothing is\n * refused in a final render. An e-invoice's texts are read the same way\n * (`readRuns`), and held to its own rules.\n *\n * A column that prints a term of an e-invoice's lines is read once for\n * every row before anything is lowered, since the totals are computed from\n * it (`e-invoice-lines.ts`); the table prints the value kept then, never\n * one read again, so that the page and the XML hold one evaluation.\n */\nimport type { AggregateScope, Inline as ReportInline } from '@formancy/report-spec'\nimport type { Inline } from './document.js'\nimport type { TypedValue } from './format.js'\nimport { fieldValue, parameterType, valueOf } from './render-context.js'\nimport type { AggregateValues, Render, Scope } from './render-context.js'\nimport { placed } from './resolve-errors.js'\n\n/** What an error names besides the inline's path: the component, and in a table the column, or what holds it outside any component. */\nexport interface Owner {\n /** What holds the inline where no component does, by name: \"the payment part\". A component is named by its id. */\n readonly said?: string\n readonly componentId?: string\n readonly columnId?: string\n}\n\n/** A run whose value is read: anything but literal text and a page counter. */\nexport type BoundInline = Exclude<ReportInline, { kind: 'text' | 'pageNumber' | 'pageCount' }>\n\n/**\n * The totals an aggregate run reads, by what it is over: every detail\n * row's wherever it stands, or the current table's or group's. report-spec\n * allows a table's only in its total rows and its group's rows, and a\n * group's only in a group's (0062), where the scope holds them.\n */\nconst OVER: { readonly [S in AggregateScope]: (render: Pick<Render, 'totals'>, scope: Scope) => AggregateValues | undefined } = {\n report: (render) => render.totals.report,\n table: (_, scope) => scope.table,\n group: (_, scope) => scope.group,\n}\n\n/** The value `inline`, at `path`, reads in `scope`, unformatted; undefined when its evaluation failed, which is recorded. */\nexport function inlineValue(\n render: Pick<Render, 'report' | 'data' | 'params' | 'expressions' | 'problems' | 'preview' | 'totals'>,\n scope: Scope,\n inline: BoundInline,\n path: string,\n): TypedValue | null | undefined {\n switch (inline.kind) {\n case 'field':\n return fieldValue(render, scope.record, inline.field)\n case 'parameter': {\n const value = render.params[inline.parameter] ?? null\n return value === null ? null : ({ type: parameterType(render.report, inline.parameter), value } as TypedValue)\n }\n case 'expression':\n return valueOf(render, scope, `${path}/expression/cel`)\n case 'aggregate':\n return OVER[inline.over](render, scope)?.get(inline.aggregate) ?? null\n }\n}\n\n/** What the e-invoice kept of the detail row `row` for the column value at `path`: the value, null among them; or undefined where it kept nothing. */\nfunction kept(render: Render, path: string, row: number | undefined): { readonly value: TypedValue | null } | undefined {\n const column = row === undefined ? undefined : render.invoice?.columns.get(path)\n // Every row was read: one that could not be has refused the render before anything is lowered.\n return column === undefined ? undefined : { value: column[row as number] as TypedValue | null }\n}\n\n/** The value `inline` reads in `scope`, and the text it prints; undefined when either could not be had, which is recorded. */\nfunction printed(\n render: Render,\n scope: Scope,\n inline: BoundInline,\n path: string,\n owner: Owner,\n): { readonly value: TypedValue | null; readonly text: string } | undefined {\n const read = kept(render, path, scope.row)\n const value = read === undefined ? inlineValue(render, scope, inline, path) : read.value\n if (value === undefined) return undefined\n const formatted = render.formatter.format(value, inline.format, scope.currency)\n if (formatted.ok) return { value, text: formatted.text }\n const where = [\n owner.componentId === undefined ? owner.said : `component ${owner.componentId}`,\n owner.columnId && `column ${owner.columnId}`,\n scope.row !== undefined && `detail row ${scope.row}`,\n ]\n .filter(Boolean)\n .join(', ')\n render.problems.error({\n stage: 'format',\n code: formatted.code,\n path,\n message: `${where}: ${formatted.message}`,\n ...placed({ componentId: owner.componentId, columnId: owner.columnId, row: scope.row }),\n })\n return undefined\n}\n\n/**\n * `inline`, at `path` in the report, as the run it prints in `scope`;\n * undefined when it could not be, which is recorded. A run carries the\n * baseline its source sets (0061), and a run that sets none carries no key,\n * so that the document of a report that sets none is the one it was. A\n * table's cell joins its runs' text and drops it, where report-spec refuses\n * one.\n */\nexport function runOf(render: Render, scope: Scope, inline: ReportInline, path: string, owner: Owner): Inline | undefined {\n if (inline.kind === 'pageNumber' || inline.kind === 'pageCount') return { field: inline.kind }\n const shift = inline.baseline === undefined ? {} : { baseline: inline.baseline }\n if (inline.kind === 'text') return { text: inline.text, ...shift }\n const run = printed(render, scope, inline, path, owner)\n return run && { text: run.text, ...shift }\n}\n\n/** What holds runs a code encodes, as an error names it: a QR code's or an EPC QR code's component, or the payment part. */\nexport interface Encoder {\n /** How an error's message names it: \"component pay-code\", \"the payment part\". */\n readonly said: string\n /** The component, for a code that is one. */\n readonly componentId?: string\n /** What the runs are encoded in. */\n readonly code: keyof typeof SCANNED_AS\n}\n\n/** What a code of less than its runs would scan as, by what they are encoded in. */\nconst SCANNED_AS = {\n 'a QR code': 'some other text',\n 'a QR-bill': 'some other bill',\n 'an EPC QR code': 'some other transfer',\n} as const\n\n/** What runs encoded in a code join to, and whether a run of them had a value that is null, which a preview prints as nothing. */\nexport interface Encoded {\n readonly text: string\n readonly lacking: boolean\n}\n\n/** What runs print, read as a paragraph's: their text, the paths of those whose value is null, and whether one could not be read, which is recorded. */\nexport interface ReadRuns {\n readonly text: string\n readonly nulls: readonly string[]\n readonly refused: boolean\n}\n\n/**\n * The runs at `path`, read in `scope` run by run as a paragraph's are, so\n * that what a code or an e-invoice holds and what a paragraph prints never\n * format a value apart. A page counter has no value before there are\n * pages, and report-spec refuses one wherever runs are read so; one that\n * reaches here all the same throws, naming what holds it, never read as\n * nothing.\n */\nexport function readRuns(render: Render, scope: Scope, runs: readonly ReportInline[], path: string, owner: Owner & { readonly said: string }): ReadRuns {\n const texts: string[] = []\n const nulls: string[] = []\n let refused = false\n for (const [index, inline] of runs.entries()) {\n const at = `${path}/${index}`\n if (inline.kind === 'pageNumber' || inline.kind === 'pageCount') {\n throw new RangeError(`${owner.said} holds a ${inline.kind} at ${at}, which has no value before there are pages; report-spec refuses it`)\n }\n const run = inline.kind === 'text' ? { value: undefined, text: inline.text } : printed(render, scope, inline, at, owner)\n if (run === undefined) refused = true\n else {\n if (run.value === null) nulls.push(at)\n texts.push(run.text)\n }\n }\n return { text: texts.join(''), nulls, refused }\n}\n\n/**\n * The text `runs`, at `path`, join to when they are encoded in a code,\n * read as `readRuns` reads them. Undefined when a run is refused, which is\n * recorded, naming `encoder`.\n *\n * A final render refuses a run whose value is null: a code of less than\n * its content scans as some other text, and the page does not say so. A\n * preview encodes it as nothing, as a paragraph prints it, and says it\n * did.\n *\n * `unused` is given for a text its code may leave out, and says whether\n * the text the runs print leaves its element unused. A text that does,\n * nulls and all -- a nullable field's way of saying \"none\" -- is no text\n * rather than one cut short, and a final render takes it as a preview\n * does; one whose other runs print something is still refused.\n */\nexport function joinedText(\n render: Render,\n scope: Scope,\n runs: readonly ReportInline[],\n path: string,\n encoder: Encoder,\n unused?: (text: string) => boolean,\n): Encoded | undefined {\n const { text, nulls, refused } = readRuns(render, scope, runs, path, encoder)\n if (!render.preview && nulls.length > 0 && unused?.(text) !== true) {\n for (const at of nulls) {\n render.problems.error({\n stage: 'resolve',\n code: 'no-qr-value',\n path: at,\n message: `${encoder.said}: this run has no value, and ${encoder.code} without it would scan as ${SCANNED_AS[encoder.code]}`,\n ...placed(encoder),\n })\n }\n return undefined\n }\n return refused ? undefined : { text, lacking: render.preview && nulls.length > 0 }\n}\n\n/**\n * The text the QR code `id` encodes: its `content`, at `path`, joined as\n * `joinedText` joins it. Undefined when it is refused, which is recorded,\n * naming the code. A final render refuses content that prints nothing at\n * all, a code of nothing, which scans as no code; a preview encodes it.\n */\nexport function encodedText(render: Render, scope: Scope, content: readonly ReportInline[], path: string, id: string): string | undefined {\n const joined = joinedText(render, scope, content, `${path}/content`, { said: `component ${id}`, componentId: id, code: 'a QR code' })\n if (joined === undefined) return undefined\n if (joined.text !== '' || render.preview) return joined.text\n render.problems.error({\n stage: 'resolve',\n code: 'empty-qr-code',\n path: `${path}/content`,\n message: `component ${id}: its content prints nothing, and a QR code of nothing scans as no code`,\n componentId: id,\n })\n return undefined\n}\n\n/** The text of runs that hold no page counter: what a table cell or a group header prints. */\nexport function textOfRuns(runs: readonly Inline[]): string {\n return runs.map((run) => ('text' in run ? run.text : '')).join('')\n}\n","/**\n * An e-invoice's lines (BG-25): one for each row of the table that prints\n * them, read once, before the totals, for the page and the XML alike\n * (0027).\n *\n * - **One evaluation.** The four columns the e-invoice names -- the item\n * name (BT-153), the invoiced quantity (BT-129), the net price (BT-146)\n * and the net amount (BT-131) -- are read here for every row, as the\n * table reads a cell, and kept by the path of each column's value and the\n * row's index: the table prints the very value kept (`inlines.ts`). So\n * the page and the XML cannot each read a line, and part. The line's\n * identifier (BT-126), its unit (BT-130) and its VAT category (BT-151)\n * are codes a page need not print, read from each row as an aggregate\n * reads it.\n * - **In the table's order** (`orderTable`, 0007), which the XML holds\n * them in.\n * - **Held to EN 16931's rules**, report-spec's functions over text, the\n * ones its validator applies to a literal (`en16931.ts`): a code from a\n * closed list, a net price that is not negative, a net amount that is a\n * whole number of cents, never rounded, a category the invoice declares.\n * And to what EN 16931 defines and no rule of CEN's tests: a net amount\n * that is the quantity times the net price, rounded once to the cent\n * (`lineNetAmount`), and a line identifier no other line has. A rule\n * broken is `invalid-e-invoice`, naming the row and the column or the\n * code, the term and the rule, never the value.\n * - **Printed as the XML holds it.** A quantity or a net price whose\n * column's format shows fewer places than it has is refused: the page\n * would round it, and the XML would not.\n * - **A preview holds what it has.** A final render refuses a term that\n * has no value (BR-21 to BR-26, BR-CO-04) and a table of no rows\n * (BR-16). A preview takes a term with no value as one it lacks, and\n * leaves a line whose net amount or category it lacks out of every\n * total, as an aggregate skips a null; what the data does hold it holds\n * to the same rules.\n */\nimport { compareDecimal, decimalFromString, decimalToString } from '@formancy/expressions'\nimport type { Decimal } from '@formancy/expressions'\nimport {\n checkEInvoiceDecimal,\n checkEInvoiceText,\n checkLineCategory,\n E_INVOICE_DECIMALS,\n E_INVOICE_LINE_CODES,\n E_INVOICE_LINE_COLUMNS,\n E_INVOICE_TEXTS,\n eInvoiceBlank,\n en16931Rule,\n walkComponents,\n} from '@formancy/report-spec'\nimport type {\n EInvoice,\n EInvoiceDecimalTerm,\n EInvoiceLineCode,\n EInvoiceLineColumn,\n EInvoiceLineTerm,\n EInvoiceTextTerm,\n En16931Rule,\n TableComponent,\n VatCategory,\n} from '@formancy/report-spec'\nimport { roundDecimalAs } from './decimal.js'\nimport { lineNetAmount } from './e-invoice-totals.js'\nimport type { TypedValue } from './format.js'\nimport { inlineValue } from './inlines.js'\nimport type { BoundInline } from './inlines.js'\nimport { fieldValue, rowScope, valueOf } from './render-context.js'\nimport type { Render, Scope } from './render-context.js'\nimport { aType, placed } from './resolve-errors.js'\nimport { orderTable } from './sort-group.js'\nimport type { OrderedRow } from './sort-group.js'\n\n/** A line's terms as the XML writes them. */\nexport interface LineTerms {\n /** BT-126. */\n readonly id: string\n /** BT-153. */\n readonly name: string\n /** BT-129, as written. */\n readonly quantity: string\n /** BT-130, a code of report-spec's `UNIT_CODES`. */\n readonly unit: string\n /** BT-146, as written. */\n readonly netPrice: string\n /** BT-131, at exactly two places. */\n readonly netAmount: Decimal\n /** The category the line names (BT-151), and so its rate (BT-152). */\n readonly category: VatCategory\n}\n\ntype LineKey = EInvoiceLineColumn | EInvoiceLineCode\n\n/** The key of each term of `LineTerms` the e-invoice names a column or a code by. */\nconst TERM_OF: { readonly [K in LineKey]: keyof LineTerms } = {\n name: 'name',\n quantity: 'quantity',\n netPrice: 'netPrice',\n netAmount: 'netAmount',\n id: 'id',\n unit: 'unit',\n vat: 'category',\n}\n\n/** A line as a render read it from its row: each term, null where a preview has no value for it, and the row's index in the data. */\nexport type ReadLine = { readonly [K in keyof LineTerms]: LineTerms[K] | null } & { readonly row: number }\n\n/** The lines in the table's order, and what the named columns printed of each row, by the path of each column's value. */\nexport interface ReadLines {\n readonly lines: readonly ReadLine[]\n readonly columns: ReadonlyMap<string, readonly (TypedValue | null)[]>\n}\n\n/** What the lines are read with: every input but what the e-invoice adds. */\ntype Reading = Omit<Render, 'invoice'>\n\n/** Where a term of a line is read, as a refusal names it. */\ninterface Place {\n readonly path: string\n readonly said: string\n readonly componentId?: string\n readonly columnId?: string\n readonly row: number\n}\n\nfunction refuse(render: Reading, place: Place, message: string): undefined {\n render.problems.error({\n stage: 'resolve',\n code: 'invalid-e-invoice',\n path: place.path,\n message: `${place.said}, detail row ${place.row}: ${message}`,\n ...placed(place),\n })\n return undefined\n}\n\n/** The rule a term with no value breaks: every line term is needed. */\nfunction required(term: EInvoiceLineTerm): string {\n const rule =\n term.term in E_INVOICE_DECIMALS ? E_INVOICE_DECIMALS[term.term as EInvoiceDecimalTerm].required : E_INVOICE_TEXTS[term.term as EInvoiceTextTerm].required\n // Every term of a line has the rule of CEN's its absence breaks (`en16931.test.ts`).\n return en16931Rule(rule as En16931Rule, 'has no value, and every line of an e-invoice has one')\n}\n\n/** A value as its term's text: a decimal and an integer by their own digits, a text as it is. */\nfunction written(value: TypedValue): string {\n return value.type === 'decimal' ? decimalToString(value.value) : String(value.value)\n}\n\n/**\n * The term `term` of a line, read as `value`, held to its rule: what the\n * XML writes, null where a preview has no value for it, or undefined when\n * it is refused, which is recorded at `place`.\n */\nfunction checked(render: Reading, term: EInvoiceLineTerm, value: TypedValue | null, place: Place): string | null | undefined {\n if (value === null || (render.preview && value.type === 'string' && eInvoiceBlank(value.value))) {\n return render.preview ? null : refuse(render, place, `${term.what} ${required(term)}`)\n }\n if (!term.types.includes(value.type))\n return refuse(render, place, `${term.what} is read from ${term.types.map(aType).join(' or ')}, and this gives ${aType(value.type)}`)\n const text = written(value)\n const outcome =\n term.term in E_INVOICE_DECIMALS ? checkEInvoiceDecimal(term.term as EInvoiceDecimalTerm, text) : checkEInvoiceText(term.term as EInvoiceTextTerm, text)\n return outcome.ok ? outcome.value : refuse(render, place, `${term.what} ${outcome.rule}`)\n}\n\n/** A column the e-invoice names: its key, its value, where that stands, and what it printed of each row. */\ninterface NamedColumn {\n readonly key: EInvoiceLineColumn\n readonly id: string\n readonly value: BoundInline\n readonly path: string\n readonly printed: (TypedValue | null)[]\n}\n\n/** The table the lines are the rows of, and the columns that print their terms. */\nfunction namedColumns(render: Reading, invoice: EInvoice): { readonly table: TableComponent; readonly columns: readonly NamedColumn[] } {\n // report-spec's validator holds the lines to this table, and each named column to it: shown, and a detail field or an expression.\n const located = walkComponents(render.report).find(({ component }) => component.kind === 'table' && component.id === invoice.lines.table) as {\n readonly component: TableComponent\n readonly path: string\n }\n const table = located.component\n const columns = (Object.keys(E_INVOICE_LINE_COLUMNS) as EInvoiceLineColumn[]).map((key): NamedColumn => {\n const index = table.columns.findIndex((column) => column.id === invoice.lines[key])\n const column = table.columns[index] as TableComponent['columns'][number]\n return {\n key,\n id: column.id,\n value: column.value as BoundInline,\n path: `${located.path}/columns/${index}/value`,\n printed: new Array<TypedValue | null>(render.data.detail.length).fill(null),\n }\n })\n return { table, columns }\n}\n\n/**\n * The columns whose term the XML writes with the data's own places, which\n * their format may not round: the quantity and the net price. The net\n * amount and every total are amounts the XML writes at two places, which\n * the editing core holds a format to where the template is written.\n */\nconst AS_WRITTEN: ReadonlySet<EInvoiceLineColumn> = new Set(['quantity', 'netPrice'])\n\n/** The places `column` prints `value` at, where printing it there would round it, by value; undefined where it prints it as it is. */\nfunction roundingPlaces(column: NamedColumn, value: TypedValue): number | undefined {\n const format = column.value.format\n if (!AS_WRITTEN.has(column.key) || value.type !== 'decimal' || (format?.kind !== 'number' && format?.kind !== 'currency')) return undefined\n const shown = roundDecimalAs(value.value, { scale: format.scale, mode: 'half-away-from-zero' })\n return compareDecimal(shown, value.value) === 0 ? undefined : format.scale\n}\n\n/** The term of `column` in `row`, read and held to its rule, and to the places its column prints; `undefined` when it could not be, which is recorded. */\nfunction readColumn(render: Reading, scope: Scope, column: NamedColumn, place: Place): string | null | undefined {\n const value = inlineValue(render, scope, column.value, column.path)\n if (value === undefined) return undefined\n column.printed[place.row] = value\n const term = E_INVOICE_LINE_COLUMNS[column.key]\n const text = checked(render, term, value, place)\n const places = typeof text === 'string' ? roundingPlaces(column, value as TypedValue) : undefined\n if (places === undefined) return text\n return refuse(\n render,\n place,\n `${term.what} has more places than its column prints, ${places}, so the page would print another than the XML holds: the column prints the places the data gives`,\n )\n}\n\n/** The line of `row`, every term read and held to its rule; undefined when a term is refused or could not be read, which is recorded. */\nfunction readLine(render: Reading, invoice: EInvoice, table: TableComponent, columns: readonly NamedColumn[], row: OrderedRow): ReadLine | undefined {\n const scope = rowScope(render, render.totals.report, row)\n const terms: Partial<Record<keyof LineTerms, string | VatCategory | Decimal | null>> = {}\n let whole = true\n const keep = (key: LineKey, value: string | VatCategory | Decimal | null | undefined): void => {\n if (value === undefined) whole = false\n else terms[TERM_OF[key]] = value\n }\n const placeOf = (column: NamedColumn): Place => ({\n path: column.path,\n said: `component ${table.id}, column ${column.id}`,\n componentId: table.id,\n columnId: column.id,\n row: row.index,\n })\n for (const column of columns) {\n const text = readColumn(render, scope, column, placeOf(column))\n keep(column.key, column.key === 'netAmount' && typeof text === 'string' ? decimalFromString(text) : text)\n }\n const { quantity, netPrice, netAmount } = terms as Partial<Record<'quantity' | 'netPrice', string | null>> & { readonly netAmount?: Decimal | null }\n if (\n typeof quantity === 'string' &&\n typeof netPrice === 'string' &&\n netAmount !== undefined &&\n netAmount !== null &&\n compareDecimal(lineNetAmount(quantity, netPrice), netAmount) !== 0\n ) {\n const amount = columns.find(({ key }) => key === 'netAmount') as NamedColumn\n keep(\n 'netAmount',\n refuse(\n render,\n placeOf(amount),\n `${E_INVOICE_LINE_COLUMNS.netAmount.what} is not ${E_INVOICE_LINE_COLUMNS.quantity.what} times ${E_INVOICE_LINE_COLUMNS.netPrice.what}, rounded once to the cent: a receiver that multiplies them reads another amount`,\n ),\n )\n }\n for (const key of Object.keys(E_INVOICE_LINE_CODES) as EInvoiceLineCode[]) {\n const code = invoice.lines[key]\n const path = `/eInvoice/lines/${key}`\n const value = code.kind === 'field' ? fieldValue(render, row.record, code.field) : valueOf(render, scope, `${path}/expression/cel`)\n if (value === undefined) {\n whole = false\n continue\n }\n const place = { path, said: 'the e-invoice', row: row.index }\n const text = checked(render, E_INVOICE_LINE_CODES[key], value, place)\n if (key !== 'vat' || typeof text !== 'string') keep(key, text)\n else {\n const category = checkLineCategory(text, invoice.vat)\n keep(key, category.ok ? category.value : refuse(render, place, `${E_INVOICE_LINE_CODES.vat.what} ${category.rule}`))\n }\n }\n return whole ? ({ ...terms, row: row.index } as ReadLine) : undefined\n}\n\n/**\n * `invoice`'s lines in the table's order, each term read once and held to\n * its rule, and what the named columns printed of each row; undefined when\n * a line is refused, or could not be read, which is recorded. A final\n * render refuses a table of no rows (BR-16).\n */\nexport function readLines(render: Reading, invoice: EInvoice): ReadLines | undefined {\n const { table, columns } = namedColumns(render, invoice)\n const lines: ReadLine[] = []\n const ids = new Set<string>()\n let whole = true\n // Every detail row, never a selection: report-spec refuses a condition on\n // the lines' table, and a second table, in a report that is an e-invoice\n // (0062), so the page prints each line the XML holds, once.\n for (const row of orderTable(render.report, table, render.data.detail).rows) {\n if (render.problems.full) return undefined\n const line = readLine(render, invoice, table, columns, row)\n if (line === undefined) whole = false\n else if (line.id !== null && ids.has(line.id)) {\n // BT-126 is the line's own (EN 16931, as XRechnung 3.0.2 gives its model): the later of two is refused.\n refuse(\n render,\n { path: '/eInvoice/lines/id', said: 'the e-invoice', row: row.index },\n `${E_INVOICE_LINE_CODES.id.what} is an earlier line's, and each line of an e-invoice has its own`,\n )\n whole = false\n } else {\n if (line.id !== null) ids.add(line.id)\n lines.push(line)\n }\n }\n if (!render.preview && render.data.detail.length === 0) {\n render.problems.error({\n stage: 'resolve',\n code: 'invalid-e-invoice',\n path: '/eInvoice/lines/table',\n message: `the e-invoice: ${en16931Rule('BR-16', `an e-invoice has one line at least, a row of the table ${table.id}, and the data has no rows`)}`,\n componentId: table.id,\n })\n return undefined\n }\n return whole ? { lines, columns: new Map(columns.map(({ path, printed }) => [path, printed])) } : undefined\n}\n\n/** The lines a final render writes: every term of each read, which a final render refuses a line without. */\nexport function writtenLines(lines: readonly ReadLine[]): readonly LineTerms[] | undefined {\n return lines.every((line) => Object.values(line).every((term) => term !== null)) ? (lines as readonly LineTerms[]) : undefined\n}\n","/**\n * An e-invoice's terms but its lines -- its number, its dates, its seller\n * and its buyer, its categories' reasons, its payment instructions, its\n * paid amount -- each read in the report's scope once the data has\n * resolved it, and held to EN 16931's rules: report-spec's `en16931.ts`,\n * the very functions its validator applies to a literal, named by the same\n * tables.\n *\n * - **Read as a paragraph.** Each text is its runs, read as a paragraph's\n * in the report's scope (`readRuns`), so the XML holds what the same runs\n * would print. A literal passes again; a value from data is held where\n * the validator could not see it.\n * - **What may be left out is.** An optional text the data resolves to\n * blank, nulls and all, is a term the XML leaves out, as an EPC QR code's\n * optional texts are: a nullable field's null is how data says \"none\".\n * A needed one that prints nothing breaks its rule (BR-02, BR-06 ...);\n * one whose runs print something around a null is refused as a text cut\n * short. The seller's contact is left out whole or written whole: one\n * the data gives in part is refused at each term it lacks (0037).\n * - **Each kind's rules.** An XRechnung's texts are held to its kind's\n * (`E_INVOICE_KIND_TEXTS`, 0038): what XRechnung needs is needed, a\n * contact's three terms among them, and its payment terms hold no line\n * led by #. An electronic address under 0204 is a Leitweg-ID in either\n * kind.\n * - **What only the whole says** -- the identifiers the lines' categories\n * need of the seller and the buyer (BR-CO-26, BR-S-02, BR-E-02,\n * BR-AE-02), the time of supply (§ 14 UStG), a category's reason (BR-E-10,\n * BR-AE-10) -- is said of the categories the lines are in, once every\n * part has resolved; an invoicing period's order (BR-29) once both its\n * dates have.\n * - **A preview holds what it has**: a term it has no value for is one it\n * lacks, and what only an absence breaks it does not say. What the data\n * holds it holds to the same rules.\n *\n * A rule broken is `invalid-e-invoice` at the term, naming its business\n * term and the rule, never the value, which may be a person's name,\n * account or VAT identifier.\n */\nimport { decimalFromString, decimalToString } from '@formancy/expressions'\nimport type { Decimal } from '@formancy/expressions'\nimport {\n buyerIdentificationBreak,\n checkEInvoiceDate,\n checkEInvoiceDecimal,\n checkEInvoiceText,\n checkElectronicAddress,\n checkInvoicingPeriod,\n E_INVOICE_DATES,\n E_INVOICE_DECIMALS,\n E_INVOICE_KIND_TEXTS,\n E_INVOICE_TEXT_TERMS,\n eInvoiceBlank,\n en16931Rule,\n sellerIdentificationBreaks,\n supplyBreak,\n vatReasonBreak,\n} from '@formancy/report-spec'\nimport type {\n AddressScheme,\n EInvoice,\n EInvoiceAddress,\n EInvoiceBuyer,\n EInvoiceDateTerm,\n EInvoiceKind,\n EInvoiceSeller,\n EInvoiceTextTerm,\n ElectronicAddress,\n Expression,\n Inline,\n PaymentCheck,\n PaymentMeansCode,\n SchemeId,\n SellerContact,\n VatCategory,\n} from '@formancy/report-spec'\nimport { readRuns } from './inlines.js'\nimport { reportScope, valueOf } from './render-context.js'\nimport type { Render, Scope } from './render-context.js'\nimport { aType } from './resolve-errors.js'\n\n/** A postal address (BG-5, BG-8) as the XML writes it. */\nexport interface AddressTerms {\n readonly line1: string\n readonly line2?: string\n readonly postalCode: string\n readonly city: string\n /** A code of report-spec's `COUNTRY_CODES`. */\n readonly country: string\n}\n\n/** The seller's contact (BG-6) as the XML writes it: all three of its terms, as a contact gives them (0037), though EN 16931 lets each be left out. */\nexport interface ContactTerms {\n readonly name: string\n readonly telephone: string\n readonly email: string\n}\n\n/** A seller (BG-4) or a buyer (BG-7) as the XML writes it; a buyer has no tax number and no contact. */\nexport interface PartyTerms {\n readonly name: string\n /** Its spaces dropped. */\n readonly vatId?: string\n readonly taxNumber?: string\n readonly legalId?: { readonly id: string; readonly scheme?: SchemeId }\n readonly electronicAddress?: { readonly id: string; readonly scheme: AddressScheme }\n readonly contact?: ContactTerms\n readonly address: AddressTerms\n}\n\n/** The payment instructions (BG-16) as the XML writes them. */\nexport interface PaymentTerms {\n readonly means: PaymentMeansCode\n /** BT-84, as the EPC QR code's account rule writes it: its spaces dropped, its letters capitals. */\n readonly account: string\n readonly bic?: string\n readonly accountName?: string\n readonly remittance?: string\n}\n\n/** Every term of an e-invoice but its lines and its totals, as the XML writes it; each date YYYY-MM-DD. */\nexport interface InvoiceTerms {\n readonly number: string\n readonly issued: string\n readonly businessProcess?: string\n readonly seller: PartyTerms\n readonly buyer: PartyTerms\n readonly buyerReference?: string\n readonly delivered?: string\n readonly period?: { readonly start?: string; readonly end?: string }\n /** The exemption reason (BT-120) of each category a line is in that gives one, by the category's id. */\n readonly reasons: ReadonlyMap<string, string>\n readonly payment?: PaymentTerms\n readonly due?: string\n readonly terms?: string\n}\n\n/** What is read with: every input but what the e-invoice adds, the report's scope, and the kind of e-invoice, whose rules each term is held to. */\ninterface Reader {\n readonly render: Omit<Render, 'invoice'>\n readonly scope: Scope\n readonly kind: EInvoiceKind\n}\n\n/** What an error names the e-invoice by: it stands in no component. */\nconst OWNER = { said: 'the e-invoice' } as const\n\nfunction refuse({ render }: Pick<Reader, 'render'>, path: string, message: string): undefined {\n render.problems.error({ stage: 'resolve', code: 'invalid-e-invoice', path, message: `the e-invoice: ${message}` })\n return undefined\n}\n\n/**\n * A read term: its value, null where it is none -- left out, or one a\n * preview has no value for -- or undefined where it was refused or could\n * not be read, which is recorded.\n */\ntype Read<T> = T | null | undefined\n\n/** The text of `term`, its runs at `path`, held to its rule of the reader's kind, or to `check` where it is given. */\nfunction text(\n reader: Reader,\n term: EInvoiceTextTerm,\n runs: readonly Inline[] | undefined,\n path: string,\n check = (written: string): PaymentCheck<string> => checkEInvoiceText(term, written, reader.kind),\n): Read<string> {\n if (runs === undefined) return null\n const read = readRuns(reader.render, reader.scope, runs, path, OWNER)\n if (read.refused) return undefined\n const rule = E_INVOICE_KIND_TEXTS[reader.kind][term]\n const blank = eInvoiceBlank(read.text)\n if (reader.render.preview && (blank || read.nulls.length > 0)) return null\n if (blank && rule.required === undefined) return null\n if (!blank && read.nulls.length > 0)\n return refuse(reader, path, `${rule.what} has a run with no value, and written without it the e-invoice would hold less than its runs print`)\n const checked = check(read.text)\n return checked.ok ? checked.value : refuse(reader, path, `${rule.what} ${checked.rule}`)\n}\n\n/** The date of `term`, its expression at `path`: a day on the calendar, YYYY-MM-DD. */\nfunction date(reader: Reader, term: EInvoiceDateTerm, expression: Expression | undefined, path: string): Read<string> {\n if (expression === undefined) return null\n const value = valueOf(reader.render, reader.scope, `${path}/cel`)\n if (value === undefined) return undefined\n const rule = E_INVOICE_DATES[term]\n if (value === null)\n return rule.required === undefined || reader.render.preview\n ? null\n : refuse(reader, path, `${rule.what} ${en16931Rule(rule.required, 'has no value, and an e-invoice needs it')}`)\n if (value.type !== 'date' && value.type !== 'string') return refuse(reader, path, `${rule.what} is a date, and this gives ${aType(value.type)}`)\n const checked = checkEInvoiceDate(value.value)\n return checked.ok ? checked.value : refuse(reader, path, `${rule.what} ${checked.rule}`)\n}\n\n/** `value` under `key` where it is a value; nothing where it is none or was refused. */\nconst term = <K extends string, V>(key: K, value: Read<V>): { [P in K]?: V } =>\n value === null || value === undefined ? {} : ({ [key]: value } as { [P in K]: V })\n\n/** Whether every one of `values` was read and is there: what a term needs of each of its parts. */\nconst all = (...values: readonly Read<unknown>[]): boolean => values.every((value) => value !== null && value !== undefined)\n\nfunction address(reader: Reader, held: EInvoiceAddress, path: string, which: 'seller' | 'buyer'): Read<AddressTerms> {\n const terms = E_INVOICE_TEXT_TERMS[which].address\n const line1 = text(reader, terms.line1, held.line1, `${path}/line1`)\n const line2 = text(reader, terms.line2, held.line2, `${path}/line2`)\n const postalCode = text(reader, terms.postalCode, held.postalCode, `${path}/postalCode`)\n const city = text(reader, terms.city, held.city, `${path}/city`)\n const country = text(reader, terms.country, held.country, `${path}/country`)\n if (line2 === undefined || !all(line1, postalCode, city, country)) return undefined\n return { line1: line1 as string, ...term('line2', line2), postalCode: postalCode as string, city: city as string, country: country as string }\n}\n\n/** An electronic address: its identifier read, held to its scheme where that is 0204, with the scheme the template names; none where the data gives the identifier as nothing. */\nfunction electronicAddress(\n reader: Reader,\n held: ElectronicAddress | undefined,\n path: string,\n term: EInvoiceTextTerm,\n): Read<{ readonly id: string; readonly scheme: AddressScheme }> {\n if (held === undefined) return null\n const id = text(reader, term, held.id, `${path}/id`, (written) => checkElectronicAddress(term, held.scheme, written, reader.kind))\n return id === null || id === undefined ? id : { id, scheme: held.scheme }\n}\n\n/**\n * The seller's contact: all three of its terms, or none where the data\n * gives none of them. One it gives in part is refused at each term it\n * lacks, as the validator refuses a literal one: a contact gives all three\n * or none (0037). A preview lacks what it has no value for, and says\n * nothing of it.\n */\nfunction contact(reader: Reader, held: SellerContact | undefined, path: string): Read<ContactTerms> {\n if (held === undefined) return null\n const terms = E_INVOICE_TEXT_TERMS.seller.contact\n const read = {\n name: text(reader, terms.name, held.name, `${path}/name`),\n telephone: text(reader, terms.telephone, held.telephone, `${path}/telephone`),\n email: text(reader, terms.email, held.email, `${path}/email`),\n }\n const { name, telephone, email } = read\n if (name === undefined || telephone === undefined || email === undefined) return undefined\n if (name !== null && telephone !== null && email !== null) return { name, telephone, email }\n if ((name === null && telephone === null && email === null) || reader.render.preview) return null\n for (const key of ['name', 'telephone', 'email'] as const) {\n if (read[key] === null)\n refuse(reader, `${path}/${key}`, `${E_INVOICE_KIND_TEXTS[reader.kind][terms[key]].what} is empty, and a contact gives all three of its terms or none`)\n }\n return undefined\n}\n\n/** A party as read, and which of its identifiers are there: one refused is there, as the validator says of one written. */\ninterface ReadParty {\n readonly party: Read<PartyTerms>\n readonly has: { readonly vatId: boolean; readonly taxNumber: boolean; readonly legalId: boolean }\n}\n\nfunction party(reader: Reader, held: EInvoiceSeller | EInvoiceBuyer, path: string, which: 'seller' | 'buyer'): ReadParty {\n const terms = E_INVOICE_TEXT_TERMS[which]\n const name = text(reader, terms.name, held.name, `${path}/name`)\n const vatId = text(reader, terms.vatId, held.vatId, `${path}/vatId`)\n // A buyer has no tax registration identifier (BT-32 is the seller's).\n const taxNumber = which === 'seller' ? text(reader, E_INVOICE_TEXT_TERMS.seller.taxNumber, (held as EInvoiceSeller).taxNumber, `${path}/taxNumber`) : null\n const legalId = text(reader, terms.legalId, held.legalId?.id, `${path}/legalId/id`)\n const reached = electronicAddress(reader, held.electronicAddress, `${path}/electronicAddress`, terms.electronicAddress)\n // A buyer has no contact (BG-9 is not written).\n const contacted = which === 'seller' ? contact(reader, (held as EInvoiceSeller).contact, `${path}/contact`) : null\n const where = address(reader, held.address, `${path}/address`, which)\n const has = { vatId: vatId !== null, taxNumber: taxNumber !== null, legalId: legalId !== null }\n if (vatId === undefined || taxNumber === undefined || legalId === undefined || reached === undefined || contacted === undefined || !all(name, where))\n return { party: undefined, has }\n const scheme = held.legalId?.scheme\n const registration = legalId === null ? {} : { legalId: { id: legalId, ...(scheme === undefined ? {} : { scheme }) } }\n return {\n party: {\n name: name as string,\n ...term('vatId', vatId),\n ...term('taxNumber', taxNumber),\n ...registration,\n ...term('electronicAddress', reached),\n ...term('contact', contacted),\n address: where as AddressTerms,\n },\n has,\n }\n}\n\nfunction payment(reader: Reader, invoice: EInvoice): { readonly payment: Read<PaymentTerms>; readonly account: string | undefined } {\n const held = invoice.payment\n if (held === undefined) return { payment: null, account: undefined }\n const terms = E_INVOICE_TEXT_TERMS.payment\n const account = text(reader, terms.iban, held.iban, '/eInvoice/payment/iban')\n const bic = text(reader, terms.bic, held.bic, '/eInvoice/payment/bic')\n const accountName = text(reader, terms.accountName, held.accountName, '/eInvoice/payment/accountName')\n const remittance = text(reader, terms.remittance, held.remittance, '/eInvoice/payment/remittance')\n const known = account ?? undefined\n if (bic === undefined || accountName === undefined || remittance === undefined || !all(account)) return { payment: undefined, account: known }\n return {\n payment: { means: held.means, account: account as string, ...term('bic', bic), ...term('accountName', accountName), ...term('remittance', remittance) },\n account: known,\n }\n}\n\n/** The paid amount (BT-113), read in the report's scope: a whole number of cents, at two places, or null where none is paid. */\nexport function paidAmount(render: Omit<Render, 'invoice'>, invoice: EInvoice): Read<Decimal> {\n if (invoice.paid === undefined) return null\n const path = '/eInvoice/paid'\n const value = valueOf(render, reportScope(render, render.totals.report), `${path}/cel`)\n if (value === undefined || value === null) return value\n const what = E_INVOICE_DECIMALS['BT-113'].what\n if (value.type !== 'decimal') return refuse({ render }, path, `${what} is a decimal, and this gives ${aType(value.type)}`)\n const checked = checkEInvoiceDecimal('BT-113', decimalToString(value.value))\n return checked.ok ? decimalFromString(checked.value) : refuse({ render }, path, `${what} ${checked.rule}`)\n}\n\n/** What reading the terms gives: the terms, where every one is there; and the payment account, where its rule took it, for a payment code to be held to. */\nexport interface ReadTerms {\n readonly terms: InvoiceTerms | undefined\n readonly account: string | undefined\n}\n\n/**\n * Every term of `invoice` but its lines and its totals, each read in the\n * report's scope and held to its rule, and what the whole breaks said of\n * `used`, the categories the lines are in. `terms` is undefined where a\n * term was refused, which is recorded, or a preview lacks one.\n */\nexport function readTerms(render: Omit<Render, 'invoice'>, invoice: EInvoice, used: readonly VatCategory[]): ReadTerms {\n const reader: Reader = { render, scope: reportScope(render, render.totals.report), kind: invoice.kind }\n const number = text(reader, E_INVOICE_TEXT_TERMS.number, invoice.number, '/eInvoice/number')\n const issued = date(reader, 'BT-2', invoice.issued, '/eInvoice/issued')\n const businessProcess = text(reader, E_INVOICE_TEXT_TERMS.businessProcess, invoice.businessProcess, '/eInvoice/businessProcess')\n const seller = party(reader, invoice.seller, '/eInvoice/seller', 'seller')\n const buyer = party(reader, invoice.buyer, '/eInvoice/buyer', 'buyer')\n const buyerReference = text(reader, E_INVOICE_TEXT_TERMS.buyerReference, invoice.buyerReference, '/eInvoice/buyerReference')\n const delivered = date(reader, 'BT-72', invoice.delivered, '/eInvoice/delivered')\n const start = date(reader, 'BT-73', invoice.period?.start, '/eInvoice/period/start')\n const end = date(reader, 'BT-74', invoice.period?.end, '/eInvoice/period/end')\n const reasons = used.map(\n (category) => [category, text(reader, E_INVOICE_TEXT_TERMS.reason, category.reason, `/eInvoice/vat/${invoice.vat.indexOf(category)}/reason`)] as const,\n )\n const paying = payment(reader, invoice)\n const due = date(reader, 'BT-9', invoice.due, '/eInvoice/due')\n const terms = text(reader, E_INVOICE_TEXT_TERMS.terms, invoice.terms, '/eInvoice/terms')\n\n const ordered = typeof start === 'string' && typeof end === 'string' ? checkInvoicingPeriod(start, end) : undefined\n if (ordered !== undefined) refuse(reader, '/eInvoice/period', ordered)\n if (!render.preview) {\n const codes = used.map(({ code }) => code)\n for (const rule of sellerIdentificationBreaks(seller.has, codes)) refuse(reader, '/eInvoice/seller', rule)\n const unidentified = buyerIdentificationBreak(buyer.has, codes)\n if (unidentified !== undefined) refuse(reader, '/eInvoice/buyer', unidentified)\n const unsupplied = supplyBreak(delivered !== null, start !== null || end !== null)\n if (unsupplied !== undefined) refuse(reader, '/eInvoice/delivered', unsupplied)\n for (const [category, reason] of reasons) {\n const unreasoned = vatReasonBreak(category.code, reason !== null)\n if (unreasoned !== undefined) refuse(reader, `/eInvoice/vat/${invoice.vat.indexOf(category)}/reason`, unreasoned)\n }\n }\n const read = [\n number,\n issued,\n businessProcess,\n seller.party,\n buyer.party,\n buyerReference,\n delivered,\n start,\n end,\n paying.payment,\n due,\n terms,\n ...reasons.map(([, reason]) => reason),\n ]\n if (render.problems.failed || read.includes(undefined) || !all(number, issued, seller.party, buyer.party))\n return { terms: undefined, account: paying.account }\n return {\n terms: {\n number: number as string,\n issued: issued as string,\n ...term('businessProcess', businessProcess),\n seller: seller.party as PartyTerms,\n buyer: buyer.party as PartyTerms,\n ...term('buyerReference', buyerReference),\n ...term('delivered', delivered),\n ...(start === null && end === null ? {} : { period: { ...term('start', start), ...term('end', end) } }),\n reasons: new Map(reasons.flatMap(([category, reason]) => (typeof reason === 'string' ? [[category.id, reason] as const] : []))),\n ...term('payment', paying.payment),\n ...term('due', due),\n ...term('terms', terms),\n },\n account: paying.account,\n }\n}\n","/**\n * A report's e-invoice resolved (0027): its lines and its totals before\n * anything is lowered, since the page prints them; and after the page is\n * lowered, in a final render, the XML the PDF embeds.\n *\n * 1. **The lines**, read once from the rows of the table that prints them\n * (`e-invoice-lines.ts`), each column's value kept for the table to\n * print.\n * 2. **The paid amount and the totals**, computed once from the lines\n * (`e-invoice-totals.ts`) and bound as `invoice`, `vatBasis` and\n * `vatAmount` for every scope that reads them.\n * 3. **The other terms**, read in the report's scope and held to EN\n * 16931's rules (`e-invoice-terms.ts`); a payment code is held to the\n * amount due and the account they give (`e-invoice-payable.ts`).\n * 4. **The XML** (`cii.ts`), written from those very values.\n *\n * **A preview is not the invoice.** In Germany the XML a hybrid invoice\n * embeds is the invoice, so a preview writes none and the PDF that leaves\n * it is no e-invoice; it prints the totals of what it has, and warns\n * `e-invoice-preview` whatever data it has, so that every page carries a\n * preview label, complete data or not. A final render writes the XML or\n * refuses.\n *\n * **Both kinds are resolved alike** (0038): an XRechnung's terms are EN\n * 16931's, read by the same readers under its kind's rules, and written by\n * the same writer, its specification identifier apart. What differs is\n * the file the document carries: a Factur-X file a PDF/A-3b embeds, or an\n * XRechnung's XML a host takes and sends.\n */\nimport { FACTUR_X, FACTUR_X_PROFILES, XRECHNUNG } from '@formancy/report-spec'\nimport type { EInvoice, EInvoiceKind } from '@formancy/report-spec'\nimport { ciiXml } from './cii.js'\nimport type { CiiInvoice } from './cii.js'\nimport type { EInvoiceFile } from './document.js'\nimport { readLines, writtenLines } from './e-invoice-lines.js'\nimport { paidAmount, readTerms } from './e-invoice-terms.js'\nimport { invoiceNames, invoiceTotals } from './e-invoice-totals.js'\nimport type { InvoiceReads, Render } from './render-context.js'\n\n/** An e-invoice resolved before lowering: what lowering reads, and what a final render writes its XML from. */\nexport interface ResolvedInvoice {\n readonly reads: InvoiceReads\n /** In a final render whose every term resolved, what the XML is written from; undefined in a preview, or where a term was refused, which is recorded. */\n readonly written: CiiInvoice | undefined\n}\n\n/** BT-24 of each kind: a Factur-X profile's identifier, or an XRechnung version's. A table over every kind, so a kind added without one does not compile. */\nconst GUIDELINES: { readonly [K in EInvoiceKind]: (invoice: Extract<EInvoice, { kind: K }>) => string } = {\n facturX: (invoice) => FACTUR_X_PROFILES[invoice.profile].guideline,\n xrechnung: (invoice) => XRECHNUNG[invoice.version].guideline,\n}\n\n/** The guideline of `invoice`, by its kind. */\nconst guidelineOf = (invoice: EInvoice): string => (GUIDELINES[invoice.kind] as (invoice: EInvoice) => string)(invoice)\n\n/**\n * `invoice`, `render`'s e-invoice, resolved before anything is lowered,\n * whatever its kind: its lines, its totals and its terms, each held to its\n * kind's rules, and in a final render whose every term resolved what its\n * XML is written from. Undefined when its lines or its totals could not\n * be, which is recorded: nothing that prints them can be lowered. A term\n * refused is recorded, and leaves nothing to write.\n */\nexport function resolveEInvoice(render: Omit<Render, 'invoice'>, invoice: EInvoice): ResolvedInvoice | undefined {\n const read = readLines(render, invoice)\n const paid = paidAmount(render, invoice)\n if (read === undefined || paid === undefined) return undefined\n // A line a preview cannot place, its amount or its category lacking, is in no total.\n const placed = read.lines.flatMap(({ netAmount, category }) => (netAmount === null || category === null ? [] : [{ netAmount, category }]))\n const totals = invoiceTotals(invoice.vat, placed, paid)\n const { terms, account } = readTerms(\n render,\n invoice,\n totals.breakdown.map(({ category }) => category),\n )\n const lines = writtenLines(read.lines)\n const written =\n render.preview || terms === undefined || lines === undefined\n ? undefined\n : { guideline: guidelineOf(invoice), type: invoice.type, currency: invoice.currency, terms, lines, totals }\n return { reads: { names: invoiceNames(invoice, totals), columns: read.columns, payable: { amount: totals.duePayable, account } }, written }\n}\n\n/**\n * The file of each kind, around its XML: Factur-X's, named as report-spec\n * names the file a PDF/A-3b embeds [S]; an XRechnung's, standalone, named\n * by its syntax, guideline and version. A table over every kind.\n */\nconst FILES: { readonly [K in EInvoiceKind]: (invoice: Extract<EInvoice, { kind: K }>, xml: string) => EInvoiceFile } = {\n facturX: (invoice, xml) => {\n const profile = FACTUR_X_PROFILES[invoice.profile]\n return { kind: 'facturX', xml, fileName: FACTUR_X.fileName, relationship: profile.relationship, conformanceLevel: profile.conformanceLevel }\n },\n xrechnung: (invoice, xml) => {\n const version = XRECHNUNG[invoice.version]\n return { kind: 'xrechnung', xml, syntax: version.syntax, guideline: version.guideline, version: invoice.version }\n },\n}\n\n/** What a preview of an e-invoice warns, whatever data it has. */\nconst PREVIEWED = 'this is a preview, which writes no e-invoice: a final render alone writes its XML, and this PDF is not the invoice'\n\n/**\n * The file the PDF of `render` embeds, once its page is lowered: in a\n * final render the XML, named as report-spec names it; in a preview none,\n * and the warning that says so. Undefined too where anything was refused,\n * which refuses the document.\n *\n * A final render with nothing to write and nothing recorded would hand on\n * a document without its XML, which a renderer draws as a plain PDF: a\n * picture of an invoice handed over as though it were one. Every way to\n * nothing records an error first, so that is a defect, and throws.\n */\nexport function eInvoiceFile(render: Render, resolved: ResolvedInvoice, invoice: EInvoice): EInvoiceFile | undefined {\n if (render.preview) {\n render.problems.warn({ stage: 'resolve', code: 'e-invoice-preview', path: '/eInvoice', message: `the e-invoice: ${PREVIEWED}` })\n return undefined\n }\n if (render.problems.failed) return undefined\n if (resolved.written === undefined)\n throw new RangeError('a final render of an e-invoice wrote no XML and recorded no reason: a defect, refused rather than drawn as a plain PDF')\n return (FILES[invoice.kind] as (invoice: EInvoice, xml: string) => EInvoiceFile)(invoice, ciiXml(resolved.written))\n}\n","/**\n * A report's font map resolved to the bytes the renderer embeds (0043).\n *\n * The definition maps each font token to approved font assets, face by face\n * ([report-spec's `font-map.ts`](../../report-spec/src/font-map.ts)); here\n * the host's lookup hands over each face's bytes, as it does an image's\n * (0033), and the runtime reads them once with report-spec's `readFont`\n * before it hands them on, so that a font the renderer could not embed is\n * refused where the data is resolved, not deep inside the engine. The\n * renderer reads them again, since it is a package boundary that takes\n * resolved input and approved bytes and refuses what it cannot draw (0011);\n * what is read here is read there too, by the one reader.\n *\n * A font is structural, not a value: a token a report maps prints all its\n * text in that face, so a face whose bytes cannot be had, or that `readFont`\n * refuses, refuses the render -- in a preview too, since a preview that\n * dropped a mapped face would print its text in another font nobody chose\n * (fail closed). Each face is fetched once, however many tokens or weights\n * share one asset.\n *\n * Nothing here is shared with the host: the bytes are copied, as an image's\n * are, so that what the host changes afterwards never reaches the document.\n */\nimport { FONT_FACE_KEYS, isFontMediaType, MAX_FONT_BYTES, readFont } from '@formancy/report-spec'\nimport type { AssetRef, FontFaceKey, FontFamily, FontMap } from '@formancy/report-spec'\nimport type { FontAsset, ResolvedFaces, ResolvedFonts } from './document.js'\nimport type { ImageBytes, Render } from './render-context.js'\n\n/** The faces of one family, by key: what `resolveFaces` builds. */\ntype Faces = { -readonly [K in FontFaceKey]?: FontAsset }\n\n/**\n * `fonts` resolved to the bytes each face prints in, or undefined when the\n * report maps nothing. A face that cannot be had or that `readFont` refuses\n * records an error and resolves nothing for that face; the caller refuses\n * the render when any error was recorded.\n */\nexport function resolveFonts(render: Render, fonts: FontMap | undefined): ResolvedFonts | undefined {\n if (fonts === undefined) return undefined\n const byId = new Map<string, FontAsset | undefined>()\n const result: { -readonly [F in FontFamily]?: ResolvedFaces } = {}\n for (const [family, faces] of Object.entries(fonts) as [FontFamily, FontMap[FontFamily]][]) {\n if (faces === undefined) continue\n const resolved: Faces = {}\n for (const key of FONT_FACE_KEYS) {\n const id = faces[key]\n if (id === undefined) continue\n const asset = faceAsset(render, byId, id, `/fonts/${family}/${key}`)\n if (asset !== undefined) resolved[key] = asset\n }\n // `normal` is required by the validator; a resolution that reached here without it has recorded the error that stops the render.\n if (resolved.normal !== undefined) result[family] = resolved as ResolvedFaces\n }\n return result\n}\n\n/** The bytes of the face asset `id`, fetched once and kept, checked with `readFont`; undefined when it could not be had, which is recorded at `path`. */\nfunction faceAsset(render: Render, byId: Map<string, FontAsset | undefined>, id: string, path: string): FontAsset | undefined {\n if (byId.has(id)) return byId.get(id)\n const asset = fetchFace(render, id, path)\n byId.set(id, asset)\n return asset\n}\n\n/** What the host holds for the font asset `id`, copied and read, or undefined with an error recorded at `path`. */\nfunction fetchFace(render: Render, id: string, path: string): FontAsset | undefined {\n const error = (code: 'missing-asset' | 'invalid-asset' | 'asset-lookup-failed', message: string): undefined => {\n render.problems.error({ stage: 'resolve', code, path, message })\n return undefined\n }\n if (render.images === undefined) return error('missing-asset', `the report maps a font, and the host gave no way to fetch approved assets`)\n // report-spec refuses a font map that names an undeclared asset, so the ref is one the report declares.\n const declared = render.report.assets.find((ref) => ref.id === id) as AssetRef\n let found: ImageBytes | undefined\n try {\n found = render.images({ asset: declared.id, digest: declared.digest })\n } catch {\n return error('asset-lookup-failed', `fetching the approved font ${id} failed`)\n }\n if (found === undefined) return error('missing-asset', `the host has no bytes for the approved font ${id} at its digest`)\n if (typeof found !== 'object' || !(found.bytes instanceof Uint8Array) || !isFontMediaType(found.mediaType)) {\n return error('invalid-asset', `the host's answer for the approved font ${id} is not bytes of ${declared.mediaType}`)\n }\n if (found.bytes.length > MAX_FONT_BYTES)\n return error('invalid-asset', `the approved font ${id} is ${found.bytes.length} bytes; a font may have ${MAX_FONT_BYTES}`)\n const bytes = new Uint8Array(found.bytes)\n const read = readFont(bytes)\n if (!read.ok) return error('invalid-asset', `the approved font ${id}: the font ${read.message}`)\n return { id, digest: declared.digest, bytes }\n}\n","/**\n * A payment code printed with an e-invoice -- the QR-bill, an EPC QR code\n * -- held to it once both have resolved: it asks for the amount due for\n * payment (BT-115), or leaves the amount to the payer, and to be paid to\n * the e-invoice's payment account (BT-84).\n *\n * The page and the XML are one invoice, or the page is a second one: a\n * picture that asks for another amount or another account than its\n * structured part says may count as a further invoice under § 14c UStG\n * (BMF, 15 October 2025, UStAE 14c.1 (4a)). report-spec refuses what a\n * template's literals break, its currency among them; what only the data\n * decides -- an amount is always an expression, an account may be read\n * from a field -- is compared here, by value, the account as each code's\n * own rule wrote it: its spaces dropped and its letters capitals. A code\n * whose amount or account its own rules refused is not compared again.\n */\nimport { compareDecimal } from '@formancy/expressions'\nimport type { Decimal } from '@formancy/expressions'\nimport type { Render } from './render-context.js'\n\n/** A payment code, as a refusal names it, and where its amount and its account stand. */\nexport interface PayingCode {\n /** \"the payment part\", \"component pay-code\". */\n readonly said: string\n /** \"the QR-bill\", \"the EPC QR code\". */\n readonly code: string\n readonly componentId?: string\n readonly amountPath: string\n readonly accountPath: string\n}\n\n/**\n * Records what `code`, which asks for `amount` -- null to leave it to the\n * payer -- to `account`, asks for that the e-invoice does not name; nothing\n * in a report that is no e-invoice, or where the e-invoice's account was\n * refused or a preview lacks it.\n */\nexport function checkPayable(render: Render, code: PayingCode, amount: Decimal | null, account: string): void {\n const payable = render.invoice?.payable\n if (payable === undefined) return\n const refuse = (path: string, message: string): void =>\n render.problems.error({\n stage: 'resolve',\n code: 'invalid-e-invoice',\n path,\n message: `${code.said}: ${message}`,\n ...(code.componentId === undefined ? {} : { componentId: code.componentId }),\n })\n if (amount !== null && compareDecimal(amount, payable.amount) !== 0) {\n refuse(code.amountPath, `${code.code} asks for another amount than the e-invoice's amount due for payment (BT-115): a page and its XML ask for one amount`)\n }\n if (payable.account !== undefined && account !== payable.account) {\n refuse(\n code.accountPath,\n `${code.code} asks to be paid to another account than the e-invoice's payment account (BT-84): a page and its XML name one account`,\n )\n }\n}\n","/**\n * A Swiss QR-bill made from values SIX's rules have accepted: the Swiss QR\n * Code's payload, and every text its slip prints.\n *\n * The rules a value is held to are report-spec's (`qr-bill.ts` there), one\n * set for a literal at validation and for a value from data here. What is\n * the runtime's alone is what a checked bill becomes:\n *\n * - **The payload**, in the order of IG Table 8, each element on its line.\n * - **The printed values**, grouped as the slip prints them (IG 3.5, 3.6).\n * - **The headings**, in the slip's language (IG Annex C).\n *\n * Nothing here reads a value as a number: an amount's digits are grouped\n * as text. \"IG\" is SIX's Swiss Implementation Guidelines for the QR-bill,\n * version 2.4 of 24 February 2026, whose payload, printing rules and\n * headings are version 2.3's, but for the Romansh headings it adds.\n */\nimport { QR_BILL_ADDRESS_RULES } from '@formancy/report-spec'\nimport type { QrBillAccount, QrBillAddress, QrBillCurrency, QrBillLanguage, QrBillReference } from '@formancy/report-spec'\nimport type { QrBill, QrBillHeadings } from './document.js'\n\n/** A party's address as SIX's rules accepted it: each part without the blanks around it, a part absent as ''. */\nexport type CheckedAddress = { readonly [P in keyof QrBillAddress]-?: string }\n\n/** A bill whose every text SIX's rules accepted, each as the code holds it. */\nexport interface CheckedQrBill {\n readonly language: QrBillLanguage\n readonly account: QrBillAccount\n readonly creditor: CheckedAddress\n readonly currency: QrBillCurrency\n /** As the code writes it: \"1949.75\"; null leaves it to the payer. */\n readonly amount: string | null\n /** Null leaves the field for the payer's name and address. */\n readonly debtor: CheckedAddress | null\n /** Null is a bill without one: NON. */\n readonly reference: QrBillReference | null\n /** '' for none. */\n readonly message: string\n /** '' for none. */\n readonly billingInformation: string\n}\n\n/** What the slip's headings say, before the payer's heading is chosen by whether the bill has a debtor. */\ntype Words = Omit<QrBillHeadings, 'payableBy'> & { readonly payableBy: string; readonly payableByBlank: string }\n\n/**\n * IG Annex C, Table 23, version 2.4, read in its PDF's text. Version 2.3's\n * English table printed Italian's currency as \"Value date\" and two French\n * words wrongly, which version 2.4 and the French edition correct; and\n * version 2.4 adds Romansh, in force since 1 January 2026.\n */\nconst HEADINGS: { readonly [L in QrBillLanguage]: Words } = {\n de: {\n paymentPart: 'Zahlteil',\n receipt: 'Empfangsschein',\n account: 'Konto / Zahlbar an',\n reference: 'Referenz',\n additionalInformation: 'Zusätzliche Informationen',\n payableBy: 'Zahlbar durch',\n payableByBlank: 'Zahlbar durch (Name/Adresse)',\n currency: 'Währung',\n amount: 'Betrag',\n acceptancePoint: 'Annahmestelle',\n separate: 'Vor der Einzahlung abzutrennen',\n },\n fr: {\n paymentPart: 'Section paiement',\n receipt: 'Récépissé',\n account: 'Compte / Payable à',\n reference: 'Référence',\n additionalInformation: 'Informations supplémentaires',\n payableBy: 'Payable par',\n payableByBlank: 'Payable par (nom/adresse)',\n currency: 'Monnaie',\n amount: 'Montant',\n acceptancePoint: 'Point de dépôt',\n separate: 'A détacher avant le versement',\n },\n it: {\n paymentPart: 'Sezione pagamento',\n receipt: 'Ricevuta',\n account: 'Conto / Pagabile a',\n reference: 'Riferimento',\n additionalInformation: 'Informazioni supplementari',\n payableBy: 'Pagabile da',\n payableByBlank: 'Pagabile da (nome/indirizzo)',\n currency: 'Valuta',\n amount: 'Importo',\n acceptancePoint: 'Punto di accettazione',\n separate: 'Da staccare prima del versamento',\n },\n en: {\n paymentPart: 'Payment part',\n receipt: 'Receipt',\n account: 'Account / Payable to',\n reference: 'Reference',\n additionalInformation: 'Additional information',\n payableBy: 'Payable by',\n payableByBlank: 'Payable by (name/address)',\n currency: 'Currency',\n amount: 'Amount',\n acceptancePoint: 'Acceptance point',\n separate: 'Separate before paying in',\n },\n rm: {\n paymentPart: 'Part da pajament',\n receipt: 'Quittanza',\n account: 'Conto / Da pajar a',\n reference: 'Referenza',\n additionalInformation: 'Infurmaziuns supplementaras',\n payableBy: 'Da pajar da',\n payableByBlank: 'Da pajar da (num/adressa)',\n currency: 'Valuta',\n amount: 'Import',\n acceptancePoint: 'Post da recepziun',\n separate: 'Da distatgar avant che pajar',\n },\n}\n\n/** An address's parts in the order the code holds them, which report-spec's table of their rules is in. */\nconst ADDRESS_PARTS = Object.keys(QR_BILL_ADDRESS_RULES) as readonly (keyof QrBillAddress)[]\n\n/** A party's seven lines (IG Table 8): the structured address type, S, and its parts; none at all, seven empty lines. */\nfunction party(address: CheckedAddress | null): string[] {\n return address === null ? ['', ...ADDRESS_PARTS.map(() => '')] : ['S', ...ADDRESS_PARTS.map((part) => address[part])]\n}\n\n/**\n * The Swiss QR Code's text (IG 4.1.4, Table 8). Every element is on its\n * line, an empty one as an empty line, and the lines are separated by a\n * line feed, with none after the last. The ultimate creditor's lines are\n * empty: SIX keeps them for later use and they \"must not be filled in\".\n * Billing information, of status A, is left out when the bill has none:\n * nothing after it is ever used, since this format has no alternative\n * procedure. Version 0200 is the only one SIX allows in master version 02,\n * and coding 1 is UTF-8 restricted to the characters of IG 4.1.1.\n */\nfunction payload(bill: CheckedQrBill): string {\n return [\n 'SPC',\n '0200',\n '1',\n bill.account.iban,\n ...party(bill.creditor),\n ...party(null),\n bill.amount ?? '',\n bill.currency,\n ...party(bill.debtor),\n bill.reference?.type ?? 'NON',\n bill.reference?.reference ?? '',\n bill.message,\n 'EPD',\n ...(bill.billingInformation === '' ? [] : [bill.billingInformation]),\n ].join('\\n')\n}\n\n/** `text` in blocks of `size` characters from its start, the last block shorter. */\nfunction blocks(text: string, size: number): string {\n const parts: string[] = []\n for (let start = 0; start < text.length; start += size) parts.push(text.slice(start, start + size))\n return parts.join(' ')\n}\n\n/** A QR reference in two digits and five blocks of five; a creditor reference in blocks of four (IG 3.5.4). */\nfunction printedReference(reference: QrBillReference): string {\n const { type, reference: text } = reference\n return type === 'QRR' ? `${text.slice(0, 2)} ${blocks(text.slice(2), 5)}` : blocks(text, 4)\n}\n\n/** The amount with a space between each three digits before the point (IG 3.5.3: \"CHF 1 590.00\"), grouped as text. */\nfunction printedAmount(amount: string): string {\n const [whole = '', cents = ''] = amount.split('.')\n const groups: string[] = []\n for (let end = whole.length; end > 0; end -= 3) groups.unshift(whole.slice(Math.max(0, end - 3), end))\n return `${groups.join(' ')}.${cents}`\n}\n\n/**\n * An address as the slip prints it, as IG 3.5.4 and SIX's style guide show\n * it: the name; the street and building number, on one line; the postal\n * code and the town. The country is printed for a party outside\n * Switzerland, Liechtenstein one of them; the guidelines do not say how,\n * and it goes before the postal code, as in \"LI-9490 Vaduz\".\n */\nfunction printedAddress(address: CheckedAddress): string[] {\n const street = [address.street, address.buildingNumber].filter((part) => part !== '').join(' ')\n const country = address.country === 'CH' ? '' : `${address.country}-`\n return [address.name, ...(street === '' ? [] : [street]), `${country}${address.postalCode} ${address.town}`]\n}\n\n/** The document's bill: `bill`'s payload, and every text its slip prints, in its language. */\nexport function qrBillPart(bill: CheckedQrBill): QrBill {\n const { payableByBlank, payableBy, ...words } = HEADINGS[bill.language]\n return {\n kind: 'swissQrBill',\n payload: payload(bill),\n headings: { ...words, payableBy: bill.debtor === null ? payableByBlank : payableBy },\n account: blocks(bill.account.iban, 4),\n creditor: printedAddress(bill.creditor),\n reference: bill.reference === null ? null : printedReference(bill.reference),\n additionalInformation: [bill.message, bill.billingInformation].filter((text) => text !== ''),\n debtor: bill.debtor === null ? null : printedAddress(bill.debtor),\n currency: bill.currency,\n amount: bill.amount === null ? null : printedAmount(bill.amount),\n }\n}\n","/**\n * A report's payment part lowered to the document's: each text read in the\n * report's scope, held to SIX's rules, and made into the bill\n * (`qr-bill.ts`).\n *\n * - **Read as a paragraph.** Every text is its runs, read as a paragraph's\n * in the report's scope and joined as a QR code's content is\n * (`joinedText`): a final render refuses a run whose value is null, as\n * `no-qr-value`, since the bill's code would say less than its texts.\n * - **Held to SIX's rules.** report-spec's checks, the very functions its\n * validator applies to a literal, are applied to every text once it has\n * resolved: a literal passes again, and a value from data is held where\n * the validator could not see it. A rule broken is `invalid-qr-bill` on\n * the field, naming the rule and never the value, which may be a\n * person's name or account.\n * - **The same in a preview.** A preview prints a value that is null, or\n * one its data lacks, as nothing, as a paragraph does; the bill that\n * leaves is held to the same rules, and refused where it breaks one,\n * saying the preview had no value for it. A bill SIX refuses cannot be\n * drawn as one: its code would scan as a bill no bank pays.\n * - **The amount** is a decimal, or null for the payer to fill in. Any\n * other value is refused by its type, and a decimal is written with its\n * own digits, never rounded: one with more than two places is refused.\n * - **Printed with an e-invoice**, it asks for the amount due and to be\n * paid to the e-invoice's account (`e-invoice-payable.ts`).\n */\nimport { decimalFromString, decimalToString } from '@formancy/expressions'\nimport {\n checkQrBillAccount,\n checkQrBillAdditionalInformation,\n checkQrBillAmount,\n checkQrBillReference,\n checkQrBillText,\n QR_BILL_ADDRESS_RULES,\n QR_BILL_BILLING_RULE,\n QR_BILL_MESSAGE_RULE,\n qrBillPairing,\n} from '@formancy/report-spec'\nimport type { Expression, Inline, PaymentPart, PaymentPartKind, QrBillAddress, QrBillCheck, QrBillTextRule, SwissQrBill } from '@formancy/report-spec'\nimport type { QrBill } from './document.js'\nimport { checkPayable } from './e-invoice-payable.js'\nimport { joinedText } from './inlines.js'\nimport type { Encoder } from './inlines.js'\nimport { qrBillPart } from './qr-bill.js'\nimport type { CheckedAddress } from './qr-bill.js'\nimport { reportScope, valueOf } from './render-context.js'\nimport type { Render, Scope } from './render-context.js'\n\nconst PATH = '/paymentPart'\n\n/** What an error in the payment part names it by: it stands in no component. */\nconst PART: Encoder = { said: 'the payment part', code: 'a QR-bill' }\n\n/** What lowering one bill reads, and records its errors in. */\ninterface Lowering {\n readonly render: Render\n readonly scope: Scope\n}\n\nfunction refuse({ render }: Lowering, path: string, message: string): undefined {\n render.problems.error({ stage: 'resolve', code: 'invalid-qr-bill', path, message })\n return undefined\n}\n\n/**\n * The text the runs at `path` print, held to `check`, as `what` names it in\n * an error: what the check made of it, or undefined when a run or the rule\n * refused it, which is recorded. Absent runs print nothing, which the rule\n * judges: an optional text, nothing; a required one, empty.\n */\nfunction checked<T>(\n lowering: Lowering,\n runs: readonly Inline[] | undefined,\n path: string,\n what: string,\n check: (text: string) => QrBillCheck<T>,\n): T | undefined {\n const joined = joinedText(lowering.render, lowering.scope, runs ?? [], path, PART)\n if (joined === undefined) return undefined\n const outcome = check(joined.text)\n if (outcome.ok) return outcome.value\n return refuse(lowering, path, `${what} ${outcome.rule}${joined.lacking ? '; this preview has no value for a run of it' : ''}`)\n}\n\nconst ADDRESS_PARTS = Object.entries(QR_BILL_ADDRESS_RULES) as readonly (readonly [keyof QrBillAddress, QrBillTextRule])[]\n\n/** A party's address, each part held to its rule; undefined when a part is refused, which is recorded. */\nfunction address(lowering: Lowering, value: QrBillAddress, path: string, party: 'creditor' | 'debtor'): CheckedAddress | undefined {\n const parts: Partial<Record<keyof QrBillAddress, string>> = {}\n let whole = true\n for (const [part, rule] of ADDRESS_PARTS) {\n const text = checked(lowering, value[part], `${path}/${part}`, `the ${party}'s ${rule.said}`, (each) => checkQrBillText(each, rule))\n if (text === undefined) whole = false\n else parts[part] = text\n }\n return whole ? (parts as CheckedAddress) : undefined\n}\n\n/** The amount as the code writes it, null for the payer to fill in, or undefined when it is refused, which is recorded. */\nfunction amount(lowering: Lowering, expression: Expression | undefined): string | null | undefined {\n if (expression === undefined) return null\n const path = `${PATH}/amount`\n const value = valueOf(lowering.render, lowering.scope, `${path}/cel`)\n if (value === undefined || value === null) return value\n if (value.type !== 'decimal')\n return refuse(lowering, path, `the amount gives ${value.type}, and a QR-bill's amount is a decimal, or null to leave it for the payer`)\n const outcome = checkQrBillAmount(decimalToString(value.value))\n return outcome.ok ? outcome.value : refuse(lowering, path, `the amount ${outcome.rule}`)\n}\n\n/** `bill`, resolved and held to SIX's rules; undefined when anything of it is refused, which is recorded. */\nfunction swissQrBill(lowering: Lowering, bill: SwissQrBill): QrBill | undefined {\n const account = checked(lowering, bill.account, `${PATH}/account`, 'the account', checkQrBillAccount)\n const creditor = address(lowering, bill.creditor, `${PATH}/creditor`, 'creditor')\n const sum = amount(lowering, bill.amount)\n const debtor = bill.debtor === undefined ? null : address(lowering, bill.debtor, `${PATH}/debtor`, 'debtor')\n const reference = bill.reference === undefined ? null : checked(lowering, bill.reference, `${PATH}/reference`, 'the reference', checkQrBillReference)\n const message = checked(lowering, bill.message, `${PATH}/message`, 'the message', (text) => checkQrBillText(text, QR_BILL_MESSAGE_RULE))\n const billing = checked(lowering, bill.billingInformation, `${PATH}/billingInformation`, 'the billing information', (text) =>\n checkQrBillText(text, QR_BILL_BILLING_RULE),\n )\n // What two texts break together, each already held to its own rules.\n const together = message === undefined || billing === undefined ? undefined : checkQrBillAdditionalInformation(message, billing)\n if (together !== undefined) refuse(lowering, `${PATH}/message`, together)\n if (account !== undefined && sum !== undefined) {\n const asked = { said: PART.said, code: 'the QR-bill', amountPath: `${PATH}/amount`, accountPath: `${PATH}/account` }\n checkPayable(lowering.render, asked, sum === null ? null : decimalFromString(sum), account.iban)\n }\n const pairing =\n account === undefined || reference === undefined ? [] : qrBillPairing(account.qrIban ? 'qrIban' : 'iban', reference?.type ?? 'NON', bill.currency)\n for (const { field, rule } of pairing) refuse(lowering, `${PATH}/${field}`, rule)\n if (together !== undefined || pairing.length > 0) return undefined\n if (\n account === undefined ||\n creditor === undefined ||\n sum === undefined ||\n debtor === undefined ||\n reference === undefined ||\n message === undefined ||\n billing === undefined\n )\n return undefined\n return qrBillPart({\n language: bill.language,\n account,\n creditor,\n currency: bill.currency,\n amount: sum,\n debtor,\n reference,\n message,\n billingInformation: billing,\n })\n}\n\ntype PartLowerer<K extends PaymentPartKind> = (lowering: Lowering, part: Extract<PaymentPart, { kind: K }>) => QrBill | undefined\n\n/** How each kind of payment part is lowered. A table over every kind, so a kind added to report-spec without a way down does not compile. */\nconst PARTS: { readonly [K in PaymentPartKind]: PartLowerer<K> } = {\n swissQrBill,\n}\n\n/** `render`'s payment part, lowered; undefined when the report has none, or when it is refused, which is recorded. */\nexport function lowerPaymentPart(render: Render): QrBill | undefined {\n const part = render.report.paymentPart\n if (part === undefined) return undefined\n return PARTS[part.kind]({ render, scope: reportScope(render, render.totals.report) }, part)\n}\n","/**\n * An image component lowered to the bytes it draws.\n *\n * An image shows an asset the template pins, or an image field of the\n * header dataset (0007). Either way it names an approved asset by its id\n * and digest, and the host's lookup hands over the bytes: the runtime never\n * follows an address and fetches nothing. What comes back is checked here --\n * bytes, and a media type a report may draw, the one the template declares\n * for its own asset -- and copied, so that nothing the host changes\n * afterwards reaches the document. Whether the bytes are a picture is the\n * renderer's to say (`invalid-asset`): for an SVG, whether they are exactly\n * the drawing report-spec's `cleanSvg` writes, by report-spec's `checkSvg`,\n * which the renderer applies (0030).\n *\n * The lookup is trusted to return the bytes the digest pins, and they are\n * not checked against it. Not for want of a hash: a pure SHA-256 reaches the\n * runtime through `@formancy/spec`, and checking digests is a decision of\n * its own, since it changes what every host's resolver must satisfy (0030).\n *\n * An image field with no value draws nothing, and its box is kept as space,\n * so that what follows it stands where it would with a picture: null prints\n * as nothing (0007), and nothing moves.\n *\n * Each approved asset is asked for once per render, and every image that\n * draws it shares the one copy, so that a logo on every page header, or a\n * photo drawn by forty components, is held once: a PNG or a JPEG is\n * embedded once, and an SVG is drawn again wherever it prints, on every\n * page of a page region (0030). An answer past its type's limit --\n * `MAX_ASSET_BYTES`, or `MAX_SVG_BYTES` for an SVG -- is refused before it\n * is copied.\n */\nimport { ASSET_MEDIA_TYPES, MAX_ASSET_BYTES, MAX_SVG_BYTES } from '@formancy/report-spec'\nimport type { AssetMediaType, ImageComponent } from '@formancy/report-spec'\nimport type { Image, ImageAsset, Spacer } from './document.js'\nimport { imageValue } from './render-context.js'\nimport type { ImageBytes, ImageRef, Render } from './render-context.js'\nimport type { ResolveErrorCode } from './resolve-errors.js'\n\n/** Why an asset's bytes could not be had: the code, and what to say after the component's id. */\ninterface Refusal {\n readonly code: ResolveErrorCode\n readonly message: string\n}\n\n/** What the host handed over, if it is bytes of a media type a report draws, within the limit: copied. A string says why it is not. */\nfunction checkedBytes(found: unknown, declared: AssetMediaType | undefined): { readonly mediaType: AssetMediaType; readonly bytes: Uint8Array } | string {\n const media = `is not bytes of ${declared === undefined ? ASSET_MEDIA_TYPES.join(' or ') : declared}`\n if (typeof found !== 'object' || found === null) return media\n const { mediaType, bytes } = found as Partial<ImageBytes>\n if (!(bytes instanceof Uint8Array) || !ASSET_MEDIA_TYPES.includes(mediaType as AssetMediaType)) return media\n if (declared !== undefined && mediaType !== declared) return media\n if (mediaType === 'image/svg+xml' && bytes.length > MAX_SVG_BYTES) return `is ${bytes.length} bytes; an SVG asset may have ${MAX_SVG_BYTES} (1 MiB)`\n if (bytes.length > MAX_ASSET_BYTES) return `is ${bytes.length} bytes; an asset may have ${MAX_ASSET_BYTES} (20 MB)`\n return { mediaType: mediaType as AssetMediaType, bytes: new Uint8Array(bytes) }\n}\n\n/** The bytes of `ref`, asked of the host and checked, or why they could not be had. */\nfunction fetched(render: Render, ref: ImageRef, declared: AssetMediaType | undefined): ImageAsset | Refusal {\n if (render.images === undefined) return { code: 'missing-asset', message: 'the report draws an image, and the host gave no way to fetch approved assets' }\n let found: unknown\n let bytes: ReturnType<typeof checkedBytes>\n try {\n // The answer is read inside the guard too: a getter on it is the host's code, and may throw.\n found = render.images(ref)\n bytes = checkedBytes(found, declared)\n } catch {\n return { code: 'asset-lookup-failed', message: `fetching the approved asset ${ref.asset} failed` }\n }\n if (found === undefined) return { code: 'missing-asset', message: `the host has no bytes for the approved asset ${ref.asset} at its digest` }\n if (typeof bytes === 'string') return { code: 'invalid-asset', message: `the host's answer for the approved asset ${ref.asset} ${bytes}` }\n return { id: ref.asset, ...bytes }\n}\n\n/** Each render's assets, by id, digest and the type declared for them: asked for once, and shared. */\nconst ASSETS = new WeakMap<Render, Map<string, ImageAsset | Refusal>>()\n\nfunction assetOf(render: Render, ref: ImageRef, declared: AssetMediaType | undefined): ImageAsset | Refusal {\n const cache = ASSETS.get(render) ?? new Map<string, ImageAsset | Refusal>()\n ASSETS.set(render, cache)\n const key = JSON.stringify([ref.asset, ref.digest, declared ?? null])\n const known = cache.get(key)\n if (known !== undefined) return known\n const asset = fetched(render, ref, declared)\n cache.set(key, asset)\n return asset\n}\n\n/** `component`, at `path`, as the image it draws, the space it keeps when its field is null, or undefined when its bytes could not be had, which is recorded. */\nexport function imageBlock(render: Render, component: ImageComponent, path: string): Image | Spacer | undefined {\n const { source } = component\n let ref: ImageRef\n let declared: AssetMediaType | undefined\n if (source.kind === 'asset') {\n // report-spec refuses an image of an asset the report does not declare.\n const asset = render.report.assets.find(({ id }) => id === source.asset) as {\n readonly id: string\n readonly mediaType: AssetMediaType\n readonly digest: string\n }\n ref = { asset: asset.id, digest: asset.digest }\n declared = asset.mediaType\n } else {\n const value = imageValue(render, source.field)\n if (value === null) return { kind: 'spacer', height: component.height }\n ref = { asset: value.asset, digest: value.digest }\n }\n const asset = assetOf(render, ref, declared)\n if ('code' in asset) {\n render.problems.error({\n stage: 'resolve',\n code: asset.code,\n path: `${path}/source`,\n message: `component ${component.id}: ${asset.message}`,\n componentId: component.id,\n })\n return undefined\n }\n return { kind: 'image', asset, width: component.width, height: component.height, fit: component.fit }\n}\n","/**\n * An EPC QR code lowered to the document's block: each text read in the\n * report's scope, held to the EPC's rules, and written into the payload the\n * renderer encodes. \"EPC\" is EPC069-12, version 3.1, by its section.\n *\n * - **Read as a paragraph.** Every text is its runs, read as a paragraph's\n * in the report's scope and joined as a QR code's content is\n * (`joinedText`): a final render refuses a run whose value is null, as\n * `no-qr-value`, since the transfer would say less than the invoice --\n * unless the text is optional and prints nothing else.\n * - **Held to the EPC's rules.** report-spec's checks (`epc-payload.ts`),\n * the very functions its validator applies to a literal, are applied to\n * every text once it has resolved: a literal passes again, and a value\n * from data is held where the validator could not see it -- the IBAN's\n * spaces dropped and its letters made capitals, its country's, its\n * length and its check digits; the BIC, and whether the account needs\n * one; the creditor reference; each text's characters and length. A rule\n * broken is `invalid-epc-qr-code` on the field, naming the code and the\n * rule and never the value, which may be a person's name or account.\n * - **An optional text that prints nothing is unused.** A BIC, a\n * reference, a text or information the data gives empty, blank or null\n * is an element the code leaves empty, as one the template does not\n * have, in a final render as in a preview: a customer with no BIC on\n * record is paid by version 002, never refused for a BIC that is no BIC.\n * The validator refuses a blank literal instead, a second spelling of an\n * element left out.\n * - **The same in a preview.** A preview prints a value that is null, or\n * one its data lacks, as nothing, as a paragraph does; the code that\n * leaves is held to the same rules, and refused where it breaks one,\n * saying the preview had no value for it. A code the EPC refuses cannot\n * be drawn as one: it would scan as a transfer no bank makes.\n * - **The amount** is a decimal, or null for the payer to fill in. Any\n * other value is refused by its type, and a decimal is written with its\n * own digits, as short as it can be, never rounded: one with more than\n * two places is refused.\n * - **The payload** is report-spec's `epcPayload` of the checked texts,\n * held to the EPC's 331 bytes in UTF-8, which only the whole can break.\n * - **Printed with an e-invoice**, it asks for the amount due and to be\n * paid to the e-invoice's account (`e-invoice-payable.ts`).\n */\nimport { decimalFromString, decimalToString } from '@formancy/expressions'\nimport { checkEpcAmount, checkEpcField, checkEpcPayload, EPC_TEXT_FIELDS, epcBlank, epcPairing, epcPayload } from '@formancy/report-spec'\nimport type { EpcQrCodeComponent, EpcTextField } from '@formancy/report-spec'\nimport type { EpcQrCode } from './document.js'\nimport { checkPayable } from './e-invoice-payable.js'\nimport { joinedText } from './inlines.js'\nimport type { Encoder } from './inlines.js'\nimport { valueOf } from './render-context.js'\nimport type { Render, Scope } from './render-context.js'\n\n/** What a refusal adds when a preview had no value for a run of the text it refuses. */\nconst LACKED = '; this preview has no value for a run of it'\n\n/** What lowering one code reads, and records its errors in. */\ninterface Lowering {\n readonly render: Render\n readonly scope: Scope\n readonly code: EpcQrCodeComponent\n readonly path: string\n readonly encoder: Encoder\n}\n\nfunction refuse({ render, code, encoder }: Lowering, path: string, message: string): undefined {\n render.problems.error({ stage: 'resolve', code: 'invalid-epc-qr-code', path, message: `${encoder.said}: ${message}`, componentId: code.id })\n return undefined\n}\n\n/** A text as its rule made it, '' for an element the code leaves unused, and whether a preview lacked a value for a run of it. */\ninterface Checked {\n readonly text: string\n readonly lacking: boolean\n}\n\n/**\n * The text `key` of the code, resolved and held to its field's rule\n * (report-spec's `EPC_TEXT_FIELDS`); undefined when a run or the rule\n * refused it, which is recorded. An optional text that prints nothing a\n * payer reads (`epcBlank`), nulls and all, is its element unused, and no\n * rule is asked.\n */\nfunction checked(lowering: Lowering, key: EpcTextField): Checked | undefined {\n const runs = lowering.code[key]\n if (runs === undefined) return { text: '', lacking: false }\n const path = `${lowering.path}/${key}`\n const { what, optional } = EPC_TEXT_FIELDS[key]\n const joined = joinedText(lowering.render, lowering.scope, runs, path, lowering.encoder, optional ? epcBlank : undefined)\n if (joined === undefined) return undefined\n if (optional && epcBlank(joined.text)) return { text: '', lacking: joined.lacking }\n const outcome = checkEpcField(key, joined.text)\n if (outcome.ok) return { text: outcome.value, lacking: joined.lacking }\n return refuse(lowering, path, `${what} ${outcome.rule}${joined.lacking ? LACKED : ''}`)\n}\n\n/** The amount as the code writes it after `EUR`, '' for the payer to fill in, or undefined when it is refused, which is recorded. */\nfunction amount(lowering: Lowering): string | undefined {\n if (lowering.code.amount === undefined) return ''\n const path = `${lowering.path}/amount`\n const value = valueOf(lowering.render, lowering.scope, `${path}/cel`)\n if (value === undefined) return undefined\n if (value === null) return ''\n if (value.type !== 'decimal')\n return refuse(lowering, path, `the amount gives ${value.type}, and an EPC QR code's amount is a decimal in euro, or null to leave it for the payer`)\n const outcome = checkEpcAmount(decimalToString(value.value))\n return outcome.ok ? outcome.value : refuse(lowering, path, `the amount ${outcome.rule}`)\n}\n\n/**\n * The block the EPC QR code `code`, at `path`, prints, read in `scope`;\n * undefined when anything of it is refused, which is recorded. Every text\n * is read and every rule broken said, not the first alone.\n */\nexport function epcQrCodeBlock(render: Render, scope: Scope, code: EpcQrCodeComponent, path: string): EpcQrCode | undefined {\n const lowering: Lowering = { render, scope, code, path, encoder: { said: `component ${code.id}`, componentId: code.id, code: 'an EPC QR code' } }\n const bic = checked(lowering, 'bic')\n const beneficiary = checked(lowering, 'beneficiary')\n const iban = checked(lowering, 'iban')\n const sum = amount(lowering)\n const reference = checked(lowering, 'reference')\n const text = checked(lowering, 'text')\n const information = checked(lowering, 'information')\n // What the IBAN and the BIC break together, each already held to its own rules: a BIC that prints nothing is none.\n const pairing = epcPairing(iban?.text, bic === undefined ? undefined : bic.text === '' ? null : bic.text)\n for (const { field, rule } of pairing) refuse(lowering, `${path}/${field}`, `${rule}${bic?.lacking === true ? LACKED : ''}`)\n if (iban !== undefined && sum !== undefined) {\n const asked = { said: lowering.encoder.said, code: 'the EPC QR code', componentId: code.id, amountPath: `${path}/amount`, accountPath: `${path}/iban` }\n checkPayable(render, asked, sum === '' ? null : decimalFromString(sum), iban.text)\n }\n if (\n pairing.length > 0 ||\n bic === undefined ||\n beneficiary === undefined ||\n iban === undefined ||\n sum === undefined ||\n reference === undefined ||\n text === undefined ||\n information === undefined\n )\n return undefined\n const payload = epcPayload({\n bic: bic.text,\n beneficiary: beneficiary.text,\n iban: iban.text,\n amount: sum,\n purpose: code.purpose,\n reference: reference.text,\n text: text.text,\n information: information.text,\n })\n const bytes = checkEpcPayload(payload)\n if (!bytes.ok) return refuse(lowering, path, `its payload ${bytes.rule}`)\n return { kind: 'epcQrCode', id: code.id, payload, size: code.size, ...(code.caption === undefined ? {} : { caption: code.caption }) }\n}\n","/**\n * Print styles resolved to the one style each piece of text prints in.\n *\n * report-spec's styles are tokens (0007); here they are laid over each other\n * once, and the document carries the result, so an engine never merges\n * styles (`TextStyle`). The order, each later one's property winning:\n *\n * 1. what the component stands in passes down: a section's, a columns\n * block's or a keep-together block's style is the base of the text\n * inside it;\n * 2. the component's own `style`;\n * 3. each of its `styleWhen` rules that holds, in order.\n *\n * In a table, the table's resolved style is the base of every row: the\n * header's `headerStyle`, a group header's, a footer row's own, and each\n * column's style and rules over a detail cell. An image, a QR code, a line,\n * a rectangle, a spacer and a page break print no text; a style on one is\n * read for its rules' conditions, and changes nothing.\n */\nimport type { PrintStyle, StyleRule } from '@formancy/report-spec'\nimport type { TextStyle } from './document.js'\nimport { holds } from './render-context.js'\nimport type { Render, Scope } from './render-context.js'\n\n/** Each print style as the document's: the same tokens without the id. */\nexport function documentStyles(styles: readonly PrintStyle[]): ReadonlyMap<string, TextStyle> {\n return new Map(styles.map(({ id, ...style }) => [id, style]))\n}\n\n/** `styles` laid over each other, a later one's property winning; undefined when none sets anything. */\nexport function layered(...styles: readonly (TextStyle | undefined)[]): TextStyle | undefined {\n const merged: TextStyle = Object.assign({}, ...styles.filter((style) => style !== undefined)) as TextStyle\n return Object.keys(merged).length === 0 ? undefined : merged\n}\n\n/**\n * `base`, then the print style `style` names, then each rule at\n * `<path>/<index>` whose condition holds in `scope`. Undefined when nothing\n * sets anything, or when a condition failed, which is recorded.\n */\nexport function styled(\n render: Render,\n scope: Scope,\n base: TextStyle | undefined,\n style: string | undefined,\n rules: readonly StyleRule[] | undefined,\n path: string,\n): TextStyle | undefined {\n const held: TextStyle[] = []\n for (const [index, rule] of (rules ?? []).entries()) {\n if (holds(render, scope, `${path}/${index}/when/cel`) === true) held.push(render.styles.get(rule.style) as TextStyle)\n }\n return layered(base, style === undefined ? undefined : render.styles.get(style), ...held)\n}\n","/**\n * A table over the detail dataset, lowered to the rows it prints.\n *\n * Its rows are those its condition selects (0062): `rowsWhen`, read once\n * for each detail row in the row's scope, in the data's order, before\n * anything is ordered, each reading counted against the render's budget;\n * a table without one has every row. A preview whose data lacks what the\n * condition reads leaves the row out, said once. The rows are ordered and\n * grouped by `sort-group.ts` (0007): the group's key first, then the sort\n * keys, ties in the provider's order. Then, in that order:\n *\n * - for each group, one line across the table read in the group's scope,\n * which keeps as many of the group's first rows as the group states, or\n * all of them where it has fewer, and says so only above one (0059); its\n * rows; and its footer rows, whose aggregates are the group's;\n * - the totals rows, read in the table's scope, whose `table` is the\n * table's aggregates over its rows and `totals` every row's;\n * - with no detail rows, the table's empty text in their place, and its\n * totals still printed: a count and a sum of nothing are 0.\n *\n * The table's aggregates are `Totals.over` its rows, the function a\n * group's are, and a table without a condition is handed the report's\n * totals themselves, so that its `table` and `totals` are one value and a\n * report without conditions prints as it did.\n *\n * A column whose condition does not hold is left out, read once per report:\n * its header, every cell under it and its footer cells, and the fill columns\n * share its width. A table every column of which is hidden prints nothing.\n * A table every shown column of which is titled with nothing, or with white\n * space alone -- one whose column titles come from its groups -- has no\n * header row, and no header style (0078): which columns show and what their\n * titles print is known here, once, and no engine decides it again.\n * Each detail cell is read in its row's scope, its column's style rules too;\n * every other row has one style.\n */\nimport type { TableColumn as ReportColumn, TableComponent, TableFooterRow } from '@formancy/report-spec'\nimport type { Table, TableRow, TextStyle } from './document.js'\nimport { runOf, textOfRuns } from './inlines.js'\nimport { groupScope, holds, reportScope, rowScope, tableScope } from './render-context.js'\nimport type { AggregateValues, Render, Scope } from './render-context.js'\nimport { orderTable } from './sort-group.js'\nimport type { OrderedRow } from './sort-group.js'\nimport { layered, styled } from './styles.js'\n\n/** A column that prints, and where it stands in the report's list of the table's columns. */\ninterface Shown {\n readonly column: ReportColumn\n readonly index: number\n}\n\n/** What every row of one table is read with. */\ninterface Lowering {\n readonly render: Render\n readonly table: TableComponent\n readonly path: string\n readonly shown: readonly Shown[]\n /** The table's own style, laid under every row's. */\n readonly base: TextStyle | undefined\n /** The table's aggregates, over the rows it prints. */\n readonly totals: AggregateValues\n}\n\n/** `style` as a row's: the table's under the named print style; absent when neither sets anything. */\nfunction rowStyle(lowering: Lowering, style: string | undefined): { readonly style?: TextStyle } {\n const resolved = layered(lowering.base, style === undefined ? undefined : lowering.render.styles.get(style))\n return resolved === undefined ? {} : { style: resolved }\n}\n\n/** One detail row: each shown column's value and own style, read in the row's scope. */\nfunction detailRow(lowering: Lowering, row: OrderedRow): TableRow {\n const { render, table, path } = lowering\n const scope = rowScope(render, render.totals.report, row)\n const cells = lowering.shown.map(({ column, index }) => {\n const run = runOf(render, scope, column.value, `${path}/columns/${index}/value`, { componentId: table.id, columnId: column.id })\n return run === undefined ? '' : textOfRuns([run])\n })\n const own = lowering.shown.map(({ column, index }) => styled(render, scope, undefined, column.style, column.styleWhen, `${path}/columns/${index}/styleWhen`))\n const cellStyles = own.some((style) => style !== undefined)\n ? { cellStyles: own.map((style) => (style === undefined ? null : (layered(lowering.base, style) as TextStyle))) }\n : {}\n return { kind: 'detail', cells, ...(lowering.base === undefined ? {} : { style: lowering.base }), ...cellStyles }\n}\n\n/** Footer rows read in `scope`: under a group, or under the table. A shown column without a cell in a row prints nothing there. */\nfunction footerRows(lowering: Lowering, rows: readonly TableFooterRow[] | undefined, at: string, kind: 'groupFooter' | 'total', scope: Scope): TableRow[] {\n const { render, table } = lowering\n return (rows ?? []).map((row, rowIndex) => {\n const cells = lowering.shown.map(({ column }) => {\n const cellIndex = row.cells.findIndex((cell) => cell.column === column.id)\n const cell = row.cells[cellIndex]\n if (cell === undefined) return ''\n const run = runOf(render, scope, cell.value, `${at}/${rowIndex}/cells/${cellIndex}/value`, { componentId: table.id, columnId: column.id })\n return run === undefined ? '' : textOfRuns([run])\n })\n return { kind, cells, ...rowStyle(lowering, row.style) }\n })\n}\n\n/** The rows of a table that groups: per group, its header line, its rows and its footer. */\nfunction groupedRows(lowering: Lowering, groups: NonNullable<ReturnType<typeof orderTable>['groups']>): TableRow[] {\n const { render, table, path } = lowering\n const group = table.group as NonNullable<TableComponent['group']>\n const rows: TableRow[] = []\n for (const each of groups) {\n if (render.problems.full) break\n const scope = groupScope(render, each, render.totals.over(each.rows), lowering.totals, group.by.field)\n const runs = group.header.map((inline, index) => runOf(render, scope, inline, `${path}/group/header/${index}`, { componentId: table.id }))\n // Counted against the group made here, so that no engine counts a group again; one row kept is every header's rule, and no member.\n const keep = Math.min(group.keepWithRows ?? 1, each.rows.length)\n rows.push({\n kind: 'groupHeader',\n cells: [textOfRuns(runs.filter((run) => run !== undefined))],\n across: true,\n ...rowStyle(lowering, group.headerStyle),\n ...(keep > 1 ? { keepWithRows: keep } : {}),\n })\n for (const row of each.rows) rows.push(detailRow(lowering, row))\n rows.push(...footerRows(lowering, group.footer, `${path}/group/footer`, 'groupFooter', scope))\n }\n return rows\n}\n\n/**\n * The detail rows `table`'s condition, at `path`, selects, in the data's\n * order; undefined for a table without one, which has every row. A row\n * whose condition could not be read is left out and recorded as an error,\n * so the report is refused.\n */\nfunction selectedRows(render: Render, table: TableComponent, path: string): OrderedRow[] | undefined {\n if (table.rowsWhen === undefined) return undefined\n const selected: OrderedRow[] = []\n for (const [index, record] of render.data.detail.entries()) {\n if (render.problems.full) break\n const row: OrderedRow = { index, record }\n if (holds(render, rowScope(render, render.totals.report, row), `${path}/rowsWhen/cel`) === true) selected.push(row)\n }\n return selected\n}\n\n/**\n * `table`, at `path`, as the document's table, `base` its own resolved\n * style; undefined when every column is hidden. A value that could not be\n * read prints nothing here, and is recorded as an error, so the report is\n * refused.\n */\nexport function tableBlock(render: Render, table: TableComponent, path: string, base: TextStyle | undefined): Table | undefined {\n const scope = reportScope(render, render.totals.report)\n const shown = table.columns\n .map((column, index) => ({ column, index }))\n .filter(({ column, index }) => column.visibleWhen === undefined || holds(render, scope, `${path}/columns/${index}/visibleWhen/cel`) === true)\n if (shown.length === 0) return undefined\n const selected = selectedRows(render, table, path)\n const totals = selected === undefined ? render.totals.report : render.totals.over(selected)\n const lowering: Lowering = { render, table, path, shown, base, totals }\n const ordered = orderTable(render.report, table, render.data.detail, selected)\n const rows: TableRow[] = []\n if (ordered.groups !== undefined) rows.push(...groupedRows(lowering, ordered.groups))\n else {\n for (const row of ordered.rows) {\n if (render.problems.full) break\n rows.push(detailRow(lowering, row))\n }\n }\n rows.push(...footerRows(lowering, table.totals, `${path}/totals`, 'total', tableScope(render, totals)))\n return {\n kind: 'table',\n id: table.id,\n columns: shown.map(({ column }) => ({ width: column.width, align: column.align })),\n ...headerOf(render, table, shown, base),\n rows,\n emptyText: table.emptyText,\n }\n}\n\n/**\n * The header row of the `shown` columns and its style, or neither where no\n * title prints (0078): white space prints nothing, read as every engine\n * reads a cell, by `trim`. A title is a literal, never a value, and a word\n * of no letter is never translated (report-spec's `not-a-word`) nor one\n * translated to white space (`blank-translation`), so a table has a header\n * in every language it is written in, or in none.\n */\nfunction headerOf(render: Render, table: TableComponent, shown: readonly Shown[], base: TextStyle | undefined): Pick<Table, 'header' | 'headerStyle'> {\n const header = shown.map(({ column }) => column.header)\n if (header.every((title) => title.trim() === '')) return {}\n const headerStyle = layered(base, table.headerStyle === undefined ? undefined : render.styles.get(table.headerStyle))\n return { header, ...(headerStyle === undefined ? {} : { headerStyle }) }\n}\n","/**\n * A report's components lowered to the document's blocks, region by region.\n *\n * Every component is read in the report's scope: its condition first, and a\n * component whose condition does not hold prints nothing, nor does anything\n * inside it. Then its style (`styles.ts`), and then what it is. A kind maps\n * to a block through a table over every kind, so a kind added to the format\n * without a way down does not compile.\n *\n * The report header is the start of the body and the summary its end, so\n * the document has three regions: the page header and footer, repeated on\n * every page, and the body; and a fourth where the report gives page 1 a\n * header of its own, which page 1 prints in the page header's place\n * (0060).\n */\nimport type { Component, ComponentKind, OptionalRegionName, RegionName } from '@formancy/report-spec'\nimport type { Block, TextStyle } from './document.js'\nimport { imageBlock } from './images.js'\nimport { encodedText, runOf } from './inlines.js'\nimport { chartBlock } from './lower-chart.js'\nimport { epcQrCodeBlock } from './lower-epc-qr-code.js'\nimport { tableBlock } from './lower-table.js'\nimport { holds, reportScope } from './render-context.js'\nimport type { Render, Scope } from './render-context.js'\nimport { styled } from './styles.js'\n\n/** The document's regions, lowered. */\nexport interface LoweredRegions {\n /** Present exactly when the report has a first page header: what its components print, an empty list for none. */\n readonly firstPageHeader?: readonly Block[]\n readonly pageHeader: readonly Block[]\n readonly pageFooter: readonly Block[]\n readonly body: readonly Block[]\n}\n\n/** What one component is lowered with: where it is, the report scope, and its resolved style. */\ninterface At {\n readonly render: Render\n readonly scope: Scope\n readonly path: string\n readonly style: TextStyle | undefined\n}\n\ntype Lowerer<K extends ComponentKind> = (component: Extract<Component, { kind: K }>, at: At) => Block | undefined\n\n/** `value` under `key` when it is defined: the document writes only what is set. */\nconst optional = <K extends string, V>(key: K, value: V | undefined): { [P in K]?: V } => (value === undefined ? {} : ({ [key]: value } as { [P in K]: V }))\n\nconst LOWER: { readonly [K in ComponentKind]: Lowerer<K> } = {\n text: (text, { render, scope, path, style }) => {\n const runs = text.content.flatMap((inline, index) => runOf(render, scope, inline, `${path}/content/${index}`, { componentId: text.id }) ?? [])\n return { kind: 'paragraph', runs, ...optional('style', style), ...(text.keepWithNext === true ? { keepWithNext: true } : {}) }\n },\n image: (image, { render, path }) => imageBlock(render, image, path),\n qrCode: (code, { render, scope, path }) => {\n const text = encodedText(render, scope, code.content, path, code.id)\n return text === undefined ? undefined : { kind: 'qrCode', id: code.id, text, size: code.size, errorCorrection: code.errorCorrection }\n },\n epcQrCode: (code, { render, scope, path }) => epcQrCodeBlock(render, scope, code, path),\n line: (line) => ({ kind: 'rule', thickness: line.thickness, ...optional('color', line.color) }),\n rectangle: (rectangle) => ({\n kind: 'rectangle',\n width: rectangle.width,\n height: rectangle.height,\n ...optional('fill', rectangle.fill),\n ...optional('stroke', rectangle.stroke),\n }),\n spacer: (spacer) => ({ kind: 'spacer', height: spacer.height }),\n columns: (columns, { render, path, style }) => ({\n kind: 'columns',\n columns: columns.columns.map((slot, index) => ({\n width: slot.width,\n blocks: blocksOf(render, slot.components, `${path}/columns/${index}/components`, style),\n })),\n }),\n section: (section, { render, path, style }) => ({\n kind: 'section',\n blocks: blocksOf(render, section.components, `${path}/components`, style),\n ...optional('border', section.border),\n ...optional('fill', section.fill),\n ...optional('padding', section.padding),\n }),\n table: (table, { render, path, style }) => tableBlock(render, table, path, style),\n chart: (chart, { render, path, style }) => chartBlock(render, chart, path, style),\n pageBreak: () => ({ kind: 'pageBreak' }),\n keepTogether: (kept, { render, path, style }) => ({ kind: 'keepTogether', blocks: blocksOf(render, kept.components, `${path}/components`, style) }),\n}\n\n/** `component`, at `path`, as the block it prints; undefined when it prints nothing, or could not be lowered, which is recorded. */\nfunction blockOf(render: Render, component: Component, path: string, inherited: TextStyle | undefined): Block | undefined {\n const scope = reportScope(render, render.totals.report)\n if (component.visibleWhen !== undefined && holds(render, scope, `${path}/visibleWhen/cel`) !== true) return undefined\n const style = styled(render, scope, inherited, component.style, component.styleWhen, `${path}/styleWhen`)\n return (LOWER[component.kind] as Lowerer<ComponentKind>)(component, { render, scope, path, style })\n}\n\n/** The components of the list at `path`, in order, as the blocks they print. */\nfunction blocksOf(render: Render, components: readonly Component[], path: string, inherited: TextStyle | undefined): Block[] {\n return components.flatMap((component, index) => blockOf(render, component, `${path}/${index}`, inherited) ?? [])\n}\n\n/** A region every report holds, lowered. */\nfunction region(render: Render, name: Exclude<RegionName, OptionalRegionName>): Block[] {\n return blocksOf(render, render.report.regions[name], `/regions/${name}`, undefined)\n}\n\n/** Every region of `render`'s report, lowered: the report header, body and summary as the one body. */\nexport function lowerRegions(render: Render): LoweredRegions {\n const own = render.report.regions.firstPageHeader\n return {\n ...(own === undefined ? {} : { firstPageHeader: blocksOf(render, own, '/regions/firstPageHeader', undefined) }),\n pageHeader: region(render, 'pageHeader'),\n pageFooter: region(render, 'pageFooter'),\n body: [...region(render, 'reportHeader'), ...region(render, 'body'), ...region(render, 'summary')],\n }\n}\n","/**\n * Whether a report can be rendered at all, before any data is read: the\n * first two levels of plan 15, structure and bindings.\n *\n * A report reaches the runtime as untrusted input, whatever its type says --\n * parsed from storage, posted by a browser. So it is validated again here,\n * with report-spec's `validateReport`, and what the runtime goes on to read\n * is the copy validation made, which no later change to the caller's object\n * reaches. Then its expressions are compiled with report-core, and a report\n * the editor's diagnostics give an error for is refused (0009): the runtime\n * never renders what the editor refuses. A report written in several\n * languages is checked for the one a render names, and what the render\n * reads is the report written in it (0063, `languages.ts`).\n */\nimport type { ReportDefinition } from '@formancy/report-spec'\nimport { validateReport } from '@formancy/report-spec'\nimport { prepareExpressions } from './evaluate.js'\nimport type { ReportExpressions } from './evaluate.js'\nimport { printLocale } from './languages.js'\nimport { fromDiagnostic, fromReport } from './resolve-errors.js'\nimport type { RuntimeError } from './resolve-errors.js'\n\nexport type ReportCheck =\n | {\n readonly ok: true\n /** The copy validation read, translations and all: what the manifest's hash names. */\n readonly report: ReportDefinition\n /** That copy written in the render's locale, with no translations (0063): what the render prints, the copy itself less its translations in its own locale. */\n readonly printed: ReportDefinition\n readonly expressions: ReportExpressions\n }\n | { readonly ok: false; readonly errors: readonly RuntimeError[] }\n\n/**\n * `report` validated and its expressions compiled for one render in\n * `locale`, the report's own where absent, or every reason it is refused:\n * each structural error; a locale the report is not written in\n * (`undeclared-locale`); or, for a report that is structurally valid,\n * each diagnostic of severity error that names no language or that\n * locale (0063).\n */\nexport function checkReport(report: unknown, locale?: string): ReportCheck {\n const validation = validateReport(report)\n if (!validation.valid) return { ok: false, errors: validation.errors.map(fromReport) }\n const chosen = printLocale(validation.report, locale)\n if (!chosen.ok) return { ok: false, errors: [chosen.error] }\n const prepared = prepareExpressions(validation.report, chosen.locale)\n if (!prepared.ok) return { ok: false, errors: prepared.diagnostics.map(fromDiagnostic) }\n return { ok: true, report: validation.report, printed: prepared.report, expressions: prepared.expressions }\n}\n","/**\n * A report resolved against its data: the renderer-neutral document it\n * prints, and the manifest that says what it was printed from (plan 14).\n *\n * The composition of the runtime's stages, each decided in its own module:\n *\n * 1. the report, validated again and its expressions compiled; one the\n * editor's diagnostics give an error for is refused (`report-check.ts`);\n * then written in the locale the render names, its own or one its\n * translations declare, which every later stage reads (`languages.ts`,\n * 0063);\n * 2. the options, the parameters and the data, each checked, and every\n * error of the three listed together (`parameters.ts`, `data.ts`);\n * 3. the aggregates, exactly, over every row (`totals.ts`);\n * 4. the e-invoice's lines, read once, and its totals and its terms, where\n * the report is one (`lower-e-invoice.ts`);\n * 5. the regions, lowered component by component (`lower.ts`), tables row\n * by row (`lower-table.ts`), images through the host's lookup\n * (`images.ts`), an EPC QR code's every text held to the EPC's rules\n * (`lower-epc-qr-code.ts`);\n * 6. the payment part, its every text held to SIX's rules\n * (`lower-payment-part.ts`);\n * 7. the e-invoice's XML, in a final render (`cii.ts`).\n *\n * It refuses rather than prints a wrong report: any error at any stage, and\n * the result is the errors, never a partial document. A preview may run on\n * data the provider calls incomplete or that lacks a field; it says so in\n * the manifest and in its warnings, and its every page carries\n * `PREVIEW_LABEL`, so that a preview printed or passed on is never taken for\n * the report. A final render refuses such data. A preview of an e-invoice\n * writes no XML, and is labelled whatever its data:\n * `E_INVOICE_PREVIEW_LABEL` where nothing else is lacking. A final render\n * of an XRechnung is labelled too, `XRECHNUNG_COPY_LABEL`: its XML is the\n * invoice, and its PDF a copy (0038). And a final render of an e-invoice\n * of either kind that a host asks for as the copy (`eInvoice: 'copy'`,\n * 0077) is labelled as one in the render's language and carries no XML\n * (`e-invoice-copy.ts`): what a Word file is written of.\n */\nimport { decimalToString } from '@formancy/expressions'\nimport type { Decimal } from '@formancy/expressions'\nimport { reportHash } from '@formancy/report-spec'\nimport type { ReportDefinition } from '@formancy/report-spec'\nimport { checkData } from './data.js'\nimport type { Completeness, Consistency, DataMode, ReportData } from './data.js'\nimport type { Block, Paragraph, ResolvedDocument } from './document.js'\nimport { E_INVOICE_COPY_LANGUAGES, eInvoiceCopyParagraph } from './e-invoice-copy.js'\nimport { createFormatter } from './format.js'\nimport { localePath } from './languages.js'\nimport { eInvoiceFile, resolveEInvoice } from './lower-e-invoice.js'\nimport { resolveFonts } from './lower-fonts.js'\nimport { lowerPaymentPart } from './lower-payment-part.js'\nimport { lowerRegions } from './lower.js'\nimport { frozen, label } from './page-label.js'\nimport { checkParameters } from './parameters.js'\nimport type { CheckedParameters } from './parameters.js'\nimport type { AssetResolver } from './render-context.js'\nimport { checkReport } from './report-check.js'\nimport { fromData, Problems } from './resolve-errors.js'\nimport type { RuntimeError } from './resolve-errors.js'\nimport type { DataSource } from './source.js'\nimport { documentStyles } from './styles.js'\nimport { computeTotals } from './totals.js'\nimport { canonicalInstant } from './values.js'\n\nexport interface ResolveOptions {\n /** A final render prints the report; a preview shows a sample and says what it lacks. */\n readonly mode: DataMode\n /** The values a person supplied, by parameter id; defaults apply to those left out. */\n readonly parameters?: Readonly<Record<string, unknown>>\n /** The host's lookup of approved assets' bytes; a report that draws an image or maps a font is refused without one (0043). */\n readonly images?: AssetResolver\n /** An ISO 8601 instant with its zone, fixed by the caller, so that the same inputs print the same PDF. */\n readonly creationDate: string\n /** The IANA zone instants are shown in, named by the host: UTC when absent, never the machine's. */\n readonly timeZone?: string\n /**\n * The locale the render prints in: the report's own when absent, or one\n * its translations declare, exactly; any other is refused as\n * `undeclared-locale` (0063). It decides every word the report prints,\n * every value's format, the order of rows and groups, the slip's\n * headings and the labels form data must have been read in.\n */\n readonly locale?: string\n /**\n * `'copy'` resolves a final render of an e-invoice as its copy (0077):\n * every header opens with the copy's label, in the render's language,\n * and the document carries no XML. The invoice's terms are held and its\n * XML written as for the invoice, so a copy is of an invoice that\n * exists. Absent, the render is the invoice. It says nothing of a\n * report that carries no e-invoice; of a preview, in a language no\n * label is written in, or as any other value it is refused,\n * `no-e-invoice-copy`.\n */\n readonly eInvoice?: 'copy'\n}\n\n/** What a document was resolved from, to keep beside the PDF (plan 14). Nothing in it is the data's. */\nexport interface RenderManifest {\n /** report-spec's hash of the report as validated, its translations and all. */\n readonly reportHash: string\n readonly reportSpecVersion: ReportDefinition['reportSpecVersion']\n /** The locale the render printed in: the report's own, or the translation's it named (0063). */\n readonly locale: string\n readonly timeZone: string\n readonly mode: DataMode\n readonly consistency: Consistency\n readonly completeness: Completeness\n /** Each parameter's value as the format writes one -- an exact number or a date as a string, a boolean -- or null. */\n readonly parameters: Readonly<Record<string, string | boolean | null>>\n /**\n * Where the data came from, as its provider named it and the check held\n * it: each submission of a formancy form with its form's id and its\n * version's schemaHash, or Formancy Data's forms (0041). Held to the\n * syntax of identifiers and to no key but its shape's; what fits that\n * syntax passes, whatever it means. Absent where the data named no\n * source.\n */\n readonly source?: DataSource\n /** `'copy'` where the document is the copy of the report's e-invoice a host asked for, and not the invoice (0077); absent otherwise. */\n readonly eInvoice?: 'copy'\n}\n\nexport type Resolution =\n | {\n readonly ok: true\n readonly document: ResolvedDocument\n readonly manifest: RenderManifest\n /** What a preview lacks; empty in a final render, which refuses it. */ readonly warnings: readonly RuntimeError[]\n }\n | { readonly ok: false; readonly errors: readonly RuntimeError[] }\n\n/** What every page of a preview that lacks data says, at the top of its page header, and of page 1's own where it has one. */\nexport const PREVIEW_LABEL = 'Preview of incomplete data: not a final report'\n\n/** What every page of a preview of an e-invoice says when it lacks nothing else: it writes no XML, and is not the invoice. */\nexport const E_INVOICE_PREVIEW_LABEL = 'Preview: not an e-invoice, and not a final report'\n\n/** What every page of a final render of an XRechnung says: the invoice is the XML the document carries, which a host sends, and the PDF drawn of the page is a copy (0038). */\nexport const XRECHNUNG_COPY_LABEL = 'Copy of an XRechnung: the invoice is its XML, and this PDF is not the invoice'\n\n/**\n * The paragraph that opens every page's header of a final render of an\n * XRechnung, as the runtime writes it: `XRECHNUNG_COPY_LABEL` in the\n * labels' style. The renderer refuses an XRechnung's document whose page\n * header, or page 1's own where it has one (0060), does not open with it,\n * style and all, since the text in white or at one point would say nothing\n * to a reader (0038). Frozen, so that what\n * the renderer holds a copy to is not a host's to change; each document\n * carries a paragraph of its own.\n */\nexport const XRECHNUNG_COPY_PARAGRAPH: Paragraph = frozen(label(XRECHNUNG_COPY_LABEL))\n\n/**\n * The label a copy of `report`'s e-invoice is headed with where `options`\n * ask for one (0077), `locale` the one the render prints in: its text,\n * undefined where no copy is asked for or the report carries no\n * e-invoice, or the error that refuses the copy. The option is the\n * host's, whatever its type says.\n */\nfunction copyLabel(report: ReportDefinition, own: ReportDefinition, locale: string, options: ResolveOptions): string | RuntimeError | undefined {\n const asked: unknown = options.eInvoice\n if (asked === undefined) return undefined\n const no = (path: string, message: string): RuntimeError => ({ stage: 'resolve', code: 'no-e-invoice-copy', path, message })\n if (asked !== 'copy') return no('', \"a render's eInvoice option is 'copy' or absent\")\n if (report.eInvoice === undefined) return undefined\n if (options.mode === 'preview') return no('', 'a copy is of a final render of an e-invoice; a preview writes no XML, and there is no invoice it is a copy of')\n const [run] = eInvoiceCopyParagraph(report.eInvoice.kind, locale)?.runs ?? []\n if (run === undefined || !('text' in run))\n return no(\n localePath(own, locale),\n `a copy of an e-invoice is labelled in the language it prints in, and the runtime has no label in the language of ${locale}: it has one in ${E_INVOICE_COPY_LANGUAGES.join(', ')}`,\n )\n return run.text\n}\n\n/** Each parameter's value as the format writes one. */\nfunction writtenParameters(values: CheckedParameters): Record<string, string | boolean | null> {\n return Object.fromEntries(\n Object.entries(values).map(([id, value]) => {\n if (value === null || typeof value === 'boolean' || typeof value === 'string') return [id, value]\n if (typeof value === 'bigint') return [id, String(value)]\n // A parameter is never an image (report-spec), so what is left is a decimal.\n return [id, decimalToString(value as Decimal)]\n }),\n )\n}\n\n/**\n * `report` resolved against `data`: the document to render and its\n * manifest, or every reason it is refused, up to a bound. Nothing is read\n * from `report`, `data` or the parameters but through the checks, and\n * nothing in the result is shared with them.\n */\nexport function resolveReport(report: ReportDefinition, data: ReportData, options: ResolveOptions): Resolution {\n const checked = checkReport(report, options.locale)\n if (!checked.ok) return { ok: false, errors: checked.errors }\n const valid = checked.printed\n const timeZone = options.timeZone ?? 'UTC'\n const errors: RuntimeError[] = []\n const creationDate = canonicalInstant(String(options.creationDate))\n if (creationDate === undefined)\n errors.push({ stage: 'resolve', code: 'invalid-creation-date', path: '', message: 'the creation date is an ISO 8601 instant with its zone' })\n const formatter = createFormatter({ locale: valid.locale, timeZone })\n if (!formatter.ok)\n errors.push({\n stage: 'format',\n code: formatter.code,\n path: formatter.code === 'unsupported-locale' ? localePath(checked.report, valid.locale) : '',\n message: formatter.message,\n })\n const parameters = checkParameters(valid, options.parameters ?? {})\n if (!parameters.ok) errors.push(...parameters.errors.map((error) => fromData('parameters', error)))\n const checkedData = checkData(valid, data, { mode: options.mode, reportLocale: checked.report.locale })\n if (!checkedData.ok) errors.push(...checkedData.errors.map((error) => fromData('data', error)))\n const copy = copyLabel(valid, checked.report, valid.locale, options)\n if (typeof copy === 'object') errors.push(copy)\n if (errors.length > 0 || creationDate === undefined || !formatter.ok || !parameters.ok || !checkedData.ok) return { ok: false, errors }\n\n const problems = new Problems()\n for (const warning of checkedData.warnings) problems.warn(fromData('data', warning))\n const preview = checkedData.data.mode === 'preview'\n const inputs = {\n report: valid,\n expressions: checked.expressions,\n formatter: formatter.formatter,\n params: parameters.values,\n data: checkedData.data,\n problems,\n preview,\n images: options.images,\n styles: documentStyles(valid.styles),\n }\n const totals = computeTotals(inputs)\n if (totals === undefined) return { ok: false, errors: problems.errors() }\n const invoice = valid.eInvoice === undefined ? undefined : resolveEInvoice({ ...inputs, totals }, valid.eInvoice)\n if (valid.eInvoice !== undefined && invoice === undefined) return { ok: false, errors: problems.errors() }\n const render = { ...inputs, totals, ...(invoice === undefined ? {} : { invoice: invoice.reads }) }\n const regions = lowerRegions(render)\n const paymentPart = lowerPaymentPart(render)\n const fonts = resolveFonts(render, valid.fonts)\n const eInvoice = invoice === undefined || valid.eInvoice === undefined ? undefined : eInvoiceFile(render, invoice, valid.eInvoice)\n if (problems.failed) return { ok: false, errors: problems.errors() }\n\n const { completeness, consistency, source } = checkedData.data\n const warnings = problems.warnings()\n const lacking = !completeness.complete || warnings.some(({ code }) => code !== 'e-invoice-preview')\n const labelled = !preview\n ? typeof copy === 'string'\n ? copy\n : eInvoice?.kind === 'xrechnung'\n ? XRECHNUNG_COPY_LABEL\n : undefined\n : lacking\n ? PREVIEW_LABEL\n : invoice === undefined\n ? undefined\n : E_INVOICE_PREVIEW_LABEL\n // Every header a page prints opens with the label, page 1's own among them, each with a paragraph of its own (0060).\n const headed = (blocks: readonly Block[]): readonly Block[] => (labelled === undefined ? blocks : [label(labelled), ...blocks])\n const document: ResolvedDocument = {\n info: { title: valid.title, creationDate },\n page: valid.page,\n ...(regions.firstPageHeader === undefined ? {} : { firstPageHeader: headed(regions.firstPageHeader) }),\n pageHeader: headed(regions.pageHeader),\n pageFooter: regions.pageFooter,\n body: regions.body,\n ...(paymentPart === undefined ? {} : { paymentPart }),\n // A copy carries no XML: no engine embeds or sends anything from it (0077).\n ...(eInvoice === undefined || typeof copy === 'string' ? {} : { eInvoice }),\n ...(fonts === undefined ? {} : { fonts }),\n }\n const manifest: RenderManifest = {\n reportHash: reportHash(checked.report),\n reportSpecVersion: valid.reportSpecVersion,\n locale: valid.locale,\n timeZone,\n mode: checkedData.data.mode,\n consistency,\n completeness,\n parameters: writtenParameters(parameters.values),\n ...(source === undefined ? {} : { source }),\n ...(typeof copy === 'string' ? { eInvoice: 'copy' as const } : {}),\n }\n return { ok: true, document, manifest, warnings }\n}\n"],"mappings":";;;;;;;;;;;;;AAyEA,MAAa,eAAe;;;;;;;;;;AAW5B,MAAa,eAAwD;CAAE,aAAa,MAAO;CAAc,WAAW,OAAQ;AAAa;AA4azI,MAAa,gBAAgB;CAAC;CAAkB;CAAqB;CAAiB;CAAa;AAAa;;;;;;;;AAUhH,IAAa,gBAAb,cAAmC,MAAM;CACvC;CACA;CAEA,YAAY,MAAmB,SAAiB,SAAkB;EAChE,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,UAAU;CACjB;AACF;;;;;;;;;;;;;;;;;;;;;AC5fA,MAAa,gBAAgB;;;;;;;;;;AAW7B,MAAa,gBAAiB,OAAY;;;;;;;;;AAU1C,MAAa,oBAAoB;AAEjC,MAAM,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