latex-kit 0.4.1 → 0.5.1

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 (56) hide show
  1. package/README.md +21 -2
  2. package/args.js +3 -3
  3. package/boilerplates.d.ts +14 -1
  4. package/boilerplates.js +200 -2
  5. package/build.d.ts +22 -2
  6. package/build.js +230 -95
  7. package/check.js +4 -3
  8. package/cli.js +2 -2
  9. package/commands.js +1 -0
  10. package/config.d.ts +13 -4
  11. package/config.js +1 -1
  12. package/diff.d.ts +2 -2
  13. package/diff.js +3 -3
  14. package/esm/args.js +3 -3
  15. package/esm/boilerplates.d.ts +14 -1
  16. package/esm/boilerplates.js +196 -1
  17. package/esm/build.d.ts +22 -2
  18. package/esm/build.js +231 -98
  19. package/esm/check.js +4 -3
  20. package/esm/cli.js +2 -2
  21. package/esm/commands.js +2 -1
  22. package/esm/config.d.ts +13 -4
  23. package/esm/config.js +1 -1
  24. package/esm/diff.d.ts +2 -2
  25. package/esm/diff.js +3 -3
  26. package/esm/import.js +1 -1
  27. package/esm/index.d.ts +6 -2
  28. package/esm/index.js +5 -2
  29. package/esm/lock.d.ts +24 -0
  30. package/esm/lock.js +50 -0
  31. package/esm/paper-style.d.ts +10 -0
  32. package/esm/paper-style.js +10 -0
  33. package/esm/project-commands.d.ts +4 -0
  34. package/esm/project-commands.js +76 -6
  35. package/esm/project.d.ts +18 -2
  36. package/esm/project.js +92 -5
  37. package/esm/render.js +4 -2
  38. package/esm/scaffold.d.ts +2 -1
  39. package/esm/scaffold.js +1 -1
  40. package/esm/usage.js +28 -7
  41. package/import.js +1 -1
  42. package/index.d.ts +6 -2
  43. package/index.js +24 -2
  44. package/lock.d.ts +24 -0
  45. package/lock.js +57 -0
  46. package/package.json +16 -17
  47. package/paper-style.d.ts +10 -0
  48. package/paper-style.js +13 -0
  49. package/project-commands.d.ts +4 -0
  50. package/project-commands.js +78 -6
  51. package/project.d.ts +18 -2
  52. package/project.js +90 -3
  53. package/render.js +4 -2
  54. package/scaffold.d.ts +2 -1
  55. package/scaffold.js +1 -1
  56. package/usage.js +28 -7
@@ -2,6 +2,9 @@
2
2
  * Files written by `latex-kit init` and `latex-kit new`. Every name, address
3
3
  * and amount is a placeholder.
4
4
  */
5
+ import { WHITEPAPER_COLORS_TEX, WHITEPAPER_TYPESCRIPT_TEX } from './paper-style';
6
+ /** Paper presets for `latex-kit init --paper --preset <name>`. */
7
+ export const PAPER_PRESETS = ['whitepaper', 'plain'];
5
8
  export function projectFiles(version) {
6
9
  return {
7
10
  'package.json': `${JSON.stringify({
@@ -124,7 +127,8 @@ data:
124
127
  `,
125
128
  };
126
129
  }
