latex-kit 0.2.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.
Files changed (54) hide show
  1. package/README.md +3 -3
  2. package/boilerplates.d.ts +8 -0
  3. package/boilerplates.js +225 -0
  4. package/build.d.ts +45 -0
  5. package/build.js +226 -0
  6. package/check.d.ts +17 -0
  7. package/check.js +58 -0
  8. package/cli.d.ts +2 -0
  9. package/cli.js +31 -0
  10. package/commands.d.ts +1 -0
  11. package/commands.js +51 -15
  12. package/config.d.ts +28 -0
  13. package/config.js +30 -0
  14. package/diff.d.ts +25 -0
  15. package/diff.js +112 -0
  16. package/esm/boilerplates.d.ts +8 -0
  17. package/esm/boilerplates.js +220 -0
  18. package/esm/build.d.ts +45 -0
  19. package/esm/build.js +220 -0
  20. package/esm/check.d.ts +17 -0
  21. package/esm/check.js +54 -0
  22. package/esm/cli.d.ts +2 -0
  23. package/esm/cli.js +29 -0
  24. package/esm/commands.d.ts +1 -0
  25. package/esm/commands.js +49 -16
  26. package/esm/config.d.ts +28 -0
  27. package/esm/config.js +25 -0
  28. package/esm/diff.d.ts +25 -0
  29. package/esm/diff.js +108 -0
  30. package/esm/import.d.ts +24 -0
  31. package/esm/import.js +113 -0
  32. package/esm/index.d.ts +15 -2
  33. package/esm/index.js +15 -15
  34. package/esm/project-commands.d.ts +16 -0
  35. package/esm/project-commands.js +324 -0
  36. package/esm/project.d.ts +46 -0
  37. package/esm/project.js +139 -0
  38. package/esm/render.js +3 -5
  39. package/esm/scaffold.d.ts +27 -0
  40. package/esm/scaffold.js +108 -0
  41. package/esm/usage.js +53 -6
  42. package/import.d.ts +24 -0
  43. package/import.js +118 -0
  44. package/index.d.ts +15 -2
  45. package/index.js +29 -15
  46. package/package.json +8 -6
  47. package/project-commands.d.ts +16 -0
  48. package/project-commands.js +340 -0
  49. package/project.d.ts +46 -0
  50. package/project.js +143 -0
  51. package/render.js +2 -4
  52. package/scaffold.d.ts +27 -0
  53. package/scaffold.js +115 -0
  54. package/usage.js +53 -6
