@latex-kit/template 0.0.0-stage → 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.
Files changed (55) hide show
  1. package/LICENSE +23 -0
  2. package/README.md +137 -2
  3. package/analyze.d.ts +38 -0
  4. package/analyze.js +144 -0
  5. package/clause.d.ts +23 -0
  6. package/clause.js +26 -0
  7. package/codemod.d.ts +25 -0
  8. package/codemod.js +67 -0
  9. package/compile.d.ts +74 -0
  10. package/compile.js +258 -0
  11. package/condition.d.ts +38 -0
  12. package/condition.js +201 -0
  13. package/diagnostics.d.ts +29 -0
  14. package/diagnostics.js +48 -0
  15. package/document.d.ts +15 -0
  16. package/document.js +25 -0
  17. package/esm/analyze.d.ts +38 -0
  18. package/esm/analyze.js +141 -0
  19. package/esm/clause.d.ts +23 -0
  20. package/esm/clause.js +21 -0
  21. package/esm/codemod.d.ts +25 -0
  22. package/esm/codemod.js +62 -0
  23. package/esm/compile.d.ts +74 -0
  24. package/esm/compile.js +253 -0
  25. package/esm/condition.d.ts +38 -0
  26. package/esm/condition.js +193 -0
  27. package/esm/diagnostics.d.ts +29 -0
  28. package/esm/diagnostics.js +40 -0
  29. package/esm/document.d.ts +15 -0
  30. package/esm/document.js +22 -0
  31. package/esm/evaluate.d.ts +40 -0
  32. package/esm/evaluate.js +235 -0
  33. package/esm/filters.d.ts +39 -0
  34. package/esm/filters.js +221 -0
  35. package/esm/index.d.ts +12 -0
  36. package/esm/index.js +12 -0
  37. package/esm/jsonschema.d.ts +24 -0
  38. package/esm/jsonschema.js +94 -0
  39. package/esm/path.d.ts +7 -0
  40. package/esm/path.js +16 -0
  41. package/esm/sty.d.ts +6 -0
  42. package/esm/sty.js +67 -0
  43. package/evaluate.d.ts +40 -0
  44. package/evaluate.js +239 -0
  45. package/filters.d.ts +39 -0
  46. package/filters.js +229 -0
  47. package/index.d.ts +12 -0
  48. package/index.js +28 -0
  49. package/jsonschema.d.ts +24 -0
  50. package/jsonschema.js +99 -0
  51. package/package.json +44 -4
  52. package/path.d.ts +7 -0
  53. package/path.js +22 -0
  54. package/sty.d.ts +6 -0
  55. package/sty.js +70 -0
