@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.
- package/LICENSE +23 -0
- package/README.md +137 -2
- package/analyze.d.ts +38 -0
- package/analyze.js +144 -0
- package/clause.d.ts +23 -0
- package/clause.js +26 -0
- package/codemod.d.ts +25 -0
- package/codemod.js +67 -0
- package/compile.d.ts +74 -0
- package/compile.js +258 -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 +38 -0
- package/esm/analyze.js +141 -0
- package/esm/clause.d.ts +23 -0
- package/esm/clause.js +21 -0
- package/esm/codemod.d.ts +25 -0
- package/esm/codemod.js +62 -0
- package/esm/compile.d.ts +74 -0
- package/esm/compile.js +253 -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 +40 -0
- package/esm/evaluate.js +235 -0
- package/esm/filters.d.ts +39 -0
- package/esm/filters.js +221 -0
- package/esm/index.d.ts +12 -0
- package/esm/index.js +12 -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 +67 -0
- package/evaluate.d.ts +40 -0
- package/evaluate.js +239 -0
- package/filters.d.ts +39 -0
- package/filters.js +229 -0
- package/index.d.ts +12 -0
- package/index.js +28 -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 +70 -0
package/compile.js
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.MACROS = void 0;
|
|
4
|
+
exports.isRelativeName = isRelativeName;
|
|
5
|
+
exports.compileTemplate = compileTemplate;
|
|
6
|
+
const unified_latex_util_parse_1 = require("@unified-latex/unified-latex-util-parse");
|
|
7
|
+
const condition_1 = require("./condition");
|
|
8
|
+
const diagnostics_1 = require("./diagnostics");
|
|
9
|
+
const filters_1 = require("./filters");
|
|
10
|
+
const path_1 = require("./path");
|
|
11
|
+
/**
|
|
12
|
+
* The template language's macros and how many {…} arguments each takes.
|
|
13
|
+
* Bare names keep templates readable; \snippet (not \partial, which is the
|
|
14
|
+
* math ∂) and \clauseref (not \ref) avoid LaTeX's own commands. \clause
|
|
15
|
+
* inserts a numbered clause from the clause library; \clauseref prints its number.
|
|
16
|
+
*/
|
|
17
|
+
exports.MACROS = {
|
|
18
|
+
field: 1,
|
|
19
|
+
raw: 1,
|
|
20
|
+
when: 2,
|
|
21
|
+
otherwise: 1,
|
|
22
|
+
each: 3,
|
|
23
|
+
sep: 1,
|
|
24
|
+
snippet: 1,
|
|
25
|
+
docid: 0,
|
|
26
|
+
clause: 1,
|
|
27
|
+
clauseref: 1,
|
|
28
|
+
};
|
|
29
|
+
const parser = (0, unified_latex_util_parse_1.getParser)({
|
|
30
|
+
macros: Object.fromEntries(Object.entries(exports.MACROS).map(([name, n]) => [name, { signature: Array(n).fill('m').join(' ') }])),
|
|
31
|
+
});
|
|
32
|
+
/** `parts/header`, `nda/confidentiality`: relative, no `..`, no empty segments. */
|
|
33
|
+
function isRelativeName(name) {
|
|
34
|
+
return /^[A-Za-z0-9_./-]+$/.test(name) && !name.split('/').some((s) => s === '..' || s === '' || s === '.');
|
|
35
|
+
}
|
|
36
|
+
/** Find our macros with unified-latex, so comments, verbatim and \verb are skipped. */
|
|
37
|
+
function findMacros(text) {
|
|
38
|
+
const out = [];
|
|
39
|
+
const seen = new Set();
|
|
40
|
+
const walk = (node) => {
|
|
41
|
+
if (Array.isArray(node)) {
|
|
42
|
+
node.forEach(walk);
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
if (!node || typeof node !== 'object')
|
|
46
|
+
return;
|
|
47
|
+
const n = node;
|
|
48
|
+
if (n.type === 'macro' && typeof n.content === 'string' && n.content in exports.MACROS && n.position) {
|
|
49
|
+
const start = n.position.start.offset;
|
|
50
|
+
if (!seen.has(start)) {
|
|
51
|
+
seen.add(start);
|
|
52
|
+
out.push({ name: n.content, start });
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
if (n.content && typeof n.content !== 'string')
|
|
56
|
+
walk(n.content);
|
|
57
|
+
if (n.args)
|
|
58
|
+
walk(n.args);
|
|
59
|
+
};
|
|
60
|
+
walk(parser.parse(text));
|
|
61
|
+
return out.sort((a, b) => a.start - b.start);
|
|
62
|
+
}
|
|
63
|
+
class SyntaxError extends Error {
|
|
64
|
+
offset;
|
|
65
|
+
constructor(message, offset) {
|
|
66
|
+
super(message);
|
|
67
|
+
this.offset = offset;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/** Skip spaces and at most one line break, as TeX does between arguments. */
|
|
71
|
+
function skipSpace(text, pos) {
|
|
72
|
+
let newlines = 0;
|
|
73
|
+
while (pos < text.length) {
|
|
74
|
+
const ch = text[pos];
|
|
75
|
+
if (ch === ' ' || ch === '\t' || ch === '\r')
|
|
76
|
+
pos++;
|
|
77
|
+
else if (ch === '\n' && newlines === 0) {
|
|
78
|
+
newlines++;
|
|
79
|
+
pos++;
|
|
80
|
+
}
|
|
81
|
+
else
|
|
82
|
+
break;
|
|
83
|
+
}
|
|
84
|
+
return pos;
|
|
85
|
+
}
|
|
86
|
+
/** Read `count` brace groups starting at `pos`. Returns the content ranges and the end. */
|
|
87
|
+
function readArgs(text, pos, count, macro) {
|
|
88
|
+
const args = [];
|
|
89
|
+
for (let i = 0; i < count; i++) {
|
|
90
|
+
const open = skipSpace(text, pos);
|
|
91
|
+
if (text[open] !== '{') {
|
|
92
|
+
throw new SyntaxError(`\\${macro} needs ${count} {…} argument${count > 1 ? 's' : ''}`, open);
|
|
93
|
+
}
|
|
94
|
+
let depth = 0;
|
|
95
|
+
let j = open;
|
|
96
|
+
for (; j < text.length; j++) {
|
|
97
|
+
const ch = text[j];
|
|
98
|
+
if (ch === '\\') {
|
|
99
|
+
j++;
|
|
100
|
+
}
|
|
101
|
+
else if (ch === '%') {
|
|
102
|
+
while (j < text.length && text[j] !== '\n')
|
|
103
|
+
j++;
|
|
104
|
+
}
|
|
105
|
+
else if (ch === '{') {
|
|
106
|
+
depth++;
|
|
107
|
+
}
|
|
108
|
+
else if (ch === '}') {
|
|
109
|
+
depth--;
|
|
110
|
+
if (depth === 0)
|
|
111
|
+
break;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
if (depth !== 0)
|
|
115
|
+
throw new SyntaxError(`unbalanced braces in \\${macro}`, open);
|
|
116
|
+
args.push({ start: open + 1, end: j });
|
|
117
|
+
pos = j + 1;
|
|
118
|
+
}
|
|
119
|
+
return { args, end: pos };
|
|
120
|
+
}
|
|
121
|
+
function compileTemplate(text, file) {
|
|
122
|
+
const diagnostics = [];
|
|
123
|
+
const lines = new diagnostics_1.LineIndex(text);
|
|
124
|
+
const at = (offset) => ({ file, ...lines.locate(offset) });
|
|
125
|
+
let occurrences;
|
|
126
|
+
try {
|
|
127
|
+
occurrences = findMacros(text);
|
|
128
|
+
}
|
|
129
|
+
catch (e) {
|
|
130
|
+
diagnostics.push((0, diagnostics_1.diag)('error', `could not parse: ${e.message}`, at(0)));
|
|
131
|
+
return { file, text, nodes: [{ kind: 'text', text }], diagnostics };
|
|
132
|
+
}
|
|
133
|
+
let next = 0; // index into occurrences
|
|
134
|
+
const compileRange = (start, end, inEach) => {
|
|
135
|
+
const nodes = [];
|
|
136
|
+
let pos = start;
|
|
137
|
+
const pushText = (to) => {
|
|
138
|
+
if (to > pos)
|
|
139
|
+
nodes.push({ kind: 'text', text: text.slice(pos, to) });
|
|
140
|
+
};
|
|
141
|
+
while (next < occurrences.length && occurrences[next].start < end) {
|
|
142
|
+
const occ = occurrences[next++];
|
|
143
|
+
if (occ.start < pos)
|
|
144
|
+
continue; // inside an argument already consumed
|
|
145
|
+
pushText(occ.start);
|
|
146
|
+
const loc = at(occ.start);
|
|
147
|
+
const nameEnd = occ.start + 1 + occ.name.length;
|
|
148
|
+
pos = nameEnd;
|
|
149
|
+
try {
|
|
150
|
+
const { args, end: macroEnd } = readArgs(text, nameEnd, exports.MACROS[occ.name], occ.name);
|
|
151
|
+
const argText = (i) => text.slice(args[i].start, args[i].end).trim();
|
|
152
|
+
switch (occ.name) {
|
|
153
|
+
case 'field':
|
|
154
|
+
case 'raw': {
|
|
155
|
+
try {
|
|
156
|
+
nodes.push({ kind: 'field', spec: (0, filters_1.parseFieldSpec)(argText(0)), raw: occ.name === 'raw', source: argText(0), loc });
|
|
157
|
+
}
|
|
158
|
+
catch (e) {
|
|
159
|
+
if (!(e instanceof filters_1.FilterError))
|
|
160
|
+
throw e;
|
|
161
|
+
diagnostics.push((0, diagnostics_1.diag)('error', `\\${occ.name}{${argText(0)}}: ${e.message}`, loc));
|
|
162
|
+
}
|
|
163
|
+
pos = macroEnd;
|
|
164
|
+
break;
|
|
165
|
+
}
|
|
166
|
+
case 'when': {
|
|
167
|
+
let cond = null;
|
|
168
|
+
try {
|
|
169
|
+
cond = (0, condition_1.parseCondition)(argText(0));
|
|
170
|
+
}
|
|
171
|
+
catch (e) {
|
|
172
|
+
if (!(e instanceof condition_1.ConditionError))
|
|
173
|
+
throw e;
|
|
174
|
+
diagnostics.push((0, diagnostics_1.diag)('error', `\\when{${argText(0)}}: ${e.message}`, loc));
|
|
175
|
+
}
|
|
176
|
+
const thenNodes = compileRange(args[1].start, args[1].end, inEach);
|
|
177
|
+
pos = macroEnd;
|
|
178
|
+
let elseNodes;
|
|
179
|
+
const after = skipSpace(text, macroEnd);
|
|
180
|
+
const nextOcc = occurrences[next];
|
|
181
|
+
if (nextOcc && nextOcc.name === 'otherwise' && nextOcc.start === after) {
|
|
182
|
+
next++;
|
|
183
|
+
const o = readArgs(text, after + '\\otherwise'.length, 1, 'otherwise');
|
|
184
|
+
elseNodes = compileRange(o.args[0].start, o.args[0].end, inEach);
|
|
185
|
+
pos = o.end;
|
|
186
|
+
}
|
|
187
|
+
if (cond)
|
|
188
|
+
nodes.push({ kind: 'when', cond, source: argText(0), then: thenNodes, else: elseNodes, loc });
|
|
189
|
+
break;
|
|
190
|
+
}
|
|
191
|
+
case 'otherwise':
|
|
192
|
+
diagnostics.push((0, diagnostics_1.diag)('error', '\\otherwise must come right after \\when{…}{…}', loc));
|
|
193
|
+
pos = macroEnd;
|
|
194
|
+
break;
|
|
195
|
+
case 'each': {
|
|
196
|
+
const path = argText(0);
|
|
197
|
+
const name = argText(1);
|
|
198
|
+
if (!(0, path_1.isPath)(path))
|
|
199
|
+
diagnostics.push((0, diagnostics_1.diag)('error', `\\each: invalid list path "${path}"`, loc));
|
|
200
|
+
if (!(0, path_1.isName)(name))
|
|
201
|
+
diagnostics.push((0, diagnostics_1.diag)('error', `\\each: invalid item name "${name}" (use a simple name like item)`, loc));
|
|
202
|
+
const body = compileRange(args[2].start, args[2].end, true);
|
|
203
|
+
nodes.push({ kind: 'each', path, name, body, loc });
|
|
204
|
+
pos = macroEnd;
|
|
205
|
+
break;
|
|
206
|
+
}
|
|
207
|
+
case 'sep': {
|
|
208
|
+
if (!inEach)
|
|
209
|
+
diagnostics.push((0, diagnostics_1.diag)('error', '\\sep only works inside \\each', loc));
|
|
210
|
+
nodes.push({ kind: 'sep', body: compileRange(args[0].start, args[0].end, inEach), loc });
|
|
211
|
+
pos = macroEnd;
|
|
212
|
+
break;
|
|
213
|
+
}
|
|
214
|
+
case 'snippet':
|
|
215
|
+
case 'clause': {
|
|
216
|
+
const name = argText(0);
|
|
217
|
+
if (!isRelativeName(name)) {
|
|
218
|
+
diagnostics.push((0, diagnostics_1.diag)('error', `\\${occ.name}{${name}}: use a relative name like ${occ.name === 'clause' ? 'nda/confidentiality' : 'parts/header'}`, loc));
|
|
219
|
+
}
|
|
220
|
+
else if (occ.name === 'snippet') {
|
|
221
|
+
nodes.push({ kind: 'snippet', name, loc });
|
|
222
|
+
}
|
|
223
|
+
else {
|
|
224
|
+
nodes.push({ kind: 'clause', id: name, loc });
|
|
225
|
+
}
|
|
226
|
+
pos = macroEnd;
|
|
227
|
+
break;
|
|
228
|
+
}
|
|
229
|
+
case 'docid': {
|
|
230
|
+
nodes.push({ kind: 'docid', loc });
|
|
231
|
+
// allow \docid{} as in plain LaTeX usage
|
|
232
|
+
pos = text.startsWith('{}', macroEnd) ? macroEnd + 2 : macroEnd;
|
|
233
|
+
break;
|
|
234
|
+
}
|
|
235
|
+
case 'clauseref': {
|
|
236
|
+
const id = argText(0);
|
|
237
|
+
if (!isRelativeName(id))
|
|
238
|
+
diagnostics.push((0, diagnostics_1.diag)('error', `\\clauseref{${id}}: use the clause's name, like nda/confidentiality`, loc));
|
|
239
|
+
else
|
|
240
|
+
nodes.push({ kind: 'clauseref', id, loc });
|
|
241
|
+
pos = macroEnd;
|
|
242
|
+
break;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
catch (e) {
|
|
247
|
+
if (!(e instanceof SyntaxError))
|
|
248
|
+
throw e;
|
|
249
|
+
diagnostics.push((0, diagnostics_1.diag)('error', e.message, at(e.offset)));
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
pushText(end);
|
|
253
|
+
pos = end;
|
|
254
|
+
return nodes;
|
|
255
|
+
};
|
|
256
|
+
const nodes = compileRange(0, text.length, false);
|
|
257
|
+
return { file, text, nodes, diagnostics };
|
|
258
|
+
}
|
package/condition.d.ts
ADDED
|
@@ -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/condition.js
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ConditionError = void 0;
|
|
4
|
+
exports.parseCondition = parseCondition;
|
|
5
|
+
exports.truthy = truthy;
|
|
6
|
+
exports.evaluateCondition = evaluateCondition;
|
|
7
|
+
exports.conditionPaths = conditionPaths;
|
|
8
|
+
const path_1 = require("./path");
|
|
9
|
+
class ConditionError extends Error {
|
|
10
|
+
name = 'ConditionError';
|
|
11
|
+
}
|
|
12
|
+
exports.ConditionError = ConditionError;
|
|
13
|
+
function tokenize(src) {
|
|
14
|
+
const out = [];
|
|
15
|
+
let i = 0;
|
|
16
|
+
while (i < src.length) {
|
|
17
|
+
const ch = src[i];
|
|
18
|
+
if (/\s/.test(ch)) {
|
|
19
|
+
i++;
|
|
20
|
+
continue;
|
|
21
|
+
}
|
|
22
|
+
const two = src.slice(i, i + 2);
|
|
23
|
+
if (['&&', '||', '==', '!=', '<=', '>='].includes(two)) {
|
|
24
|
+
out.push({ t: 'op', v: two });
|
|
25
|
+
i += 2;
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
if ('!<>()'.includes(ch)) {
|
|
29
|
+
out.push({ t: 'op', v: ch });
|
|
30
|
+
i++;
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
if (ch === '"') {
|
|
34
|
+
let s = '';
|
|
35
|
+
i++;
|
|
36
|
+
while (i < src.length && src[i] !== '"') {
|
|
37
|
+
if (src[i] === '\\' && i + 1 < src.length)
|
|
38
|
+
i++;
|
|
39
|
+
s += src[i++];
|
|
40
|
+
}
|
|
41
|
+
if (src[i] !== '"')
|
|
42
|
+
throw new ConditionError('unterminated string');
|
|
43
|
+
i++;
|
|
44
|
+
out.push({ t: 'str', v: s });
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
const num = /^-?\d+(?:\.\d+)?/.exec(src.slice(i));
|
|
48
|
+
if (num) {
|
|
49
|
+
out.push({ t: 'num', v: Number(num[0]) });
|
|
50
|
+
i += num[0].length;
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
const word = /^\$?[A-Za-z_][A-Za-z0-9_]*(?:\.(?:[A-Za-z_][A-Za-z0-9_]*|\d+))*/.exec(src.slice(i));
|
|
54
|
+
if (word) {
|
|
55
|
+
out.push({ t: 'word', v: word[0] });
|
|
56
|
+
i += word[0].length;
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
if (ch === '=')
|
|
60
|
+
throw new ConditionError('use == to compare, not =');
|
|
61
|
+
if (ch === '&' || ch === '|')
|
|
62
|
+
throw new ConditionError(`use ${ch}${ch}, not ${ch}`);
|
|
63
|
+
throw new ConditionError(`unexpected "${ch}"`);
|
|
64
|
+
}
|
|
65
|
+
return out;
|
|
66
|
+
}
|
|
67
|
+
function parseCondition(src) {
|
|
68
|
+
const tokens = tokenize(src);
|
|
69
|
+
if (tokens.length === 0)
|
|
70
|
+
throw new ConditionError('empty condition');
|
|
71
|
+
let pos = 0;
|
|
72
|
+
const peek = () => tokens[pos];
|
|
73
|
+
const isOp = (v) => peek()?.t === 'op' && peek().v === v;
|
|
74
|
+
const primary = () => {
|
|
75
|
+
const tok = tokens[pos++];
|
|
76
|
+
if (!tok)
|
|
77
|
+
throw new ConditionError('condition ends too early');
|
|
78
|
+
if (tok.t === 'op' && tok.v === '(') {
|
|
79
|
+
const e = or();
|
|
80
|
+
if (!isOp(')'))
|
|
81
|
+
throw new ConditionError('missing )');
|
|
82
|
+
pos++;
|
|
83
|
+
return e;
|
|
84
|
+
}
|
|
85
|
+
if (tok.t === 'num')
|
|
86
|
+
return { type: 'literal', value: tok.v };
|
|
87
|
+
if (tok.t === 'str')
|
|
88
|
+
return { type: 'literal', value: tok.v };
|
|
89
|
+
if (tok.t === 'word') {
|
|
90
|
+
if (tok.v === 'true')
|
|
91
|
+
return { type: 'literal', value: true };
|
|
92
|
+
if (tok.v === 'false')
|
|
93
|
+
return { type: 'literal', value: false };
|
|
94
|
+
if (tok.v === 'null')
|
|
95
|
+
return { type: 'literal', value: null };
|
|
96
|
+
if (!(0, path_1.isPath)(tok.v))
|
|
97
|
+
throw new ConditionError(`invalid path ${tok.v}`);
|
|
98
|
+
return { type: 'path', path: tok.v };
|
|
99
|
+
}
|
|
100
|
+
throw new ConditionError(`unexpected "${tok.v}"`);
|
|
101
|
+
};
|
|
102
|
+
const compare = () => {
|
|
103
|
+
const left = primary();
|
|
104
|
+
const tok = peek();
|
|
105
|
+
if (tok?.t === 'op' && ['==', '!=', '<', '<=', '>', '>='].includes(tok.v)) {
|
|
106
|
+
pos++;
|
|
107
|
+
return { type: 'compare', op: tok.v, left, right: primary() };
|
|
108
|
+
}
|
|
109
|
+
return left;
|
|
110
|
+
};
|
|
111
|
+
const not = () => {
|
|
112
|
+
if (isOp('!')) {
|
|
113
|
+
pos++;
|
|
114
|
+
return { type: 'not', expr: not() };
|
|
115
|
+
}
|
|
116
|
+
return compare();
|
|
117
|
+
};
|
|
118
|
+
const and = () => {
|
|
119
|
+
let left = not();
|
|
120
|
+
while (isOp('&&')) {
|
|
121
|
+
pos++;
|
|
122
|
+
left = { type: 'and', left, right: not() };
|
|
123
|
+
}
|
|
124
|
+
return left;
|
|
125
|
+
};
|
|
126
|
+
const or = () => {
|
|
127
|
+
let left = and();
|
|
128
|
+
while (isOp('||')) {
|
|
129
|
+
pos++;
|
|
130
|
+
left = { type: 'or', left, right: and() };
|
|
131
|
+
}
|
|
132
|
+
return left;
|
|
133
|
+
};
|
|
134
|
+
const expr = or();
|
|
135
|
+
if (pos < tokens.length) {
|
|
136
|
+
const t = tokens[pos];
|
|
137
|
+
throw new ConditionError(`unexpected "${t.t === 'str' ? `"${t.v}"` : t.v}"`);
|
|
138
|
+
}
|
|
139
|
+
return expr;
|
|
140
|
+
}
|
|
141
|
+
function truthy(v) {
|
|
142
|
+
if (Array.isArray(v))
|
|
143
|
+
return v.length > 0;
|
|
144
|
+
return v !== undefined && v !== null && v !== false && v !== 0 && v !== '';
|
|
145
|
+
}
|
|
146
|
+
function evaluateCondition(expr, lookup) {
|
|
147
|
+
return truthy(value(expr, lookup));
|
|
148
|
+
}
|
|
149
|
+
function value(expr, lookup) {
|
|
150
|
+
switch (expr.type) {
|
|
151
|
+
case 'path':
|
|
152
|
+
return lookup(expr.path);
|
|
153
|
+
case 'literal':
|
|
154
|
+
return expr.value;
|
|
155
|
+
case 'not':
|
|
156
|
+
return !truthy(value(expr.expr, lookup));
|
|
157
|
+
case 'and':
|
|
158
|
+
return truthy(value(expr.left, lookup)) && truthy(value(expr.right, lookup));
|
|
159
|
+
case 'or':
|
|
160
|
+
return truthy(value(expr.left, lookup)) || truthy(value(expr.right, lookup));
|
|
161
|
+
case 'compare': {
|
|
162
|
+
const l = value(expr.left, lookup);
|
|
163
|
+
const r = value(expr.right, lookup);
|
|
164
|
+
switch (expr.op) {
|
|
165
|
+
case '==':
|
|
166
|
+
return (l ?? null) === (r ?? null);
|
|
167
|
+
case '!=':
|
|
168
|
+
return (l ?? null) !== (r ?? null);
|
|
169
|
+
default: {
|
|
170
|
+
// ordering only between two numbers or two strings; anything else is false
|
|
171
|
+
if (!((typeof l === 'number' && typeof r === 'number') || (typeof l === 'string' && typeof r === 'string')))
|
|
172
|
+
return false;
|
|
173
|
+
if (expr.op === '<')
|
|
174
|
+
return l < r;
|
|
175
|
+
if (expr.op === '<=')
|
|
176
|
+
return l <= r;
|
|
177
|
+
if (expr.op === '>')
|
|
178
|
+
return l > r;
|
|
179
|
+
return l >= r;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
function conditionPaths(expr, out = []) {
|
|
186
|
+
switch (expr.type) {
|
|
187
|
+
case 'path':
|
|
188
|
+
out.push(expr.path);
|
|
189
|
+
break;
|
|
190
|
+
case 'not':
|
|
191
|
+
conditionPaths(expr.expr, out);
|
|
192
|
+
break;
|
|
193
|
+
case 'and':
|
|
194
|
+
case 'or':
|
|
195
|
+
case 'compare':
|
|
196
|
+
conditionPaths(expr.left, out);
|
|
197
|
+
conditionPaths(expr.right, out);
|
|
198
|
+
break;
|
|
199
|
+
}
|
|
200
|
+
return out;
|
|
201
|
+
}
|
package/diagnostics.d.ts
ADDED
|
@@ -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
|
+
}
|
package/diagnostics.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.LineIndex = exports.TemplateError = void 0;
|
|
4
|
+
exports.diag = diag;
|
|
5
|
+
exports.formatDiagnostic = formatDiagnostic;
|
|
6
|
+
exports.hasErrors = hasErrors;
|
|
7
|
+
class TemplateError extends Error {
|
|
8
|
+
diagnostics;
|
|
9
|
+
constructor(message, diagnostics) {
|
|
10
|
+
super(message);
|
|
11
|
+
this.diagnostics = diagnostics;
|
|
12
|
+
this.name = 'TemplateError';
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
exports.TemplateError = TemplateError;
|
|
16
|
+
function diag(severity, message, loc) {
|
|
17
|
+
return loc ? { severity, message, file: loc.file, line: loc.line, column: loc.column } : { severity, message };
|
|
18
|
+
}
|
|
19
|
+
/** `file:line:col: error: message`, the format editors and CI annotate. */
|
|
20
|
+
function formatDiagnostic(d) {
|
|
21
|
+
const where = d.file ? `${d.file}${d.line ? `:${d.line}${d.column ? `:${d.column}` : ''}` : ''}: ` : '';
|
|
22
|
+
return `${where}${d.severity}: ${d.message}`;
|
|
23
|
+
}
|
|
24
|
+
function hasErrors(diagnostics) {
|
|
25
|
+
return diagnostics.some((d) => d.severity === 'error');
|
|
26
|
+
}
|
|
27
|
+
/** Maps string offsets to 1-based line and column. */
|
|
28
|
+
class LineIndex {
|
|
29
|
+
starts = [0];
|
|
30
|
+
constructor(text) {
|
|
31
|
+
for (let i = 0; i < text.length; i++)
|
|
32
|
+
if (text.charCodeAt(i) === 10)
|
|
33
|
+
this.starts.push(i + 1);
|
|
34
|
+
}
|
|
35
|
+
locate(offset) {
|
|
36
|
+
let lo = 0;
|
|
37
|
+
let hi = this.starts.length - 1;
|
|
38
|
+
while (lo < hi) {
|
|
39
|
+
const mid = (lo + hi + 1) >> 1;
|
|
40
|
+
if (this.starts[mid] <= offset)
|
|
41
|
+
lo = mid;
|
|
42
|
+
else
|
|
43
|
+
hi = mid - 1;
|
|
44
|
+
}
|
|
45
|
+
return { line: lo + 1, column: offset - this.starts[lo] + 1 };
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
exports.LineIndex = LineIndex;
|
package/document.d.ts
ADDED
|
@@ -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/document.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.wrapDocument = wrapDocument;
|
|
4
|
+
const escape_1 = require("@latex-kit/escape");
|
|
5
|
+
const USES_PACKAGE = /\\(?:usepackage|RequirePackage)\s*(?:\[[^\]]*\])?\s*\{[^}]*\blatex-kit\b[^}]*\}/;
|
|
6
|
+
/**
|
|
7
|
+
* Make a filled template ready for TeX: tell `latex-kit.sty` it is rendering
|
|
8
|
+
* a document (not previewing a template) and which variant, and load the
|
|
9
|
+
* package if the template did not.
|
|
10
|
+
*
|
|
11
|
+
* The settings go at the very start of line 1, so line numbers in TeX's
|
|
12
|
+
* errors still match the generated file line for line.
|
|
13
|
+
*/
|
|
14
|
+
function wrapDocument(tex, options) {
|
|
15
|
+
const stamp = options.stamp ? (0, escape_1.escapeLatex)(options.stamp) : '';
|
|
16
|
+
const prefix = `\\PassOptionsToPackage{rendered,${options.variant}}{latex-kit}\\def\\lkstamp{${stamp}}`;
|
|
17
|
+
let body = tex;
|
|
18
|
+
if (!USES_PACKAGE.test(body)) {
|
|
19
|
+
const at = body.indexOf('\\begin{document}');
|
|
20
|
+
if (at === -1)
|
|
21
|
+
throw new Error('the template has no \\begin{document}');
|
|
22
|
+
body = `${body.slice(0, at)}\\usepackage{latex-kit}${body.slice(at)}`;
|
|
23
|
+
}
|
|
24
|
+
return prefix + body;
|
|
25
|
+
}
|
package/esm/analyze.d.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { LoadedClause } from './clause';
|
|
2
|
+
import { CompiledTemplate } from './compile';
|
|
3
|
+
import { Diagnostic } from './diagnostics';
|
|
4
|
+
import { JsonSchema } from './jsonschema';
|
|
5
|
+
export interface FieldRef {
|
|
6
|
+
/** How the template reads it: `field`, `raw`, `when`, `each`. */
|
|
7
|
+
kind: 'field' | 'raw' | 'when' | 'each';
|
|
8
|
+
/** The path as written, e.g. `item.price`. */
|
|
9
|
+
path: string;
|
|
10
|
+
/** The path from the data root, e.g. `items[].price`. */
|
|
11
|
+
absolute: string;
|
|
12
|
+
filters: string[];
|
|
13
|
+
file: string;
|
|
14
|
+
line: number;
|
|
15
|
+
column: number;
|
|
16
|
+
}
|
|
17
|
+
export interface AnalyzeOptions {
|
|
18
|
+
/** JSON Schema of the record's data. Without it only syntax is checked. */
|
|
19
|
+
schema?: JsonSchema;
|
|
20
|
+
loadSnippet?: (name: string, from: string) => CompiledTemplate | null;
|
|
21
|
+
loadClause?: (id: string) => LoadedClause | null;
|
|
22
|
+
}
|
|
23
|
+
export interface AnalyzeResult {
|
|
24
|
+
fields: FieldRef[];
|
|
25
|
+
snippets: string[];
|
|
26
|
+
/** Library clauses the template can place, with versions. */
|
|
27
|
+
clauses: {
|
|
28
|
+
id: string;
|
|
29
|
+
version?: string;
|
|
30
|
+
file: string;
|
|
31
|
+
}[];
|
|
32
|
+
diagnostics: Diagnostic[];
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Static checks for a template: every path exists in the schema, \each walks
|
|
36
|
+
* a list, \raw is flagged, snippets resolve. Lists every field it reads.
|
|
37
|
+
*/
|
|
38
|
+
export declare function analyzeTemplate(template: CompiledTemplate, options?: AnalyzeOptions): AnalyzeResult;
|