package/esm/project.js ADDED
@@ -0,0 +1,139 @@
1
+ import { DATA_EXTENSIONS, loadTemplateSchema, toJsonSchema } from '@latex-kit/schema';
2
+ import { compileTemplate, isRelativeName, parseClauseHeader } from '@latex-kit/template';
3
+ import { existsSync, readdirSync, readFileSync, statSync } from 'fs';
4
+ import { basename, dirname, extname, isAbsolute, join, relative, resolve } from 'path';
5
+ import { loadConfig } from './config';
6
+ const SCHEMA_FILES = ['schema.ts', 'schema.mts', 'schema.js', 'schema.mjs', 'schema.cjs'];
7
+ /** A latex-kit project: a folder with templates, data and documents. */
8
+ export class Project {
9
+ root;
10
+ config;
11
+ templates = new Map();
12
+ snippets = new Map();
13
+ clauses = new Map();
14
+ constructor(root, config) {
15
+ this.root = root;
16
+ this.config = config;
17
+ }
18
+ static async open(root = process.cwd()) {
19
+ const abs = resolve(root);
20
+ return new Project(abs, await loadConfig(abs));
21
+ }
22
+ path(...parts) {
23
+ return join(this.root, ...parts);
24
+ }
25
+ rel(file) {
26
+ return relative(process.cwd(), file) || '.';
27
+ }
28
+ get templatesDir() {
29
+ return this.path(this.config.templates);
30
+ }
31
+ get dataDir() {
32
+ return this.path(this.config.data);
33
+ }
34
+ get documentsDir() {
35
+ return this.path(this.config.documents);
36
+ }
37
+ get outDir() {
38
+ return this.path(this.config.out);
39
+ }
40
+ /** Template names: folders under templates/ that contain template.tex. */
41
+ templateNames() {
42
+ if (!existsSync(this.templatesDir))
43
+ return [];
44
+ return readdirSync(this.templatesDir)
45
+ .filter((n) => !n.startsWith('.') && !n.startsWith('_'))
46
+ .filter((n) => existsSync(join(this.templatesDir, n, 'template.tex')))
47
+ .sort();
48
+ }
49
+ /** Document record files under documents/ (any depth). */
50
+ documentFiles() {
51
+ const out = [];
52
+ const walk = (dir) => {
53
+ if (!existsSync(dir))
54
+ return;
55
+ for (const name of readdirSync(dir).sort()) {
56
+ if (name.startsWith('.') || name.startsWith('_'))
57
+ continue;
58
+ const p = join(dir, name);
59
+ if (statSync(p).isDirectory())
60
+ walk(p);
61
+ else if (DATA_EXTENSIONS.includes(extname(name).toLowerCase()) && !name.endsWith('.d.ts'))
62
+ out.push(p);
63
+ }
64
+ };
65
+ walk(this.documentsDir);
66
+ return out;
67
+ }
68
+ /** A document's name: its path under documents/ without extension, `/` → `-`. */
69
+ documentName(file) {
70
+ const rel = relative(this.documentsDir, file);
71
+ const base = rel.startsWith('..') || isAbsolute(rel) ? basename(file) : rel;
72
+ return base.slice(0, -extname(base).length).split(/[\\/]/).join('-');
73
+ }
74
+ template(name) {
75
+ let t = this.templates.get(name);
76
+ if (!t) {
77
+ t = this.loadTemplate(name);
78
+ this.templates.set(name, t);
79
+ }
80
+ return t;
81
+ }
82
+ async loadTemplate(name) {
83
+ if (!/^[A-Za-z0-9_-]+$/.test(name))
84
+ throw new Error(`invalid template name "${name}"`);
85
+ const dir = join(this.templatesDir, name);
86
+ const texFile = join(dir, 'template.tex');
87
+ if (!existsSync(texFile)) {
88
+ const known = this.templateNames();
89
+ throw new Error(`no template "${name}" (expected ${this.rel(texFile)}${known.length ? `; templates: ${known.join(', ')}` : ''})`);
90
+ }
91
+ const compiled = compileTemplate(readFileSync(texFile, 'utf8'), this.rel(texFile));
92
+ const schemaFile = SCHEMA_FILES.map((f) => join(dir, f)).find((f) => existsSync(f)) ?? null;
93
+ let schema = null;
94
+ let meta = {};
95
+ let jsonSchema = null;
96
+ if (schemaFile) {
97
+ ({ schema, meta } = await loadTemplateSchema(schemaFile));
98
+ jsonSchema = toJsonSchema(schema);
99
+ }
100
+ return { name, dir, texFile, compiled, schemaFile, schema, jsonSchema, meta };
101
+ }
102
+ /**
103
+ * \snippet{name}: first next to the file that uses it, then in snippets/.
104
+ * `.tex` is added when the name has no extension. Never outside the project.
105
+ */
106
+ loadSnippet = (name, from) => {
107
+ const file = name.endsWith('.tex') ? name : `${name}.tex`;
108
+ const candidates = [resolve(dirname(resolve(from)), file), join(this.path(this.config.snippets), file)];
109
+ for (const c of candidates) {
110
+ const rel = relative(this.root, c);
111
+ if (rel.startsWith('..') || isAbsolute(rel) || !existsSync(c))
112
+ continue;
113
+ let compiled = this.snippets.get(c);
114
+ if (!compiled) {
115
+ compiled = compileTemplate(readFileSync(c, 'utf8'), this.rel(c));
116
+ this.snippets.set(c, compiled);
117
+ }
118
+ return compiled;
119
+ }
120
+ return null;
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
+ };
135
+ /** Absolute paths of every snippet loaded so far. */
136
+ snippetFiles() {
137
+ return [...this.snippets.keys()];
138
+ }
139
+ }
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,8 +3,30 @@ const MAIN = `latex-kit — build typed, reproducible LaTeX documents
3
3
  Usage
4
4
  latex-kit <command> [options]
5
5
 
6
- Commands
7
- render <file.tex> Build a PDF with latexmk in a pinned Docker image
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
+
13
+ Project commands (run in a folder with templates/, data/, documents/)
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
17
+ check Check templates, schemas, records and IDs without TeX
18
+ fields <template> List every field a template reads
19
+ typegen Write JSON Schema and .d.ts for each template's data
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
27
+
28
+ Other commands
29
+ render <file.tex> Build a plain .tex file with latexmk in a pinned image
8
30
  doctor Check Docker, the image and local TeX
9
31
 
10
32
  Options
@@ -19,10 +41,10 @@ always produces the same PDF bytes.
19
41
 
20
42
  Options
21
43
  -o, --out <dir> Output directory, relative to --root (default: out)
22
- -e, --engine <name> lualatex (default), xelatex or pdflatex
44
+ -e, --engine <name> lualatex (default), xelatex, pdflatex or pdfps
23
45
  --root <dir> Directory TeX can see (default: current directory)
24
- --image <ref> Docker image (default: pinned pyramation/latex digest)
25
- --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)
26
48
  --local Use latexmk on PATH instead of Docker (not pinned)
27
49
  --source-date-epoch <s> Build timestamp in seconds since 1970
28
50
  --verify Build twice and fail if the PDFs differ
@@ -30,6 +52,31 @@ Options
30
52
 
31
53
  Only lualatex is byte-reproducible in the default image.
32
54
  `;
