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