latex-kit 0.3.0 → 0.4.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.
- package/README.md +3 -3
- package/boilerplates.d.ts +8 -0
- package/boilerplates.js +225 -0
- package/build.d.ts +6 -0
- package/build.js +12 -8
- package/check.js +2 -2
- package/cli.js +14 -3
- package/commands.js +6 -0
- package/config.d.ts +3 -1
- package/config.js +1 -1
- package/diff.d.ts +25 -0
- package/diff.js +112 -0
- package/esm/boilerplates.d.ts +8 -0
- package/esm/boilerplates.js +220 -0
- package/esm/build.d.ts +6 -0
- package/esm/build.js +13 -9
- package/esm/check.js +2 -2
- package/esm/cli.js +14 -3
- package/esm/commands.js +7 -1
- package/esm/config.d.ts +3 -1
- 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 +3 -0
- package/esm/index.js +3 -0
- package/esm/project-commands.d.ts +10 -0
- package/esm/project-commands.js +163 -2
- package/esm/project.d.ts +4 -1
- package/esm/project.js +15 -1
- package/esm/render.js +3 -5
- package/esm/scaffold.d.ts +27 -0
- package/esm/scaffold.js +108 -0
- package/esm/usage.js +20 -5
- package/import.d.ts +24 -0
- package/import.js +118 -0
- package/index.d.ts +3 -0
- package/index.js +3 -0
- package/package.json +5 -5
- package/project-commands.d.ts +10 -0
- package/project-commands.js +167 -0
- package/project.d.ts +4 -1
- package/project.js +14 -0
- package/render.js +2 -4
- package/scaffold.d.ts +27 -0
- package/scaffold.js +115 -0
- package/usage.js +20 -5
package/import.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.templateNameFor = templateNameFor;
|
|
4
|
+
exports.starterSchema = starterSchema;
|
|
5
|
+
exports.importDocument = importDocument;
|
|
6
|
+
const render_1 = require("@latex-kit/render");
|
|
7
|
+
const template_1 = require("@latex-kit/template");
|
|
8
|
+
const fs_1 = require("fs");
|
|
9
|
+
const path_1 = require("path");
|
|
10
|
+
function templateNameFor(file) {
|
|
11
|
+
return ((0, path_1.basename)(file, (0, path_1.extname)(file))
|
|
12
|
+
.replace(/([a-z0-9])([A-Z])/g, '$1-$2')
|
|
13
|
+
.toLowerCase()
|
|
14
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
15
|
+
.replace(/^-|-$/g, '') || 'imported');
|
|
16
|
+
}
|
|
17
|
+
/** A zod schema source with every converted field as a string, nested by path. */
|
|
18
|
+
function starterSchema(paths) {
|
|
19
|
+
const root = {};
|
|
20
|
+
const conflicts = new Set();
|
|
21
|
+
for (const p of paths) {
|
|
22
|
+
const segs = p.split('.');
|
|
23
|
+
if (segs[0].startsWith('$'))
|
|
24
|
+
continue;
|
|
25
|
+
let node = root;
|
|
26
|
+
segs.forEach((seg, i) => {
|
|
27
|
+
const last = i === segs.length - 1;
|
|
28
|
+
const key = /^\d+$/.test(seg) ? null : seg;
|
|
29
|
+
if (key === null)
|
|
30
|
+
return; // list indexes: leave lists to the author
|
|
31
|
+
if (last) {
|
|
32
|
+
if (node[key] && node[key] !== null)
|
|
33
|
+
conflicts.add(segs.slice(0, i + 1).join('.'));
|
|
34
|
+
else
|
|
35
|
+
node[key] = null;
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
if (node[key] === null)
|
|
39
|
+
conflicts.add(segs.slice(0, i + 1).join('.'));
|
|
40
|
+
node[key] ??= {};
|
|
41
|
+
node = node[key];
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
const render = (t, indent) => Object.keys(t)
|
|
46
|
+
.sort()
|
|
47
|
+
.map((k) => {
|
|
48
|
+
const name = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(k) ? k : JSON.stringify(k);
|
|
49
|
+
const v = t[k];
|
|
50
|
+
return v === null ? `${indent}${name}: z.string(),` : `${indent}${name}: z.object({\n${render(v, indent + ' ')}\n${indent}}),`;
|
|
51
|
+
})
|
|
52
|
+
.join('\n');
|
|
53
|
+
const note = conflicts.size ? `\n// Used both as a value and as a group, check: ${[...conflicts].join(', ')}` : '';
|
|
54
|
+
return `// Starter schema written by \`latex-kit import\`: every field is a string.
|
|
55
|
+
// Tighten the types (numbers, dates, lists) and add the fields' rules.${note}
|
|
56
|
+
import { z } from 'latex-kit';
|
|
57
|
+
|
|
58
|
+
export default z.object({
|
|
59
|
+
${render(root, ' ')}
|
|
60
|
+
});
|
|
61
|
+
`;
|
|
62
|
+
}
|
|
63
|
+
/** Convert a document (Word, Markdown, HTML, …, or an older .tex) into a template. */
|
|
64
|
+
async function importDocument(project, file, options = {}) {
|
|
65
|
+
const input = (0, path_1.resolve)(file);
|
|
66
|
+
if (!(0, fs_1.existsSync)(input))
|
|
67
|
+
throw new Error(`no such file: ${file}`);
|
|
68
|
+
const name = options.name ?? templateNameFor(input);
|
|
69
|
+
if (!/^[a-z0-9][a-z0-9_-]*$/.test(name))
|
|
70
|
+
throw new Error(`invalid template name "${name}" (use lowercase letters, digits and -)`);
|
|
71
|
+
const dir = (0, path_1.join)(project.templatesDir, name);
|
|
72
|
+
const target = (0, path_1.join)(dir, 'template.tex');
|
|
73
|
+
if ((0, fs_1.existsSync)(target) && !options.force)
|
|
74
|
+
throw new Error(`${project.rel(target)} exists; use --force to replace it`);
|
|
75
|
+
(0, fs_1.mkdirSync)(dir, { recursive: true });
|
|
76
|
+
let tex;
|
|
77
|
+
let media = null;
|
|
78
|
+
if ((0, path_1.extname)(input).toLowerCase() === '.tex') {
|
|
79
|
+
tex = (0, fs_1.readFileSync)(input, 'utf8');
|
|
80
|
+
}
|
|
81
|
+
else {
|
|
82
|
+
// pandoc runs in Docker with the project mounted, so the input must be inside it
|
|
83
|
+
const rel = (0, path_1.relative)(project.root, input);
|
|
84
|
+
let staged = null;
|
|
85
|
+
let source = input;
|
|
86
|
+
if (rel.startsWith('..') || (0, path_1.isAbsolute)(rel)) {
|
|
87
|
+
const stage = (0, path_1.join)(project.outDir, '.import');
|
|
88
|
+
(0, fs_1.mkdirSync)(stage, { recursive: true });
|
|
89
|
+
staged = (0, path_1.join)(stage, (0, path_1.basename)(input));
|
|
90
|
+
(0, fs_1.copyFileSync)(input, staged);
|
|
91
|
+
source = staged;
|
|
92
|
+
}
|
|
93
|
+
const mediaDir = (0, path_1.join)(dir, 'media');
|
|
94
|
+
try {
|
|
95
|
+
await (0, render_1.runPandoc)({ root: project.root, input: source, output: target, extractMedia: mediaDir, backend: options.backend });
|
|
96
|
+
}
|
|
97
|
+
finally {
|
|
98
|
+
if (staged)
|
|
99
|
+
(0, fs_1.rmSync)(staged, { force: true });
|
|
100
|
+
}
|
|
101
|
+
tex = (0, fs_1.readFileSync)(target, 'utf8');
|
|
102
|
+
if ((0, fs_1.existsSync)(mediaDir)) {
|
|
103
|
+
media = mediaDir;
|
|
104
|
+
// pandoc writes media paths relative to the project root; TeX looks in the template folder
|
|
105
|
+
tex = tex.split((0, path_1.relative)(project.root, mediaDir) + '/').join('media/');
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
const { tex: converted, converted: fields, skipped } = (0, template_1.convertPlaceholders)(tex);
|
|
109
|
+
(0, fs_1.writeFileSync)(target, (0, template_1.ensureLatexKitPackage)(converted));
|
|
110
|
+
let schema = null;
|
|
111
|
+
const schemaFile = (0, path_1.join)(dir, 'schema.ts');
|
|
112
|
+
if (options.schema !== false && fields.length > 0 && !(0, fs_1.existsSync)(schemaFile)) {
|
|
113
|
+
const paths = [...new Set(fields.map((f) => f.to.slice('\\field{'.length, -1)))];
|
|
114
|
+
(0, fs_1.writeFileSync)(schemaFile, starterSchema(paths));
|
|
115
|
+
schema = schemaFile;
|
|
116
|
+
}
|
|
117
|
+
return { name, template: target, schema, media, converted: fields, skipped };
|
|
118
|
+
}
|
package/index.d.ts
CHANGED
package/index.js
CHANGED
|
@@ -24,5 +24,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
24
24
|
__exportStar(require("./build"), exports);
|
|
25
25
|
__exportStar(require("./check"), exports);
|
|
26
26
|
__exportStar(require("./config"), exports);
|
|
27
|
+
__exportStar(require("./diff"), exports);
|
|
28
|
+
__exportStar(require("./import"), exports);
|
|
27
29
|
__exportStar(require("./project"), exports);
|
|
30
|
+
__exportStar(require("./scaffold"), exports);
|
|
28
31
|
__exportStar(require("@latex-kit/schema"), exports);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "latex-kit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.1",
|
|
4
4
|
"description": "Build typed, reproducible LaTeX documents from the command line",
|
|
5
5
|
"author": "Constructive <developers@constructive.io>",
|
|
6
6
|
"main": "index.js",
|
|
@@ -44,12 +44,12 @@
|
|
|
44
44
|
"latex-kit": "cli.js"
|
|
45
45
|
},
|
|
46
46
|
"dependencies": {
|
|
47
|
-
"@latex-kit/render": "0.
|
|
48
|
-
"@latex-kit/schema": "0.
|
|
49
|
-
"@latex-kit/template": "0.
|
|
47
|
+
"@latex-kit/render": "0.4.0",
|
|
48
|
+
"@latex-kit/schema": "0.3.0",
|
|
49
|
+
"@latex-kit/template": "0.3.0",
|
|
50
50
|
"inquirerer": "^4.9.5",
|
|
51
51
|
"minimist": "^1.2.8",
|
|
52
52
|
"yanse": "^0.2.3"
|
|
53
53
|
},
|
|
54
|
-
"gitHead": "
|
|
54
|
+
"gitHead": "023ede48131a32e9250ec48b0dde17e71c6a1536"
|
|
55
55
|
}
|
package/project-commands.d.ts
CHANGED
|
@@ -4,3 +4,13 @@ export declare function checkCommand(argv: Partial<ParsedArgs>): Promise<number>
|
|
|
4
4
|
export declare function fieldsCommand(argv: Partial<ParsedArgs>): Promise<number>;
|
|
5
5
|
export declare function typegenCommand(argv: Partial<ParsedArgs>): Promise<number>;
|
|
6
6
|
export declare function styCommand(argv: Partial<ParsedArgs>): Promise<number>;
|
|
7
|
+
export declare function importCommand(argv: Partial<ParsedArgs>): Promise<number>;
|
|
8
|
+
export declare function diffCommand(argv: Partial<ParsedArgs>): Promise<number>;
|
|
9
|
+
export declare function initCommand(argv: Partial<ParsedArgs>): Promise<number>;
|
|
10
|
+
export declare function newCommand(argv: Partial<ParsedArgs>): Promise<number>;
|
|
11
|
+
export declare function cleanCommand(argv: Partial<ParsedArgs>): Promise<number>;
|
|
12
|
+
/**
|
|
13
|
+
* Rebuild when templates, snippets, clauses, data or records change. Builds
|
|
14
|
+
* drafts unless --variant says otherwise; never mints IDs (use build --final).
|
|
15
|
+
*/
|
|
16
|
+
export declare function watchCommand(argv: Partial<ParsedArgs>): Promise<number>;
|
package/project-commands.js
CHANGED
|
@@ -8,6 +8,12 @@ exports.checkCommand = checkCommand;
|
|
|
8
8
|
exports.fieldsCommand = fieldsCommand;
|
|
9
9
|
exports.typegenCommand = typegenCommand;
|
|
10
10
|
exports.styCommand = styCommand;
|
|
11
|
+
exports.importCommand = importCommand;
|
|
12
|
+
exports.diffCommand = diffCommand;
|
|
13
|
+
exports.initCommand = initCommand;
|
|
14
|
+
exports.newCommand = newCommand;
|
|
15
|
+
exports.cleanCommand = cleanCommand;
|
|
16
|
+
exports.watchCommand = watchCommand;
|
|
11
17
|
const render_1 = require("@latex-kit/render");
|
|
12
18
|
const schema_1 = require("@latex-kit/schema");
|
|
13
19
|
const template_1 = require("@latex-kit/template");
|
|
@@ -17,7 +23,11 @@ const yanse_1 = __importDefault(require("yanse"));
|
|
|
17
23
|
const args_1 = require("./args");
|
|
18
24
|
const build_1 = require("./build");
|
|
19
25
|
const check_1 = require("./check");
|
|
26
|
+
const commands_1 = require("./commands");
|
|
27
|
+
const diff_1 = require("./diff");
|
|
28
|
+
const import_1 = require("./import");
|
|
20
29
|
const project_1 = require("./project");
|
|
30
|
+
const scaffold_1 = require("./scaffold");
|
|
21
31
|
function printDiagnostics(ds, json) {
|
|
22
32
|
if (json)
|
|
23
33
|
return;
|
|
@@ -171,3 +181,160 @@ async function styCommand(argv) {
|
|
|
171
181
|
console.log(`${yanse_1.default.green('✓')} ${rel(file)} (lets editors compile templates as blank previews)`);
|
|
172
182
|
return 0;
|
|
173
183
|
}
|
|
184
|
+
async function importCommand(argv) {
|
|
185
|
+
const file = argv._?.[0];
|
|
186
|
+
if (!file)
|
|
187
|
+
throw new args_1.UsageError('usage: latex-kit import <file.docx|.md|.html|.tex> [--name <template>] [--force]');
|
|
188
|
+
const project = await project_1.Project.open(argv.root);
|
|
189
|
+
const r = await (0, import_1.importDocument)(project, String(file), {
|
|
190
|
+
name: argv.name,
|
|
191
|
+
force: Boolean(argv.force),
|
|
192
|
+
backend: argv.local ? 'local' : undefined,
|
|
193
|
+
schema: argv.schema !== false,
|
|
194
|
+
});
|
|
195
|
+
console.log(`${yanse_1.default.green('✓')} ${rel(r.template)}`);
|
|
196
|
+
if (r.media)
|
|
197
|
+
console.log(yanse_1.default.dim(` images in ${rel(r.media)}`));
|
|
198
|
+
console.log(yanse_1.default.dim(` ${r.converted.length} placeholder${r.converted.length === 1 ? '' : 's'} became \\field{…}`));
|
|
199
|
+
for (const s of r.skipped)
|
|
200
|
+
console.log(yanse_1.default.yellow(` line ${s.line}: left ${s.from} as is (not a valid field path)`));
|
|
201
|
+
if (r.schema)
|
|
202
|
+
console.log(yanse_1.default.dim(` starter schema: ${rel(r.schema)} (every field is a string; tighten it)`));
|
|
203
|
+
console.log(yanse_1.default.dim(` next: latex-kit fields ${r.name}, then latex-kit build --variant blank --template ${r.name}`));
|
|
204
|
+
return 0;
|
|
205
|
+
}
|
|
206
|
+
async function diffCommand(argv) {
|
|
207
|
+
const args = (argv._ ?? []).map(String);
|
|
208
|
+
const variant = (argv.variant ?? 'final');
|
|
209
|
+
if (!template_1.VARIANTS.includes(variant))
|
|
210
|
+
throw new args_1.UsageError(`--variant must be one of ${template_1.VARIANTS.join(', ')}`);
|
|
211
|
+
const project = await project_1.Project.open(argv.root);
|
|
212
|
+
const options = { variant, engine: argv.engine, backend: argv.local ? 'local' : undefined, image: argv.image, platform: argv.platform };
|
|
213
|
+
const abs = (p) => (0, path_1.join)(process.cwd(), p);
|
|
214
|
+
let result;
|
|
215
|
+
try {
|
|
216
|
+
if (args.length === 2 && !argv.against) {
|
|
217
|
+
result = await (0, diff_1.diffFiles)(project, abs(args[0]), abs(args[1]), options);
|
|
218
|
+
}
|
|
219
|
+
else if (args.length === 1 && argv.against) {
|
|
220
|
+
result = await (0, diff_1.diffDocument)(project, abs(args[0]), String(argv.against), options);
|
|
221
|
+
}
|
|
222
|
+
else {
|
|
223
|
+
throw new args_1.UsageError('usage: latex-kit diff <old.tex> <new.tex>\n latex-kit diff <document> --against <git-ref>');
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
catch (e) {
|
|
227
|
+
if (e instanceof build_1.BuildError) {
|
|
228
|
+
printDiagnostics(e.diagnostics, Boolean(argv.json));
|
|
229
|
+
console.error(yanse_1.default.red(`✗ ${e.message}`));
|
|
230
|
+
return 1;
|
|
231
|
+
}
|
|
232
|
+
throw e;
|
|
233
|
+
}
|
|
234
|
+
if (argv.json)
|
|
235
|
+
console.log(JSON.stringify({ pdf: rel(result.pdf), tex: rel(result.tex), old: rel(result.old), new: rel(result.new) }, null, 2));
|
|
236
|
+
else
|
|
237
|
+
console.log(`${yanse_1.default.green('✓')} ${rel(result.pdf)} ${yanse_1.default.dim('(insertions underlined in blue, deletions struck through in red)')}`);
|
|
238
|
+
return 0;
|
|
239
|
+
}
|
|
240
|
+
async function initCommand(argv) {
|
|
241
|
+
const dir = (0, path_1.join)(process.cwd(), argv._?.[0] ? String(argv._[0]) : '.');
|
|
242
|
+
const r = (0, scaffold_1.initProject)(dir, { paper: Boolean(argv.paper), force: Boolean(argv.force), version: (0, commands_1.version)() });
|
|
243
|
+
for (const f of r.written)
|
|
244
|
+
console.log(`${yanse_1.default.green('+')} ${rel(f)}`);
|
|
245
|
+
for (const f of r.skipped)
|
|
246
|
+
console.log(yanse_1.default.dim(` kept ${rel(f)} (exists)`));
|
|
247
|
+
const cd = rel(dir) === '.' ? '' : `cd ${rel(dir)} && `;
|
|
248
|
+
console.log(argv.paper
|
|
249
|
+
? yanse_1.default.dim(`\nnext: ${cd}latex-kit render paper/main.tex --verify`)
|
|
250
|
+
: yanse_1.default.dim(`\nnext: ${cd}latex-kit check && latex-kit build`));
|
|
251
|
+
return 0;
|
|
252
|
+
}
|
|
253
|
+
async function newCommand(argv) {
|
|
254
|
+
const [kind, name] = (argv._ ?? []).map(String);
|
|
255
|
+
const project = await project_1.Project.open(argv.root);
|
|
256
|
+
if (kind === 'template' && name) {
|
|
257
|
+
const r = (0, scaffold_1.newTemplate)(project, name, Boolean(argv.force));
|
|
258
|
+
for (const f of r.written)
|
|
259
|
+
console.log(`${yanse_1.default.green('+')} ${rel(f)}`);
|
|
260
|
+
console.log(yanse_1.default.dim(`\nnext: latex-kit new document <name> --template ${name}`));
|
|
261
|
+
return 0;
|
|
262
|
+
}
|
|
263
|
+
if (kind === 'document' && name) {
|
|
264
|
+
if (!argv.template)
|
|
265
|
+
throw new args_1.UsageError('usage: latex-kit new document <name> --template <template>');
|
|
266
|
+
const r = await (0, scaffold_1.newDocument)(project, name, String(argv.template), Boolean(argv.force));
|
|
267
|
+
for (const f of r.written)
|
|
268
|
+
console.log(`${yanse_1.default.green('+')} ${rel(f)}`);
|
|
269
|
+
if (r.schemaFile)
|
|
270
|
+
console.log(yanse_1.default.dim(` editors autocomplete it from ${rel(r.schemaFile)}`));
|
|
271
|
+
console.log(yanse_1.default.dim(`\nnext: fill in the data, then latex-kit build ${r.written[0] ? rel(r.written[0]) : ''}`));
|
|
272
|
+
return 0;
|
|
273
|
+
}
|
|
274
|
+
throw new args_1.UsageError('usage: latex-kit new template <name>\n latex-kit new document <name> --template <template>');
|
|
275
|
+
}
|
|
276
|
+
async function cleanCommand(argv) {
|
|
277
|
+
const project = await project_1.Project.open(argv.root);
|
|
278
|
+
const rel = (0, path_1.relative)(project.root, project.outDir);
|
|
279
|
+
if (rel === '' || rel.startsWith('..') || (0, path_1.isAbsolute)(rel))
|
|
280
|
+
throw new args_1.UsageError(`refusing to delete ${project.outDir}: the out folder must be inside the project`);
|
|
281
|
+
if (!(0, fs_1.existsSync)(project.outDir)) {
|
|
282
|
+
console.log(yanse_1.default.dim(`nothing to clean (${project.rel(project.outDir)}/ does not exist)`));
|
|
283
|
+
return 0;
|
|
284
|
+
}
|
|
285
|
+
(0, fs_1.rmSync)(project.outDir, { recursive: true, force: true });
|
|
286
|
+
console.log(`${yanse_1.default.green('✓')} removed ${project.rel(project.outDir)}/`);
|
|
287
|
+
return 0;
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Rebuild when templates, snippets, clauses, data or records change. Builds
|
|
291
|
+
* drafts unless --variant says otherwise; never mints IDs (use build --final).
|
|
292
|
+
*/
|
|
293
|
+
async function watchCommand(argv) {
|
|
294
|
+
const variant = (argv.variant ?? 'draft');
|
|
295
|
+
if (variant === 'final' || variant === 'signed')
|
|
296
|
+
throw new args_1.UsageError('watch builds drafts or blanks; run latex-kit build --final when you are done');
|
|
297
|
+
const project = await project_1.Project.open(argv.root);
|
|
298
|
+
const dirs = [project.config.templates, project.config.snippets, project.config.clauses, project.config.data, project.config.documents]
|
|
299
|
+
.map((d) => project.path(d))
|
|
300
|
+
.filter((d) => (0, fs_1.existsSync)(d));
|
|
301
|
+
if (dirs.length === 0)
|
|
302
|
+
throw new args_1.UsageError('nothing to watch: no templates/, data/ or documents/ here');
|
|
303
|
+
let running = false;
|
|
304
|
+
let again = false;
|
|
305
|
+
let timer = null;
|
|
306
|
+
const run = async () => {
|
|
307
|
+
if (running) {
|
|
308
|
+
again = true;
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
running = true;
|
|
312
|
+
console.log(yanse_1.default.dim(`\n— ${new Date().toLocaleTimeString()} —`));
|
|
313
|
+
try {
|
|
314
|
+
await buildCommand({ ...argv, variant });
|
|
315
|
+
}
|
|
316
|
+
catch (e) {
|
|
317
|
+
console.error(yanse_1.default.red(e.message));
|
|
318
|
+
}
|
|
319
|
+
running = false;
|
|
320
|
+
if (again) {
|
|
321
|
+
again = false;
|
|
322
|
+
void run();
|
|
323
|
+
}
|
|
324
|
+
};
|
|
325
|
+
const schedule = (file) => {
|
|
326
|
+
// generated files and editor swap files are not changes worth a build
|
|
327
|
+
if (file && /(\.schema\.json|types\.d\.ts|~|\.swp)$/.test(file))
|
|
328
|
+
return;
|
|
329
|
+
if (timer)
|
|
330
|
+
clearTimeout(timer);
|
|
331
|
+
timer = setTimeout(() => void run(), 250);
|
|
332
|
+
};
|
|
333
|
+
for (const d of dirs)
|
|
334
|
+
(0, fs_1.watch)(d, { recursive: true }, (_event, file) => schedule(file ? String(file) : null));
|
|
335
|
+
console.log(yanse_1.default.dim(`watching ${dirs.map((d) => project.rel(d)).join(', ')} (Ctrl-C to stop)`));
|
|
336
|
+
await run();
|
|
337
|
+
return new Promise(() => {
|
|
338
|
+
// runs until interrupted
|
|
339
|
+
});
|
|
340
|
+
}
|
package/project.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { JsonSchema, TemplateMeta, z } from '@latex-kit/schema';
|
|
2
|
-
import { CompiledTemplate } from '@latex-kit/template';
|
|
2
|
+
import { CompiledTemplate, LoadedClause } from '@latex-kit/template';
|
|
3
3
|
import { ResolvedConfig } from './config';
|
|
4
4
|
export interface Template {
|
|
5
5
|
name: string;
|
|
@@ -17,6 +17,7 @@ export declare class Project {
|
|
|
17
17
|
readonly config: ResolvedConfig;
|
|
18
18
|
private templates;
|
|
19
19
|
private snippets;
|
|
20
|
+
private clauses;
|
|
20
21
|
private constructor();
|
|
21
22
|
static open(root?: string): Promise<Project>;
|
|
22
23
|
path(...parts: string[]): string;
|
|
@@ -38,6 +39,8 @@ export declare class Project {
|
|
|
38
39
|
* `.tex` is added when the name has no extension. Never outside the project.
|
|
39
40
|
*/
|
|
40
41
|
loadSnippet: (name: string, from: string) => CompiledTemplate | null;
|
|
42
|
+
/** \\clause{id}: `clauses/<id>.tex` from the clause library. */
|
|
43
|
+
loadClause: (id: string) => LoadedClause | null;
|
|
41
44
|
/** Absolute paths of every snippet loaded so far. */
|
|
42
45
|
snippetFiles(): string[];
|
|
43
46
|
}
|
package/project.js
CHANGED
|
@@ -13,6 +13,7 @@ class Project {
|
|
|
13
13
|
config;
|
|
14
14
|
templates = new Map();
|
|
15
15
|
snippets = new Map();
|
|
16
|
+
clauses = new Map();
|
|
16
17
|
constructor(root, config) {
|
|
17
18
|
this.root = root;
|
|
18
19
|
this.config = config;
|
|
@@ -121,6 +122,19 @@ class Project {
|
|
|
121
122
|
}
|
|
122
123
|
return null;
|
|
123
124
|
};
|
|
125
|
+
/** \\clause{id}: `clauses/<id>.tex` from the clause library. */
|
|
126
|
+
loadClause = (id) => {
|
|
127
|
+
if (this.clauses.has(id))
|
|
128
|
+
return this.clauses.get(id);
|
|
129
|
+
let loaded = null;
|
|
130
|
+
const file = (0, path_1.join)(this.path(this.config.clauses), `${id}.tex`);
|
|
131
|
+
if ((0, template_1.isRelativeName)(id) && (0, fs_1.existsSync)(file)) {
|
|
132
|
+
const text = (0, fs_1.readFileSync)(file, 'utf8');
|
|
133
|
+
loaded = { id, template: (0, template_1.compileTemplate)(text, this.rel(file)), ...(0, template_1.parseClauseHeader)(text) };
|
|
134
|
+
}
|
|
135
|
+
this.clauses.set(id, loaded);
|
|
136
|
+
return loaded;
|
|
137
|
+
};
|
|
124
138
|
/** Absolute paths of every snippet loaded so far. */
|
|
125
139
|
snippetFiles() {
|
|
126
140
|
return [...this.snippets.keys()];
|
package/render.js
CHANGED
|
@@ -5,7 +5,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.renderCommand = renderCommand;
|
|
7
7
|
const render_1 = require("@latex-kit/render");
|
|
8
|
-
const fs_1 = require("fs");
|
|
9
8
|
const path_1 = require("path");
|
|
10
9
|
const yanse_1 = __importDefault(require("yanse"));
|
|
11
10
|
const args_1 = require("./args");
|
|
@@ -54,11 +53,10 @@ async function renderCommand(argv, prompter) {
|
|
|
54
53
|
}
|
|
55
54
|
let verified;
|
|
56
55
|
if (argv.verify) {
|
|
57
|
-
|
|
56
|
+
// same output path: some tools (Ghostscript) hash the path into the PDF ID
|
|
58
57
|
log(yanse_1.default.dim('rendering again to check the output is byte-identical…'));
|
|
59
|
-
const second = await (0, render_1.render)({ ...opts, file: opts.file,
|
|
58
|
+
const second = await (0, render_1.render)({ ...opts, file: opts.file, sourceDateEpoch: first.sourceDateEpoch });
|
|
60
59
|
verified = second.sha256 === first.sha256;
|
|
61
|
-
(0, fs_1.rmSync)((0, path_1.dirname)(second.pdf), { recursive: true, force: true });
|
|
62
60
|
}
|
|
63
61
|
if (argv.json) {
|
|
64
62
|
console.log(JSON.stringify({ ...summary(first), verified }, null, 2));
|
package/scaffold.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { FileMap } from './boilerplates';
|
|
2
|
+
import { Project } from './project';
|
|
3
|
+
export interface WriteResult {
|
|
4
|
+
written: string[];
|
|
5
|
+
skipped: string[];
|
|
6
|
+
}
|
|
7
|
+
/** Write files under `dir`. Existing files are kept unless `force`. */
|
|
8
|
+
export declare function writeFiles(dir: string, files: FileMap, force?: boolean): WriteResult;
|
|
9
|
+
/** Scaffold a latex-kit project (or a paper) in `dir`. */
|
|
10
|
+
export declare function initProject(dir: string, options: {
|
|
11
|
+
paper?: boolean;
|
|
12
|
+
force?: boolean;
|
|
13
|
+
version: string;
|
|
14
|
+
}): WriteResult;
|
|
15
|
+
export declare function newTemplate(project: Project, name: string, force?: boolean): WriteResult;
|
|
16
|
+
type Schema = Record<string, unknown>;
|
|
17
|
+
/** A placeholder value for a JSON Schema: required fields only, typed. */
|
|
18
|
+
export declare function skeleton(schema: Schema | undefined, root: Schema, depth?: number): unknown;
|
|
19
|
+
/**
|
|
20
|
+
* documents/<name>.json for a template: every required field with a
|
|
21
|
+
* placeholder, and `$schema` pointing at the generated JSON Schema so editors
|
|
22
|
+
* autocomplete and validate it.
|
|
23
|
+
*/
|
|
24
|
+
export declare function newDocument(project: Project, name: string, templateName: string, force?: boolean): Promise<WriteResult & {
|
|
25
|
+
schemaFile: string | null;
|
|
26
|
+
}>;
|
|
27
|
+
export {};
|
package/scaffold.js
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.writeFiles = writeFiles;
|
|
4
|
+
exports.initProject = initProject;
|
|
5
|
+
exports.newTemplate = newTemplate;
|
|
6
|
+
exports.skeleton = skeleton;
|
|
7
|
+
exports.newDocument = newDocument;
|
|
8
|
+
const schema_1 = require("@latex-kit/schema");
|
|
9
|
+
const fs_1 = require("fs");
|
|
10
|
+
const path_1 = require("path");
|
|
11
|
+
const boilerplates_1 = require("./boilerplates");
|
|
12
|
+
const config_1 = require("./config");
|
|
13
|
+
/** Write files under `dir`. Existing files are kept unless `force`. */
|
|
14
|
+
function writeFiles(dir, files, force = false) {
|
|
15
|
+
const written = [];
|
|
16
|
+
const skipped = [];
|
|
17
|
+
for (const [rel, content] of Object.entries(files)) {
|
|
18
|
+
const file = (0, path_1.join)(dir, rel);
|
|
19
|
+
if ((0, fs_1.existsSync)(file) && !force) {
|
|
20
|
+
skipped.push(file);
|
|
21
|
+
continue;
|
|
22
|
+
}
|
|
23
|
+
(0, fs_1.mkdirSync)((0, path_1.dirname)(file), { recursive: true });
|
|
24
|
+
(0, fs_1.writeFileSync)(file, content);
|
|
25
|
+
written.push(file);
|
|
26
|
+
}
|
|
27
|
+
return { written, skipped };
|
|
28
|
+
}
|
|
29
|
+
/** Scaffold a latex-kit project (or a paper) in `dir`. */
|
|
30
|
+
function initProject(dir, options) {
|
|
31
|
+
(0, fs_1.mkdirSync)(dir, { recursive: true });
|
|
32
|
+
if (!options.paper && !options.force) {
|
|
33
|
+
const existing = config_1.CONFIG_FILES.find((f) => (0, fs_1.existsSync)((0, path_1.join)(dir, f)));
|
|
34
|
+
if (existing)
|
|
35
|
+
throw new Error(`${(0, path_1.join)(dir, existing)} already exists; use --force to add the starter files anyway`);
|
|
36
|
+
}
|
|
37
|
+
return writeFiles(dir, options.paper ? (0, boilerplates_1.paperFiles)() : (0, boilerplates_1.projectFiles)(options.version), options.force);
|
|
38
|
+
}
|
|
39
|
+
function newTemplate(project, name, force = false) {
|
|
40
|
+
if (!/^[a-z0-9][a-z0-9_-]*$/.test(name))
|
|
41
|
+
throw new Error(`invalid template name "${name}" (use lowercase letters, digits and -)`);
|
|
42
|
+
if ((0, fs_1.existsSync)((0, path_1.join)(project.templatesDir, name)) && !force)
|
|
43
|
+
throw new Error(`template ${name} already exists`);
|
|
44
|
+
const files = (0, boilerplates_1.templateFiles)(name);
|
|
45
|
+
const mapped = {};
|
|
46
|
+
for (const [rel, content] of Object.entries(files))
|
|
47
|
+
mapped[(0, path_1.join)(project.config.templates, rel.replace(/^templates\//, ''))] = content;
|
|
48
|
+
return writeFiles(project.root, mapped, force);
|
|
49
|
+
}
|
|
50
|
+
/** A placeholder value for a JSON Schema: required fields only, typed. */
|
|
51
|
+
function skeleton(schema, root, depth = 0) {
|
|
52
|
+
if (!schema || depth > 12)
|
|
53
|
+
return '';
|
|
54
|
+
if (typeof schema.$ref === 'string') {
|
|
55
|
+
const m = /^#\/(\$defs|definitions)\/(.+)$/.exec(schema.$ref);
|
|
56
|
+
const target = m ? root[m[1]]?.[m[2]] : undefined;
|
|
57
|
+
return skeleton(target, root, depth + 1);
|
|
58
|
+
}
|
|
59
|
+
if ('default' in schema)
|
|
60
|
+
return schema.default;
|
|
61
|
+
if ('const' in schema)
|
|
62
|
+
return schema.const;
|
|
63
|
+
if (Array.isArray(schema.enum))
|
|
64
|
+
return schema.enum[0];
|
|
65
|
+
const alt = (schema.anyOf ?? schema.oneOf);
|
|
66
|
+
if (alt?.length)
|
|
67
|
+
return skeleton(alt.find((a) => a.type !== 'null') ?? alt[0], root, depth + 1);
|
|
68
|
+
const type = Array.isArray(schema.type) ? schema.type[0] : schema.type;
|
|
69
|
+
switch (type) {
|
|
70
|
+
case 'object': {
|
|
71
|
+
const props = (schema.properties ?? {});
|
|
72
|
+
const required = (schema.required ?? []);
|
|
73
|
+
const out = {};
|
|
74
|
+
for (const key of required)
|
|
75
|
+
out[key] = skeleton(props[key], root, depth + 1);
|
|
76
|
+
return out;
|
|
77
|
+
}
|
|
78
|
+
case 'array':
|
|
79
|
+
return [];
|
|
80
|
+
case 'number':
|
|
81
|
+
case 'integer':
|
|
82
|
+
return 0;
|
|
83
|
+
case 'boolean':
|
|
84
|
+
return false;
|
|
85
|
+
case 'string':
|
|
86
|
+
return typeof schema.pattern === 'string' && schema.pattern.includes('\\d{4}-\\d{2}-\\d{2}') ? '2026-01-01' : '';
|
|
87
|
+
default:
|
|
88
|
+
return '';
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* documents/<name>.json for a template: every required field with a
|
|
93
|
+
* placeholder, and `$schema` pointing at the generated JSON Schema so editors
|
|
94
|
+
* autocomplete and validate it.
|
|
95
|
+
*/
|
|
96
|
+
async function newDocument(project, name, templateName, force = false) {
|
|
97
|
+
if (!/^[a-z0-9][a-z0-9_-]*$/.test(name))
|
|
98
|
+
throw new Error(`invalid document name "${name}" (use lowercase letters, digits and -)`);
|
|
99
|
+
const existing = (0, fs_1.existsSync)(project.documentsDir) ? (0, fs_1.readdirSync)(project.documentsDir).find((f) => f.replace(/\.[^.]+$/, '') === name) : undefined;
|
|
100
|
+
if (existing && !force)
|
|
101
|
+
throw new Error(`documents/${existing} already exists`);
|
|
102
|
+
const template = await project.template(templateName);
|
|
103
|
+
const file = (0, path_1.join)(project.documentsDir, `${name}.json`);
|
|
104
|
+
let schemaFile = null;
|
|
105
|
+
const record = {};
|
|
106
|
+
if (template.jsonSchema) {
|
|
107
|
+
schemaFile = (0, path_1.join)(template.dir, `${templateName}.schema.json`);
|
|
108
|
+
(0, fs_1.writeFileSync)(schemaFile, JSON.stringify((0, schema_1.documentJsonSchema)(templateName, template.jsonSchema), null, 2) + '\n');
|
|
109
|
+
record.$schema = (0, path_1.relative)(project.documentsDir, schemaFile).split('\\').join('/');
|
|
110
|
+
}
|
|
111
|
+
record.template = templateName;
|
|
112
|
+
record.data = template.jsonSchema ? skeleton(template.jsonSchema, template.jsonSchema) : {};
|
|
113
|
+
const r = writeFiles((0, path_1.dirname)(file), { [`${name}.json`]: JSON.stringify(record, null, 2) + '\n' }, force);
|
|
114
|
+
return { ...r, schemaFile };
|
|
115
|
+
}
|
package/usage.js
CHANGED
|
@@ -6,12 +6,27 @@ const MAIN = `latex-kit — build typed, reproducible LaTeX documents
|
|
|
6
6
|
Usage
|
|
7
7
|
latex-kit <command> [options]
|
|
8
8
|
|
|
9
|
+
Start
|
|
10
|
+
init [dir] A new project: a letter template, data and a record
|
|
11
|
+
init [dir] --paper A paper: main.tex, refs.bib and a GitHub Actions workflow
|
|
12
|
+
new template <name> A template folder with template.tex and schema.ts
|
|
13
|
+
new document <name> --template <t>
|
|
14
|
+
A record with every required field, linked to its schema
|
|
15
|
+
|
|
9
16
|
Project commands (run in a folder with templates/, data/, documents/)
|
|
10
17
|
build [documents…] Fill templates with records and build PDFs
|
|
18
|
+
watch [documents…] Rebuild drafts whenever a template, clause or record changes
|
|
19
|
+
clean Delete the out/ folder
|
|
11
20
|
check Check templates, schemas, records and IDs without TeX
|
|
12
21
|
fields <template> List every field a template reads
|
|
13
22
|
typegen Write JSON Schema and .d.ts for each template's data
|
|
14
23
|
sty [dir] Write latex-kit.sty so editors can preview templates
|
|
24
|
+
import <file> Turn a Word/Markdown/HTML document (or an older .tex)
|
|
25
|
+
into a template; {{x}} and @GROUP@FIELD@ become \\field
|
|
26
|
+
diff <document> --against <ref>
|
|
27
|
+
Redline PDF of a document against an earlier commit
|
|
28
|
+
diff <old.tex> <new.tex>
|
|
29
|
+
Redline PDF of any two .tex files
|
|
15
30
|
|
|
16
31
|
Other commands
|
|
17
32
|
render <file.tex> Build a plain .tex file with latexmk in a pinned image
|
|
@@ -29,10 +44,10 @@ always produces the same PDF bytes.
|
|
|
29
44
|
|
|
30
45
|
Options
|
|
31
46
|
-o, --out <dir> Output directory, relative to --root (default: out)
|
|
32
|
-
-e, --engine <name> lualatex (default), xelatex or
|
|
47
|
+
-e, --engine <name> lualatex (default), xelatex, pdflatex or pdfps
|
|
33
48
|
--root <dir> Directory TeX can see (default: current directory)
|
|
34
|
-
--image <ref> Docker image (default: pinned
|
|
35
|
-
--platform <os/arch> Docker --platform (default:
|
|
49
|
+
--image <ref> Docker image (default: pinned ghcr.io/constructive-io/latex-kit)
|
|
50
|
+
--platform <os/arch> Docker --platform (default: native)
|
|
36
51
|
--local Use latexmk on PATH instead of Docker (not pinned)
|
|
37
52
|
--source-date-epoch <s> Build timestamp in seconds since 1970
|
|
38
53
|
--verify Build twice and fail if the PDFs differ
|
|
@@ -57,9 +72,9 @@ Variants
|
|
|
57
72
|
Options
|
|
58
73
|
--template <name> Only documents that use this template
|
|
59
74
|
--strict Fail on missing values in drafts too
|
|
60
|
-
-e, --engine <name> lualatex (default), xelatex or
|
|
75
|
+
-e, --engine <name> lualatex (default), xelatex, pdflatex or pdfps
|
|
61
76
|
--local Use latexmk on PATH instead of Docker
|
|
62
|
-
--image <ref> Docker image (default: pinned
|
|
77
|
+
--image <ref> Docker image (default: pinned ghcr.io/constructive-io/latex-kit)
|
|
63
78
|
--verify Build twice and fail unless the PDFs are identical
|
|
64
79
|
--tex-only Write the .tex without running TeX
|
|
65
80
|
--json JSON results on stdout
|