latex-kit 0.2.0 → 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/build.d.ts +39 -0
- package/build.js +222 -0
- package/check.d.ts +17 -0
- package/check.js +58 -0
- package/cli.d.ts +2 -0
- package/cli.js +20 -0
- package/commands.d.ts +1 -0
- package/commands.js +45 -15
- package/config.d.ts +26 -0
- package/config.js +30 -0
- package/esm/build.d.ts +39 -0
- package/esm/build.js +216 -0
- package/esm/check.d.ts +17 -0
- package/esm/check.js +54 -0
- package/esm/cli.d.ts +2 -0
- package/esm/cli.js +18 -0
- package/esm/commands.d.ts +1 -0
- package/esm/commands.js +43 -16
- package/esm/config.d.ts +26 -0
- package/esm/config.js +25 -0
- package/esm/index.d.ts +12 -2
- package/esm/index.js +12 -15
- package/esm/project-commands.d.ts +6 -0
- package/esm/project-commands.js +163 -0
- package/esm/project.d.ts +43 -0
- package/esm/project.js +125 -0
- package/esm/usage.js +35 -3
- package/index.d.ts +12 -2
- package/index.js +26 -15
- package/package.json +8 -6
- package/project-commands.d.ts +6 -0
- package/project-commands.js +173 -0
- package/project.d.ts +43 -0
- package/project.js +129 -0
- package/usage.js +35 -3
package/esm/build.js
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import { gitCommitTime, render, RenderError } from '@latex-kit/render';
|
|
2
|
+
import { loadDocument, mintDocId, validate, writeDocId } from '@latex-kit/schema';
|
|
3
|
+
import { diag, evaluateTemplate, hasErrors, LATEX_KIT_STY, wrapDocument, } from '@latex-kit/template';
|
|
4
|
+
import { execFileSync } from 'child_process';
|
|
5
|
+
import { createHash } from 'crypto';
|
|
6
|
+
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs';
|
|
7
|
+
import { basename, extname, join, relative, resolve } from 'path';
|
|
8
|
+
export class BuildError extends Error {
|
|
9
|
+
diagnostics;
|
|
10
|
+
constructor(message, diagnostics) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.diagnostics = diagnostics;
|
|
13
|
+
this.name = 'BuildError';
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
const sha256 = (data) => createHash('sha256').update(data).digest('hex');
|
|
17
|
+
function isCI() {
|
|
18
|
+
return process.env.CI === 'true' || process.env.CI === '1';
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* The build date: SOURCE_DATE_EPOCH if set, else the newest commit among
|
|
22
|
+
* every input file. Same commit → same date → same PDF bytes.
|
|
23
|
+
*/
|
|
24
|
+
function buildEpoch(files) {
|
|
25
|
+
const env = process.env.SOURCE_DATE_EPOCH;
|
|
26
|
+
if (env && /^\d+$/.test(env.trim()))
|
|
27
|
+
return { epoch: Number(env.trim()), reproducible: true };
|
|
28
|
+
let newest = -1;
|
|
29
|
+
let allCommitted = true;
|
|
30
|
+
for (const f of files) {
|
|
31
|
+
const t = gitCommitTime(f);
|
|
32
|
+
if (t && /^\d+$/.test(t))
|
|
33
|
+
newest = Math.max(newest, Number(t));
|
|
34
|
+
else
|
|
35
|
+
allCommitted = false;
|
|
36
|
+
}
|
|
37
|
+
if (newest < 0)
|
|
38
|
+
return { epoch: Math.floor(Date.now() / 1000), reproducible: false };
|
|
39
|
+
return { epoch: newest, reproducible: allCommitted };
|
|
40
|
+
}
|
|
41
|
+
function gitShortHead(cwd) {
|
|
42
|
+
try {
|
|
43
|
+
return execFileSync('git', ['rev-parse', '--short', 'HEAD'], { cwd, stdio: ['ignore', 'pipe', 'ignore'], encoding: 'utf8' }).trim();
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
return 'no-git';
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
async function run(job) {
|
|
50
|
+
const { project, template, variant, options } = job;
|
|
51
|
+
const diagnostics = job.diagnostics;
|
|
52
|
+
// 1. fill the template
|
|
53
|
+
const snippets = new Set();
|
|
54
|
+
const loadSnippet = (name, from) => {
|
|
55
|
+
const s = project.loadSnippet(name, from);
|
|
56
|
+
if (s)
|
|
57
|
+
snippets.add(resolve(s.file));
|
|
58
|
+
return s;
|
|
59
|
+
};
|
|
60
|
+
const strict = options.strict ?? isCI();
|
|
61
|
+
const files = [...job.inputs, template.texFile, ...(template.schemaFile ? [template.schemaFile] : [])];
|
|
62
|
+
const { epoch, reproducible } = buildEpoch(files);
|
|
63
|
+
let docId = job.docId;
|
|
64
|
+
let minted = false;
|
|
65
|
+
if (!docId && job.mintInto) {
|
|
66
|
+
docId = mintDocId({ prefix: template.meta.docIdPrefix ?? template.name, epoch: Math.floor(Date.now() / 1000) });
|
|
67
|
+
minted = true;
|
|
68
|
+
}
|
|
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
|
+
});
|
|
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 });
|
|
86
|
+
const job_ = variant === 'final' ? job.name : `${job.name}-${variant}`;
|
|
87
|
+
const texPath = join(outDir, `${job_}.tex`);
|
|
88
|
+
const stamp = `${new Date(finalEpoch.epoch * 1000).toISOString().slice(0, 10)} ${gitShortHead(project.root)}`;
|
|
89
|
+
const tex = wrapDocument(evaluated.tex, { variant, stamp });
|
|
90
|
+
writeFileSync(texPath, tex);
|
|
91
|
+
writeFileSync(join(outDir, 'latex-kit.sty'), LATEX_KIT_STY);
|
|
92
|
+
const result = {
|
|
93
|
+
name: job.name,
|
|
94
|
+
variant,
|
|
95
|
+
tex: texPath,
|
|
96
|
+
pdf: null,
|
|
97
|
+
sha256: null,
|
|
98
|
+
docId: docId ?? null,
|
|
99
|
+
minted: false,
|
|
100
|
+
sourceDateEpoch: finalEpoch.epoch,
|
|
101
|
+
reproducible: finalEpoch.reproducible,
|
|
102
|
+
diagnostics,
|
|
103
|
+
};
|
|
104
|
+
if (options.texOnly)
|
|
105
|
+
return result;
|
|
106
|
+
// 3. render
|
|
107
|
+
const engine = options.engine ?? template.meta.engine ?? project.config.engine ?? 'lualatex';
|
|
108
|
+
const renderOpts = {
|
|
109
|
+
file: texPath,
|
|
110
|
+
root: project.root,
|
|
111
|
+
engine,
|
|
112
|
+
backend: options.backend ?? project.config.backend,
|
|
113
|
+
image: options.image ?? project.config.image,
|
|
114
|
+
platform: options.platform !== undefined ? options.platform : project.config.platform,
|
|
115
|
+
sourceDateEpoch: finalEpoch.epoch,
|
|
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
|
+
]);
|
|
129
|
+
}
|
|
130
|
+
throw e;
|
|
131
|
+
}
|
|
132
|
+
result.pdf = rendered.pdf;
|
|
133
|
+
result.sha256 = rendered.sha256;
|
|
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
|
+
}
|
|
140
|
+
// 4. keep the ID: only after a successful final build
|
|
141
|
+
if (minted && job.mintInto) {
|
|
142
|
+
writeDocId(job.mintInto, docId);
|
|
143
|
+
result.minted = true;
|
|
144
|
+
}
|
|
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
|
+
}
|
|
163
|
+
/** Build one document record. */
|
|
164
|
+
export async function buildDocument(project, file, options = {}) {
|
|
165
|
+
const variant = options.variant ?? 'draft';
|
|
166
|
+
const diagnostics = [];
|
|
167
|
+
const doc = await loadDocument(file, { dataDir: project.dataDir });
|
|
168
|
+
const template = await project.template(doc.record.template);
|
|
169
|
+
const at = { file: project.rel(file), line: 1, column: 1 };
|
|
170
|
+
let data = doc.data;
|
|
171
|
+
if (template.schema) {
|
|
172
|
+
const v = validate(template.schema, doc.data);
|
|
173
|
+
if (v.ok) {
|
|
174
|
+
data = v.value;
|
|
175
|
+
}
|
|
176
|
+
else {
|
|
177
|
+
const sev = variant === 'final' || variant === 'signed' ? 'error' : 'warning';
|
|
178
|
+
for (const i of v.issues)
|
|
179
|
+
diagnostics.push(diag(sev, `data.${i.path}: ${i.message}`, at));
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
const needsId = (variant === 'final' || variant === 'signed') && !doc.record.docId;
|
|
183
|
+
if (needsId && !['.json', '.yaml', '.yml'].includes(extname(file).toLowerCase())) {
|
|
184
|
+
const suggestion = mintDocId({ prefix: template.meta.docIdPrefix ?? template.name, epoch: Math.floor(Date.now() / 1000) });
|
|
185
|
+
diagnostics.push(diag('error', `a ${variant} build needs a document ID, and latex-kit does not edit code. Add: docId: '${suggestion}'`, at));
|
|
186
|
+
throw new BuildError(`${doc.record.template}: no document ID`, diagnostics);
|
|
187
|
+
}
|
|
188
|
+
return run({
|
|
189
|
+
project,
|
|
190
|
+
template,
|
|
191
|
+
name: project.documentName(file),
|
|
192
|
+
variant,
|
|
193
|
+
data,
|
|
194
|
+
locale: doc.record.locale ?? template.meta.locale ?? project.config.locale,
|
|
195
|
+
docId: doc.record.docId,
|
|
196
|
+
inputs: [file, ...doc.refFiles],
|
|
197
|
+
diagnostics,
|
|
198
|
+
options,
|
|
199
|
+
mintInto: needsId ? file : undefined,
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
/** Build a template as a blank form, without a record. */
|
|
203
|
+
export async function buildBlank(project, templateName, options = {}) {
|
|
204
|
+
const template = await project.template(templateName);
|
|
205
|
+
return run({
|
|
206
|
+
project,
|
|
207
|
+
template,
|
|
208
|
+
name: `${templateName}`,
|
|
209
|
+
variant: 'blank',
|
|
210
|
+
data: {},
|
|
211
|
+
locale: template.meta.locale ?? project.config.locale,
|
|
212
|
+
inputs: [],
|
|
213
|
+
diagnostics: [],
|
|
214
|
+
options: { ...options, variant: 'blank' },
|
|
215
|
+
});
|
|
216
|
+
}
|
package/esm/check.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { Diagnostic, FieldRef } from '@latex-kit/template';
|
|
2
|
+
import { Project } from './project';
|
|
3
|
+
export interface CheckResult {
|
|
4
|
+
diagnostics: Diagnostic[];
|
|
5
|
+
templates: string[];
|
|
6
|
+
documents: string[];
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Everything that can be checked without TeX: template syntax, field names
|
|
10
|
+
* against each schema, every document's data, references, and duplicate IDs.
|
|
11
|
+
*/
|
|
12
|
+
export declare function checkProject(project: Project): Promise<CheckResult>;
|
|
13
|
+
/** Every field a template reads, including through snippets. */
|
|
14
|
+
export declare function templateFields(project: Project, name: string): Promise<{
|
|
15
|
+
fields: FieldRef[];
|
|
16
|
+
diagnostics: Diagnostic[];
|
|
17
|
+
}>;
|
package/esm/check.js
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { loadDocument, validate } from '@latex-kit/schema';
|
|
2
|
+
import { analyzeTemplate, diag } from '@latex-kit/template';
|
|
3
|
+
/**
|
|
4
|
+
* Everything that can be checked without TeX: template syntax, field names
|
|
5
|
+
* against each schema, every document's data, references, and duplicate IDs.
|
|
6
|
+
*/
|
|
7
|
+
export async function checkProject(project) {
|
|
8
|
+
const diagnostics = [];
|
|
9
|
+
const templates = project.templateNames();
|
|
10
|
+
for (const name of templates) {
|
|
11
|
+
try {
|
|
12
|
+
const t = await project.template(name);
|
|
13
|
+
if (!t.jsonSchema) {
|
|
14
|
+
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
|
+
diagnostics.push(...analyzeTemplate(t.compiled, { schema: t.jsonSchema ?? undefined, loadSnippet: project.loadSnippet }).diagnostics);
|
|
17
|
+
}
|
|
18
|
+
catch (e) {
|
|
19
|
+
diagnostics.push(diag('error', e.message, { file: project.rel(project.path(project.config.templates, name)), line: 1, column: 1 }));
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
const files = project.documentFiles();
|
|
23
|
+
const ids = new Map();
|
|
24
|
+
for (const file of files) {
|
|
25
|
+
const at = { file: project.rel(file), line: 1, column: 1 };
|
|
26
|
+
try {
|
|
27
|
+
const doc = await loadDocument(file, { dataDir: project.dataDir });
|
|
28
|
+
if (doc.record.docId) {
|
|
29
|
+
const prev = ids.get(doc.record.docId);
|
|
30
|
+
if (prev)
|
|
31
|
+
diagnostics.push(diag('error', `document ID ${doc.record.docId} is also used by ${prev}; never reuse an ID`, at));
|
|
32
|
+
else
|
|
33
|
+
ids.set(doc.record.docId, project.rel(file));
|
|
34
|
+
}
|
|
35
|
+
const t = await project.template(doc.record.template);
|
|
36
|
+
if (t.schema) {
|
|
37
|
+
const v = validate(t.schema, doc.data);
|
|
38
|
+
if (!v.ok)
|
|
39
|
+
for (const i of v.issues)
|
|
40
|
+
diagnostics.push(diag('error', `data.${i.path}: ${i.message}`, at));
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
catch (e) {
|
|
44
|
+
diagnostics.push(diag('error', e.message.replace(`${file}: `, ''), at));
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return { diagnostics, templates, documents: files.map((f) => project.rel(f)) };
|
|
48
|
+
}
|
|
49
|
+
/** Every field a template reads, including through snippets. */
|
|
50
|
+
export async function templateFields(project, name) {
|
|
51
|
+
const t = await project.template(name);
|
|
52
|
+
const r = analyzeTemplate(t.compiled, { schema: t.jsonSchema ?? undefined, loadSnippet: project.loadSnippet });
|
|
53
|
+
return { fields: r.fields, diagnostics: r.diagnostics };
|
|
54
|
+
}
|
package/esm/cli.d.ts
ADDED
package/esm/cli.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { CLI } from 'inquirerer';
|
|
3
|
+
import { commands, version } from './commands';
|
|
4
|
+
const app = new CLI(commands, {
|
|
5
|
+
noTty: !process.stdin.isTTY,
|
|
6
|
+
// inquirerer answers --version itself; make it report latex-kit
|
|
7
|
+
version: version(),
|
|
8
|
+
minimistOpts: {
|
|
9
|
+
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 },
|
|
13
|
+
},
|
|
14
|
+
});
|
|
15
|
+
app.run().catch((error) => {
|
|
16
|
+
console.error(error instanceof Error ? error.message : error);
|
|
17
|
+
process.exit(1);
|
|
18
|
+
});
|
package/esm/commands.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { CLIOptions, Inquirerer } from 'inquirerer';
|
|
2
2
|
import type { ParsedArgs } from 'minimist';
|
|
3
|
+
/** The package version, from package.json next to the built files. */
|
|
3
4
|
export declare function version(): string;
|
|
4
5
|
export declare const commands: (argv: Partial<ParsedArgs>, prompter: Inquirerer, _options: CLIOptions) => Promise<Partial<ParsedArgs>>;
|
package/esm/commands.js
CHANGED
|
@@ -1,10 +1,31 @@
|
|
|
1
|
-
import { readFileSync } from 'fs';
|
|
1
|
+
import { existsSync, readFileSync } from 'fs';
|
|
2
|
+
import { join } from 'path';
|
|
3
|
+
import chalk from 'yanse';
|
|
4
|
+
import { UsageError } from './args';
|
|
2
5
|
import { doctorCommand } from './doctor';
|
|
6
|
+
import { buildCommand, checkCommand, fieldsCommand, styCommand, typegenCommand } from './project-commands';
|
|
3
7
|
import { renderCommand } from './render';
|
|
4
8
|
import { help } from './usage';
|
|
9
|
+
/** The package version, from package.json next to the built files. */
|
|
5
10
|
export function version() {
|
|
6
|
-
|
|
11
|
+
for (const p of [join(__dirname, 'package.json'), join(__dirname, '..', 'package.json')]) {
|
|
12
|
+
if (existsSync(p)) {
|
|
13
|
+
const pkg = JSON.parse(readFileSync(p, 'utf8'));
|
|
14
|
+
if (pkg.name === 'latex-kit')
|
|
15
|
+
return pkg.version;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
return 'unknown';
|
|
7
19
|
}
|
|
20
|
+
const COMMANDS = {
|
|
21
|
+
build: buildCommand,
|
|
22
|
+
check: checkCommand,
|
|
23
|
+
fields: fieldsCommand,
|
|
24
|
+
typegen: typegenCommand,
|
|
25
|
+
sty: styCommand,
|
|
26
|
+
render: renderCommand,
|
|
27
|
+
doctor: doctorCommand,
|
|
28
|
+
};
|
|
8
29
|
export const commands = async (argv, prompter, _options) => {
|
|
9
30
|
const [command, ...rest] = (argv._ ?? []).map(String);
|
|
10
31
|
if (argv.version) {
|
|
@@ -15,20 +36,26 @@ export const commands = async (argv, prompter, _options) => {
|
|
|
15
36
|
help(command === 'help' ? rest[0] : argv.help ? command : undefined);
|
|
16
37
|
return argv;
|
|
17
38
|
}
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
39
|
+
const run = COMMANDS[command];
|
|
40
|
+
if (!run) {
|
|
41
|
+
console.error(`unknown command: ${command}\n`);
|
|
42
|
+
help();
|
|
43
|
+
process.exitCode = 2;
|
|
44
|
+
return argv;
|
|
45
|
+
}
|
|
46
|
+
try {
|
|
47
|
+
const code = await run({ ...argv, _: rest }, prompter);
|
|
48
|
+
if (code !== 0)
|
|
49
|
+
process.exitCode = code;
|
|
50
|
+
}
|
|
51
|
+
catch (e) {
|
|
52
|
+
if (e instanceof UsageError) {
|
|
53
|
+
console.error(chalk.red(e.message));
|
|
54
|
+
process.exitCode = 2;
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
throw e;
|
|
58
|
+
}
|
|
30
59
|
}
|
|
31
|
-
if (code !== 0)
|
|
32
|
-
process.exitCode = code;
|
|
33
60
|
return argv;
|
|
34
61
|
};
|
package/esm/config.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { Backend, Engine } from '@latex-kit/render';
|
|
2
|
+
/** latex-kit.config.ts (or .js, .mjs, .cjs, .json) at the project root. */
|
|
3
|
+
export interface LatexKitConfig {
|
|
4
|
+
/** One folder per template: `<templates>/<name>/template.tex` and optional `schema.ts`. Default `templates`. */
|
|
5
|
+
templates?: string;
|
|
6
|
+
/** Shared pieces for \snippet{name}. Default `snippets`. */
|
|
7
|
+
snippets?: string;
|
|
8
|
+
/** Shared records that references point at: `<data>/<collection>/<id>.json`. Default `data`. */
|
|
9
|
+
data?: string;
|
|
10
|
+
/** Document records: `<documents>/<name>.json|yaml|ts`. Default `documents`. */
|
|
11
|
+
documents?: string;
|
|
12
|
+
/** Generated .tex and PDFs. Default `out`. */
|
|
13
|
+
out?: string;
|
|
14
|
+
/** Default locale for dates, numbers and money. Default `en-US`. */
|
|
15
|
+
locale?: string;
|
|
16
|
+
engine?: Engine;
|
|
17
|
+
backend?: Backend;
|
|
18
|
+
image?: string;
|
|
19
|
+
platform?: string | null;
|
|
20
|
+
}
|
|
21
|
+
export type ResolvedConfig = Required<Pick<LatexKitConfig, 'templates' | 'snippets' | 'data' | 'documents' | 'out' | 'locale'>> & Pick<LatexKitConfig, 'engine' | 'backend' | 'image' | 'platform'> & {
|
|
22
|
+
file: string | null;
|
|
23
|
+
};
|
|
24
|
+
export declare function defineConfig(config: LatexKitConfig): LatexKitConfig;
|
|
25
|
+
export declare const CONFIG_FILES: string[];
|
|
26
|
+
export declare function loadConfig(root: string): Promise<ResolvedConfig>;
|
package/esm/config.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { loadModule } from '@latex-kit/schema';
|
|
2
|
+
import { existsSync, readFileSync } from 'fs';
|
|
3
|
+
import { join, resolve } from 'path';
|
|
4
|
+
export function defineConfig(config) {
|
|
5
|
+
return config;
|
|
6
|
+
}
|
|
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' };
|
|
9
|
+
export async function loadConfig(root) {
|
|
10
|
+
for (const name of CONFIG_FILES) {
|
|
11
|
+
const file = join(resolve(root), name);
|
|
12
|
+
if (!existsSync(file))
|
|
13
|
+
continue;
|
|
14
|
+
let config;
|
|
15
|
+
if (name.endsWith('.json')) {
|
|
16
|
+
config = JSON.parse(readFileSync(file, 'utf8'));
|
|
17
|
+
}
|
|
18
|
+
else {
|
|
19
|
+
const mod = await loadModule(file);
|
|
20
|
+
config = (mod.default ?? mod);
|
|
21
|
+
}
|
|
22
|
+
return { ...DEFAULTS, ...config, file };
|
|
23
|
+
}
|
|
24
|
+
return { ...DEFAULTS, file: null };
|
|
25
|
+
}
|
package/esm/index.d.ts
CHANGED
|
@@ -1,2 +1,12 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
/**
|
|
2
|
+
* latex-kit: typed, reproducible LaTeX documents.
|
|
3
|
+
*
|
|
4
|
+
* The CLI is `latex-kit`. This module is what project files import:
|
|
5
|
+
* `defineConfig` for latex-kit.config.ts, and `z` plus the shared types and
|
|
6
|
+
* `ref()` for templates' schema.ts and TypeScript records.
|
|
7
|
+
*/
|
|
8
|
+
export * from './build';
|
|
9
|
+
export * from './check';
|
|
10
|
+
export * from './config';
|
|
11
|
+
export * from './project';
|
|
12
|
+
export * from '@latex-kit/schema';
|
package/esm/index.js
CHANGED
|
@@ -1,15 +1,12 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
console.error(error instanceof Error ? error.message : error);
|
|
14
|
-
process.exit(1);
|
|
15
|
-
});
|
|
1
|
+
/**
|
|
2
|
+
* latex-kit: typed, reproducible LaTeX documents.
|
|
3
|
+
*
|
|
4
|
+
* The CLI is `latex-kit`. This module is what project files import:
|
|
5
|
+
* `defineConfig` for latex-kit.config.ts, and `z` plus the shared types and
|
|
6
|
+
* `ref()` for templates' schema.ts and TypeScript records.
|
|
7
|
+
*/
|
|
8
|
+
export * from './build';
|
|
9
|
+
export * from './check';
|
|
10
|
+
export * from './config';
|
|
11
|
+
export * from './project';
|
|
12
|
+
export * from '@latex-kit/schema';
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { ParsedArgs } from 'minimist';
|
|
2
|
+
export declare function buildCommand(argv: Partial<ParsedArgs>): Promise<number>;
|
|
3
|
+
export declare function checkCommand(argv: Partial<ParsedArgs>): Promise<number>;
|
|
4
|
+
export declare function fieldsCommand(argv: Partial<ParsedArgs>): Promise<number>;
|
|
5
|
+
export declare function typegenCommand(argv: Partial<ParsedArgs>): Promise<number>;
|
|
6
|
+
export declare function styCommand(argv: Partial<ParsedArgs>): Promise<number>;
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { ENGINES } from '@latex-kit/render';
|
|
2
|
+
import { documentJsonSchema, generateTypes, loadDocument } from '@latex-kit/schema';
|
|
3
|
+
import { formatDiagnostic, LATEX_KIT_STY, VARIANTS } from '@latex-kit/template';
|
|
4
|
+
import { existsSync, mkdirSync, writeFileSync } from 'fs';
|
|
5
|
+
import { join, relative } from 'path';
|
|
6
|
+
import chalk from 'yanse';
|
|
7
|
+
import { UsageError } from './args';
|
|
8
|
+
import { buildBlank, buildDocument, BuildError } from './build';
|
|
9
|
+
import { checkProject, templateFields } from './check';
|
|
10
|
+
import { Project } from './project';
|
|
11
|
+
function printDiagnostics(ds, json) {
|
|
12
|
+
if (json)
|
|
13
|
+
return;
|
|
14
|
+
for (const d of ds)
|
|
15
|
+
console.error((d.severity === 'error' ? chalk.red : chalk.yellow)(formatDiagnostic(d)));
|
|
16
|
+
}
|
|
17
|
+
const rel = (p) => (p ? relative(process.cwd(), p) : null);
|
|
18
|
+
export async function buildCommand(argv) {
|
|
19
|
+
const variant = (argv.variant ?? (argv.final ? 'final' : 'draft'));
|
|
20
|
+
if (!VARIANTS.includes(variant))
|
|
21
|
+
throw new UsageError(`--variant must be one of ${VARIANTS.join(', ')}`);
|
|
22
|
+
if (argv.engine && !ENGINES.includes(argv.engine))
|
|
23
|
+
throw new UsageError(`--engine must be one of ${ENGINES.join(', ')}`);
|
|
24
|
+
const project = await Project.open(argv.root);
|
|
25
|
+
const options = {
|
|
26
|
+
variant,
|
|
27
|
+
strict: argv.strict === undefined ? undefined : Boolean(argv.strict),
|
|
28
|
+
engine: argv.engine,
|
|
29
|
+
backend: argv.local ? 'local' : undefined,
|
|
30
|
+
image: argv.image,
|
|
31
|
+
platform: argv.platform,
|
|
32
|
+
verify: Boolean(argv.verify),
|
|
33
|
+
texOnly: Boolean(argv['tex-only']),
|
|
34
|
+
};
|
|
35
|
+
const json = Boolean(argv.json);
|
|
36
|
+
const log = (s) => !json && console.error(s);
|
|
37
|
+
const targets = [];
|
|
38
|
+
const files = (argv._ ?? []).map(String);
|
|
39
|
+
if (variant === 'blank' && files.length === 0) {
|
|
40
|
+
const names = argv.template ? [String(argv.template)] : project.templateNames();
|
|
41
|
+
for (const n of names)
|
|
42
|
+
targets.push({ label: `template ${n}`, run: () => buildBlank(project, n, options) });
|
|
43
|
+
}
|
|
44
|
+
else {
|
|
45
|
+
let docs = files.length ? files.map((f) => join(process.cwd(), f)) : project.documentFiles();
|
|
46
|
+
for (const f of docs)
|
|
47
|
+
if (!existsSync(f))
|
|
48
|
+
throw new UsageError(`no such document: ${rel(f)}`);
|
|
49
|
+
if (argv.template) {
|
|
50
|
+
const wanted = String(argv.template);
|
|
51
|
+
const keep = [];
|
|
52
|
+
for (const f of docs)
|
|
53
|
+
if ((await loadDocument(f, { dataDir: project.dataDir })).record.template === wanted)
|
|
54
|
+
keep.push(f);
|
|
55
|
+
docs = keep;
|
|
56
|
+
}
|
|
57
|
+
for (const f of docs)
|
|
58
|
+
targets.push({ label: rel(f), run: () => buildDocument(project, f, options) });
|
|
59
|
+
}
|
|
60
|
+
if (targets.length === 0) {
|
|
61
|
+
log(chalk.yellow(`nothing to build (no documents in ${project.rel(project.documentsDir)}/)`));
|
|
62
|
+
return 0;
|
|
63
|
+
}
|
|
64
|
+
const results = [];
|
|
65
|
+
let failed = 0;
|
|
66
|
+
for (const t of targets) {
|
|
67
|
+
log(chalk.dim(`building ${t.label} (${variant})…`));
|
|
68
|
+
try {
|
|
69
|
+
const r = await t.run();
|
|
70
|
+
printDiagnostics(r.diagnostics, json);
|
|
71
|
+
const bad = r.verified === false;
|
|
72
|
+
if (bad)
|
|
73
|
+
failed++;
|
|
74
|
+
results.push({ ...r, tex: rel(r.tex), pdf: rel(r.pdf), diagnostics: r.diagnostics.length });
|
|
75
|
+
if (!json) {
|
|
76
|
+
console.log(`${bad ? chalk.red('✗') : chalk.green('✓')} ${rel(r.pdf ?? r.tex)}${r.docId ? chalk.dim(` ${r.docId}`) : ''}`);
|
|
77
|
+
if (r.minted)
|
|
78
|
+
console.log(chalk.dim(` minted ${r.docId} and saved it in ${t.label}`));
|
|
79
|
+
if (r.verified !== undefined)
|
|
80
|
+
console.log(r.verified ? chalk.dim(' byte-identical on a second build') : chalk.red(' second build differs'));
|
|
81
|
+
if (!r.reproducible)
|
|
82
|
+
console.log(chalk.yellow(' not reproducible: some inputs are not committed, so the build date is "now"'));
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
catch (e) {
|
|
86
|
+
failed++;
|
|
87
|
+
if (e instanceof BuildError) {
|
|
88
|
+
printDiagnostics(e.diagnostics, json);
|
|
89
|
+
if (!json)
|
|
90
|
+
console.error(chalk.red(`✗ ${t.label}: ${e.message}`));
|
|
91
|
+
results.push({ target: t.label, error: e.message, diagnostics: e.diagnostics });
|
|
92
|
+
}
|
|
93
|
+
else {
|
|
94
|
+
if (!json)
|
|
95
|
+
console.error(chalk.red(`✗ ${t.label}: ${e.message}`));
|
|
96
|
+
results.push({ target: t.label, error: e.message });
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
if (json)
|
|
101
|
+
console.log(JSON.stringify(results, null, 2));
|
|
102
|
+
return failed ? 1 : 0;
|
|
103
|
+
}
|
|
104
|
+
export async function checkCommand(argv) {
|
|
105
|
+
const project = await Project.open(argv.root);
|
|
106
|
+
const r = await checkProject(project);
|
|
107
|
+
const errors = r.diagnostics.filter((d) => d.severity === 'error').length;
|
|
108
|
+
const warnings = r.diagnostics.length - errors;
|
|
109
|
+
if (argv.json) {
|
|
110
|
+
console.log(JSON.stringify(r, null, 2));
|
|
111
|
+
}
|
|
112
|
+
else {
|
|
113
|
+
printDiagnostics(r.diagnostics, false);
|
|
114
|
+
const summary = `${r.templates.length} template${r.templates.length === 1 ? '' : 's'}, ${r.documents.length} document${r.documents.length === 1 ? '' : 's'}: ${errors} error${errors === 1 ? '' : 's'}, ${warnings} warning${warnings === 1 ? '' : 's'}`;
|
|
115
|
+
console.log(errors ? chalk.red(`✗ ${summary}`) : `${chalk.green('✓')} ${summary}`);
|
|
116
|
+
}
|
|
117
|
+
return errors ? 1 : 0;
|
|
118
|
+
}
|
|
119
|
+
export async function fieldsCommand(argv) {
|
|
120
|
+
const name = argv._?.[0];
|
|
121
|
+
if (!name)
|
|
122
|
+
throw new UsageError('usage: latex-kit fields <template>');
|
|
123
|
+
const project = await Project.open(argv.root);
|
|
124
|
+
const { fields, diagnostics } = await templateFields(project, String(name));
|
|
125
|
+
if (argv.json) {
|
|
126
|
+
console.log(JSON.stringify(fields, null, 2));
|
|
127
|
+
return 0;
|
|
128
|
+
}
|
|
129
|
+
printDiagnostics(diagnostics, false);
|
|
130
|
+
const width = Math.max(...fields.map((f) => f.absolute.length), 4);
|
|
131
|
+
for (const f of fields) {
|
|
132
|
+
const filters = f.filters.length ? chalk.cyan(` | ${f.filters.join(' | ')}`) : '';
|
|
133
|
+
console.log(`${f.absolute.padEnd(width)} ${chalk.dim(f.kind.padEnd(5))} ${chalk.dim(`${f.file}:${f.line}`)}${filters}`);
|
|
134
|
+
}
|
|
135
|
+
return diagnostics.some((d) => d.severity === 'error') ? 1 : 0;
|
|
136
|
+
}
|
|
137
|
+
export async function typegenCommand(argv) {
|
|
138
|
+
const project = await Project.open(argv.root);
|
|
139
|
+
let n = 0;
|
|
140
|
+
for (const name of project.templateNames()) {
|
|
141
|
+
const t = await project.template(name);
|
|
142
|
+
if (!t.jsonSchema)
|
|
143
|
+
continue;
|
|
144
|
+
const schemaFile = join(t.dir, `${name}.schema.json`);
|
|
145
|
+
const typesFile = join(t.dir, 'types.d.ts');
|
|
146
|
+
writeFileSync(schemaFile, JSON.stringify(documentJsonSchema(name, t.jsonSchema), null, 2) + '\n');
|
|
147
|
+
writeFileSync(typesFile, `// Generated by latex-kit typegen from schema.ts. Do not edit.\n${generateTypes(name, t.jsonSchema)}\n`);
|
|
148
|
+
console.log(`${chalk.green('✓')} ${rel(schemaFile)} ${rel(typesFile)}`);
|
|
149
|
+
n++;
|
|
150
|
+
}
|
|
151
|
+
if (n === 0)
|
|
152
|
+
console.log(chalk.yellow('no templates with a schema.ts'));
|
|
153
|
+
return 0;
|
|
154
|
+
}
|
|
155
|
+
export async function styCommand(argv) {
|
|
156
|
+
const project = await Project.open(argv.root);
|
|
157
|
+
const dir = argv._?.[0] ? join(process.cwd(), String(argv._[0])) : project.templatesDir;
|
|
158
|
+
mkdirSync(dir, { recursive: true });
|
|
159
|
+
const file = join(dir, 'latex-kit.sty');
|
|
160
|
+
writeFileSync(file, LATEX_KIT_STY);
|
|
161
|
+
console.log(`${chalk.green('✓')} ${rel(file)} (lets editors compile templates as blank previews)`);
|
|
162
|
+
return 0;
|
|
163
|
+
}
|