latex-kit 0.3.0 → 0.5.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/README.md +22 -3
- package/args.js +3 -3
- package/boilerplates.d.ts +8 -0
- package/boilerplates.js +225 -0
- package/build.d.ts +28 -2
- package/build.js +233 -94
- package/check.js +4 -3
- package/cli.js +14 -3
- package/commands.js +7 -0
- package/config.d.ts +14 -3
- package/config.js +1 -1
- package/diff.d.ts +25 -0
- package/diff.js +112 -0
- package/esm/args.js +3 -3
- package/esm/boilerplates.d.ts +8 -0
- package/esm/boilerplates.js +220 -0
- package/esm/build.d.ts +28 -2
- package/esm/build.js +234 -97
- package/esm/check.js +4 -3
- package/esm/cli.js +14 -3
- package/esm/commands.js +8 -1
- package/esm/config.d.ts +14 -3
- package/esm/config.js +1 -1
- package/esm/diff.d.ts +25 -0
- package/esm/diff.js +108 -0
- package/esm/import.d.ts +24 -0
- package/esm/import.js +113 -0
- package/esm/index.d.ts +9 -2
- package/esm/index.js +8 -2
- package/esm/lock.d.ts +24 -0
- package/esm/lock.js +50 -0
- package/esm/project-commands.d.ts +14 -0
- package/esm/project-commands.js +232 -7
- package/esm/project.d.ts +20 -1
- package/esm/project.js +105 -4
- package/esm/render.js +6 -6
- package/esm/scaffold.d.ts +27 -0
- package/esm/scaffold.js +108 -0
- package/esm/usage.js +40 -7
- package/import.d.ts +24 -0
- package/import.js +118 -0
- package/index.d.ts +9 -2
- package/index.js +27 -2
- package/lock.d.ts +24 -0
- package/lock.js +57 -0
- package/package.json +6 -5
- package/project-commands.d.ts +14 -0
- package/project-commands.js +238 -5
- package/project.d.ts +20 -1
- package/project.js +103 -2
- package/render.js +5 -5
- package/scaffold.d.ts +27 -0
- package/scaffold.js +115 -0
- package/usage.js +40 -7
package/esm/build.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import { gitCommitTime, render, RenderError } from '@latex-kit/render';
|
|
1
|
+
import { detectEngine, gitCommitTime, render, RenderError } from '@latex-kit/render';
|
|
2
2
|
import { loadDocument, mintDocId, validate, writeDocId } from '@latex-kit/schema';
|
|
3
3
|
import { diag, evaluateTemplate, hasErrors, LATEX_KIT_STY, wrapDocument, } from '@latex-kit/template';
|
|
4
4
|
import { execFileSync } from 'child_process';
|
|
5
5
|
import { createHash } from 'crypto';
|
|
6
|
-
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs';
|
|
7
|
-
import {
|
|
6
|
+
import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'fs';
|
|
7
|
+
import { homedir } from 'os';
|
|
8
|
+
import { basename, extname, isAbsolute, join, posix, relative, resolve, sep } from 'path';
|
|
8
9
|
export class BuildError extends Error {
|
|
9
10
|
diagnostics;
|
|
10
11
|
constructor(message, diagnostics) {
|
|
@@ -46,6 +47,42 @@ function gitShortHead(cwd) {
|
|
|
46
47
|
return 'no-git';
|
|
47
48
|
}
|
|
48
49
|
}
|
|
50
|
+
/** A folder name for a signer: "Avery Example" → "avery-example". */
|
|
51
|
+
export function signerSlug(name) {
|
|
52
|
+
return name
|
|
53
|
+
.normalize('NFKD')
|
|
54
|
+
.replace(/[\u0300-\u036f]/g, '')
|
|
55
|
+
.toLowerCase()
|
|
56
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
57
|
+
.replace(/^-|-$/g, '');
|
|
58
|
+
}
|
|
59
|
+
const IMAGE_EXTENSIONS = ['.pdf', '.png', '.jpg', '.jpeg'];
|
|
60
|
+
/** The signatures folder: option, LATEX_KIT_SIGNATURES, then config. `~` is home. */
|
|
61
|
+
export function signaturesDir(project, option) {
|
|
62
|
+
const raw = option ?? process.env.LATEX_KIT_SIGNATURES ?? project.config.signatures ?? null;
|
|
63
|
+
if (!raw)
|
|
64
|
+
return null;
|
|
65
|
+
const expanded = raw === '~' || raw.startsWith('~/') ? join(homedir(), raw.slice(1)) : raw;
|
|
66
|
+
return resolve(project.root, expanded);
|
|
67
|
+
}
|
|
68
|
+
/** Every file under a folder, for the cache key. */
|
|
69
|
+
function filesUnder(dir) {
|
|
70
|
+
const out = [];
|
|
71
|
+
const walk = (d) => {
|
|
72
|
+
if (!existsSync(d))
|
|
73
|
+
return;
|
|
74
|
+
for (const name of readdirSync(d).sort()) {
|
|
75
|
+
const p = join(d, name);
|
|
76
|
+
if (statSync(p).isDirectory())
|
|
77
|
+
walk(p);
|
|
78
|
+
else
|
|
79
|
+
out.push(p);
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
walk(dir);
|
|
83
|
+
return out;
|
|
84
|
+
}
|
|
85
|
+
const posixRel = (root, p) => relative(root, p).split(sep).join(posix.sep);
|
|
49
86
|
async function run(job) {
|
|
50
87
|
const { project, template, variant, options } = job;
|
|
51
88
|
const diagnostics = job.diagnostics;
|
|
@@ -66,99 +103,194 @@ async function run(job) {
|
|
|
66
103
|
docId = mintDocId({ prefix: template.meta.docIdPrefix ?? template.name, epoch: Math.floor(Date.now() / 1000) });
|
|
67
104
|
minted = true;
|
|
68
105
|
}
|
|
69
|
-
const
|
|
70
|
-
data: job.data,
|
|
71
|
-
variant,
|
|
72
|
-
locale: job.locale,
|
|
73
|
-
docId,
|
|
74
|
-
template: template.name,
|
|
75
|
-
allowMissing: variant === 'draft' ? !strict : undefined,
|
|
76
|
-
loadSnippet,
|
|
77
|
-
});
|
|
78
|
-
diagnostics.push(...evaluated.diagnostics);
|
|
79
|
-
if (hasErrors(diagnostics))
|
|
80
|
-
throw new BuildError(`${job.name}: cannot build ${variant}`, diagnostics);
|
|
81
|
-
// snippets count as inputs for the build date too
|
|
82
|
-
const finalEpoch = snippets.size ? buildEpoch([...files, ...snippets]) : { epoch, reproducible };
|
|
83
|
-
// 2. write the .tex next to latex-kit.sty
|
|
84
|
-
const outDir = join(project.outDir, job.name);
|
|
85
|
-
mkdirSync(outDir, { recursive: true });
|
|
106
|
+
const outDir = options.outDir ?? join(project.outDir, job.name);
|
|
86
107
|
const job_ = variant === 'final' ? job.name : `${job.name}-${variant}`;
|
|
87
|
-
|
|
88
|
-
const
|
|
89
|
-
const
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
texInputs: [relative(project.root, outDir) || '.', relative(project.root, template.dir) || '.'],
|
|
117
|
-
onOutput: options.onOutput,
|
|
118
|
-
};
|
|
119
|
-
let rendered;
|
|
120
|
-
try {
|
|
121
|
-
rendered = await render({ ...renderOpts, outDir: relative(project.root, outDir) });
|
|
122
|
-
}
|
|
123
|
-
catch (e) {
|
|
124
|
-
if (e instanceof RenderError) {
|
|
125
|
-
throw new BuildError(`${job.name}: ${e.message}`, [
|
|
126
|
-
...diagnostics,
|
|
127
|
-
...e.diagnostics.map((d) => diag(d.severity, d.message, d.file ? { file: project.rel(join(outDir, basename(d.file))), line: d.line ?? 0, column: 0 } : undefined)),
|
|
128
|
-
]);
|
|
108
|
+
// signed builds: copy signature images next to the .tex for this build only
|
|
109
|
+
const stageDir = join(outDir, 'lk-signatures');
|
|
110
|
+
const staged = [];
|
|
111
|
+
let signatureImage;
|
|
112
|
+
const sigDir = variant === 'signed' ? signaturesDir(project, options.signatures) : null;
|
|
113
|
+
if (sigDir) {
|
|
114
|
+
const at = { file: project.rel(sigDir), line: 1, column: 1 };
|
|
115
|
+
if (!existsSync(sigDir)) {
|
|
116
|
+
diagnostics.push(diag('error', `signatures folder not found: ${project.rel(sigDir)}`, at));
|
|
117
|
+
}
|
|
118
|
+
else {
|
|
119
|
+
const inside = relative(project.root, sigDir);
|
|
120
|
+
if (!inside.startsWith('..') && !isAbsolute(inside)) {
|
|
121
|
+
diagnostics.push(diag('warning', 'the signatures folder is inside the project; keep signature images out of the repository', at));
|
|
122
|
+
}
|
|
123
|
+
signatureImage = (signer) => {
|
|
124
|
+
const names = signer.image ? [signer.image] : IMAGE_EXTENSIONS.map((e) => `${signerSlug(signer.name)}${e}`);
|
|
125
|
+
const found = names.find((n) => basename(n) === n && existsSync(join(sigDir, n)));
|
|
126
|
+
if (!found) {
|
|
127
|
+
diagnostics.push(diag('warning', `no signature image for ${signer.name} in ${project.rel(sigDir)} (looked for ${names.join(', ')}); printed /s/ ${signer.name}`, at));
|
|
128
|
+
return null;
|
|
129
|
+
}
|
|
130
|
+
mkdirSync(stageDir, { recursive: true });
|
|
131
|
+
const target = join(stageDir, found);
|
|
132
|
+
copyFileSync(join(sigDir, found), target);
|
|
133
|
+
if (!staged.includes(target))
|
|
134
|
+
staged.push(target);
|
|
135
|
+
return posixRel(project.root, target);
|
|
136
|
+
};
|
|
129
137
|
}
|
|
130
|
-
throw e;
|
|
131
138
|
}
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
if (options.verify) {
|
|
135
|
-
const verifyDir = `${outDir}.verify`;
|
|
136
|
-
const again = await render({ ...renderOpts, outDir: relative(project.root, verifyDir) });
|
|
137
|
-
result.verified = again.sha256 === rendered.sha256;
|
|
138
|
-
rmSync(verifyDir, { recursive: true, force: true });
|
|
139
|
+
try {
|
|
140
|
+
return await fill();
|
|
139
141
|
}
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
142
|
+
finally {
|
|
143
|
+
rmSync(stageDir, { recursive: true, force: true });
|
|
144
|
+
}
|
|
145
|
+
async function fill() {
|
|
146
|
+
const evaluated = evaluateTemplate(template.compiled, {
|
|
147
|
+
data: job.data,
|
|
148
|
+
variant,
|
|
149
|
+
locale: job.locale,
|
|
150
|
+
docId,
|
|
151
|
+
template: template.name,
|
|
152
|
+
allowMissing: variant === 'draft' ? !strict : undefined,
|
|
153
|
+
loadSnippet,
|
|
154
|
+
loadClause: project.loadClause,
|
|
155
|
+
components: project.components,
|
|
156
|
+
signatureImage,
|
|
157
|
+
signed: job.signed,
|
|
158
|
+
});
|
|
159
|
+
diagnostics.push(...evaluated.diagnostics);
|
|
160
|
+
if (hasErrors(diagnostics))
|
|
161
|
+
throw new BuildError(`${job.name}: cannot build ${variant}`, diagnostics);
|
|
162
|
+
// snippets, clauses and components count as inputs for the build date too
|
|
163
|
+
const clauseFiles = evaluated.clauses.map((c) => resolve(c.file));
|
|
164
|
+
const componentFiles = evaluated.components.map((n) => project.componentFiles[n]).filter((f) => !!f);
|
|
165
|
+
const extra = [...snippets, ...clauseFiles, ...componentFiles];
|
|
166
|
+
const finalEpoch = extra.length ? buildEpoch([...files, ...extra]) : { epoch, reproducible };
|
|
167
|
+
// 2. write the .tex next to latex-kit.sty
|
|
168
|
+
mkdirSync(outDir, { recursive: true });
|
|
169
|
+
const texPath = join(outDir, `${job_}.tex`);
|
|
170
|
+
const stamp = `${new Date(finalEpoch.epoch * 1000).toISOString().slice(0, 10)} ${gitShortHead(project.root)}`;
|
|
171
|
+
const tex = wrapDocument(evaluated.tex, { variant, stamp });
|
|
172
|
+
writeFileSync(texPath, tex);
|
|
173
|
+
writeFileSync(join(outDir, 'latex-kit.sty'), LATEX_KIT_STY);
|
|
174
|
+
const result = {
|
|
175
|
+
name: job.name,
|
|
176
|
+
template: template.name,
|
|
177
|
+
variant,
|
|
178
|
+
tex: texPath,
|
|
179
|
+
pdf: null,
|
|
180
|
+
sha256: null,
|
|
181
|
+
docId: docId ?? null,
|
|
182
|
+
minted: false,
|
|
183
|
+
sourceDateEpoch: finalEpoch.epoch,
|
|
184
|
+
reproducible: finalEpoch.reproducible,
|
|
185
|
+
engine: null,
|
|
186
|
+
engineReason: null,
|
|
187
|
+
cached: false,
|
|
188
|
+
diagnostics,
|
|
189
|
+
};
|
|
190
|
+
if (options.texOnly)
|
|
191
|
+
return result;
|
|
192
|
+
// 3. render, unless the last build had exactly these inputs
|
|
193
|
+
const choice = options.engine ?? template.meta.engine ?? project.config.engine ?? 'auto';
|
|
194
|
+
let engine;
|
|
195
|
+
let engineReason;
|
|
196
|
+
if (choice === 'auto') {
|
|
197
|
+
const d = detectEngine(tex);
|
|
198
|
+
engine = d.engine;
|
|
199
|
+
engineReason = `auto: ${d.reason}`;
|
|
200
|
+
for (const w of d.warnings)
|
|
201
|
+
diagnostics.push(diag('warning', w, { file: template.compiled.file, line: 1, column: 1 }));
|
|
202
|
+
}
|
|
203
|
+
else {
|
|
204
|
+
engine = choice;
|
|
205
|
+
engineReason = 'chosen';
|
|
206
|
+
}
|
|
207
|
+
result.engine = engine;
|
|
208
|
+
result.engineReason = engineReason;
|
|
209
|
+
const backend = options.backend ?? project.config.backend ?? 'docker';
|
|
210
|
+
const image = project.image(options.image);
|
|
211
|
+
const platform = options.platform !== undefined ? options.platform : project.config.platform;
|
|
212
|
+
const renderOpts = {
|
|
213
|
+
file: texPath,
|
|
214
|
+
root: project.root,
|
|
215
|
+
engine,
|
|
216
|
+
backend,
|
|
217
|
+
image,
|
|
218
|
+
platform,
|
|
219
|
+
sourceDateEpoch: finalEpoch.epoch,
|
|
220
|
+
texInputs: [relative(project.root, outDir) || '.', relative(project.root, template.dir) || '.'],
|
|
221
|
+
onOutput: options.onOutput,
|
|
222
|
+
};
|
|
223
|
+
// content-addressed: the PDF depends on the .tex, the .sty, the template
|
|
224
|
+
// folder (images, \\input files), signature images, the engine, the image
|
|
225
|
+
// and the build date. Same key → same bytes, so the last PDF is reused.
|
|
226
|
+
const keyInputs = [...filesUnder(template.dir), ...staged].map((f) => [posixRel(project.root, f), sha256(readFileSync(f))]);
|
|
227
|
+
const cacheKey = sha256(JSON.stringify({ v: 1, tex: sha256(tex), sty: sha256(LATEX_KIT_STY), engine, backend, image: backend === 'docker' ? (image ?? 'default') : null, platform: platform ?? null, epoch: finalEpoch.epoch, inputs: keyInputs }));
|
|
228
|
+
const manifestPath = join(outDir, `${job_}.manifest.json`);
|
|
229
|
+
const pdfPath = join(outDir, `${job_}.pdf`);
|
|
230
|
+
if (!options.force && !options.verify && existsSync(manifestPath) && existsSync(pdfPath)) {
|
|
231
|
+
try {
|
|
232
|
+
const m = JSON.parse(readFileSync(manifestPath, 'utf8'));
|
|
233
|
+
const pdfSha = sha256(readFileSync(pdfPath));
|
|
234
|
+
if (m.cacheKey === cacheKey && m.pdf?.sha256 === pdfSha) {
|
|
235
|
+
result.pdf = pdfPath;
|
|
236
|
+
result.sha256 = pdfSha;
|
|
237
|
+
result.cached = true;
|
|
238
|
+
return result;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
catch {
|
|
242
|
+
// an unreadable manifest just means a rebuild
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
let rendered;
|
|
246
|
+
try {
|
|
247
|
+
rendered = await render({ ...renderOpts, outDir: relative(project.root, outDir) });
|
|
248
|
+
}
|
|
249
|
+
catch (e) {
|
|
250
|
+
if (e instanceof RenderError) {
|
|
251
|
+
throw new BuildError(`${job.name}: ${e.message}`, [
|
|
252
|
+
...diagnostics,
|
|
253
|
+
...e.diagnostics.map((d) => diag(d.severity, d.message, d.file ? { file: project.rel(join(outDir, basename(d.file))), line: d.line ?? 0, column: 0 } : undefined)),
|
|
254
|
+
]);
|
|
255
|
+
}
|
|
256
|
+
throw e;
|
|
257
|
+
}
|
|
258
|
+
result.pdf = rendered.pdf;
|
|
259
|
+
result.sha256 = rendered.sha256;
|
|
260
|
+
if (options.verify) {
|
|
261
|
+
// same output path: some tools (Ghostscript) hash the path into the PDF ID
|
|
262
|
+
const again = await render({ ...renderOpts, outDir: relative(project.root, outDir) });
|
|
263
|
+
result.verified = again.sha256 === rendered.sha256;
|
|
264
|
+
}
|
|
265
|
+
// 4. keep the ID: only after a successful final build
|
|
266
|
+
if (minted && job.mintInto) {
|
|
267
|
+
writeDocId(job.mintInto, docId);
|
|
268
|
+
result.minted = true;
|
|
269
|
+
}
|
|
270
|
+
// 5. manifest: what went in, what came out
|
|
271
|
+
const inputFiles = [...new Set([...files, ...extra])].filter(existsSync).sort();
|
|
272
|
+
writeFileSync(manifestPath, JSON.stringify({
|
|
273
|
+
document: job.name,
|
|
274
|
+
template: template.name,
|
|
275
|
+
variant,
|
|
276
|
+
docId: docId ?? null,
|
|
277
|
+
locale: job.locale,
|
|
278
|
+
engine,
|
|
279
|
+
engineReason,
|
|
280
|
+
image: rendered.image,
|
|
281
|
+
cacheKey,
|
|
282
|
+
sourceDateEpoch: finalEpoch.epoch,
|
|
283
|
+
inputs: inputFiles.map((f) => ({ file: relative(project.root, f), sha256: sha256(readFileSync(f)) })),
|
|
284
|
+
tex: { file: relative(project.root, texPath), sha256: sha256(tex) },
|
|
285
|
+
pdf: { file: relative(project.root, rendered.pdf), sha256: rendered.sha256 },
|
|
286
|
+
clauses: evaluated.clauses.map((c) => ({ id: c.id, version: c.version ?? null, file: relative(project.root, resolve(c.file)) })),
|
|
287
|
+
components: evaluated.components,
|
|
288
|
+
fields: evaluated.fields.map((f) => ({ path: f.path, missing: f.missing })),
|
|
289
|
+
// which signers had an image; never the images or where they live
|
|
290
|
+
signatureImages: staged.map((f) => basename(f)),
|
|
291
|
+
}, null, 2) + '\n');
|
|
292
|
+
return result;
|
|
144
293
|
}
|
|
145
|
-
// 5. manifest: what went in, what came out
|
|
146
|
-
const inputFiles = [...new Set([...files, ...snippets])].filter(existsSync).sort();
|
|
147
|
-
writeFileSync(join(outDir, `${job_}.manifest.json`), JSON.stringify({
|
|
148
|
-
document: job.name,
|
|
149
|
-
template: template.name,
|
|
150
|
-
variant,
|
|
151
|
-
docId: docId ?? null,
|
|
152
|
-
locale: job.locale,
|
|
153
|
-
engine,
|
|
154
|
-
image: rendered.image,
|
|
155
|
-
sourceDateEpoch: finalEpoch.epoch,
|
|
156
|
-
inputs: inputFiles.map((f) => ({ file: relative(project.root, f), sha256: sha256(readFileSync(f)) })),
|
|
157
|
-
tex: { file: relative(project.root, texPath), sha256: sha256(tex) },
|
|
158
|
-
pdf: { file: relative(project.root, rendered.pdf), sha256: rendered.sha256 },
|
|
159
|
-
fields: evaluated.fields.map((f) => ({ path: f.path, missing: f.missing })),
|
|
160
|
-
}, null, 2) + '\n');
|
|
161
|
-
return result;
|
|
162
294
|
}
|
|
163
295
|
/** Build one document record. */
|
|
164
296
|
export async function buildDocument(project, file, options = {}) {
|
|
@@ -179,20 +311,24 @@ export async function buildDocument(project, file, options = {}) {
|
|
|
179
311
|
diagnostics.push(diag(sev, `data.${i.path}: ${i.message}`, at));
|
|
180
312
|
}
|
|
181
313
|
}
|
|
182
|
-
const needsId = (variant === 'final' || variant === 'signed') && !doc.record.docId;
|
|
314
|
+
const needsId = (variant === 'final' || variant === 'signed') && !doc.record.docId && !options.docIdFallback;
|
|
183
315
|
if (needsId && !['.json', '.yaml', '.yml'].includes(extname(file).toLowerCase())) {
|
|
184
316
|
const suggestion = mintDocId({ prefix: template.meta.docIdPrefix ?? template.name, epoch: Math.floor(Date.now() / 1000) });
|
|
185
317
|
diagnostics.push(diag('error', `a ${variant} build needs a document ID, and latex-kit does not edit code. Add: docId: '${suggestion}'`, at));
|
|
186
318
|
throw new BuildError(`${doc.record.template}: no document ID`, diagnostics);
|
|
187
319
|
}
|
|
320
|
+
const natural = doc.record.locale ?? template.meta.locale ?? project.config.locale;
|
|
321
|
+
const name = project.documentName(file);
|
|
188
322
|
return run({
|
|
189
323
|
project,
|
|
190
324
|
template,
|
|
191
|
-
|
|
325
|
+
// another language is another PDF, next to the usual one
|
|
326
|
+
name: options.locale && options.locale !== natural ? `${name}-${options.locale}` : name,
|
|
192
327
|
variant,
|
|
193
328
|
data,
|
|
194
|
-
locale:
|
|
195
|
-
docId: doc.record.docId,
|
|
329
|
+
locale: options.locale ?? natural,
|
|
330
|
+
docId: doc.record.docId ?? options.docIdFallback,
|
|
331
|
+
signed: doc.record.signed,
|
|
196
332
|
inputs: [file, ...doc.refFiles],
|
|
197
333
|
diagnostics,
|
|
198
334
|
options,
|
|
@@ -202,13 +338,14 @@ export async function buildDocument(project, file, options = {}) {
|
|
|
202
338
|
/** Build a template as a blank form, without a record. */
|
|
203
339
|
export async function buildBlank(project, templateName, options = {}) {
|
|
204
340
|
const template = await project.template(templateName);
|
|
341
|
+
const natural = template.meta.locale ?? project.config.locale;
|
|
205
342
|
return run({
|
|
206
343
|
project,
|
|
207
344
|
template,
|
|
208
|
-
name: `${templateName}
|
|
345
|
+
name: options.locale && options.locale !== natural ? `${templateName}-${options.locale}` : templateName,
|
|
209
346
|
variant: 'blank',
|
|
210
347
|
data: {},
|
|
211
|
-
locale:
|
|
348
|
+
locale: options.locale ?? natural,
|
|
212
349
|
inputs: [],
|
|
213
350
|
diagnostics: [],
|
|
214
351
|
options: { ...options, variant: 'blank' },
|
package/esm/check.js
CHANGED
|
@@ -5,15 +5,16 @@ import { analyzeTemplate, diag } from '@latex-kit/template';
|
|
|
5
5
|
* against each schema, every document's data, references, and duplicate IDs.
|
|
6
6
|
*/
|
|
7
7
|
export async function checkProject(project) {
|
|
8
|
-
const diagnostics = [];
|
|
8
|
+
const diagnostics = [...project.codeDiagnostics];
|
|
9
9
|
const templates = project.templateNames();
|
|
10
|
+
const components = project.componentNames();
|
|
10
11
|
for (const name of templates) {
|
|
11
12
|
try {
|
|
12
13
|
const t = await project.template(name);
|
|
13
14
|
if (!t.jsonSchema) {
|
|
14
15
|
diagnostics.push(diag('warning', `template ${name} has no schema.ts, so field names are not checked`, { file: t.compiled.file, line: 1, column: 1 }));
|
|
15
16
|
}
|
|
16
|
-
diagnostics.push(...analyzeTemplate(t.compiled, { schema: t.jsonSchema ?? undefined, loadSnippet: project.loadSnippet }).diagnostics);
|
|
17
|
+
diagnostics.push(...analyzeTemplate(t.compiled, { schema: t.jsonSchema ?? undefined, loadSnippet: project.loadSnippet, loadClause: project.loadClause, components }).diagnostics);
|
|
17
18
|
}
|
|
18
19
|
catch (e) {
|
|
19
20
|
diagnostics.push(diag('error', e.message, { file: project.rel(project.path(project.config.templates, name)), line: 1, column: 1 }));
|
|
@@ -49,6 +50,6 @@ export async function checkProject(project) {
|
|
|
49
50
|
/** Every field a template reads, including through snippets. */
|
|
50
51
|
export async function templateFields(project, name) {
|
|
51
52
|
const t = await project.template(name);
|
|
52
|
-
const r = analyzeTemplate(t.compiled, { schema: t.jsonSchema ?? undefined, loadSnippet: project.loadSnippet });
|
|
53
|
+
const r = analyzeTemplate(t.compiled, { schema: t.jsonSchema ?? undefined, loadSnippet: project.loadSnippet, loadClause: project.loadClause, components: project.componentNames() });
|
|
53
54
|
return { fields: r.fields, diagnostics: r.diagnostics };
|
|
54
55
|
}
|
package/esm/cli.js
CHANGED
|
@@ -1,15 +1,26 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { setModuleAliases } from '@latex-kit/schema';
|
|
2
3
|
import { CLI } from 'inquirerer';
|
|
4
|
+
import { dirname } from 'path';
|
|
3
5
|
import { commands, version } from './commands';
|
|
6
|
+
// Project files import 'latex-kit' (and zod through it). Point those names at
|
|
7
|
+
// this CLI's own copies, so a project works without its own node_modules and
|
|
8
|
+
// every file shares one zod.
|
|
9
|
+
const schemaDir = dirname(require.resolve('@latex-kit/schema'));
|
|
10
|
+
setModuleAliases({
|
|
11
|
+
'latex-kit': __dirname,
|
|
12
|
+
'@latex-kit/schema': schemaDir,
|
|
13
|
+
zod: dirname(require.resolve('zod/package.json', { paths: [schemaDir] })),
|
|
14
|
+
});
|
|
4
15
|
const app = new CLI(commands, {
|
|
5
16
|
noTty: !process.stdin.isTTY,
|
|
6
17
|
// inquirerer answers --version itself; make it report latex-kit
|
|
7
18
|
version: version(),
|
|
8
19
|
minimistOpts: {
|
|
9
20
|
alias: { h: 'help', v: 'version', o: 'out', e: 'engine' },
|
|
10
|
-
boolean: ['help', 'version', 'local', 'verify', 'json', 'final', 'strict', 'tex-only'],
|
|
11
|
-
string: ['out', 'engine', 'image', 'root', 'platform', 'source-date-epoch', 'variant', 'template'],
|
|
12
|
-
default: { strict: undefined },
|
|
21
|
+
boolean: ['help', 'version', 'local', 'verify', 'json', 'final', 'strict', 'tex-only', 'force', 'schema', 'paper', 'check'],
|
|
22
|
+
string: ['out', 'engine', 'image', 'root', 'platform', 'source-date-epoch', 'variant', 'template', 'name', 'against', 'only', 'locale', 'signatures'],
|
|
23
|
+
default: { strict: undefined, schema: true },
|
|
13
24
|
},
|
|
14
25
|
});
|
|
15
26
|
app.run().catch((error) => {
|
package/esm/commands.js
CHANGED
|
@@ -3,7 +3,7 @@ import { join } from 'path';
|
|
|
3
3
|
import chalk from 'yanse';
|
|
4
4
|
import { UsageError } from './args';
|
|
5
5
|
import { doctorCommand } from './doctor';
|
|
6
|
-
import { buildCommand, checkCommand, fieldsCommand, styCommand, typegenCommand } from './project-commands';
|
|
6
|
+
import { buildCommand, checkCommand, cleanCommand, diffCommand, fieldsCommand, importCommand, initCommand, lockCommand, newCommand, styCommand, typegenCommand, watchCommand } from './project-commands';
|
|
7
7
|
import { renderCommand } from './render';
|
|
8
8
|
import { help } from './usage';
|
|
9
9
|
/** The package version, from package.json next to the built files. */
|
|
@@ -18,11 +18,18 @@ export function version() {
|
|
|
18
18
|
return 'unknown';
|
|
19
19
|
}
|
|
20
20
|
const COMMANDS = {
|
|
21
|
+
init: initCommand,
|
|
22
|
+
new: newCommand,
|
|
21
23
|
build: buildCommand,
|
|
24
|
+
watch: watchCommand,
|
|
25
|
+
clean: cleanCommand,
|
|
22
26
|
check: checkCommand,
|
|
23
27
|
fields: fieldsCommand,
|
|
24
28
|
typegen: typegenCommand,
|
|
29
|
+
import: importCommand,
|
|
30
|
+
diff: diffCommand,
|
|
25
31
|
sty: styCommand,
|
|
32
|
+
lock: lockCommand,
|
|
26
33
|
render: renderCommand,
|
|
27
34
|
doctor: doctorCommand,
|
|
28
35
|
};
|
package/esm/config.d.ts
CHANGED
|
@@ -1,10 +1,14 @@
|
|
|
1
|
-
import type { Backend,
|
|
1
|
+
import type { Backend, EngineChoice } from '@latex-kit/render';
|
|
2
2
|
/** latex-kit.config.ts (or .js, .mjs, .cjs, .json) at the project root. */
|
|
3
3
|
export interface LatexKitConfig {
|
|
4
4
|
/** One folder per template: `<templates>/<name>/template.tex` and optional `schema.ts`. Default `templates`. */
|
|
5
5
|
templates?: string;
|
|
6
6
|
/** Shared pieces for \snippet{name}. Default `snippets`. */
|
|
7
7
|
snippets?: string;
|
|
8
|
+
/** The clause library for \\clause{id}: `<clauses>/<id>.tex` or `.ts`. Default `clauses`. */
|
|
9
|
+
clauses?: string;
|
|
10
|
+
/** TypeScript components for \\component{name}{path}: `<components>/<name>.ts`. Default `components`. */
|
|
11
|
+
components?: string;
|
|
8
12
|
/** Shared records that references point at: `<data>/<collection>/<id>.json`. Default `data`. */
|
|
9
13
|
data?: string;
|
|
10
14
|
/** Document records: `<documents>/<name>.json|yaml|ts`. Default `documents`. */
|
|
@@ -13,12 +17,19 @@ export interface LatexKitConfig {
|
|
|
13
17
|
out?: string;
|
|
14
18
|
/** Default locale for dates, numbers and money. Default `en-US`. */
|
|
15
19
|
locale?: string;
|
|
16
|
-
|
|
20
|
+
/** Default `auto`: chosen from the packages each document loads. */
|
|
21
|
+
engine?: EngineChoice;
|
|
22
|
+
/**
|
|
23
|
+
* Folder with signature images for signed builds (`<name>.png|pdf|jpg`).
|
|
24
|
+
* Keep it outside the repository; `--signatures` and LATEX_KIT_SIGNATURES
|
|
25
|
+
* override it. A leading ~ is the home folder.
|
|
26
|
+
*/
|
|
27
|
+
signatures?: string;
|
|
17
28
|
backend?: Backend;
|
|
18
29
|
image?: string;
|
|
19
30
|
platform?: string | null;
|
|
20
31
|
}
|
|
21
|
-
export type ResolvedConfig = Required<Pick<LatexKitConfig, 'templates' | 'snippets' | 'data' | 'documents' | 'out' | 'locale'>> & Pick<LatexKitConfig, 'engine' | 'backend' | 'image' | 'platform'> & {
|
|
32
|
+
export type ResolvedConfig = Required<Pick<LatexKitConfig, 'templates' | 'snippets' | 'clauses' | 'components' | 'data' | 'documents' | 'out' | 'locale'>> & Pick<LatexKitConfig, 'engine' | 'backend' | 'image' | 'platform' | 'signatures'> & {
|
|
22
33
|
file: string | null;
|
|
23
34
|
};
|
|
24
35
|
export declare function defineConfig(config: LatexKitConfig): LatexKitConfig;
|
package/esm/config.js
CHANGED
|
@@ -5,7 +5,7 @@ export function defineConfig(config) {
|
|
|
5
5
|
return config;
|
|
6
6
|
}
|
|
7
7
|
export const CONFIG_FILES = ['latex-kit.config.ts', 'latex-kit.config.mts', 'latex-kit.config.js', 'latex-kit.config.mjs', 'latex-kit.config.cjs', 'latex-kit.config.json'];
|
|
8
|
-
const DEFAULTS = { templates: 'templates', snippets: 'snippets', data: 'data', documents: 'documents', out: 'out', locale: 'en-US' };
|
|
8
|
+
const DEFAULTS = { templates: 'templates', snippets: 'snippets', clauses: 'clauses', components: 'components', data: 'data', documents: 'documents', out: 'out', locale: 'en-US' };
|
|
9
9
|
export async function loadConfig(root) {
|
|
10
10
|
for (const name of CONFIG_FILES) {
|
|
11
11
|
const file = join(resolve(root), name);
|
package/esm/diff.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { EngineChoice } from '@latex-kit/render';
|
|
2
|
+
import { Variant } from '@latex-kit/template';
|
|
3
|
+
import { Project } from './project';
|
|
4
|
+
export interface DiffOptions {
|
|
5
|
+
variant?: Variant;
|
|
6
|
+
engine?: EngineChoice;
|
|
7
|
+
backend?: 'docker' | 'local';
|
|
8
|
+
image?: string;
|
|
9
|
+
platform?: string | null;
|
|
10
|
+
}
|
|
11
|
+
export interface DiffResult {
|
|
12
|
+
/** The redline PDF. */
|
|
13
|
+
pdf: string;
|
|
14
|
+
/** latexdiff's marked-up .tex. */
|
|
15
|
+
tex: string;
|
|
16
|
+
old: string;
|
|
17
|
+
new: string;
|
|
18
|
+
}
|
|
19
|
+
/** Redline two .tex files inside the project. */
|
|
20
|
+
export declare function diffFiles(project: Project, oldFile: string, newFile: string, options?: DiffOptions): Promise<DiffResult>;
|
|
21
|
+
/**
|
|
22
|
+
* Redline a document against an earlier commit: build it as it was at `ref`
|
|
23
|
+
* (in a temporary git worktree) and as it is now, then latexdiff the two.
|
|
24
|
+
*/
|
|
25
|
+
export declare function diffDocument(project: Project, file: string, ref: string, options?: DiffOptions): Promise<DiffResult>;
|
package/esm/diff.js
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { render, runLatexdiff } from '@latex-kit/render';
|
|
2
|
+
import { LATEX_KIT_STY } from '@latex-kit/template';
|
|
3
|
+
import { execFileSync } from 'child_process';
|
|
4
|
+
import { copyFileSync, existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs';
|
|
5
|
+
import { tmpdir } from 'os';
|
|
6
|
+
import { basename, dirname, join, relative } from 'path';
|
|
7
|
+
import { buildDocument, BuildError } from './build';
|
|
8
|
+
import { Project } from './project';
|
|
9
|
+
function git(cwd, args) {
|
|
10
|
+
return execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
|
|
11
|
+
}
|
|
12
|
+
/** latexdiff old → new in `dir`, then render the redline. */
|
|
13
|
+
async function redline(project, oldTex, newTex, dir, name, texInputs, options) {
|
|
14
|
+
mkdirSync(dir, { recursive: true });
|
|
15
|
+
writeFileSync(join(dir, 'latex-kit.sty'), LATEX_KIT_STY);
|
|
16
|
+
const tex = join(dir, `${name}.tex`);
|
|
17
|
+
const rel = (p) => relative(project.root, p);
|
|
18
|
+
await runLatexdiff({ root: project.root, old: rel(oldTex), new: rel(newTex), output: rel(tex), backend: options.backend, image: project.image(options.image), platform: options.platform });
|
|
19
|
+
const r = await render({
|
|
20
|
+
file: tex,
|
|
21
|
+
root: project.root,
|
|
22
|
+
outDir: rel(dir),
|
|
23
|
+
engine: options.engine ?? project.config.engine ?? 'auto',
|
|
24
|
+
backend: options.backend ?? project.config.backend,
|
|
25
|
+
image: project.image(options.image),
|
|
26
|
+
platform: options.platform !== undefined ? options.platform : project.config.platform,
|
|
27
|
+
texInputs: [rel(dir), ...texInputs.map(rel)],
|
|
28
|
+
});
|
|
29
|
+
return { pdf: r.pdf, tex, old: oldTex, new: newTex };
|
|
30
|
+
}
|
|
31
|
+
/** Redline two .tex files inside the project. */
|
|
32
|
+
export async function diffFiles(project, oldFile, newFile, options = {}) {
|
|
33
|
+
for (const f of [oldFile, newFile])
|
|
34
|
+
if (!existsSync(f))
|
|
35
|
+
throw new Error(`no such file: ${project.rel(f)}`);
|
|
36
|
+
const name = `${basename(newFile, '.tex')}-vs-${basename(oldFile, '.tex')}`;
|
|
37
|
+
const dir = join(project.outDir, 'diff', name);
|
|
38
|
+
mkdirSync(dir, { recursive: true });
|
|
39
|
+
// copies inside out/, so the files are always visible to Docker
|
|
40
|
+
const oldCopy = join(dir, 'old.tex');
|
|
41
|
+
const newCopy = join(dir, 'new.tex');
|
|
42
|
+
copyFileSync(oldFile, oldCopy);
|
|
43
|
+
copyFileSync(newFile, newCopy);
|
|
44
|
+
return redline(project, oldCopy, newCopy, dir, name, [dirname(newFile)], options);
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Redline a document against an earlier commit: build it as it was at `ref`
|
|
48
|
+
* (in a temporary git worktree) and as it is now, then latexdiff the two.
|
|
49
|
+
*/
|
|
50
|
+
export async function diffDocument(project, file, ref, options = {}) {
|
|
51
|
+
const variant = options.variant ?? 'final';
|
|
52
|
+
let top;
|
|
53
|
+
try {
|
|
54
|
+
top = git(project.root, ['rev-parse', '--show-toplevel']);
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
throw new Error('diff --against needs the project to be in a git repository');
|
|
58
|
+
}
|
|
59
|
+
const relDoc = relative(top, file);
|
|
60
|
+
const relProject = relative(top, project.root);
|
|
61
|
+
let sha;
|
|
62
|
+
try {
|
|
63
|
+
sha = git(top, ['rev-parse', '--short', `${ref}^{commit}`]);
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
throw new Error(`unknown git ref: ${ref}`);
|
|
67
|
+
}
|
|
68
|
+
try {
|
|
69
|
+
git(top, ['cat-file', '-e', `${sha}:${relDoc}`]);
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
throw new Error(`${relDoc} does not exist at ${ref}`);
|
|
73
|
+
}
|
|
74
|
+
const name = project.documentName(file);
|
|
75
|
+
const dir = join(project.outDir, name, 'diff');
|
|
76
|
+
const common = { variant, texOnly: true, strict: false, docIdFallback: 'UNASSIGNED' };
|
|
77
|
+
const current = await buildDocument(project, file, { ...common, outDir: join(dir, 'new') }).catch((e) => {
|
|
78
|
+
if (e instanceof BuildError)
|
|
79
|
+
throw new BuildError(`the current ${name} does not build: ${e.message}`, e.diagnostics);
|
|
80
|
+
throw e;
|
|
81
|
+
});
|
|
82
|
+
const tree = mkdtempSync(join(tmpdir(), 'latex-kit-diff-'));
|
|
83
|
+
try {
|
|
84
|
+
git(top, ['worktree', 'add', '--detach', '--quiet', tree, sha]);
|
|
85
|
+
const oldProject = await Project.open(join(tree, relProject));
|
|
86
|
+
const old = await buildDocument(oldProject, join(tree, relDoc), { ...common, outDir: join(dir, 'old') }).catch((e) => {
|
|
87
|
+
if (e instanceof BuildError)
|
|
88
|
+
throw new BuildError(`${name} at ${ref} (${sha}) does not build: ${e.message}`, e.diagnostics);
|
|
89
|
+
throw e;
|
|
90
|
+
});
|
|
91
|
+
const template = await project.template(current.template);
|
|
92
|
+
return await redline(project, old.tex, current.tex, dir, `${name}-vs-${sha}`, [template.dir], options);
|
|
93
|
+
}
|
|
94
|
+
finally {
|
|
95
|
+
try {
|
|
96
|
+
git(top, ['worktree', 'remove', '--force', tree]);
|
|
97
|
+
}
|
|
98
|
+
catch {
|
|
99
|
+
rmSync(tree, { recursive: true, force: true });
|
|
100
|
+
try {
|
|
101
|
+
git(top, ['worktree', 'prune']);
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
// nothing left to clean
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|