@@ -0,0 +1,193 @@
1
+ import { isPath } from './path';
2
+ export class ConditionError extends Error {
3
+ name = 'ConditionError';
4
+ }
5
+ function tokenize(src) {
6
+ const out = [];
7
+ let i = 0;
8
+ while (i < src.length) {
9
+ const ch = src[i];
10
+ if (/\s/.test(ch)) {
11
+ i++;
12
+ continue;
13
+ }
14
+ const two = src.slice(i, i + 2);
15
+ if (['&&', '||', '==', '!=', '<=', '>='].includes(two)) {
16
+ out.push({ t: 'op', v: two });
17
+ i += 2;
18
+ continue;
19
+ }
20
+ if ('!<>()'.includes(ch)) {
21
+ out.push({ t: 'op', v: ch });
22
+ i++;
23
+ continue;
24
+ }
25
+ if (ch === '"') {
26
+ let s = '';
27
+ i++;
28
+ while (i < src.length && src[i] !== '"') {
29
+ if (src[i] === '\\' && i + 1 < src.length)
30
+ i++;
31
+ s += src[i++];
32
+ }
33
+ if (src[i] !== '"')
34
+ throw new ConditionError('unterminated string');
35
+ i++;
36
+ out.push({ t: 'str', v: s });
37
+ continue;
38
+ }
39
+ const num = /^-?\d+(?:\.\d+)?/.exec(src.slice(i));
40
+ if (num) {
41
+ out.push({ t: 'num', v: Number(num[0]) });
42
+ i += num[0].length;
43
+ continue;
44
+ }
45
+ const word = /^\$?[A-Za-z_][A-Za-z0-9_]*(?:\.(?:[A-Za-z_][A-Za-z0-9_]*|\d+))*/.exec(src.slice(i));
46
+ if (word) {
47
+ out.push({ t: 'word', v: word[0] });
48
+ i += word[0].length;
49
+ continue;
50
+ }
51
+ if (ch === '=')
52
+ throw new ConditionError('use == to compare, not =');
53
+ if (ch === '&' || ch === '|')
54
+ throw new ConditionError(`use ${ch}${ch}, not ${ch}`);
55
+ throw new ConditionError(`unexpected "${ch}"`);
56
+ }
57
+ return out;
58
+ }
59
+ export function parseCondition(src) {
60
+ const tokens = tokenize(src);
61
+ if (tokens.length === 0)
62
+ throw new ConditionError('empty condition');
63
+ let pos = 0;
64
+ const peek = () => tokens[pos];
65
+ const isOp = (v) => peek()?.t === 'op' && peek().v === v;
66
+ const primary = () => {
67
+ const tok = tokens[pos++];
68
+ if (!tok)
69
+ throw new ConditionError('condition ends too early');
70
+ if (tok.t === 'op' && tok.v === '(') {
71
+ const e = or();
72
+ if (!isOp(')'))
73
+ throw new ConditionError('missing )');
74
+ pos++;
75
+ return e;
76
+ }
77
+ if (tok.t === 'num')
78
+ return { type: 'literal', value: tok.v };
79
+ if (tok.t === 'str')
80
+ return { type: 'literal', value: tok.v };
81
+ if (tok.t === 'word') {
82
+ if (tok.v === 'true')
83
+ return { type: 'literal', value: true };
84
+ if (tok.v === 'false')
85
+ return { type: 'literal', value: false };
86
+ if (tok.v === 'null')
87
+ return { type: 'literal', value: null };
88
+ if (!isPath(tok.v))
89
+ throw new ConditionError(`invalid path ${tok.v}`);
90
+ return { type: 'path', path: tok.v };
91
+ }
92
+ throw new ConditionError(`unexpected "${tok.v}"`);
93
+ };
94
+ const compare = () => {
95
+ const left = primary();
96
+ const tok = peek();
97
+ if (tok?.t === 'op' && ['==', '!=', '<', '<=', '>', '>='].includes(tok.v)) {
98
+ pos++;
99
+ return { type: 'compare', op: tok.v, left, right: primary() };
100
+ }
101
+ return left;
102
+ };
103
+ const not = () => {
104
+ if (isOp('!')) {
105
+ pos++;
106
+ return { type: 'not', expr: not() };
107
+ }
108
+ return compare();
109
+ };
110
+ const and = () => {
111
+ let left = not();
112
+ while (isOp('&&')) {
113
+ pos++;
114
+ left = { type: 'and', left, right: not() };
115
+ }
116
+ return left;
117
+ };
118
+ const or = () => {
119
+ let left = and();
120
+ while (isOp('||')) {
121
+ pos++;
122
+ left = { type: 'or', left, right: and() };
123
+ }
124
+ return left;
125
+ };
126
+ const expr = or();
127
+ if (pos < tokens.length) {
128
+ const t = tokens[pos];
129
+ throw new ConditionError(`unexpected "${t.t === 'str' ? `"${t.v}"` : t.v}"`);
130
+ }
131
+ return expr;
132
+ }
133
+ export function truthy(v) {
134
+ if (Array.isArray(v))
135
+ return v.length > 0;
136
+ return v !== undefined && v !== null && v !== false && v !== 0 && v !== '';
137
+ }
138
+ export function evaluateCondition(expr, lookup) {
139
+ return truthy(value(expr, lookup));
140
+ }
141
+ function value(expr, lookup) {
142
+ switch (expr.type) {
143
+ case 'path':
144
+ return lookup(expr.path);
145
+ case 'literal':
146
+ return expr.value;
147
+ case 'not':
148
+ return !truthy(value(expr.expr, lookup));
149
+ case 'and':
150
+ return truthy(value(expr.left, lookup)) && truthy(value(expr.right, lookup));
151
+ case 'or':
152
+ return truthy(value(expr.left, lookup)) || truthy(value(expr.right, lookup));
153
+ case 'compare': {
154
+ const l = value(expr.left, lookup);
155
+ const r = value(expr.right, lookup);
156
+ switch (expr.op) {
157
+ case '==':
158
+ return (l ?? null) === (r ?? null);
159
+ case '!=':
160
+ return (l ?? null) !== (r ?? null);
161
+ default: {
162
+ // ordering only between two numbers or two strings; anything else is false
163
+ if (!((typeof l === 'number' && typeof r === 'number') || (typeof l === 'string' && typeof r === 'string')))
164
+ return false;
165
+ if (expr.op === '<')
166
+ return l < r;
167
+ if (expr.op === '<=')
168
+ return l <= r;
169
+ if (expr.op === '>')
170
+ return l > r;
171
+ return l >= r;
172
+ }
173
+ }
174
+ }
175
+ }
176
+ }
177
+ export function conditionPaths(expr, out = []) {
178
+ switch (expr.type) {
179
+ case 'path':
180
+ out.push(expr.path);
181
+ break;
182
+ case 'not':
183
+ conditionPaths(expr.expr, out);
184
+ break;
185
+ case 'and':
186
+ case 'or':
187
+ case 'compare':
188
+ conditionPaths(expr.left, out);
189
+ conditionPaths(expr.right, out);
190
+ break;
191
+ }
192
+ return out;
193
+ }
@@ -0,0 +1,29 @@
1
+ export interface Location {
2
+ file: string;
3
+ line: number;
4
+ column: number;
5
+ }
6
+ export interface Diagnostic {
7
+ severity: 'error' | 'warning';
8
+ message: string;
9
+ file?: string;
10
+ line?: number;
11
+ column?: number;
12
+ }
13
+ export declare class TemplateError extends Error {
14
+ readonly diagnostics: Diagnostic[];
15
+ constructor(message: string, diagnostics: Diagnostic[]);
16
+ }
17
+ export declare function diag(severity: Diagnostic['severity'], message: string, loc?: Location): Diagnostic;
18
+ /** `file:line:col: error: message`, the format editors and CI annotate. */
19
+ export declare function formatDiagnostic(d: Diagnostic): string;
20
+ export declare function hasErrors(diagnostics: Diagnostic[]): boolean;
21
+ /** Maps string offsets to 1-based line and column. */
22
+ export declare class LineIndex {
23
+ private starts;
24
+ constructor(text: string);
25
+ locate(offset: number): {
26
+ line: number;
27
+ column: number;
28
+ };
29
+ }
@@ -0,0 +1,40 @@
1
+ export class TemplateError extends Error {
2
+ diagnostics;
3
+ constructor(message, diagnostics) {
4
+ super(message);
5
+ this.diagnostics = diagnostics;
6
+ this.name = 'TemplateError';
7
+ }
8
+ }
9
+ export function diag(severity, message, loc) {
10
+ return loc ? { severity, message, file: loc.file, line: loc.line, column: loc.column } : { severity, message };
11
+ }
12
+ /** `file:line:col: error: message`, the format editors and CI annotate. */
13
+ export function formatDiagnostic(d) {
14
+ const where = d.file ? `${d.file}${d.line ? `:${d.line}${d.column ? `:${d.column}` : ''}` : ''}: ` : '';
15
+ return `${where}${d.severity}: ${d.message}`;
16
+ }
17
+ export function hasErrors(diagnostics) {
18
+ return diagnostics.some((d) => d.severity === 'error');
19
+ }
20
+ /** Maps string offsets to 1-based line and column. */
21
+ export class LineIndex {
22
+ starts = [0];
23
+ constructor(text) {
24
+ for (let i = 0; i < text.length; i++)
25
+ if (text.charCodeAt(i) === 10)
26
+ this.starts.push(i + 1);
27
+ }
28
+ locate(offset) {
29
+ let lo = 0;
30
+ let hi = this.starts.length - 1;
31
+ while (lo < hi) {
32
+ const mid = (lo + hi + 1) >> 1;
33
+ if (this.starts[mid] <= offset)
34
+ lo = mid;
35
+ else
36
+ hi = mid - 1;
37
+ }
38
+ return { line: lo + 1, column: offset - this.starts[lo] + 1 };
39
+ }
40
+ }
@@ -0,0 +1,15 @@
1
+ import { Variant } from './evaluate';
2
+ export interface WrapOptions {
3
+ variant: Variant;
4
+ /** Short text printed on draft pages, e.g. date and git commit. */
5
+ stamp?: string;
6
+ }
7
+ /**
8
+ * Make a filled template ready for TeX: tell `latex-kit.sty` it is rendering
9
+ * a document (not previewing a template) and which variant, and load the
10
+ * package if the template did not.
11
+ *
12
+ * The settings go at the very start of line 1, so line numbers in TeX's
13
+ * errors still match the generated file line for line.
14
+ */
15
+ export declare function wrapDocument(tex: string, options: WrapOptions): string;
@@ -0,0 +1,22 @@
1
+ import { escapeLatex } from '@latex-kit/escape';
2
+ const USES_PACKAGE = /\\(?:usepackage|RequirePackage)\s*(?:\[[^\]]*\])?\s*\{[^}]*\blatex-kit\b[^}]*\}/;
3
+ /**
4
+ * Make a filled template ready for TeX: tell `latex-kit.sty` it is rendering
5
+ * a document (not previewing a template) and which variant, and load the
6
+ * package if the template did not.
7
+ *
8
+ * The settings go at the very start of line 1, so line numbers in TeX's
9
+ * errors still match the generated file line for line.
10
+ */
11
+ export function wrapDocument(tex, options) {
12
+ const stamp = options.stamp ? escapeLatex(options.stamp) : '';
13
+ const prefix = `\\PassOptionsToPackage{rendered,${options.variant}}{latex-kit}\\def\\lkstamp{${stamp}}`;
14
+ let body = tex;
15
+ if (!USES_PACKAGE.test(body)) {
16
+ const at = body.indexOf('\\begin{document}');
17
+ if (at === -1)
18
+ throw new Error('the template has no \\begin{document}');
19
+ body = `${body.slice(0, at)}\\usepackage{latex-kit}${body.slice(at)}`;
20
+ }
21
+ return prefix + body;
22
+ }
@@ -0,0 +1,40 @@
1
+ import { ClauseUse, LoadedClause } from './clause';
2
+ import { CompiledTemplate } from './compile';
3
+ import { truthy } from './condition';
4
+ import { Diagnostic } from './diagnostics';
5
+ export type Variant = 'draft' | 'blank' | 'final' | 'signed';
6
+ export declare const VARIANTS: Variant[];
7
+ export interface EvaluateOptions {
8
+ /** The record's data. */
9
+ data: unknown;
10
+ variant: Variant;
11
+ locale?: string;
12
+ docId?: string;
13
+ template?: string;
14
+ /**
15
+ * Missing values print a red marker instead of failing. Defaults to true
16
+ * for `draft`; `final` and `signed` always fail on a missing value.
17
+ */
18
+ allowMissing?: boolean;
19
+ /** Resolve \snippet{name} from the file that uses it. */
20
+ loadSnippet?: (name: string, from: string) => CompiledTemplate | null;
21
+ /** Resolve \clause{id} from the clause library. */
22
+ loadClause?: (id: string) => LoadedClause | null;
23
+ }
24
+ export interface FieldUse {
25
+ path: string;
26
+ file: string;
27
+ line: number;
28
+ column: number;
29
+ missing: boolean;
30
+ }
31
+ export interface EvaluateResult {
32
+ tex: string;
33
+ diagnostics: Diagnostic[];
34
+ /** Every field that was filled (or found missing), in document order. */
35
+ fields: FieldUse[];
36
+ /** Library clauses placed in the document, in order, with versions. */
37
+ clauses: ClauseUse[];
38
+ }
39
+ export declare function evaluateTemplate(template: CompiledTemplate, options: EvaluateOptions): EvaluateResult;
40
+ export { truthy };
@@ -0,0 +1,235 @@
1
+ import { escapeLatex, LatexEscapeError, RawLatex } from '@latex-kit/escape';
2
+ import { clauseLabel } from './clause';
3
+ import { evaluateCondition, truthy } from './condition';
4
+ import { diag } from './diagnostics';
5
+ import { applyFilters, FilterError, isMissing } from './filters';
6
+ import { splitPath } from './path';
7
+ export const VARIANTS = ['draft', 'blank', 'final', 'signed'];
8
+ function own(obj, key) {
9
+ if (obj === null || typeof obj !== 'object')
10
+ return undefined;
11
+ if (Array.isArray(obj))
12
+ return /^\d+$/.test(key) ? obj[Number(key)] : undefined;
13
+ return Object.prototype.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
14
+ }
15
+ function isRaw(v) {
16
+ return v instanceof RawLatex || (!!v && typeof v === 'object' && v.constructor?.name === 'RawLatex' && typeof v.value === 'string');
17
+ }
18
+ export function evaluateTemplate(template, options) {
19
+ const variant = options.variant;
20
+ const locale = options.locale ?? 'en-US';
21
+ const allowMissing = variant === 'blank' || (options.allowMissing ?? variant === 'draft');
22
+ const diagnostics = [...template.diagnostics];
23
+ const fields = [];
24
+ const frames = [];
25
+ const stack = [template.file];
26
+ const clauses = [];
27
+ const refs = [];
28
+ const lookup = (path) => {
29
+ const [head, ...rest] = splitPath(path);
30
+ let value;
31
+ if (head.startsWith('$')) {
32
+ const loop = frames[frames.length - 1];
33
+ switch (head) {
34
+ case '$variant':
35
+ value = variant;
36
+ break;
37
+ case '$locale':
38
+ value = locale;
39
+ break;
40
+ case '$docid':
41
+ value = options.docId;
42
+ break;
43
+ case '$template':
44
+ value = options.template;
45
+ break;
46
+ case '$index':
47
+ value = loop ? loop.index + 1 : undefined;
48
+ break;
49
+ case '$first':
50
+ value = loop ? loop.index === 0 : undefined;
51
+ break;
52
+ case '$last':
53
+ value = loop ? loop.index === loop.count - 1 : undefined;
54
+ break;
55
+ }
56
+ }
57
+ else {
58
+ const frame = [...frames].reverse().find((f) => f.name === head);
59
+ value = frame ? frame.item : own(options.data, head);
60
+ }
61
+ for (const seg of rest)
62
+ value = own(value, seg);
63
+ return value;
64
+ };
65
+ const missing = (what, loc) => {
66
+ if (allowMissing) {
67
+ if (variant !== 'blank')
68
+ diagnostics.push(diag('warning', `missing value for ${what}`, loc));
69
+ return `\\lkmissing{${what}}`;
70
+ }
71
+ diagnostics.push(diag('error', `missing value for ${what}`, loc));
72
+ return '';
73
+ };
74
+ const toTex = (value, raw, newlines, what, loc) => {
75
+ if (isRaw(value))
76
+ return value.value;
77
+ if (value instanceof Date)
78
+ value = value.toISOString().slice(0, 10);
79
+ if (typeof value === 'number') {
80
+ if (!Number.isFinite(value)) {
81
+ diagnostics.push(diag('error', `${what} is ${value}`, loc));
82
+ return '';
83
+ }
84
+ value = String(value);
85
+ }
86
+ if (typeof value === 'bigint')
87
+ value = String(value);
88
+ if (typeof value === 'string') {
89
+ if (raw)
90
+ return value;
91
+ try {
92
+ return escapeLatex(value, newlines ? { newlines } : {});
93
+ }
94
+ catch (e) {
95
+ if (!(e instanceof LatexEscapeError))
96
+ throw e;
97
+ diagnostics.push(diag('error', `${what}: ${e.message}`, loc));
98
+ return '';
99
+ }
100
+ }
101
+ const kind = typeof value === 'boolean' ? 'true/false (use \\when to test it)' : Array.isArray(value) ? 'a list (use \\each or |join)' : 'an object (pick a field inside it)';
102
+ diagnostics.push(diag('error', `${what} is ${kind}`, loc));
103
+ return '';
104
+ };
105
+ const render = (nodes) => {
106
+ let out = '';
107
+ for (const node of nodes) {
108
+ switch (node.kind) {
109
+ case 'text':
110
+ out += node.text;
111
+ break;
112
+ case 'field': {
113
+ const { path, filters } = node.spec;
114
+ if (variant === 'blank') {
115
+ fields.push({ path, ...node.loc, missing: false });
116
+ out += `\\lkblank{${path}}`;
117
+ break;
118
+ }
119
+ let result;
120
+ try {
121
+ result = applyFilters(lookup(path), filters, { locale });
122
+ }
123
+ catch (e) {
124
+ if (!(e instanceof FilterError))
125
+ throw e;
126
+ diagnostics.push(diag('error', `\\field{${node.source}}: ${e.message}`, node.loc));
127
+ break;
128
+ }
129
+ const isGone = !result.defaulted && isMissing(result.value);
130
+ fields.push({ path, ...node.loc, missing: isGone });
131
+ out += isGone ? missing(path, node.loc) : toTex(result.value, node.raw, result.newlines, path, node.loc);
132
+ break;
133
+ }
134
+ case 'docid':
135
+ if (variant === 'blank')
136
+ out += '\\lkblank{docid}';
137
+ else if (options.docId)
138
+ out += escapeLatex(options.docId);
139
+ else
140
+ out += missing('the document ID', node.loc);
141
+ break;
142
+ case 'when':
143
+ if (evaluateCondition(node.cond, lookup))
144
+ out += render(node.then);
145
+ else if (node.else)
146
+ out += render(node.else);
147
+ break;
148
+ case 'each': {
149
+ const list = lookup(node.path);
150
+ if (list === undefined || list === null) {
151
+ if (variant === 'blank') {
152
+ frames.push({ name: node.name, item: undefined, index: 0, count: 1 });
153
+ out += render(node.body);
154
+ frames.pop();
155
+ }
156
+ else {
157
+ out += missing(node.path, node.loc);
158
+ }
159
+ break;
160
+ }
161
+ if (!Array.isArray(list)) {
162
+ diagnostics.push(diag('error', `\\each{${node.path}}: expected a list, got ${typeof list}`, node.loc));
163
+ break;
164
+ }
165
+ list.forEach((item, index) => {
166
+ frames.push({ name: node.name, item, index, count: list.length });
167
+ out += render(node.body);
168
+ frames.pop();
169
+ });
170
+ break;
171
+ }
172
+ case 'sep': {
173
+ const loop = frames[frames.length - 1];
174
+ if (loop && loop.index < loop.count - 1)
175
+ out += render(node.body);
176
+ break;
177
+ }
178
+ case 'snippet': {
179
+ const from = stack[stack.length - 1];
180
+ const snippet = options.loadSnippet?.(node.name, from) ?? null;
181
+ if (!snippet) {
182
+ diagnostics.push(diag('error', `snippet not found: ${node.name}`, node.loc));
183
+ break;
184
+ }
185
+ if (stack.includes(snippet.file)) {
186
+ diagnostics.push(diag('error', `snippet ${node.name} includes itself (${[...stack, snippet.file].join(' → ')})`, node.loc));
187
+ break;
188
+ }
189
+ diagnostics.push(...snippet.diagnostics);
190
+ stack.push(snippet.file);
191
+ out += render(snippet.nodes);
192
+ stack.pop();
193
+ break;
194
+ }
195
+ case 'clause': {
196
+ const clause = options.loadClause?.(node.id) ?? null;
197
+ if (!clause) {
198
+ diagnostics.push(diag('error', `clause not found: ${node.id}`, node.loc));
199
+ break;
200
+ }
201
+ if (stack.includes(clause.template.file)) {
202
+ diagnostics.push(diag('error', `clause ${node.id} includes itself`, node.loc));
203
+ break;
204
+ }
205
+ if (clauses.some((c) => c.id === node.id)) {
206
+ diagnostics.push(diag('error', `clause ${node.id} is placed twice`, node.loc));
207
+ break;
208
+ }
209
+ clauses.push({ id: node.id, version: clause.version, file: clause.template.file });
210
+ diagnostics.push(...clause.template.diagnostics);
211
+ out += `\\lkclause{${clause.title ? escapeLatex(clause.title) : ''}}{${clauseLabel(node.id)}}`;
212
+ stack.push(clause.template.file);
213
+ out += render(clause.template.nodes);
214
+ stack.pop();
215
+ break;
216
+ }
217
+ case 'clauseref':
218
+ refs.push({ id: node.id, loc: node.loc });
219
+ out += `\\ref{${clauseLabel(node.id)}}`;
220
+ break;
221
+ }
222
+ }
223
+ return out;
224
+ };
225
+ const tex = render(template.nodes);
226
+ // a reference to a clause this document does not contain would print "??"
227
+ for (const r of refs) {
228
+ if (!clauses.some((c) => c.id === r.id)) {
229
+ const msg = `\\clauseref{${r.id}}: clause ${r.id} is not in this document`;
230
+ diagnostics.push(diag(allowMissing ? 'warning' : 'error', msg, r.loc));
231
+ }
232
+ }
233
+ return { tex, diagnostics, fields, clauses };
234
+ }
235
+ export { truthy };
@@ -0,0 +1,39 @@
1
+ export interface FilterCall {
2
+ name: string;
3
+ arg?: string;
4
+ }
5
+ export interface FieldSpec {
6
+ path: string;
7
+ filters: FilterCall[];
8
+ }
9
+ export interface FilterContext {
10
+ locale: string;
11
+ }
12
+ /** Value marker: the filter produced line-preserving text. */
13
+ export interface Newlines {
14
+ newlines?: 'linebreak' | 'paragraph';
15
+ /** `default` supplied the value, so an empty result is intended. */
16
+ defaulted?: boolean;
17
+ }
18
+ interface FilterDef {
19
+ arg: 'none' | 'optional' | 'required';
20
+ /** Return an error message when the argument is invalid. */
21
+ checkArg?: (arg: string) => string | null;
22
+ /** `default` runs on missing values; every other filter is skipped for them. */
23
+ onMissing?: boolean;
24
+ apply: (value: unknown, arg: string | undefined, ctx: FilterContext, out: Newlines) => unknown;
25
+ }
26
+ export declare class FilterError extends Error {
27
+ name: string;
28
+ }
29
+ export declare const FILTERS: Record<string, FilterDef>;
30
+ export declare function isMissing(v: unknown): boolean;
31
+ /** Parse the inside of \field{…}: `path | filter | filter:arg | filter:"quoted arg"`. */
32
+ export declare function parseFieldSpec(text: string): FieldSpec;
33
+ /** Run filters left to right. Missing values skip every filter except `default`. */
34
+ export declare function applyFilters(value: unknown, filters: FilterCall[], ctx: FilterContext): {
35
+ value: unknown;
36
+ } & Newlines;
37
+ /** 1200 → "one thousand two hundred". Integers only, up to the trillions. */
38
+ export declare function numberToWords(n: number): string;
39
+ export {};