127
- export function paperFiles() {
130
+ /** A minimal LuaLaTeX paper: fontspec, natbib. */
131
+ export function plainPaperFiles() {
128
132
  return {
129
133
  '.gitignore': 'out/\n',
130
134
  'paper/main.tex': `\\documentclass[11pt]{article}
@@ -218,3 +222,194 @@ export default z.object({
218
222
  `,
219
223
  };
220
224
  }
225
+ const PAPER_WORKFLOW = (file, name) => `name: Paper
226
+
227
+ on:
228
+ push:
229
+ branches: [main]
230
+ tags: ['v*']
231
+ pull_request:
232
+
233
+ jobs:
234
+ pdf:
235
+ runs-on: ubuntu-latest
236
+ permissions:
237
+ contents: read
238
+ steps:
239
+ - uses: actions/checkout@v4
240
+ with:
241
+ fetch-depth: 0 # the build date comes from the last commit
242
+ - uses: constructive-io/latex-kit/action@v1
243
+ with:
244
+ file: ${file}
245
+ engine: auto
246
+ verify: 'true'
247
+ artifact-name: ${name}.pdf
248
+
249
+ # pushing a tag like v1.0.0 attaches the PDF to a GitHub release
250
+ release:
251
+ needs: pdf
252
+ if: startsWith(github.ref, 'refs/tags/v')
253
+ runs-on: ubuntu-latest
254
+ permissions:
255
+ contents: write
256
+ steps:
257
+ - uses: actions/download-artifact@v4
258
+ with:
259
+ name: ${name}.pdf
260
+ path: pdf
261
+ - env:
262
+ GH_TOKEN: \${{ github.token }}
263
+ run: |
264
+ pdf=$(find pdf -name '*.pdf' | head -n 1)
265
+ cp "$pdf" "${name}-$GITHUB_REF_NAME.pdf"
266
+ gh release create "$GITHUB_REF_NAME" "${name}-$GITHUB_REF_NAME.pdf" -R "$GITHUB_REPOSITORY" --title "$GITHUB_REF_NAME" --generate-notes
267
+ `;
268
+ /**
269
+ * The Constructive whitepaper style (rls-whitepaper, hyperweb-whitepaper):
270
+ * article class, the code colour palette and TypeScript listings style,
271
+ * TikZ and PSTricks, IEEE references. PSTricks means latex → dvips → ps2pdf,
272
+ * which `engine: auto` picks.
273
+ */
274
+ export function whitepaperFiles() {
275
+ return {
276
+ '.gitignore': 'out/\n',
277
+ 'paper/main.tex': `% A paper in the Constructive whitepaper style (as rls-whitepaper and
278
+ % hyperweb-whitepaper). It loads PSTricks, so latex-kit builds it with
279
+ % latex -> bibtex -> dvips -> ps2pdf; \`latex-kit render paper/main.tex\` picks that.
280
+ \\documentclass{article}
281
+ \\usepackage{amsmath}
282
+ \\usepackage{graphicx}
283
+ \\usepackage{xcolor}
284
+ \\usepackage{listings}
285
+ \\usepackage{geometry}
286
+ \\usepackage{enumitem}
287
+ \\usepackage{amsfonts}
288
+ \\usepackage{amssymb}
289
+ \\usepackage[hidelinks]{hyperref}
290
+ \\usepackage{cleveref}
291
+
292
+ \\usepackage{pstricks}
293
+ \\usepackage{tikz}
294
+ \\usetikzlibrary{arrows.meta, positioning, shapes, calc}
295
+
296
+ \\input{headers/colors.tex}
297
+ \\input{headers/typescript.tex}
298
+
299
+ \\title{Paper Title: What the Paper Shows}
300
+ \\author{Your Name, A. Co-Author
301
+ \\\\ \\\\
302
+ \\texttt{info@example.com}}
303
+ \\date{v0.0.1 --- \\today}
304
+
305
+ \\begin{document}
306
+
307
+ \\maketitle
308
+
309
+ \\begin{abstract}
310
+ One paragraph: the problem, why existing approaches fall short, what this
311
+ paper presents, and what it achieves.
312
+ \\end{abstract}
313
+
314
+ \\tableofcontents
315
+
316
+ \\input{sections/introduction.tex}
317
+ \\input{sections/design.tex}
318
+ \\input{sections/conclusion.tex}
319
+
320
+ \\newpage
321
+
322
+ \\section{Bibliography}
323
+ \\bibliographystyle{IEEEtran}
324
+ \\bibliography{references}
325
+
326
+ \\end{document}
327
+ `,
328
+ 'paper/headers/colors.tex': WHITEPAPER_COLORS_TEX,
329
+ 'paper/headers/typescript.tex': WHITEPAPER_TYPESCRIPT_TEX,
330
+ 'paper/sections/introduction.tex': `\\section{Introduction}
331
+
332
+ State the problem and why it matters. Cite prior work like this~\\cite{stonebraker1986}.
333
+ \\Cref{fig:flow} is drawn with PSTricks.
334
+
335
+ \\begin{figure}[ht]
336
+ \\centering
337
+ \\begin{pspicture}(0,0)(9,3)
338
+ \\psframe[fillstyle=solid,fillcolor=lightpurple,framearc=0.2](0,0.75)(3,2.25)
339
+ \\rput(1.5,1.5){Client}
340
+ \\psline[linewidth=1pt]{->}(3,1.5)(6,1.5)
341
+ \\rput(4.5,1.85){\\small request}
342
+ \\pscircle[fillstyle=solid,fillcolor=codelightgreen](7.5,1.5){1.2}
343
+ \\rput(7.5,1.5){Server}
344
+ \\end{pspicture}
345
+ \\caption{A request flow, drawn with PSTricks.}
346
+ \\label{fig:flow}
347
+ \\end{figure}
348
+ `,
349
+ 'paper/sections/design.tex': `\\section{Design}
350
+
351
+ \\Cref{fig:layers} is drawn with TikZ, and \\cref{lst:counter} uses the
352
+ TypeScript listing style.
353
+
354
+ \\begin{figure}[ht]
355
+ \\centering
356
+ \\begin{tikzpicture}[
357
+ node distance=1.2cm,
358
+ box/.style={rectangle, draw, rounded corners, fill=blue!10, text width=2.8cm, text centered, minimum height=0.9cm},
359
+ store/.style={rectangle, draw, rounded corners, fill=orange!10, text width=2.8cm, text centered, minimum height=0.9cm},
360
+ arrow/.style={-{Stealth}, thick}
361
+ ]
362
+ \\node[box] (api) {API};
363
+ \\node[box, below=of api] (policy) {Policy check};
364
+ \\node[store, right=1.6cm of policy] (data) {Data};
365
+ \\draw[arrow] (api) -- (policy);
366
+ \\draw[arrow] (policy) -- node[above] {\\small allowed} (data);
367
+ \\end{tikzpicture}
368
+ \\caption{Layers, drawn with TikZ.}
369
+ \\label{fig:layers}
370
+ \\end{figure}
371
+
372
+ \\begin{lstlisting}[language=typescript, caption=A small contract, label=lst:counter, style=typescript]
373
+ export default class Counter {
374
+ state = { count: 0 };
375
+
376
+ increment(by: number) {
377
+ this.state.count += by;
378
+ return this.state.count;
379
+ }
380
+ }
381
+ \\end{lstlisting}
382
+ `,
383
+ 'paper/sections/conclusion.tex': `\\section{Conclusion}
384
+
385
+ Summarize what the paper showed and what comes next.
386
+ `,
387
+ 'paper/references.bib': `@techreport{stonebraker1986,
388
+ author = {Michael Stonebraker and Lawrence A. Rowe},
389
+ title = {The Design of {POSTGRES}},
390
+ institution = {University of California, Berkeley},
391
+ number = {UCB/ERL M85/95},
392
+ year = {1986}
393
+ }
394
+ `,
395
+ '.github/workflows/paper.yml': PAPER_WORKFLOW('paper/main.tex', 'paper'),
396
+ 'README.md': `# Paper
397
+
398
+ \`\`\`bash
399
+ npx latex-kit render paper/main.tex --verify # → out/main.pdf, byte-identical on every build
400
+ \`\`\`
401
+
402
+ The Constructive whitepaper style: \`paper/headers/colors.tex\` (code colours)
403
+ and \`paper/headers/typescript.tex\` (\`style=typescript\` listings), TikZ and
404
+ PSTricks figures, IEEE references. PSTricks builds through latex → dvips →
405
+ ps2pdf, which latex-kit picks by itself.
406
+
407
+ CI builds the PDF on every push and attaches it to the run. Pushing a tag
408
+ like \`v1.0.0\` publishes it as a GitHub release.
409
+ `,
410
+ };
411
+ }
412
+ /** Files for `latex-kit init --paper`. */
413
+ export function paperFiles(preset = 'whitepaper') {
414
+ return preset === 'plain' ? plainPaperFiles() : whitepaperFiles();
415
+ }
package/esm/build.d.ts CHANGED
@@ -1,11 +1,21 @@
1
- import { Engine } from '@latex-kit/render';
1
+ import { Engine, EngineChoice } from '@latex-kit/render';
2
2
  import { Diagnostic, Variant } from '@latex-kit/template';
3
3
  import { Project } from './project';
4
4
  export interface BuildOptions {
5
5
  variant?: Variant;
6
6
  /** Fail on missing values even in drafts. Default: on when CI=true. */
7
7
  strict?: boolean;
8
- engine?: Engine;
8
+ /** Default: the template's, the config's, else `auto`. */
9
+ engine?: EngineChoice;
10
+ /** Build in this locale instead of the record's; the output name gets `-<locale>`. */
11
+ locale?: string;
12
+ /** Rebuild even when the cached PDF matches every input. */
13
+ force?: boolean;
14
+ /**
15
+ * Folder of signature images for signed builds. Default: the
16
+ * LATEX_KIT_SIGNATURES environment variable, then the config.
17
+ */
18
+ signatures?: string | null;
9
19
  backend?: 'docker' | 'local';
10
20
  image?: string;
11
21
  platform?: string | null;
@@ -33,12 +43,22 @@ export interface BuildResult {
33
43
  sourceDateEpoch: number;
34
44
  reproducible: boolean;
35
45
  verified?: boolean;
46
+ /** The engine TeX ran with (null for --tex-only). */
47
+ engine: Engine | null;
48
+ /** "chosen", or why `auto` picked it. */
49
+ engineReason: string | null;
50
+ /** The PDF was already up to date: same inputs, same image, same date. */
51
+ cached: boolean;
36
52
  diagnostics: Diagnostic[];
37
53
  }
38
54
  export declare class BuildError extends Error {
39
55
  readonly diagnostics: Diagnostic[];
40
56
  constructor(message: string, diagnostics: Diagnostic[]);
41
57
  }
58
+ /** A folder name for a signer: "Avery Example" → "avery-example". */
59
+ export declare function signerSlug(name: string): string;
60
+ /** The signatures folder: option, LATEX_KIT_SIGNATURES, then config. `~` is home. */
61
+ export declare function signaturesDir(project: Project, option?: string | null): string | null;
42
62
  /** Build one document record. */
43
63
  export declare function buildDocument(project: Project, file: string, options?: BuildOptions): Promise<BuildResult>;
44
64
  /** Build a template as a blank form, without a record. */
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, writeFileSync } from 'fs';
7
- import { basename, extname, join, relative, resolve } from 'path';
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,103 +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 evaluated = evaluateTemplate(template.compiled, {
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
- loadClause: project.loadClause,
78
- });
79
- diagnostics.push(...evaluated.diagnostics);
80
- if (hasErrors(diagnostics))
81
- throw new BuildError(`${job.name}: cannot build ${variant}`, diagnostics);
82
- // snippets count as inputs for the build date too
83
- const clauseFiles = evaluated.clauses.map((c) => resolve(c.file));
84
- const extra = [...snippets, ...clauseFiles];
85
- const finalEpoch = extra.length ? buildEpoch([...files, ...extra]) : { epoch, reproducible };
86
- // 2. write the .tex next to latex-kit.sty
87
106
  const outDir = options.outDir ?? join(project.outDir, job.name);
88
- mkdirSync(outDir, { recursive: true });
89
107
  const job_ = variant === 'final' ? job.name : `${job.name}-${variant}`;
90
- const texPath = join(outDir, `${job_}.tex`);
91
- const stamp = `${new Date(finalEpoch.epoch * 1000).toISOString().slice(0, 10)} ${gitShortHead(project.root)}`;
92
- const tex = wrapDocument(evaluated.tex, { variant, stamp });
93
- writeFileSync(texPath, tex);
94
- writeFileSync(join(outDir, 'latex-kit.sty'), LATEX_KIT_STY);
95
- const result = {
96
- name: job.name,
97
- template: template.name,
98
- variant,
99
- tex: texPath,
100
- pdf: null,
101
- sha256: null,
102
- docId: docId ?? null,
103
- minted: false,
104
- sourceDateEpoch: finalEpoch.epoch,
105
- reproducible: finalEpoch.reproducible,
106
- diagnostics,
107
- };
108
- if (options.texOnly)
109
- return result;
110
- // 3. render
111
- const engine = options.engine ?? template.meta.engine ?? project.config.engine ?? 'lualatex';
112
- const renderOpts = {
113
- file: texPath,
114
- root: project.root,
115
- engine,
116
- backend: options.backend ?? project.config.backend,
117
- image: options.image ?? project.config.image,
118
- platform: options.platform !== undefined ? options.platform : project.config.platform,
119
- sourceDateEpoch: finalEpoch.epoch,
120
- texInputs: [relative(project.root, outDir) || '.', relative(project.root, template.dir) || '.'],
121
- onOutput: options.onOutput,
122
- };
123
- let rendered;
124
- try {
125
- rendered = await render({ ...renderOpts, outDir: relative(project.root, outDir) });
126
- }
127
- catch (e) {
128
- if (e instanceof RenderError) {
129
- throw new BuildError(`${job.name}: ${e.message}`, [
130
- ...diagnostics,
131
- ...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)),
132
- ]);
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
+ };
133
137
  }
