@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.
- package/LICENSE +23 -0
- package/README.md +120 -2
- package/analyze.d.ts +30 -0
- package/analyze.js +113 -0
- package/compile.d.ts +62 -0
- package/compile.js +242 -0
- package/condition.d.ts +38 -0
- package/condition.js +201 -0
- package/diagnostics.d.ts +29 -0
- package/diagnostics.js +48 -0
- package/document.d.ts +15 -0
- package/document.js +25 -0
- package/esm/analyze.d.ts +30 -0
- package/esm/analyze.js +110 -0
- package/esm/compile.d.ts +62 -0
- package/esm/compile.js +238 -0
- package/esm/condition.d.ts +38 -0
- package/esm/condition.js +193 -0
- package/esm/diagnostics.d.ts +29 -0
- package/esm/diagnostics.js +40 -0
- package/esm/document.d.ts +15 -0
- package/esm/document.js +22 -0
- package/esm/evaluate.d.ts +35 -0
- package/esm/evaluate.js +199 -0
- package/esm/filters.d.ts +39 -0
- package/esm/filters.js +221 -0
- package/esm/index.d.ts +10 -0
- package/esm/index.js +10 -0
- package/esm/jsonschema.d.ts +24 -0
- package/esm/jsonschema.js +94 -0
- package/esm/path.d.ts +7 -0
- package/esm/path.js +16 -0
- package/esm/sty.d.ts +6 -0
- package/esm/sty.js +62 -0
- package/evaluate.d.ts +35 -0
- package/evaluate.js +203 -0
- package/filters.d.ts +39 -0
- package/filters.js +229 -0
- package/index.d.ts +10 -0
- package/index.js +26 -0
- package/jsonschema.d.ts +24 -0
- package/jsonschema.js +99 -0
- package/package.json +44 -4
- package/path.d.ts +7 -0
- package/path.js +22 -0
- package/sty.d.ts +6 -0
- package/sty.js +65 -0
package/esm/compile.js
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
import { getParser } from '@unified-latex/unified-latex-util-parse';
|
|
2
|
+
import { ConditionError, parseCondition } from './condition';
|
|
3
|
+
import { diag, LineIndex } from './diagnostics';
|
|
4
|
+
import { FilterError, parseFieldSpec } from './filters';
|
|
5
|
+
import { isName, isPath } from './path';
|
|
6
|
+
/**
|
|
7
|
+
* The template language's macros and how many {…} arguments each takes.
|
|
8
|
+
* Bare names keep templates readable; \snippet (not \partial, which is the
|
|
9
|
+
* math ∂) and \clauseref (not \ref) avoid LaTeX's own commands.
|
|
10
|
+
*/
|
|
11
|
+
export const MACROS = {
|
|
12
|
+
field: 1,
|
|
13
|
+
raw: 1,
|
|
14
|
+
when: 2,
|
|
15
|
+
otherwise: 1,
|
|
16
|
+
each: 3,
|
|
17
|
+
sep: 1,
|
|
18
|
+
snippet: 1,
|
|
19
|
+
docid: 0,
|
|
20
|
+
clauseref: 1,
|
|
21
|
+
};
|
|
22
|
+
const parser = getParser({
|
|
23
|
+
macros: Object.fromEntries(Object.entries(MACROS).map(([name, n]) => [name, { signature: Array(n).fill('m').join(' ') }])),
|
|
24
|
+
});
|
|
25
|
+
/** Find our macros with unified-latex, so comments, verbatim and \verb are skipped. */
|
|
26
|
+
function findMacros(text) {
|
|
27
|
+
const out = [];
|
|
28
|
+
const seen = new Set();
|
|
29
|
+
const walk = (node) => {
|
|
30
|
+
if (Array.isArray(node)) {
|
|
31
|
+
node.forEach(walk);
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
if (!node || typeof node !== 'object')
|
|
35
|
+
return;
|
|
36
|
+
const n = node;
|
|
37
|
+
if (n.type === 'macro' && typeof n.content === 'string' && n.content in MACROS && n.position) {
|
|
38
|
+
const start = n.position.start.offset;
|
|
39
|
+
if (!seen.has(start)) {
|
|
40
|
+
seen.add(start);
|
|
41
|
+
out.push({ name: n.content, start });
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
if (n.content && typeof n.content !== 'string')
|
|
45
|
+
walk(n.content);
|
|
46
|
+
if (n.args)
|
|
47
|
+
walk(n.args);
|
|
48
|
+
};
|
|
49
|
+
walk(parser.parse(text));
|
|
50
|
+
return out.sort((a, b) => a.start - b.start);
|
|
51
|
+
}
|
|
52
|
+
class SyntaxError extends Error {
|
|
53
|
+
offset;
|
|
54
|
+
constructor(message, offset) {
|
|
55
|
+
super(message);
|
|
56
|
+
this.offset = offset;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/** Skip spaces and at most one line break, as TeX does between arguments. */
|
|
60
|
+
function skipSpace(text, pos) {
|
|
61
|
+
let newlines = 0;
|
|
62
|
+
while (pos < text.length) {
|
|
63
|
+
const ch = text[pos];
|
|
64
|
+
if (ch === ' ' || ch === '\t' || ch === '\r')
|
|
65
|
+
pos++;
|
|
66
|
+
else if (ch === '\n' && newlines === 0) {
|
|
67
|
+
newlines++;
|
|
68
|
+
pos++;
|
|
69
|
+
}
|
|
70
|
+
else
|
|
71
|
+
break;
|
|
72
|
+
}
|
|
73
|
+
return pos;
|
|
74
|
+
}
|
|
75
|
+
/** Read `count` brace groups starting at `pos`. Returns the content ranges and the end. */
|
|
76
|
+
function readArgs(text, pos, count, macro) {
|
|
77
|
+
const args = [];
|
|
78
|
+
for (let i = 0; i < count; i++) {
|
|
79
|
+
const open = skipSpace(text, pos);
|
|
80
|
+
if (text[open] !== '{') {
|
|
81
|
+
throw new SyntaxError(`\\${macro} needs ${count} {…} argument${count > 1 ? 's' : ''}`, open);
|
|
82
|
+
}
|
|
83
|
+
let depth = 0;
|
|
84
|
+
let j = open;
|
|
85
|
+
for (; j < text.length; j++) {
|
|
86
|
+
const ch = text[j];
|
|
87
|
+
if (ch === '\\') {
|
|
88
|
+
j++;
|
|
89
|
+
}
|
|
90
|
+
else if (ch === '%') {
|
|
91
|
+
while (j < text.length && text[j] !== '\n')
|
|
92
|
+
j++;
|
|
93
|
+
}
|
|
94
|
+
else if (ch === '{') {
|
|
95
|
+
depth++;
|
|
96
|
+
}
|
|
97
|
+
else if (ch === '}') {
|
|
98
|
+
depth--;
|
|
99
|
+
if (depth === 0)
|
|
100
|
+
break;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
if (depth !== 0)
|
|
104
|
+
throw new SyntaxError(`unbalanced braces in \\${macro}`, open);
|
|
105
|
+
args.push({ start: open + 1, end: j });
|
|
106
|
+
pos = j + 1;
|
|
107
|
+
}
|
|
108
|
+
return { args, end: pos };
|
|
109
|
+
}
|
|
110
|
+
export function compileTemplate(text, file) {
|
|
111
|
+
const diagnostics = [];
|
|
112
|
+
const lines = new LineIndex(text);
|
|
113
|
+
const at = (offset) => ({ file, ...lines.locate(offset) });
|
|
114
|
+
let occurrences;
|
|
115
|
+
try {
|
|
116
|
+
occurrences = findMacros(text);
|
|
117
|
+
}
|
|
118
|
+
catch (e) {
|
|
119
|
+
diagnostics.push(diag('error', `could not parse: ${e.message}`, at(0)));
|
|
120
|
+
return { file, text, nodes: [{ kind: 'text', text }], diagnostics };
|
|
121
|
+
}
|
|
122
|
+
let next = 0; // index into occurrences
|
|
123
|
+
const compileRange = (start, end, inEach) => {
|
|
124
|
+
const nodes = [];
|
|
125
|
+
let pos = start;
|
|
126
|
+
const pushText = (to) => {
|
|
127
|
+
if (to > pos)
|
|
128
|
+
nodes.push({ kind: 'text', text: text.slice(pos, to) });
|
|
129
|
+
};
|
|
130
|
+
while (next < occurrences.length && occurrences[next].start < end) {
|
|
131
|
+
const occ = occurrences[next++];
|
|
132
|
+
if (occ.start < pos)
|
|
133
|
+
continue; // inside an argument already consumed
|
|
134
|
+
pushText(occ.start);
|
|
135
|
+
const loc = at(occ.start);
|
|
136
|
+
const nameEnd = occ.start + 1 + occ.name.length;
|
|
137
|
+
pos = nameEnd;
|
|
138
|
+
try {
|
|
139
|
+
const { args, end: macroEnd } = readArgs(text, nameEnd, MACROS[occ.name], occ.name);
|
|
140
|
+
const argText = (i) => text.slice(args[i].start, args[i].end).trim();
|
|
141
|
+
switch (occ.name) {
|
|
142
|
+
case 'field':
|
|
143
|
+
case 'raw': {
|
|
144
|
+
try {
|
|
145
|
+
nodes.push({ kind: 'field', spec: parseFieldSpec(argText(0)), raw: occ.name === 'raw', source: argText(0), loc });
|
|
146
|
+
}
|
|
147
|
+
catch (e) {
|
|
148
|
+
if (!(e instanceof FilterError))
|
|
149
|
+
throw e;
|
|
150
|
+
diagnostics.push(diag('error', `\\${occ.name}{${argText(0)}}: ${e.message}`, loc));
|
|
151
|
+
}
|
|
152
|
+
pos = macroEnd;
|
|
153
|
+
break;
|
|
154
|
+
}
|
|
155
|
+
case 'when': {
|
|
156
|
+
let cond = null;
|
|
157
|
+
try {
|
|
158
|
+
cond = parseCondition(argText(0));
|
|
159
|
+
}
|
|
160
|
+
catch (e) {
|
|
161
|
+
if (!(e instanceof ConditionError))
|
|
162
|
+
throw e;
|
|
163
|
+
diagnostics.push(diag('error', `\\when{${argText(0)}}: ${e.message}`, loc));
|
|
164
|
+
}
|
|
165
|
+
const thenNodes = compileRange(args[1].start, args[1].end, inEach);
|
|
166
|
+
pos = macroEnd;
|
|
167
|
+
let elseNodes;
|
|
168
|
+
const after = skipSpace(text, macroEnd);
|
|
169
|
+
const nextOcc = occurrences[next];
|
|
170
|
+
if (nextOcc && nextOcc.name === 'otherwise' && nextOcc.start === after) {
|
|
171
|
+
next++;
|
|
172
|
+
const o = readArgs(text, after + '\\otherwise'.length, 1, 'otherwise');
|
|
173
|
+
elseNodes = compileRange(o.args[0].start, o.args[0].end, inEach);
|
|
174
|
+
pos = o.end;
|
|
175
|
+
}
|
|
176
|
+
if (cond)
|
|
177
|
+
nodes.push({ kind: 'when', cond, source: argText(0), then: thenNodes, else: elseNodes, loc });
|
|
178
|
+
break;
|
|
179
|
+
}
|
|
180
|
+
case 'otherwise':
|
|
181
|
+
diagnostics.push(diag('error', '\\otherwise must come right after \\when{…}{…}', loc));
|
|
182
|
+
pos = macroEnd;
|
|
183
|
+
break;
|
|
184
|
+
case 'each': {
|
|
185
|
+
const path = argText(0);
|
|
186
|
+
const name = argText(1);
|
|
187
|
+
if (!isPath(path))
|
|
188
|
+
diagnostics.push(diag('error', `\\each: invalid list path "${path}"`, loc));
|
|
189
|
+
if (!isName(name))
|
|
190
|
+
diagnostics.push(diag('error', `\\each: invalid item name "${name}" (use a simple name like item)`, loc));
|
|
191
|
+
const body = compileRange(args[2].start, args[2].end, true);
|
|
192
|
+
nodes.push({ kind: 'each', path, name, body, loc });
|
|
193
|
+
pos = macroEnd;
|
|
194
|
+
break;
|
|
195
|
+
}
|
|
196
|
+
case 'sep': {
|
|
197
|
+
if (!inEach)
|
|
198
|
+
diagnostics.push(diag('error', '\\sep only works inside \\each', loc));
|
|
199
|
+
nodes.push({ kind: 'sep', body: compileRange(args[0].start, args[0].end, inEach), loc });
|
|
200
|
+
pos = macroEnd;
|
|
201
|
+
break;
|
|
202
|
+
}
|
|
203
|
+
case 'snippet': {
|
|
204
|
+
const name = argText(0);
|
|
205
|
+
if (!/^[A-Za-z0-9_\-./]+$/.test(name) || name.split('/').some((s) => s === '..' || s === '')) {
|
|
206
|
+
diagnostics.push(diag('error', `\\snippet{${name}}: use a relative name like parts/header`, loc));
|
|
207
|
+
}
|
|
208
|
+
else {
|
|
209
|
+
nodes.push({ kind: 'snippet', name, loc });
|
|
210
|
+
}
|
|
211
|
+
pos = macroEnd;
|
|
212
|
+
break;
|
|
213
|
+
}
|
|
214
|
+
case 'docid': {
|
|
215
|
+
nodes.push({ kind: 'docid', loc });
|
|
216
|
+
// allow \docid{} as in plain LaTeX usage
|
|
217
|
+
pos = text.startsWith('{}', macroEnd) ? macroEnd + 2 : macroEnd;
|
|
218
|
+
break;
|
|
219
|
+
}
|
|
220
|
+
case 'clauseref':
|
|
221
|
+
diagnostics.push(diag('error', '\\clauseref is reserved for the clause library, which is not available yet', loc));
|
|
222
|
+
pos = macroEnd;
|
|
223
|
+
break;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
catch (e) {
|
|
227
|
+
if (!(e instanceof SyntaxError))
|
|
228
|
+
throw e;
|
|
229
|
+
diagnostics.push(diag('error', e.message, at(e.offset)));
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
pushText(end);
|
|
233
|
+
pos = end;
|
|
234
|
+
return nodes;
|
|
235
|
+
};
|
|
236
|
+
const nodes = compileRange(0, text.length, false);
|
|
237
|
+
return { file, text, nodes, diagnostics };
|
|
238
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The condition language for \when{…}: a small, safe expression grammar.
|
|
3
|
+
* Never evaluated with eval.
|
|
4
|
+
*
|
|
5
|
+
* expr := or
|
|
6
|
+
* or := and ('||' and)*
|
|
7
|
+
* and := not ('&&' not)*
|
|
8
|
+
* not := '!' not | compare
|
|
9
|
+
* compare := primary (('==' | '!=' | '<' | '<=' | '>' | '>=') primary)?
|
|
10
|
+
* primary := path | number | "string" | true | false | null | '(' expr ')'
|
|
11
|
+
*/
|
|
12
|
+
export type Expr = {
|
|
13
|
+
type: 'path';
|
|
14
|
+
path: string;
|
|
15
|
+
} | {
|
|
16
|
+
type: 'literal';
|
|
17
|
+
value: string | number | boolean | null;
|
|
18
|
+
} | {
|
|
19
|
+
type: 'not';
|
|
20
|
+
expr: Expr;
|
|
21
|
+
} | {
|
|
22
|
+
type: 'and' | 'or';
|
|
23
|
+
left: Expr;
|
|
24
|
+
right: Expr;
|
|
25
|
+
} | {
|
|
26
|
+
type: 'compare';
|
|
27
|
+
op: CompareOp;
|
|
28
|
+
left: Expr;
|
|
29
|
+
right: Expr;
|
|
30
|
+
};
|
|
31
|
+
export type CompareOp = '==' | '!=' | '<' | '<=' | '>' | '>=';
|
|
32
|
+
export declare class ConditionError extends Error {
|
|
33
|
+
name: string;
|
|
34
|
+
}
|
|
35
|
+
export declare function parseCondition(src: string): Expr;
|
|
36
|
+
export declare function truthy(v: unknown): boolean;
|
|
37
|
+
export declare function evaluateCondition(expr: Expr, lookup: (path: string) => unknown): boolean;
|
|
38
|
+
export declare function conditionPaths(expr: Expr, out?: string[]): string[];
|
package/esm/condition.js
ADDED
|
@@ -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;
|
package/esm/document.js
ADDED
|
@@ -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,35 @@
|
|
|
1
|
+
import { CompiledTemplate } from './compile';
|
|
2
|
+
import { truthy } from './condition';
|
|
3
|
+
import { Diagnostic } from './diagnostics';
|
|
4
|
+
export type Variant = 'draft' | 'blank' | 'final' | 'signed';
|
|
5
|
+
export declare const VARIANTS: Variant[];
|
|
6
|
+
export interface EvaluateOptions {
|
|
7
|
+
/** The record's data. */
|
|
8
|
+
data: unknown;
|
|
9
|
+
variant: Variant;
|
|
10
|
+
locale?: string;
|
|
11
|
+
docId?: string;
|
|
12
|
+
template?: string;
|
|
13
|
+
/**
|
|
14
|
+
* Missing values print a red marker instead of failing. Defaults to true
|
|
15
|
+
* for `draft`; `final` and `signed` always fail on a missing value.
|
|
16
|
+
*/
|
|
17
|
+
allowMissing?: boolean;
|
|
18
|
+
/** Resolve \snippet{name} from the file that uses it. */
|
|
19
|
+
loadSnippet?: (name: string, from: string) => CompiledTemplate | null;
|
|
20
|
+
}
|
|
21
|
+
export interface FieldUse {
|
|
22
|
+
path: string;
|
|
23
|
+
file: string;
|
|
24
|
+
line: number;
|
|
25
|
+
column: number;
|
|
26
|
+
missing: boolean;
|
|
27
|
+
}
|
|
28
|
+
export interface EvaluateResult {
|
|
29
|
+
tex: string;
|
|
30
|
+
diagnostics: Diagnostic[];
|
|
31
|
+
/** Every field that was filled (or found missing), in document order. */
|
|
32
|
+
fields: FieldUse[];
|
|
33
|
+
}
|
|
34
|
+
export declare function evaluateTemplate(template: CompiledTemplate, options: EvaluateOptions): EvaluateResult;
|
|
35
|
+
export { truthy };
|