@latex-kit/template 0.0.0-stage → 0.2.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.
@@ -0,0 +1,199 @@
1
+ import { escapeLatex, LatexEscapeError, RawLatex } from '@latex-kit/escape';
2
+ import { evaluateCondition, truthy } from './condition';
3
+ import { diag } from './diagnostics';
4
+ import { applyFilters, FilterError, isMissing } from './filters';
5
+ import { splitPath } from './path';
6
+ export const VARIANTS = ['draft', 'blank', 'final', 'signed'];
7
+ function own(obj, key) {
8
+ if (obj === null || typeof obj !== 'object')
9
+ return undefined;
10
+ if (Array.isArray(obj))
11
+ return /^\d+$/.test(key) ? obj[Number(key)] : undefined;
12
+ return Object.prototype.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
13
+ }
14
+ function isRaw(v) {
15
+ return v instanceof RawLatex || (!!v && typeof v === 'object' && v.constructor?.name === 'RawLatex' && typeof v.value === 'string');
16
+ }
17
+ export function evaluateTemplate(template, options) {
18
+ const variant = options.variant;
19
+ const locale = options.locale ?? 'en-US';
20
+ const allowMissing = variant === 'blank' || (options.allowMissing ?? variant === 'draft');
21
+ const diagnostics = [...template.diagnostics];
22
+ const fields = [];
23
+ const frames = [];
24
+ const stack = [template.file];
25
+ const lookup = (path) => {
26
+ const [head, ...rest] = splitPath(path);
27
+ let value;
28
+ if (head.startsWith('$')) {
29
+ const loop = frames[frames.length - 1];
30
+ switch (head) {
31
+ case '$variant':
32
+ value = variant;
33
+ break;
34
+ case '$locale':
35
+ value = locale;
36
+ break;
37
+ case '$docid':
38
+ value = options.docId;
39
+ break;
40
+ case '$template':
41
+ value = options.template;
42
+ break;
43
+ case '$index':
44
+ value = loop ? loop.index + 1 : undefined;
45
+ break;
46
+ case '$first':
47
+ value = loop ? loop.index === 0 : undefined;
48
+ break;
49
+ case '$last':
50
+ value = loop ? loop.index === loop.count - 1 : undefined;
51
+ break;
52
+ }
53
+ }
54
+ else {
55
+ const frame = [...frames].reverse().find((f) => f.name === head);
56
+ value = frame ? frame.item : own(options.data, head);
57
+ }
58
+ for (const seg of rest)
59
+ value = own(value, seg);
60
+ return value;
61
+ };
62
+ const missing = (what, loc) => {
63
+ if (allowMissing) {
64
+ if (variant !== 'blank')
65
+ diagnostics.push(diag('warning', `missing value for ${what}`, loc));
66
+ return `\\lkmissing{${what}}`;
67
+ }
68
+ diagnostics.push(diag('error', `missing value for ${what}`, loc));
69
+ return '';
70
+ };
71
+ const toTex = (value, raw, newlines, what, loc) => {
72
+ if (isRaw(value))
73
+ return value.value;
74
+ if (value instanceof Date)
75
+ value = value.toISOString().slice(0, 10);
76
+ if (typeof value === 'number') {
77
+ if (!Number.isFinite(value)) {
78
+ diagnostics.push(diag('error', `${what} is ${value}`, loc));
79
+ return '';
80
+ }
81
+ value = String(value);
82
+ }
83
+ if (typeof value === 'bigint')
84
+ value = String(value);
85
+ if (typeof value === 'string') {
86
+ if (raw)
87
+ return value;
88
+ try {
89
+ return escapeLatex(value, newlines ? { newlines } : {});
90
+ }
91
+ catch (e) {
92
+ if (!(e instanceof LatexEscapeError))
93
+ throw e;
94
+ diagnostics.push(diag('error', `${what}: ${e.message}`, loc));
95
+ return '';
96
+ }
97
+ }
98
+ 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)';
99
+ diagnostics.push(diag('error', `${what} is ${kind}`, loc));
100
+ return '';
101
+ };
102
+ const render = (nodes) => {
103
+ let out = '';
104
+ for (const node of nodes) {
105
+ switch (node.kind) {
106
+ case 'text':
107
+ out += node.text;
108
+ break;
109
+ case 'field': {
110
+ const { path, filters } = node.spec;
111
+ if (variant === 'blank') {
112
+ fields.push({ path, ...node.loc, missing: false });
113
+ out += `\\lkblank{${path}}`;
114
+ break;
115
+ }
116
+ let result;
117
+ try {
118
+ result = applyFilters(lookup(path), filters, { locale });
119
+ }
120
+ catch (e) {
121
+ if (!(e instanceof FilterError))
122
+ throw e;
123
+ diagnostics.push(diag('error', `\\field{${node.source}}: ${e.message}`, node.loc));
124
+ break;
125
+ }
126
+ const isGone = !result.defaulted && isMissing(result.value);
127
+ fields.push({ path, ...node.loc, missing: isGone });
128
+ out += isGone ? missing(path, node.loc) : toTex(result.value, node.raw, result.newlines, path, node.loc);
129
+ break;
130
+ }
131
+ case 'docid':
132
+ if (variant === 'blank')
133
+ out += '\\lkblank{docid}';
134
+ else if (options.docId)
135
+ out += escapeLatex(options.docId);
136
+ else
137
+ out += missing('the document ID', node.loc);
138
+ break;
139
+ case 'when':
140
+ if (evaluateCondition(node.cond, lookup))
141
+ out += render(node.then);
142
+ else if (node.else)
143
+ out += render(node.else);
144
+ break;
145
+ case 'each': {
146
+ const list = lookup(node.path);
147
+ if (list === undefined || list === null) {
148
+ if (variant === 'blank') {
149
+ frames.push({ name: node.name, item: undefined, index: 0, count: 1 });
150
+ out += render(node.body);
151
+ frames.pop();
152
+ }
153
+ else {
154
+ out += missing(node.path, node.loc);
155
+ }
156
+ break;
157
+ }
158
+ if (!Array.isArray(list)) {
159
+ diagnostics.push(diag('error', `\\each{${node.path}}: expected a list, got ${typeof list}`, node.loc));
160
+ break;
161
+ }
162
+ list.forEach((item, index) => {
163
+ frames.push({ name: node.name, item, index, count: list.length });
164
+ out += render(node.body);
165
+ frames.pop();
166
+ });
167
+ break;
168
+ }
169
+ case 'sep': {
170
+ const loop = frames[frames.length - 1];
171
+ if (loop && loop.index < loop.count - 1)
172
+ out += render(node.body);
173
+ break;
174
+ }
175
+ case 'snippet': {
176
+ const from = stack[stack.length - 1];
177
+ const snippet = options.loadSnippet?.(node.name, from) ?? null;
178
+ if (!snippet) {
179
+ diagnostics.push(diag('error', `snippet not found: ${node.name}`, node.loc));
180
+ break;
181
+ }
182
+ if (stack.includes(snippet.file)) {
183
+ diagnostics.push(diag('error', `snippet ${node.name} includes itself (${[...stack, snippet.file].join(' → ')})`, node.loc));
184
+ break;
185
+ }
186
+ diagnostics.push(...snippet.diagnostics);
187
+ stack.push(snippet.file);
188
+ out += render(snippet.nodes);
189
+ stack.pop();
190
+ break;
191
+ }
192
+ }
193
+ }
194
+ return out;
195
+ };
196
+ const tex = render(template.nodes);
197
+ return { tex, diagnostics, fields };
198
+ }
199
+ 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 {};
package/esm/filters.js ADDED
@@ -0,0 +1,221 @@
1
+ import { isPath } from './path';
2
+ export class FilterError extends Error {
3
+ name = 'FilterError';
4
+ }
5
+ const DATE_STYLES = ['long', 'short', 'medium', 'full', 'iso'];
6
+ function toDate(value) {
7
+ if (value instanceof Date)
8
+ return value;
9
+ if (typeof value === 'string') {
10
+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
11
+ const d = m ? new Date(Date.UTC(+m[1], +m[2] - 1, +m[3])) : new Date(value);
12
+ if (!Number.isNaN(d.getTime()))
13
+ return d;
14
+ }
15
+ throw new FilterError(`date: expected a date like 2026-11-25, got ${JSON.stringify(value)}`);
16
+ }
17
+ function toNumber(name, value) {
18
+ const n = typeof value === 'string' && value.trim() !== '' ? Number(value) : value;
19
+ if (typeof n !== 'number' || !Number.isFinite(n)) {
20
+ throw new FilterError(`${name}: expected a number, got ${JSON.stringify(value)}`);
21
+ }
22
+ return n;
23
+ }
24
+ function digits(name, arg) {
25
+ if (arg === undefined)
26
+ return undefined;
27
+ const d = Number(arg);
28
+ if (!Number.isInteger(d) || d < 0 || d > 20)
29
+ throw new FilterError(`${name}: digits must be 0–20, got ${arg}`);
30
+ return d;
31
+ }
32
+ const digitsArg = (arg) => (/^\d{1,2}$/.test(arg) && Number(arg) <= 20 ? null : 'expected a number of digits (0–20)');
33
+ export const FILTERS = {
34
+ upper: { arg: 'none', apply: (v, _a, c) => String(v).toLocaleUpperCase(c.locale) },
35
+ lower: { arg: 'none', apply: (v, _a, c) => String(v).toLocaleLowerCase(c.locale) },
36
+ title: {
37
+ arg: 'none',
38
+ apply: (v, _a, c) => String(v).replace(/(^|[\s\-(])(\p{L})/gu, (_m, pre, ch) => pre + ch.toLocaleUpperCase(c.locale)),
39
+ },
40
+ trim: { arg: 'none', apply: (v) => String(v).trim() },
41
+ date: {
42
+ arg: 'optional',
43
+ checkArg: (a) => (DATE_STYLES.includes(a) ? null : `expected one of ${DATE_STYLES.join(', ')}`),
44
+ apply: (v, arg, c) => {
45
+ const d = toDate(v);
46
+ const style = (arg ?? 'long');
47
+ if (style === 'iso')
48
+ return d.toISOString().slice(0, 10);
49
+ return new Intl.DateTimeFormat(c.locale, { dateStyle: style, timeZone: 'UTC' }).format(d);
50
+ },
51
+ },
52
+ money: {
53
+ arg: 'optional',
54
+ checkArg: (a) => (/^[A-Z]{3}$/.test(a) ? null : 'expected a 3-letter currency code like USD'),
55
+ apply: (v, arg, c) => {
56
+ let amount = v;
57
+ let currency = arg;
58
+ if (v && typeof v === 'object' && 'amount' in v) {
59
+ amount = v.amount;
60
+ currency = currency ?? v.currency;
61
+ }
62
+ if (!currency)
63
+ throw new FilterError('money: no currency (use money:USD or a { amount, currency } value)');
64
+ return new Intl.NumberFormat(c.locale, { style: 'currency', currency }).format(toNumber('money', amount));
65
+ },
66
+ },
67
+ number: {
68
+ arg: 'optional',
69
+ checkArg: digitsArg,
70
+ apply: (v, arg, c) => {
71
+ const d = digits('number', arg);
72
+ return new Intl.NumberFormat(c.locale, d === undefined ? {} : { minimumFractionDigits: d, maximumFractionDigits: d }).format(toNumber('number', v));
73
+ },
74
+ },
75
+ percent: {
76
+ arg: 'optional',
77
+ checkArg: digitsArg,
78
+ apply: (v, arg, c) => {
79
+ const d = digits('percent', arg) ?? 0;
80
+ return new Intl.NumberFormat(c.locale, { style: 'percent', minimumFractionDigits: d, maximumFractionDigits: d }).format(toNumber('percent', v));
81
+ },
82
+ },
83
+ words: {
84
+ arg: 'none',
85
+ apply: (v, _a, c) => {
86
+ if (!c.locale.toLowerCase().startsWith('en'))
87
+ throw new FilterError(`words: only English is supported (locale ${c.locale})`);
88
+ return numberToWords(toNumber('words', v));
89
+ },
90
+ },
91
+ join: {
92
+ arg: 'optional',
93
+ apply: (v, arg) => {
94
+ if (!Array.isArray(v))
95
+ throw new FilterError(`join: expected a list, got ${typeof v}`);
96
+ return v
97
+ .map((x) => {
98
+ if (typeof x !== 'string' && typeof x !== 'number')
99
+ throw new FilterError('join: list items must be text or numbers');
100
+ return String(x);
101
+ })
102
+ .join(arg ?? ', ');
103
+ },
104
+ },
105
+ default: { arg: 'required', onMissing: true, apply: (v, arg) => (isMissing(v) ? arg : v) },
106
+ lines: { arg: 'none', apply: (v, _a, _c, out) => ((out.newlines = 'linebreak'), v) },
107
+ paragraphs: { arg: 'none', apply: (v, _a, _c, out) => ((out.newlines = 'paragraph'), v) },
108
+ };
109
+ export function isMissing(v) {
110
+ return v === undefined || v === null || v === '';
111
+ }
112
+ /** Parse the inside of \field{…}: `path | filter | filter:arg | filter:"quoted arg"`. */
113
+ export function parseFieldSpec(text) {
114
+ const parts = [];
115
+ let cur = '';
116
+ let quoted = false;
117
+ for (let i = 0; i < text.length; i++) {
118
+ const ch = text[i];
119
+ if (quoted && ch === '\\' && i + 1 < text.length) {
120
+ cur += ch + text[++i];
121
+ continue;
122
+ }
123
+ if (ch === '"')
124
+ quoted = !quoted;
125
+ if (ch === '|' && !quoted) {
126
+ parts.push(cur);
127
+ cur = '';
128
+ continue;
129
+ }
130
+ cur += ch;
131
+ }
132
+ if (quoted)
133
+ throw new FilterError('unterminated quoted filter argument');
134
+ parts.push(cur);
135
+ const path = parts[0].trim();
136
+ if (!isPath(path)) {
137
+ throw new FilterError(path === '' ? 'empty field path' : `invalid field path "${path}" (use names and dots, like party.name or items.0.price)`);
138
+ }
139
+ const filters = parts.slice(1).map((raw) => {
140
+ const t = raw.trim();
141
+ const m = /^([a-z]+)(?::([\s\S]*))?$/.exec(t);
142
+ if (!m)
143
+ throw new FilterError(`invalid filter "${t}"`);
144
+ const name = m[1];
145
+ const def = FILTERS[name];
146
+ if (!def)
147
+ throw new FilterError(`unknown filter "${name}" (known: ${Object.keys(FILTERS).join(', ')})`);
148
+ let arg = m[2]?.trim();
149
+ if (arg !== undefined && arg.startsWith('"')) {
150
+ if (!arg.endsWith('"') || arg.length < 2)
151
+ throw new FilterError(`filter ${name}: bad quoted argument`);
152
+ arg = arg.slice(1, -1).replace(/\\(.)/g, '$1');
153
+ }
154
+ else if (arg === '') {
155
+ arg = undefined;
156
+ }
157
+ if (def.arg === 'none' && arg !== undefined)
158
+ throw new FilterError(`filter ${name} takes no argument`);
159
+ if (def.arg === 'required' && arg === undefined)
160
+ throw new FilterError(`filter ${name} needs an argument, like ${name}:"…"`);
161
+ if (arg !== undefined && def.checkArg) {
162
+ const problem = def.checkArg(arg);
163
+ if (problem)
164
+ throw new FilterError(`filter ${name}: ${problem}`);
165
+ }
166
+ return arg === undefined ? { name } : { name, arg };
167
+ });
168
+ return { path, filters };
169
+ }
170
+ /** Run filters left to right. Missing values skip every filter except `default`. */
171
+ export function applyFilters(value, filters, ctx) {
172
+ const out = {};
173
+ let v = value;
174
+ for (const f of filters) {
175
+ const def = FILTERS[f.name];
176
+ if (isMissing(v) && !def.onMissing)
177
+ continue;
178
+ if (f.name === 'default' && isMissing(v))
179
+ out.defaulted = true;
180
+ v = def.apply(v, f.arg, ctx, out);
181
+ }
182
+ return { value: v, ...out };
183
+ }
184
+ const ONES = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
185
+ const TENS = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
186
+ const SCALES = ['', 'thousand', 'million', 'billion', 'trillion'];
187
+ function below1000(n) {
188
+ const parts = [];
189
+ if (n >= 100) {
190
+ parts.push(`${ONES[Math.floor(n / 100)]} hundred`);
191
+ n %= 100;
192
+ }
193
+ if (n >= 20) {
194
+ parts.push(TENS[Math.floor(n / 10)] + (n % 10 ? `-${ONES[n % 10]}` : ''));
195
+ }
196
+ else if (n > 0) {
197
+ parts.push(ONES[n]);
198
+ }
199
+ return parts.join(' ');
200
+ }
201
+ /** 1200 → "one thousand two hundred". Integers only, up to the trillions. */
202
+ export function numberToWords(n) {
203
+ if (!Number.isInteger(n))
204
+ throw new FilterError(`words: expected a whole number, got ${n}`);
205
+ if (Math.abs(n) >= 1e15)
206
+ throw new FilterError(`words: ${n} is too large`);
207
+ if (n === 0)
208
+ return 'zero';
209
+ if (n < 0)
210
+ return `minus ${numberToWords(-n)}`;
211
+ const groups = [];
212
+ let scale = 0;
213
+ while (n > 0) {
214
+ const chunk = n % 1000;
215
+ if (chunk)
216
+ groups.unshift(below1000(chunk) + (SCALES[scale] ? ` ${SCALES[scale]}` : ''));
217
+ n = Math.floor(n / 1000);
218
+ scale++;
219
+ }
220
+ return groups.join(' ');
221
+ }
package/esm/index.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ export * from './analyze';
2
+ export * from './compile';
3
+ export * from './condition';
4
+ export * from './diagnostics';
5
+ export * from './document';
6
+ export * from './evaluate';
7
+ export * from './filters';
8
+ export * from './jsonschema';
9
+ export * from './path';
10
+ export * from './sty';
package/esm/index.js ADDED
@@ -0,0 +1,10 @@
1
+ export * from './analyze';
2
+ export * from './compile';
3
+ export * from './condition';
4
+ export * from './diagnostics';
5
+ export * from './document';
6
+ export * from './evaluate';
7
+ export * from './filters';
8
+ export * from './jsonschema';
9
+ export * from './path';
10
+ export * from './sty';
@@ -0,0 +1,24 @@
1
+ /** A JSON Schema node, loosely typed: only the keywords the walker needs. */
2
+ export type JsonSchema = boolean | {
3
+ $ref?: string;
4
+ $defs?: Record<string, JsonSchema>;
5
+ definitions?: Record<string, JsonSchema>;
6
+ type?: string | string[];
7
+ properties?: Record<string, JsonSchema>;
8
+ additionalProperties?: JsonSchema;
9
+ items?: JsonSchema | JsonSchema[];
10
+ prefixItems?: JsonSchema[];
11
+ anyOf?: JsonSchema[];
12
+ oneOf?: JsonSchema[];
13
+ allOf?: JsonSchema[];
14
+ [key: string]: unknown;
15
+ };
16
+ /** "anything goes" from here down: no further checking is possible. */
17
+ export declare const ANY: JsonSchema;
18
+ /**
19
+ * The sub-schema at `segments`, or `undefined` when the path cannot exist.
20
+ * Unions are walked branch by branch; a path is valid if any branch has it.
21
+ */
22
+ export declare function schemaAt(node: JsonSchema, segments: string[], root?: JsonSchema): JsonSchema | undefined;
23
+ /** The schema for one element of a list, for \each. `undefined` if not a list. */
24
+ export declare function itemSchema(node: JsonSchema, root: JsonSchema): JsonSchema | undefined;
@@ -0,0 +1,94 @@
1
+ /** "anything goes" from here down: no further checking is possible. */
2
+ export const ANY = true;
3
+ function deref(node, root, depth = 0) {
4
+ if (typeof node === 'boolean' || !node.$ref || depth > 32)
5
+ return node;
6
+ const m = /^#\/(\$defs|definitions)\/(.+)$/.exec(node.$ref);
7
+ if (!m || typeof root === 'boolean')
8
+ return ANY;
9
+ const table = root[m[1]];
10
+ const target = table?.[decodeURIComponent(m[2]).replace(/~1/g, '/').replace(/~0/g, '~')];
11
+ return target === undefined ? ANY : deref(target, root, depth + 1);
12
+ }
13
+ function variants(node) {
14
+ if (typeof node === 'boolean')
15
+ return null;
16
+ return node.anyOf ?? node.oneOf ?? null;
17
+ }
18
+ function isPermissive(node) {
19
+ if (node === true)
20
+ return true;
21
+ if (node === false)
22
+ return false;
23
+ const keys = Object.keys(node).filter((k) => !['$schema', 'description', 'title', 'default', 'examples', '$id'].includes(k));
24
+ return keys.length === 0;
25
+ }
26
+ /**
27
+ * The sub-schema at `segments`, or `undefined` when the path cannot exist.
28
+ * Unions are walked branch by branch; a path is valid if any branch has it.
29
+ */
30
+ export function schemaAt(node, segments, root = node) {
31
+ node = deref(node, root);
32
+ if (segments.length === 0)
33
+ return node;
34
+ if (typeof node === 'boolean')
35
+ return node ? ANY : undefined;
36
+ if (isPermissive(node))
37
+ return ANY;
38
+ const alts = variants(node);
39
+ if (alts) {
40
+ const found = alts.map((a) => schemaAt(a, segments, root)).filter((x) => x !== undefined);
41
+ if (found.length === 0)
42
+ return undefined;
43
+ return found.length === 1 ? found[0] : { anyOf: found };
44
+ }
45
+ if (node.allOf) {
46
+ for (const part of node.allOf) {
47
+ const found = schemaAt(part, segments, root);
48
+ if (found !== undefined)
49
+ return found;
50
+ }
51
+ return undefined;
52
+ }
53
+ const [seg, ...rest] = segments;
54
+ const types = node.type === undefined ? [] : Array.isArray(node.type) ? node.type : [node.type];
55
+ if (types.includes('array') || node.items !== undefined || node.prefixItems !== undefined) {
56
+ if (!/^\d+$/.test(seg))
57
+ return undefined;
58
+ const i = Number(seg);
59
+ const item = node.prefixItems?.[i] ?? (Array.isArray(node.items) ? node.items[i] : node.items) ?? ANY;
60
+ return schemaAt(item, rest, root);
61
+ }
62
+ if (types.includes('object') || node.properties || node.additionalProperties !== undefined) {
63
+ const prop = node.properties?.[seg];
64
+ if (prop !== undefined)
65
+ return schemaAt(prop, rest, root);
66
+ const extra = node.additionalProperties;
67
+ if (extra === undefined || extra === true)
68
+ return types.includes('object') && node.properties ? undefined : ANY;
69
+ if (extra === false)
70
+ return undefined;
71
+ return schemaAt(extra, rest, root);
72
+ }
73
+ return undefined;
74
+ }
75
+ /** The schema for one element of a list, for \each. `undefined` if not a list. */
76
+ export function itemSchema(node, root) {
77
+ node = deref(node, root);
78
+ if (isPermissive(node))
79
+ return ANY;
80
+ if (typeof node === 'boolean')
81
+ return undefined;
82
+ const alts = variants(node);
83
+ if (alts) {
84
+ const found = alts.map((a) => itemSchema(a, root)).filter((x) => x !== undefined);
85
+ return found.length === 0 ? undefined : found.length === 1 ? found[0] : { anyOf: found };
86
+ }
87
+ const types = node.type === undefined ? [] : Array.isArray(node.type) ? node.type : [node.type];
88
+ if (types.includes('array') || node.items !== undefined) {
89
+ return Array.isArray(node.items) ? ANY : (node.items ?? ANY);
90
+ }
91
+ if (types.length > 0)
92
+ return undefined; // a known non-list type
93
+ return ANY;
94
+ }
package/esm/path.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ /** Values every template can read. */
2
+ export declare const GLOBAL_SPECIALS: readonly ["$variant", "$locale", "$docid", "$template"];
3
+ /** Values only readable inside \each. */
4
+ export declare const LOOP_SPECIALS: readonly ["$index", "$first", "$last"];
5
+ export declare function isPath(text: string): boolean;
6
+ export declare function isName(text: string): boolean;
7
+ export declare function splitPath(path: string): string[];
package/esm/path.js ADDED
@@ -0,0 +1,16 @@
1
+ const IDENT = '[A-Za-z_][A-Za-z0-9_]*';
2
+ const PATH_RE = new RegExp(`^\\$?${IDENT}(?:\\.(?:${IDENT}|\\d+))*$`);
3
+ const NAME_RE = new RegExp(`^${IDENT}$`);
4
+ /** Values every template can read. */
5
+ export const GLOBAL_SPECIALS = ['$variant', '$locale', '$docid', '$template'];
6
+ /** Values only readable inside \each. */
7
+ export const LOOP_SPECIALS = ['$index', '$first', '$last'];
8
+ export function isPath(text) {
9
+ return PATH_RE.test(text);
10
+ }
11
+ export function isName(text) {
12
+ return NAME_RE.test(text) && !text.startsWith('$');
13
+ }
14
+ export function splitPath(path) {
15
+ return path.split('.');
16
+ }
package/esm/sty.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ /**
2
+ * latex-kit.sty, the LaTeX side of the template language. Written next to
3
+ * every generated document; `latex-kit sty <dir>` writes it for previewing
4
+ * templates in an editor.
5
+ */
6
+ export declare const LATEX_KIT_STY = "% latex-kit.sty: support for latex-kit templates.\n%\n% Load it in a template with \\usepackage{latex-kit}. Compiled directly, a\n% template previews as a blank form: every \\field becomes a labelled line.\n% When latex-kit renders a document it passes the `rendered` option and the\n% variant (draft, blank, final, signed); the template macros are gone by then.\n%\n% https://github.com/constructive-io/latex-kit (MIT)\n\\NeedsTeXFormat{LaTeX2e}\n\\ProvidesPackage{latex-kit}[2026/11/25 v0.3 latex-kit template support]\n\n\\newif\\iflk@rendered\n\\newif\\iflk@draft\n\\DeclareOption{rendered}{\\lk@renderedtrue}\n\\DeclareOption{draft}{\\lk@drafttrue}\n\\DeclareOption{blank}{}\n\\DeclareOption{final}{}\n\\DeclareOption{signed}{}\n\\ProcessOptions\\relax\n\n\\RequirePackage{xcolor}\n\\definecolor{lkmeta}{gray}{0.55}\n\\providecommand\\lkstamp{}\n\n% A labelled blank line: \\lkblank{party.name}\n\\newlength\\lkblankwidth\n\\setlength\\lkblankwidth{3.5cm}\n\\newcommand\\lkblank[1]{\\leavevmode\\underline{\\makebox[\\lkblankwidth][l]{\\color{lkmeta}\\tiny\\ttfamily\\detokenize{#1}}}}\n\n% A value the data does not have yet (draft builds only).\n\\newcommand\\lkmissing[1]{\\leavevmode{\\color{red}\\fbox{\\scriptsize\\ttfamily missing: \\detokenize{#1}}}}\n\n\\iflk@draft\n \\RequirePackage{draftwatermark}\n \\SetWatermarkText{DRAFT}\n \\SetWatermarkScale{1}\n \\SetWatermarkColor[gray]{0.9}\n \\RequirePackage{eso-pic}\n \\AddToShipoutPictureFG{%\n \\AtPageLowerLeft{\\raisebox{6mm}{\\hspace{10mm}\\color{lkmeta}\\scriptsize\\ttfamily DRAFT \\lkstamp}}}\n\\fi\n\n\\iflk@rendered\\else\n % Previewing the template itself: show its structure.\n \\newcommand\\field[1]{\\lkblank{#1}}\n \\newcommand\\raw[1]{\\lkblank{#1}}\n \\newcommand\\docid{\\lkblank{docid}}\n \\newcommand\\when[2]{{\\color{lkmeta}\\tiny[if \\detokenize{#1}]}#2}\n \\newcommand\\otherwise[1]{{\\color{lkmeta}\\tiny[otherwise]}#1}\n \\newcommand\\each[3]{{\\color{lkmeta}\\tiny[each \\detokenize{#2} in \\detokenize{#1}]}#3}\n \\newcommand\\sep[1]{#1}\n \\newcommand\\snippet[1]{\\InputIfFileExists{#1}{}{\\lkblank{snippet #1}}}\n \\newcommand\\clauseref[1]{\\lkblank{clause #1}}\n\\fi\n\n\\endinput\n";