134
- throw e;
135
138
  }
136
- result.pdf = rendered.pdf;
137
- result.sha256 = rendered.sha256;
138
- if (options.verify) {
139
- // same output path: some tools (Ghostscript) hash the path into the PDF ID
140
- const again = await render({ ...renderOpts, outDir: relative(project.root, outDir) });
141
- result.verified = again.sha256 === rendered.sha256;
139
+ try {
140
+ return await fill();
142
141
  }
143
- // 4. keep the ID: only after a successful final build
144
- if (minted && job.mintInto) {
145
- writeDocId(job.mintInto, docId);
146
- result.minted = true;
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;
147
293
  }
148
- // 5. manifest: what went in, what came out
149
- const inputFiles = [...new Set([...files, ...extra])].filter(existsSync).sort();
150
- writeFileSync(join(outDir, `${job_}.manifest.json`), JSON.stringify({
151
- document: job.name,
152
- template: template.name,
153
- variant,
154
- docId: docId ?? null,
155
- locale: job.locale,
156
- engine,
157
- image: rendered.image,
158
- sourceDateEpoch: finalEpoch.epoch,
159
- inputs: inputFiles.map((f) => ({ file: relative(project.root, f), sha256: sha256(readFileSync(f)) })),
160
- tex: { file: relative(project.root, texPath), sha256: sha256(tex) },
161
- pdf: { file: relative(project.root, rendered.pdf), sha256: rendered.sha256 },
162
- clauses: evaluated.clauses.map((c) => ({ id: c.id, version: c.version ?? null, file: relative(project.root, resolve(c.file)) })),
163
- fields: evaluated.fields.map((f) => ({ path: f.path, missing: f.missing })),
164
- }, null, 2) + '\n');
165
- return result;
166
294
  }
