@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
package/evaluate.js ADDED
@@ -0,0 +1,239 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.truthy = exports.VARIANTS = void 0;
4
+ exports.evaluateTemplate = evaluateTemplate;
5
+ const escape_1 = require("@latex-kit/escape");
6
+ const clause_1 = require("./clause");
7
+ const condition_1 = require("./condition");
8
+ Object.defineProperty(exports, "truthy", { enumerable: true, get: function () { return condition_1.truthy; } });
9
+ const diagnostics_1 = require("./diagnostics");
10
+ const filters_1 = require("./filters");
11
+ const path_1 = require("./path");
12
+ exports.VARIANTS = ['draft', 'blank', 'final', 'signed'];
13
+ function own(obj, key) {
14
+ if (obj === null || typeof obj !== 'object')
15
+ return undefined;
16
+ if (Array.isArray(obj))
17
+ return /^\d+$/.test(key) ? obj[Number(key)] : undefined;
18
+ return Object.prototype.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
19
+ }
20
+ function isRaw(v) {
21
+ return v instanceof escape_1.RawLatex || (!!v && typeof v === 'object' && v.constructor?.name === 'RawLatex' && typeof v.value === 'string');
22
+ }
23
+ function evaluateTemplate(template, options) {
24
+ const variant = options.variant;
25
+ const locale = options.locale ?? 'en-US';
26
+ const allowMissing = variant === 'blank' || (options.allowMissing ?? variant === 'draft');
27
+ const diagnostics = [...template.diagnostics];
28
+ const fields = [];
29
+ const frames = [];
30
+ const stack = [template.file];
31
+ const clauses = [];
32
+ const refs = [];
33
+ const lookup = (path) => {
34
+ const [head, ...rest] = (0, path_1.splitPath)(path);
35
+ let value;
36
+ if (head.startsWith('$')) {
37
+ const loop = frames[frames.length - 1];
38
+ switch (head) {
39
+ case '$variant':
40
+ value = variant;
41
+ break;
42
+ case '$locale':
43
+ value = locale;
44
+ break;
45
+ case '$docid':
46
+ value = options.docId;
47
+ break;
48
+ case '$template':
49
+ value = options.template;
50
+ break;
51
+ case '$index':
52
+ value = loop ? loop.index + 1 : undefined;
53
+ break;
54
+ case '$first':
55
+ value = loop ? loop.index === 0 : undefined;
56
+ break;
57
+ case '$last':
58
+ value = loop ? loop.index === loop.count - 1 : undefined;
59
+ break;
60
+ }
61
+ }
62
+ else {
63
+ const frame = [...frames].reverse().find((f) => f.name === head);
64
+ value = frame ? frame.item : own(options.data, head);
65
+ }
66
+ for (const seg of rest)
67
+ value = own(value, seg);
68
+ return value;
69
+ };
70
+ const missing = (what, loc) => {
71
+ if (allowMissing) {
72
+ if (variant !== 'blank')
73
+ diagnostics.push((0, diagnostics_1.diag)('warning', `missing value for ${what}`, loc));
74
+ return `\\lkmissing{${what}}`;
75
+ }
76
+ diagnostics.push((0, diagnostics_1.diag)('error', `missing value for ${what}`, loc));
77
+ return '';
78
+ };
79
+ const toTex = (value, raw, newlines, what, loc) => {
80
+ if (isRaw(value))
81
+ return value.value;
82
+ if (value instanceof Date)
83
+ value = value.toISOString().slice(0, 10);
84
+ if (typeof value === 'number') {
85
+ if (!Number.isFinite(value)) {
86
+ diagnostics.push((0, diagnostics_1.diag)('error', `${what} is ${value}`, loc));
87
+ return '';
88
+ }
89
+ value = String(value);
90
+ }
91
+ if (typeof value === 'bigint')
92
+ value = String(value);
93
+ if (typeof value === 'string') {
94
+ if (raw)
95
+ return value;
96
+ try {
97
+ return (0, escape_1.escapeLatex)(value, newlines ? { newlines } : {});
98
+ }
99
+ catch (e) {
100
+ if (!(e instanceof escape_1.LatexEscapeError))
101
+ throw e;
102
+ diagnostics.push((0, diagnostics_1.diag)('error', `${what}: ${e.message}`, loc));
103
+ return '';
104
+ }
105
+ }
106
+ 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)';
107
+ diagnostics.push((0, diagnostics_1.diag)('error', `${what} is ${kind}`, loc));
108
+ return '';
109
+ };
110
+ const render = (nodes) => {
111
+ let out = '';
112
+ for (const node of nodes) {
113
+ switch (node.kind) {
114
+ case 'text':
115
+ out += node.text;
116
+ break;
117
+ case 'field': {
118
+ const { path, filters } = node.spec;
119
+ if (variant === 'blank') {
120
+ fields.push({ path, ...node.loc, missing: false });
121
+ out += `\\lkblank{${path}}`;
122
+ break;
123
+ }
124
+ let result;
125
+ try {
126
+ result = (0, filters_1.applyFilters)(lookup(path), filters, { locale });
127
+ }
128
+ catch (e) {
129
+ if (!(e instanceof filters_1.FilterError))
130
+ throw e;
131
+ diagnostics.push((0, diagnostics_1.diag)('error', `\\field{${node.source}}: ${e.message}`, node.loc));
132
+ break;
133
+ }
134
+ const isGone = !result.defaulted && (0, filters_1.isMissing)(result.value);
135
+ fields.push({ path, ...node.loc, missing: isGone });
136
+ out += isGone ? missing(path, node.loc) : toTex(result.value, node.raw, result.newlines, path, node.loc);
137
+ break;
138
+ }
139
+ case 'docid':
140
+ if (variant === 'blank')
141
+ out += '\\lkblank{docid}';
142
+ else if (options.docId)
143
+ out += (0, escape_1.escapeLatex)(options.docId);
144
+ else
145
+ out += missing('the document ID', node.loc);
146
+ break;
147
+ case 'when':
148
+ if ((0, condition_1.evaluateCondition)(node.cond, lookup))
149
+ out += render(node.then);
150
+ else if (node.else)
151
+ out += render(node.else);
152
+ break;
153
+ case 'each': {
154
+ const list = lookup(node.path);
155
+ if (list === undefined || list === null) {
156
+ if (variant === 'blank') {
157
+ frames.push({ name: node.name, item: undefined, index: 0, count: 1 });
158
+ out += render(node.body);
159
+ frames.pop();
160
+ }
161
+ else {
162
+ out += missing(node.path, node.loc);
163
+ }
164
+ break;
165
+ }
166
+ if (!Array.isArray(list)) {
167
+ diagnostics.push((0, diagnostics_1.diag)('error', `\\each{${node.path}}: expected a list, got ${typeof list}`, node.loc));
168
+ break;
169
+ }
170
+ list.forEach((item, index) => {
171
+ frames.push({ name: node.name, item, index, count: list.length });
172
+ out += render(node.body);
173
+ frames.pop();
174
+ });
175
+ break;
176
+ }
177
+ case 'sep': {
178
+ const loop = frames[frames.length - 1];
179
+ if (loop && loop.index < loop.count - 1)
180
+ out += render(node.body);
181
+ break;
182
+ }
183
+ case 'snippet': {
184
+ const from = stack[stack.length - 1];
185
+ const snippet = options.loadSnippet?.(node.name, from) ?? null;
186
+ if (!snippet) {
187
+ diagnostics.push((0, diagnostics_1.diag)('error', `snippet not found: ${node.name}`, node.loc));
188
+ break;
189
+ }
190
+ if (stack.includes(snippet.file)) {
191
+ diagnostics.push((0, diagnostics_1.diag)('error', `snippet ${node.name} includes itself (${[...stack, snippet.file].join(' → ')})`, node.loc));
192
+ break;
193
+ }
194
+ diagnostics.push(...snippet.diagnostics);
195
+ stack.push(snippet.file);
196
+ out += render(snippet.nodes);
197
+ stack.pop();
198
+ break;
199
+ }
200
+ case 'clause': {
201
+ const clause = options.loadClause?.(node.id) ?? null;
202
+ if (!clause) {
203
+ diagnostics.push((0, diagnostics_1.diag)('error', `clause not found: ${node.id}`, node.loc));
204
+ break;
205
+ }
206
+ if (stack.includes(clause.template.file)) {
207
+ diagnostics.push((0, diagnostics_1.diag)('error', `clause ${node.id} includes itself`, node.loc));
208
+ break;
209
+ }
210
+ if (clauses.some((c) => c.id === node.id)) {
211
+ diagnostics.push((0, diagnostics_1.diag)('error', `clause ${node.id} is placed twice`, node.loc));
212
+ break;
213
+ }
214
+ clauses.push({ id: node.id, version: clause.version, file: clause.template.file });
215
+ diagnostics.push(...clause.template.diagnostics);
216
+ out += `\\lkclause{${clause.title ? (0, escape_1.escapeLatex)(clause.title) : ''}}{${(0, clause_1.clauseLabel)(node.id)}}`;
217
+ stack.push(clause.template.file);
218
+ out += render(clause.template.nodes);
219
+ stack.pop();
220
+ break;
221
+ }
222
+ case 'clauseref':
223
+ refs.push({ id: node.id, loc: node.loc });
224
+ out += `\\ref{${(0, clause_1.clauseLabel)(node.id)}}`;
225
+ break;
226
+ }
227
+ }
228
+ return out;
229
+ };
230
+ const tex = render(template.nodes);
231
+ // a reference to a clause this document does not contain would print "??"
232
+ for (const r of refs) {
233
+ if (!clauses.some((c) => c.id === r.id)) {
234
+ const msg = `\\clauseref{${r.id}}: clause ${r.id} is not in this document`;
235
+ diagnostics.push((0, diagnostics_1.diag)(allowMissing ? 'warning' : 'error', msg, r.loc));
236
+ }
237
+ }
238
+ return { tex, diagnostics, fields, clauses };
239
+ }
package/filters.d.ts ADDED
@@ -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/filters.js ADDED
@@ -0,0 +1,229 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FILTERS = exports.FilterError = void 0;
4
+ exports.isMissing = isMissing;
5
+ exports.parseFieldSpec = parseFieldSpec;
6
+ exports.applyFilters = applyFilters;
7
+ exports.numberToWords = numberToWords;
8
+ const path_1 = require("./path");
9
+ class FilterError extends Error {
10
+ name = 'FilterError';
11
+ }
12
+ exports.FilterError = FilterError;
13
+ const DATE_STYLES = ['long', 'short', 'medium', 'full', 'iso'];
14
+ function toDate(value) {
15
+ if (value instanceof Date)
16
+ return value;
17
+ if (typeof value === 'string') {
18
+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
19
+ const d = m ? new Date(Date.UTC(+m[1], +m[2] - 1, +m[3])) : new Date(value);
20
+ if (!Number.isNaN(d.getTime()))
21
+ return d;
22
+ }
23
+ throw new FilterError(`date: expected a date like 2026-11-25, got ${JSON.stringify(value)}`);
24
+ }
25
+ function toNumber(name, value) {
26
+ const n = typeof value === 'string' && value.trim() !== '' ? Number(value) : value;
27
+ if (typeof n !== 'number' || !Number.isFinite(n)) {
28
+ throw new FilterError(`${name}: expected a number, got ${JSON.stringify(value)}`);
29
+ }
30
+ return n;
31
+ }
32
+ function digits(name, arg) {
33
+ if (arg === undefined)
34
+ return undefined;
35
+ const d = Number(arg);
36
+ if (!Number.isInteger(d) || d < 0 || d > 20)
37
+ throw new FilterError(`${name}: digits must be 0–20, got ${arg}`);
38
+ return d;
39
+ }
40
+ const digitsArg = (arg) => (/^\d{1,2}$/.test(arg) && Number(arg) <= 20 ? null : 'expected a number of digits (0–20)');
41
+ exports.FILTERS = {
42
+ upper: { arg: 'none', apply: (v, _a, c) => String(v).toLocaleUpperCase(c.locale) },
43
+ lower: { arg: 'none', apply: (v, _a, c) => String(v).toLocaleLowerCase(c.locale) },
44
+ title: {
45
+ arg: 'none',
46
+ apply: (v, _a, c) => String(v).replace(/(^|[\s\-(])(\p{L})/gu, (_m, pre, ch) => pre + ch.toLocaleUpperCase(c.locale)),
47
+ },
48
+ trim: { arg: 'none', apply: (v) => String(v).trim() },
49
+ date: {
50
+ arg: 'optional',
51
+ checkArg: (a) => (DATE_STYLES.includes(a) ? null : `expected one of ${DATE_STYLES.join(', ')}`),
52
+ apply: (v, arg, c) => {
53
+ const d = toDate(v);
54
+ const style = (arg ?? 'long');
55
+ if (style === 'iso')
56
+ return d.toISOString().slice(0, 10);
57
+ return new Intl.DateTimeFormat(c.locale, { dateStyle: style, timeZone: 'UTC' }).format(d);
58
+ },
59
+ },
60
+ money: {
61
+ arg: 'optional',
62
+ checkArg: (a) => (/^[A-Z]{3}$/.test(a) ? null : 'expected a 3-letter currency code like USD'),
63
+ apply: (v, arg, c) => {
64
+ let amount = v;
65
+ let currency = arg;
66
+ if (v && typeof v === 'object' && 'amount' in v) {
67
+ amount = v.amount;
68
+ currency = currency ?? v.currency;
69
+ }
70
+ if (!currency)
71
+ throw new FilterError('money: no currency (use money:USD or a { amount, currency } value)');
72
+ return new Intl.NumberFormat(c.locale, { style: 'currency', currency }).format(toNumber('money', amount));
73
+ },
74
+ },
75
+ number: {
76
+ arg: 'optional',
77
+ checkArg: digitsArg,
78
+ apply: (v, arg, c) => {
79
+ const d = digits('number', arg);
80
+ return new Intl.NumberFormat(c.locale, d === undefined ? {} : { minimumFractionDigits: d, maximumFractionDigits: d }).format(toNumber('number', v));
81
+ },
82
+ },
83
+ percent: {
84
+ arg: 'optional',
85
+ checkArg: digitsArg,
86
+ apply: (v, arg, c) => {
87
+ const d = digits('percent', arg) ?? 0;
88
+ return new Intl.NumberFormat(c.locale, { style: 'percent', minimumFractionDigits: d, maximumFractionDigits: d }).format(toNumber('percent', v));
89
+ },
90
+ },
91
+ words: {
92
+ arg: 'none',
93
+ apply: (v, _a, c) => {
94
+ if (!c.locale.toLowerCase().startsWith('en'))
95
+ throw new FilterError(`words: only English is supported (locale ${c.locale})`);
96
+ return numberToWords(toNumber('words', v));
97
+ },
98
+ },
99
+ join: {
100
+ arg: 'optional',
101
+ apply: (v, arg) => {
102
+ if (!Array.isArray(v))
103
+ throw new FilterError(`join: expected a list, got ${typeof v}`);
104
+ return v
105
+ .map((x) => {
106
+ if (typeof x !== 'string' && typeof x !== 'number')
107
+ throw new FilterError('join: list items must be text or numbers');
108
+ return String(x);
109
+ })
110
+ .join(arg ?? ', ');
111
+ },
112
+ },
113
+ default: { arg: 'required', onMissing: true, apply: (v, arg) => (isMissing(v) ? arg : v) },
114
+ lines: { arg: 'none', apply: (v, _a, _c, out) => ((out.newlines = 'linebreak'), v) },
115
+ paragraphs: { arg: 'none', apply: (v, _a, _c, out) => ((out.newlines = 'paragraph'), v) },
116
+ };
117
+ function isMissing(v) {
118
+ return v === undefined || v === null || v === '';
119
+ }
120
+ /** Parse the inside of \field{…}: `path | filter | filter:arg | filter:"quoted arg"`. */
121
+ function parseFieldSpec(text) {
122
+ const parts = [];
123
+ let cur = '';
124
+ let quoted = false;
125
+ for (let i = 0; i < text.length; i++) {
126
+ const ch = text[i];
127
+ if (quoted && ch === '\\' && i + 1 < text.length) {
128
+ cur += ch + text[++i];
129
+ continue;
130
+ }
131
+ if (ch === '"')
132
+ quoted = !quoted;
133
+ if (ch === '|' && !quoted) {
134
+ parts.push(cur);
135
+ cur = '';
136
+ continue;
137
+ }
138
+ cur += ch;
139
+ }
140
+ if (quoted)
141
+ throw new FilterError('unterminated quoted filter argument');
142
+ parts.push(cur);
143
+ const path = parts[0].trim();
144
+ if (!(0, path_1.isPath)(path)) {
145
+ throw new FilterError(path === '' ? 'empty field path' : `invalid field path "${path}" (use names and dots, like party.name or items.0.price)`);
146
+ }
147
+ const filters = parts.slice(1).map((raw) => {
148
+ const t = raw.trim();
149
+ const m = /^([a-z]+)(?::([\s\S]*))?$/.exec(t);
150
+ if (!m)
151
+ throw new FilterError(`invalid filter "${t}"`);
152
+ const name = m[1];
153
+ const def = exports.FILTERS[name];
154
+ if (!def)
155
+ throw new FilterError(`unknown filter "${name}" (known: ${Object.keys(exports.FILTERS).join(', ')})`);
156
+ let arg = m[2]?.trim();
157
+ if (arg !== undefined && arg.startsWith('"')) {
158
+ if (!arg.endsWith('"') || arg.length < 2)
159
+ throw new FilterError(`filter ${name}: bad quoted argument`);
160
+ arg = arg.slice(1, -1).replace(/\\(.)/g, '$1');
161
+ }
162
+ else if (arg === '') {
163
+ arg = undefined;
164
+ }
165
+ if (def.arg === 'none' && arg !== undefined)
166
+ throw new FilterError(`filter ${name} takes no argument`);
167
+ if (def.arg === 'required' && arg === undefined)
168
+ throw new FilterError(`filter ${name} needs an argument, like ${name}:"…"`);
169
+ if (arg !== undefined && def.checkArg) {
170
+ const problem = def.checkArg(arg);
171
+ if (problem)
172
+ throw new FilterError(`filter ${name}: ${problem}`);
173
+ }
174
+ return arg === undefined ? { name } : { name, arg };
175
+ });
176
+ return { path, filters };
177
+ }
178
+ /** Run filters left to right. Missing values skip every filter except `default`. */
179
+ function applyFilters(value, filters, ctx) {
180
+ const out = {};
181
+ let v = value;
182
+ for (const f of filters) {
183
+ const def = exports.FILTERS[f.name];
184
+ if (isMissing(v) && !def.onMissing)
185
+ continue;
186
+ if (f.name === 'default' && isMissing(v))
187
+ out.defaulted = true;
188
+ v = def.apply(v, f.arg, ctx, out);
189
+ }
190
+ return { value: v, ...out };
191
+ }
192
+ const ONES = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
193
+ const TENS = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
194
+ const SCALES = ['', 'thousand', 'million', 'billion', 'trillion'];
195
+ function below1000(n) {
196
+ const parts = [];
197
+ if (n >= 100) {
198
+ parts.push(`${ONES[Math.floor(n / 100)]} hundred`);
199
+ n %= 100;
200
+ }
201
+ if (n >= 20) {
202
+ parts.push(TENS[Math.floor(n / 10)] + (n % 10 ? `-${ONES[n % 10]}` : ''));
203
+ }
204
+ else if (n > 0) {
205
+ parts.push(ONES[n]);
206
+ }
207
+ return parts.join(' ');
208
+ }
209
+ /** 1200 → "one thousand two hundred". Integers only, up to the trillions. */
210
+ function numberToWords(n) {
211
+ if (!Number.isInteger(n))
212
+ throw new FilterError(`words: expected a whole number, got ${n}`);
213
+ if (Math.abs(n) >= 1e15)
214
+ throw new FilterError(`words: ${n} is too large`);
215
+ if (n === 0)
216
+ return 'zero';
217
+ if (n < 0)
218
+ return `minus ${numberToWords(-n)}`;
219
+ const groups = [];
220
+ let scale = 0;
221
+ while (n > 0) {
222
+ const chunk = n % 1000;
223
+ if (chunk)
224
+ groups.unshift(below1000(chunk) + (SCALES[scale] ? ` ${SCALES[scale]}` : ''));
225
+ n = Math.floor(n / 1000);
226
+ scale++;
227
+ }
228
+ return groups.join(' ');
229
+ }
package/index.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ export * from './analyze';
2
+ export * from './clause';
3
+ export * from './codemod';
4
+ export * from './compile';
5
+ export * from './condition';
6
+ export * from './diagnostics';
7
+ export * from './document';
8
+ export * from './evaluate';
9
+ export * from './filters';
10
+ export * from './jsonschema';
11
+ export * from './path';
12
+ export * from './sty';
package/index.js ADDED
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./analyze"), exports);
18
+ __exportStar(require("./clause"), exports);
19
+ __exportStar(require("./codemod"), exports);
20
+ __exportStar(require("./compile"), exports);
21
+ __exportStar(require("./condition"), exports);
22
+ __exportStar(require("./diagnostics"), exports);
23
+ __exportStar(require("./document"), exports);
24
+ __exportStar(require("./evaluate"), exports);
25
+ __exportStar(require("./filters"), exports);
26
+ __exportStar(require("./jsonschema"), exports);
27
+ __exportStar(require("./path"), exports);
28
+ __exportStar(require("./sty"), exports);
@@ -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;
package/jsonschema.js ADDED
@@ -0,0 +1,99 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ANY = void 0;
4
+ exports.schemaAt = schemaAt;
5
+ exports.itemSchema = itemSchema;
6
+ /** "anything goes" from here down: no further checking is possible. */
7
+ exports.ANY = true;
8
+ function deref(node, root, depth = 0) {
9
+ if (typeof node === 'boolean' || !node.$ref || depth > 32)
10
+ return node;
11
+ const m = /^#\/(\$defs|definitions)\/(.+)$/.exec(node.$ref);
12
+ if (!m || typeof root === 'boolean')
13
+ return exports.ANY;
14
+ const table = root[m[1]];
15
+ const target = table?.[decodeURIComponent(m[2]).replace(/~1/g, '/').replace(/~0/g, '~')];
16
+ return target === undefined ? exports.ANY : deref(target, root, depth + 1);
17
+ }
18
+ function variants(node) {
19
+ if (typeof node === 'boolean')
20
+ return null;
21
+ return node.anyOf ?? node.oneOf ?? null;
22
+ }
23
+ function isPermissive(node) {
24
+ if (node === true)
25
+ return true;
26
+ if (node === false)
27
+ return false;
28
+ const keys = Object.keys(node).filter((k) => !['$schema', 'description', 'title', 'default', 'examples', '$id'].includes(k));
29
+ return keys.length === 0;
30
+ }
31
+ /**
32
+ * The sub-schema at `segments`, or `undefined` when the path cannot exist.
33
+ * Unions are walked branch by branch; a path is valid if any branch has it.
34
+ */
35
+ function schemaAt(node, segments, root = node) {
36
+ node = deref(node, root);
37
+ if (segments.length === 0)
38
+ return node;
39
+ if (typeof node === 'boolean')
40
+ return node ? exports.ANY : undefined;
41
+ if (isPermissive(node))
42
+ return exports.ANY;
43
+ const alts = variants(node);
44
+ if (alts) {
45
+ const found = alts.map((a) => schemaAt(a, segments, root)).filter((x) => x !== undefined);
46
+ if (found.length === 0)
47
+ return undefined;
48
+ return found.length === 1 ? found[0] : { anyOf: found };
49
+ }
50
+ if (node.allOf) {
51
+ for (const part of node.allOf) {
52
+ const found = schemaAt(part, segments, root);
53
+ if (found !== undefined)
54
+ return found;
55
+ }
56
+ return undefined;
57
+ }
58
+ const [seg, ...rest] = segments;
59
+ const types = node.type === undefined ? [] : Array.isArray(node.type) ? node.type : [node.type];
60
+ if (types.includes('array') || node.items !== undefined || node.prefixItems !== undefined) {
61
+ if (!/^\d+$/.test(seg))
62
+ return undefined;
63
+ const i = Number(seg);
64
+ const item = node.prefixItems?.[i] ?? (Array.isArray(node.items) ? node.items[i] : node.items) ?? exports.ANY;
65
+ return schemaAt(item, rest, root);
66
+ }
67
+ if (types.includes('object') || node.properties || node.additionalProperties !== undefined) {
68
+ const prop = node.properties?.[seg];
69
+ if (prop !== undefined)
70
+ return schemaAt(prop, rest, root);
71
+ const extra = node.additionalProperties;
72
+ if (extra === undefined || extra === true)
73
+ return types.includes('object') && node.properties ? undefined : exports.ANY;
74
+ if (extra === false)
75
+ return undefined;
76
+ return schemaAt(extra, rest, root);
77
+ }
78
+ return undefined;
79
+ }
80
+ /** The schema for one element of a list, for \each. `undefined` if not a list. */
81
+ function itemSchema(node, root) {
82
+ node = deref(node, root);
83
+ if (isPermissive(node))
84
+ return exports.ANY;
85
+ if (typeof node === 'boolean')
86
+ return undefined;
87
+ const alts = variants(node);
88
+ if (alts) {
89
+ const found = alts.map((a) => itemSchema(a, root)).filter((x) => x !== undefined);
90
+ return found.length === 0 ? undefined : found.length === 1 ? found[0] : { anyOf: found };
91
+ }
92
+ const types = node.type === undefined ? [] : Array.isArray(node.type) ? node.type : [node.type];
93
+ if (types.includes('array') || node.items !== undefined) {
94
+ return Array.isArray(node.items) ? exports.ANY : (node.items ?? exports.ANY);
95
+ }
96
+ if (types.length > 0)
97
+ return undefined; // a known non-list type
98
+ return exports.ANY;
99
+ }