55
+ const BUILD = `latex-kit build [documents…] [options]
56
+
57
+ Fills each document's template with its data and builds a PDF in
58
+ out/<document>/. Without arguments, builds every record in documents/.
59
+
60
+ Variants
61
+ --variant draft (default) DRAFT watermark and stamp; missing values show
62
+ as red markers (they fail instead when CI=true or --strict)
63
+ --variant final No marks. Missing values fail. Mints a document ID on the
64
+ --final first build and saves it in the record (JSON/YAML)
65
+ --variant signed Like final; templates can test \\when{$variant == "signed"}
66
+ --variant blank Every field is a labelled line. With no documents, builds
67
+ each template (or --template <name>) as an empty form
68
+
69
+ Options
70
+ --template <name> Only documents that use this template
71
+ --strict Fail on missing values in drafts too
72
+ -e, --engine <name> lualatex (default), xelatex, pdflatex or pdfps
73
+ --local Use latexmk on PATH instead of Docker
74
+ --image <ref> Docker image (default: pinned ghcr.io/constructive-io/latex-kit)
75
+ --verify Build twice and fail unless the PDFs are identical
76
+ --tex-only Write the .tex without running TeX
77
+ --json JSON results on stdout
78
+ --root <dir> Project folder (default: current directory)
79
+ `;
33
80
  const DOCTOR = `latex-kit doctor [--image <ref>] [--json]
34
81
 
35
82
  Reports the Node version, whether Docker is running, whether the image is
@@ -37,5 +84,5 @@ pulled and whether it runs natively on this machine, and whether latexmk
37
84
  is available for --local builds. Exits 1 if rendering cannot work.
38
85
  `;
39
86
  export function help(command) {
40
- console.log(command === 'render' ? RENDER : command === 'doctor' ? DOCTOR : MAIN);
87
+ console.log(command === 'render' ? RENDER : command === 'doctor' ? DOCTOR : command === 'build' ? BUILD : MAIN);
41
88
  }
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>;
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
@@ -1,2 +1,15 @@
1
- #!/usr/bin/env node
2
- export {};
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 './diff';
12
+ export * from './import';
13
+ export * from './project';
14
+ export * from './scaffold';
15
+ export * from '@latex-kit/schema';
package/index.js CHANGED
@@ -1,17 +1,31 @@
1
- #!/usr/bin/env node
2
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
3
16
  Object.defineProperty(exports, "__esModule", { value: true });
4
- const inquirerer_1 = require("inquirerer");
5
- const commands_1 = require("./commands");
6
- const app = new inquirerer_1.CLI(commands_1.commands, {
7
- noTty: !process.stdin.isTTY,
8
- minimistOpts: {
9
- alias: { h: 'help', v: 'version', o: 'out', e: 'engine' },
10
- boolean: ['help', 'version', 'local', 'verify', 'json'],
11
- string: ['out', 'engine', 'image', 'root', 'platform', 'source-date-epoch'],
12
- },
13
- });
14
- app.run().catch((error) => {
15
- console.error(error instanceof Error ? error.message : error);
16
- process.exit(1);
17
- });
17
+ /**
18
+ * latex-kit: typed, reproducible LaTeX documents.
19
+ *
20
+ * The CLI is `latex-kit`. This module is what project files import:
21
+ * `defineConfig` for latex-kit.config.ts, and `z` plus the shared types and
22
+ * `ref()` for templates' schema.ts and TypeScript records.
23
+ */
24
+ __exportStar(require("./build"), exports);
25
+ __exportStar(require("./check"), exports);
26
+ __exportStar(require("./config"), exports);
27
+ __exportStar(require("./diff"), exports);
28
+ __exportStar(require("./import"), exports);
29
+ __exportStar(require("./project"), exports);
30
+ __exportStar(require("./scaffold"), exports);
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.2.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",
@@ -26,8 +26,8 @@
26
26
  "build": "makage build",
27
27
  "build:dev": "makage build --dev",
28
28
  "lint": "eslint . --fix",
29
- "test": "jest",
30
- "test:watch": "jest --watch"
29
+ "test": "NODE_OPTIONS=--experimental-vm-modules jest",
30
+ "test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch"
31
31
  },
32
32
  "devDependencies": {
33
33
  "@types/minimist": "^1.2.5",
@@ -41,13 +41,15 @@
41
41
  "reproducible-builds"
42
42
  ],
43
43
  "bin": {
44
- "latex-kit": "index.js"
44
+ "latex-kit": "cli.js"
45
45
  },
46
46
  "dependencies": {
47
- "@latex-kit/render": "0.2.0",
47
+ "@latex-kit/render": "0.4.0",
48
+ "@latex-kit/schema": "0.3.0",
49
+ "@latex-kit/template": "0.3.0",
48
50
  "inquirerer": "^4.9.5",
49
51
  "minimist": "^1.2.8",
50
52
  "yanse": "^0.2.3"
51
53
  },
52
- "gitHead": "b88becdf229a9f5689fcc3b8ff087f718e04f216"
54
+ "gitHead": "023ede48131a32e9250ec48b0dde17e71c6a1536"
53
55
  }
@@ -0,0 +1,16 @@
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>;
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>;