167
295
  /** Build one document record. */
168
296
  export async function buildDocument(project, file, options = {}) {
@@ -189,14 +317,18 @@ export async function buildDocument(project, file, options = {}) {
189
317
  diagnostics.push(diag('error', `a ${variant} build needs a document ID, and latex-kit does not edit code. Add: docId: '${suggestion}'`, at));
190
318
  throw new BuildError(`${doc.record.template}: no document ID`, diagnostics);
191
319
  }
320
+ const natural = doc.record.locale ?? template.meta.locale ?? project.config.locale;
321
+ const name = project.documentName(file);
192
322
  return run({
193
323
  project,
194
324
  template,
195
- name: project.documentName(file),
325
+ // another language is another PDF, next to the usual one
326
+ name: options.locale && options.locale !== natural ? `${name}-${options.locale}` : name,
196
327
  variant,
197
328
  data,
198
- locale: doc.record.locale ?? template.meta.locale ?? project.config.locale,
329
+ locale: options.locale ?? natural,
199
330
  docId: doc.record.docId ?? options.docIdFallback,
331
+ signed: doc.record.signed,
200
332
  inputs: [file, ...doc.refFiles],
201
333
  diagnostics,
202
334
  options,
@@ -206,13 +338,14 @@ export async function buildDocument(project, file, options = {}) {
206
338
  /** Build a template as a blank form, without a record. */
207
339
  export async function buildBlank(project, templateName, options = {}) {
208
340
  const template = await project.template(templateName);
341
+ const natural = template.meta.locale ?? project.config.locale;
209
342
  return run({
210
343
  project,
211
344
  template,
212
- name: `${templateName}`,
345
+ name: options.locale && options.locale !== natural ? `${templateName}-${options.locale}` : templateName,
213
346
  variant: 'blank',
214
347
  data: {},
215
- locale: template.meta.locale ?? project.config.locale,
348
+ locale: options.locale ?? natural,
216
349
  inputs: [],
217
350
  diagnostics: [],
218
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, loadClause: project.loadClause }).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, loadClause: project.loadClause });
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
  }