@latex-kit/template 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/LICENSE +23 -0
  2. package/README.md +137 -2
  3. package/analyze.d.ts +38 -0
  4. package/analyze.js +144 -0
  5. package/clause.d.ts +23 -0
  6. package/clause.js +26 -0
  7. package/codemod.d.ts +25 -0
  8. package/codemod.js +67 -0
  9. package/compile.d.ts +74 -0
  10. package/compile.js +258 -0
  11. package/condition.d.ts +38 -0
  12. package/condition.js +201 -0
  13. package/diagnostics.d.ts +29 -0
  14. package/diagnostics.js +48 -0
  15. package/document.d.ts +15 -0
  16. package/document.js +25 -0
  17. package/esm/analyze.d.ts +38 -0
  18. package/esm/analyze.js +141 -0
  19. package/esm/clause.d.ts +23 -0
  20. package/esm/clause.js +21 -0
  21. package/esm/codemod.d.ts +25 -0
  22. package/esm/codemod.js +62 -0
  23. package/esm/compile.d.ts +74 -0
  24. package/esm/compile.js +253 -0
  25. package/esm/condition.d.ts +38 -0
  26. package/esm/condition.js +193 -0
  27. package/esm/diagnostics.d.ts +29 -0
  28. package/esm/diagnostics.js +40 -0
  29. package/esm/document.d.ts +15 -0
  30. package/esm/document.js +22 -0
  31. package/esm/evaluate.d.ts +40 -0
  32. package/esm/evaluate.js +235 -0
  33. package/esm/filters.d.ts +39 -0
  34. package/esm/filters.js +221 -0
  35. package/esm/index.d.ts +12 -0
  36. package/esm/index.js +12 -0
  37. package/esm/jsonschema.d.ts +24 -0
  38. package/esm/jsonschema.js +94 -0
  39. package/esm/path.d.ts +7 -0
  40. package/esm/path.js +16 -0
  41. package/esm/sty.d.ts +6 -0
  42. package/esm/sty.js +67 -0
  43. package/evaluate.d.ts +40 -0
  44. package/evaluate.js +239 -0
  45. package/filters.d.ts +39 -0
  46. package/filters.js +229 -0
  47. package/index.d.ts +12 -0
  48. package/index.js +28 -0
  49. package/jsonschema.d.ts +24 -0
  50. package/jsonschema.js +99 -0
  51. package/package.json +44 -4
  52. package/path.d.ts +7 -0
  53. package/path.js +22 -0
  54. package/sty.d.ts +6 -0
  55. package/sty.js +70 -0
package/LICENSE ADDED
@@ -0,0 +1,23 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Dan Lynch <pyramation@gmail.com>
4
+ Copyright (c) 2026 Constructive <developers@constructive.io>
5
+ Copyright (c) 2020-present, Interweb, Inc.
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,138 @@
1
- # Temporary Holding Version
1
+ # @latex-kit/template
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <p align="center" width="100%">
4
+ <img height="250" src="https://raw.githubusercontent.com/constructive-io/constructive/refs/heads/main/assets/outline-logo.svg" />
5
+ </p>
6
+
7
+ <p align="center" width="100%">
8
+ <a href="https://github.com/constructive-io/latex-kit/actions/workflows/ci.yml">
9
+ <img height="20" src="https://github.com/constructive-io/latex-kit/actions/workflows/ci.yml/badge.svg" />
10
+ </a>
11
+ <a href="https://github.com/constructive-io/latex-kit/blob/main/LICENSE">
12
+ <img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/>
13
+ </a>
14
+ <a href="https://www.npmjs.com/package/@latex-kit/template">
15
+ <img height="20" src="https://img.shields.io/npm/v/@latex-kit/template.svg"/>
16
+ </a>
17
+ </p>
18
+
19
+ <p align="center">The latex-kit template language: fill-in macros inside real <code>.tex</code> files, checked and escaped.</p>
20
+
21
+ A latex-kit template is an ordinary LaTeX file with a few extra macros. It
22
+ opens in any LaTeX editor and, with `latex-kit.sty`, compiles on its own as
23
+ a blank form. latex-kit replaces only those macros: every other byte of the
24
+ file is kept exactly as written, and every value is escaped.
25
+
26
+ ```latex
27
+ \documentclass{article}
28
+ \usepackage{latex-kit}
29
+ \begin{document}
30
+ This Agreement is made on \field{effectiveDate|date:long} between
31
+ \field{discloser.name} and \field{recipient.name}.
32
+
33
+ \when{mutual}{Each party may disclose}\otherwise{The Discloser may disclose}
34
+ Confidential Information for \field{termMonths|words} (\field{termMonths}) months.
35
+
36
+ Fees: \each{fees}{fee}{\field{fee.label} \field{fee.amount|money:USD}\sep{; }}.
37
+
38
+ Document ID: \docid
39
+ \end{document}
40
+ ```
41
+
42
+ ## The language
43
+
44
+ | Macro | Does |
45
+ |---|---|
46
+ | `\field{path}` | Inserts a value, escaped. Paths use dots: `party.address.city`, `items.0.name` |
47
+ | `\field{path\|filter\|filter:arg}` | Runs filters left to right (see below) |
48
+ | `\raw{path}` | Inserts a value **unescaped**. `latex-kit check` warns on every use |
49
+ | `\when{condition}{…}\otherwise{…}` | Conditional. `\otherwise` is optional and may follow on the next line |
50
+ | `\each{list}{item}{…}` | Loop. Inside: `item`, `$index` (1-based), `$first`, `$last` |
51
+ | `\sep{…}` | Inside `\each`: printed between items, not after the last |
52
+ | `\snippet{name}` | Includes `name.tex` (next to the template, then `snippets/`) with the same data |
53
+ | `\docid` | The document's ID, minted once and stored on the record |
54
+ | `\clause{id}` | Places a numbered clause from the library (`clauses/<id>.tex`), filled with the same data |
55
+ | `\clauseref{id}` | Prints that clause's number. A reference to a clause the document doesn't contain fails a final build |
56
+
57
+ Special values: `$variant`, `$locale`, `$docid`, `$template`.
58
+
59
+ `\snippet` and `\clauseref` are named so they never collide with LaTeX's
60
+ `\partial` and `\ref`.
61
+
62
+ ### Clauses
63
+
64
+ A clause is a template fragment with a short header:
65
+
66
+ ```latex
67
+ % title: Confidentiality
68
+ % version: 3
69
+ The Recipient will keep it confidential for \field{termMonths|words} months,
70
+ subject to Section~\clauseref{nda/exclusions}.
71
+ ```
72
+
73
+ Each placed clause becomes `\lkclause{title}{label}` (a numbered section by
74
+ default; redefine `\lkclause` to change the style). Every build's manifest
75
+ lists the clause IDs and versions it used.
76
+
77
+ ### Conditions
78
+
79
+ A small, safe grammar, never `eval`:
80
+ `==` `!=` `<` `<=` `>` `>=`, `&&` `||` `!`, parentheses, paths, numbers,
81
+ `"strings"`, `true` `false` `null`. A missing path is false; an empty list
82
+ is false.
83
+
84
+ ```latex
85
+ \when{fee > 0 && !waived}{…}
86
+ \when{party.kind == "organization" || $variant == "blank"}{…}
87
+ ```
88
+
89
+ ### Filters
90
+
91
+ | Filter | Example | Output (en-US) |
92
+ |---|---|---|
93
+ | `date`, `date:long\|short\|medium\|full\|iso` | `2026-11-25` | November 25, 2026 |
94
+ | `money`, `money:USD` | `5400` or `{ amount, currency }` | $5,400.00 |
95
+ | `number`, `number:2` | `1234.5` | 1,234.50 |
96
+ | `percent`, `percent:1` | `0.15` | 15% |
97
+ | `words` | `24` | twenty-four |
98
+ | `upper`, `lower`, `title`, `trim` | | |
99
+ | `join`, `join:" and "` | `["a", "b"]` | a, b |
100
+ | `default:"text"` | missing | text |
101
+ | `lines`, `paragraphs` | multi-line text | keeps line / paragraph breaks |
102
+
103
+ Dates, numbers and money follow the record's locale (`ja-JP`, `de-DE`, …).
104
+
105
+ ### Variants
106
+
107
+ | Variant | Fields | Marks |
108
+ |---|---|---|
109
+ | `draft` | filled; a missing value prints a red `missing: path` box | DRAFT watermark, date and git commit |
110
+ | `blank` | every field is a labelled line | none |
111
+ | `final` | filled; a missing value is an error | none |
112
+ | `signed` | like `final`; test `$variant == "signed"` for signature text | none |
113
+
114
+ ## Usage
115
+
116
+ ```ts
117
+ import { analyzeTemplate, compileTemplate, evaluateTemplate, wrapDocument } from '@latex-kit/template';
118
+
119
+ const t = compileTemplate(source, 'templates/nda/template.tex');
120
+ const { tex, diagnostics } = evaluateTemplate(t, { data, variant: 'final', locale: 'en-US', docId });
121
+ const ready = wrapDocument(tex, { variant: 'final' });
122
+
123
+ // static checks against a JSON Schema of the data
124
+ const { fields, diagnostics: problems } = analyzeTemplate(t, { schema });
125
+ ```
126
+
127
+ Diagnostics carry `file`, `line` and `column`, formatted as
128
+ `templates/nda/template.tex:12:3: error: unknown field party.nmae`.
129
+
130
+ ## Credits
131
+
132
+ **🛠 Built by the [Constructive](https://constructive.io) team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
133
+
134
+ ## Disclaimer
135
+
136
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
137
+
138
+ No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
package/analyze.d.ts ADDED
@@ -0,0 +1,38 @@
1
+ import { LoadedClause } from './clause';
2
+ import { CompiledTemplate } from './compile';
3
+ import { Diagnostic } from './diagnostics';
4
+ import { JsonSchema } from './jsonschema';
5
+ export interface FieldRef {
6
+ /** How the template reads it: `field`, `raw`, `when`, `each`. */
7
+ kind: 'field' | 'raw' | 'when' | 'each';
8
+ /** The path as written, e.g. `item.price`. */
9
+ path: string;
10
+ /** The path from the data root, e.g. `items[].price`. */
11
+ absolute: string;
12
+ filters: string[];
13
+ file: string;
14
+ line: number;
15
+ column: number;
16
+ }
17
+ export interface AnalyzeOptions {
18
+ /** JSON Schema of the record's data. Without it only syntax is checked. */
19
+ schema?: JsonSchema;
20
+ loadSnippet?: (name: string, from: string) => CompiledTemplate | null;
21
+ loadClause?: (id: string) => LoadedClause | null;
22
+ }
23
+ export interface AnalyzeResult {
24
+ fields: FieldRef[];
25
+ snippets: string[];
26
+ /** Library clauses the template can place, with versions. */
27
+ clauses: {
28
+ id: string;
29
+ version?: string;
30
+ file: string;
31
+ }[];
32
+ diagnostics: Diagnostic[];
33
+ }
34
+ /**
35
+ * Static checks for a template: every path exists in the schema, \each walks
36
+ * a list, \raw is flagged, snippets resolve. Lists every field it reads.
37
+ */
38
+ export declare function analyzeTemplate(template: CompiledTemplate, options?: AnalyzeOptions): AnalyzeResult;
package/analyze.js ADDED
@@ -0,0 +1,144 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.analyzeTemplate = analyzeTemplate;
4
+ const condition_1 = require("./condition");
5
+ const diagnostics_1 = require("./diagnostics");
6
+ const jsonschema_1 = require("./jsonschema");
7
+ const path_1 = require("./path");
8
+ /**
9
+ * Static checks for a template: every path exists in the schema, \each walks
10
+ * a list, \raw is flagged, snippets resolve. Lists every field it reads.
11
+ */
12
+ function analyzeTemplate(template, options = {}) {
13
+ const root = options.schema;
14
+ const diagnostics = [...template.diagnostics];
15
+ const fields = [];
16
+ const snippets = [];
17
+ const clauses = [];
18
+ const refs = [];
19
+ const stack = [template.file];
20
+ const resolve = (path, scopes, loc) => {
21
+ const [head, ...rest] = (0, path_1.splitPath)(path);
22
+ if (head.startsWith('$')) {
23
+ if (path_1.LOOP_SPECIALS.includes(head)) {
24
+ if (scopes.length === 0)
25
+ diagnostics.push((0, diagnostics_1.diag)('error', `${head} only works inside \\each`, loc));
26
+ }
27
+ else if (!path_1.GLOBAL_SPECIALS.includes(head)) {
28
+ diagnostics.push((0, diagnostics_1.diag)('error', `unknown special value ${head} (known: ${[...path_1.GLOBAL_SPECIALS, ...path_1.LOOP_SPECIALS].join(', ')})`, loc));
29
+ }
30
+ if (rest.length)
31
+ diagnostics.push((0, diagnostics_1.diag)('error', `${head} has no fields`, loc));
32
+ return { absolute: path, schema: jsonschema_1.ANY };
33
+ }
34
+ const scope = [...scopes].reverse().find((s) => s.name === head);
35
+ const absolute = scope ? [scope.absolute, ...rest].join('.') : path;
36
+ if (!root)
37
+ return { absolute, schema: jsonschema_1.ANY };
38
+ const base = scope ? scope.schema : root;
39
+ const segs = scope ? rest : [head, ...rest];
40
+ const found = base === undefined ? undefined : (0, jsonschema_1.schemaAt)(base, segs, root);
41
+ if (found === undefined && base !== undefined) {
42
+ diagnostics.push((0, diagnostics_1.diag)('error', `unknown field ${absolute} (not in the template's schema)`, loc));
43
+ }
44
+ return { absolute, schema: found };
45
+ };
46
+ const walk = (nodes, scopes) => {
47
+ for (const node of nodes) {
48
+ switch (node.kind) {
49
+ case 'text':
50
+ case 'docid':
51
+ break;
52
+ case 'field': {
53
+ const { absolute } = resolve(node.spec.path, scopes, node.loc);
54
+ fields.push({
55
+ kind: node.raw ? 'raw' : 'field',
56
+ path: node.spec.path,
57
+ absolute,
58
+ filters: node.spec.filters.map((f) => (f.arg === undefined ? f.name : `${f.name}:${f.arg}`)),
59
+ ...node.loc,
60
+ });
61
+ if (node.raw) {
62
+ diagnostics.push((0, diagnostics_1.diag)('warning', `\\raw{${node.spec.path}} inserts LaTeX unescaped; only use it for trusted values`, node.loc));
63
+ }
64
+ break;
65
+ }
66
+ case 'when':
67
+ for (const p of (0, condition_1.conditionPaths)(node.cond)) {
68
+ const { absolute } = resolve(p, scopes, node.loc);
69
+ fields.push({ kind: 'when', path: p, absolute, filters: [], ...node.loc });
70
+ }
71
+ walk(node.then, scopes);
72
+ if (node.else)
73
+ walk(node.else, scopes);
74
+ break;
75
+ case 'each': {
76
+ const { absolute, schema } = resolve(node.path, scopes, node.loc);
77
+ fields.push({ kind: 'each', path: node.path, absolute, filters: [], ...node.loc });
78
+ let item = jsonschema_1.ANY;
79
+ if (root && schema !== undefined) {
80
+ item = (0, jsonschema_1.itemSchema)(schema, root);
81
+ if (item === undefined)
82
+ diagnostics.push((0, diagnostics_1.diag)('error', `\\each{${node.path}}: ${absolute} is not a list in the schema`, node.loc));
83
+ }
84
+ walk(node.body, [...scopes, { name: node.name, absolute: `${absolute}[]`, schema: item }]);
85
+ break;
86
+ }
87
+ case 'sep':
88
+ walk(node.body, scopes);
89
+ break;
90
+ case 'snippet': {
91
+ const from = stack[stack.length - 1];
92
+ const snippet = options.loadSnippet?.(node.name, from) ?? null;
93
+ if (!snippet) {
94
+ diagnostics.push((0, diagnostics_1.diag)('error', `snippet not found: ${node.name}`, node.loc));
95
+ break;
96
+ }
97
+ if (stack.includes(snippet.file)) {
98
+ diagnostics.push((0, diagnostics_1.diag)('error', `snippet ${node.name} includes itself`, node.loc));
99
+ break;
100
+ }
101
+ if (!snippets.includes(snippet.file)) {
102
+ snippets.push(snippet.file);
103
+ diagnostics.push(...snippet.diagnostics);
104
+ }
105
+ stack.push(snippet.file);
106
+ walk(snippet.nodes, scopes);
107
+ stack.pop();
108
+ break;
109
+ }
110
+ case 'clause': {
111
+ const clause = options.loadClause?.(node.id) ?? null;
112
+ if (!clause) {
113
+ diagnostics.push((0, diagnostics_1.diag)('error', `clause not found: ${node.id}`, node.loc));
114
+ break;
115
+ }
116
+ if (stack.includes(clause.template.file)) {
117
+ diagnostics.push((0, diagnostics_1.diag)('error', `clause ${node.id} includes itself`, node.loc));
118
+ break;
119
+ }
120
+ if (!clauses.some((c) => c.id === node.id)) {
121
+ clauses.push({ id: node.id, version: clause.version, file: clause.template.file });
122
+ diagnostics.push(...clause.template.diagnostics);
123
+ if (!clause.title)
124
+ diagnostics.push((0, diagnostics_1.diag)('warning', `clause ${node.id} has no "% title:" line, so it prints as a bare number`, { file: clause.template.file, line: 1, column: 1 }));
125
+ }
126
+ stack.push(clause.template.file);
127
+ walk(clause.template.nodes, scopes);
128
+ stack.pop();
129
+ break;
130
+ }
131
+ case 'clauseref':
132
+ refs.push({ id: node.id, loc: node.loc });
133
+ break;
134
+ }
135
+ }
136
+ };
137
+ walk(template.nodes, []);
138
+ for (const r of refs) {
139
+ if (!clauses.some((c) => c.id === r.id)) {
140
+ diagnostics.push((0, diagnostics_1.diag)('error', `\\clauseref{${r.id}}: the template never places \\clause{${r.id}}`, r.loc));
141
+ }
142
+ }
143
+ return { fields, snippets, clauses, diagnostics };
144
+ }
package/clause.d.ts ADDED
@@ -0,0 +1,23 @@
1
+ import { CompiledTemplate } from './compile';
2
+ export interface ClauseMeta {
3
+ title?: string;
4
+ version?: string;
5
+ }
6
+ /** A clause from the library, compiled, with its header. */
7
+ export interface LoadedClause extends ClauseMeta {
8
+ id: string;
9
+ template: CompiledTemplate;
10
+ }
11
+ export interface ClauseUse {
12
+ id: string;
13
+ version?: string;
14
+ file: string;
15
+ }
16
+ /**
17
+ * Read a clause file's header: the leading `%` comment lines.
18
+ *
19
+ * % title: Confidentiality
20
+ * % version: 3
21
+ */
22
+ export declare function parseClauseHeader(text: string): ClauseMeta;
23
+ export declare const clauseLabel: (id: string) => string;
package/clause.js ADDED
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.clauseLabel = void 0;
4
+ exports.parseClauseHeader = parseClauseHeader;
5
+ /**
6
+ * Read a clause file's header: the leading `%` comment lines.
7
+ *
8
+ * % title: Confidentiality
9
+ * % version: 3
10
+ */
11
+ function parseClauseHeader(text) {
12
+ const meta = {};
13
+ for (const line of text.split('\n')) {
14
+ const t = line.trim();
15
+ if (t === '')
16
+ continue;
17
+ if (!t.startsWith('%'))
18
+ break;
19
+ const m = /^%\s*(title|version)\s*:\s*(.*?)\s*$/i.exec(t);
20
+ if (m)
21
+ meta[m[1].toLowerCase()] = m[2];
22
+ }
23
+ return meta;
24
+ }
25
+ const clauseLabel = (id) => `clause:${id}`;
26
+ exports.clauseLabel = clauseLabel;
package/codemod.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ export interface Converted {
2
+ /** The token as it appeared, e.g. `@COMPANY@LEGAL_NAME@` or `{{ party.name }}`. */
3
+ from: string;
4
+ /** What it became, e.g. `\field{company.legalName}`. */
5
+ to: string;
6
+ line: number;
7
+ }
8
+ export interface ConvertResult {
9
+ tex: string;
10
+ converted: Converted[];
11
+ /** Tokens that looked like placeholders but could not become a valid path. */
12
+ skipped: Converted[];
13
+ }
14
+ /** LEGAL_NAME → legalName, COMPANY → company, already camelCase → unchanged. */
15
+ export declare function camelSegment(seg: string): string;
16
+ /**
17
+ * Turn placeholder tokens from older templates or Word documents into
18
+ * `\field{…}`: `@GROUP@FIELD@` (the legacy generator's tokens) and
19
+ * `{{ path }}` (common in Word/Markdown templates, also after pandoc
20
+ * escaped it). Anything that cannot become a valid path is left alone and
21
+ * reported.
22
+ */
23
+ export declare function convertPlaceholders(tex: string): ConvertResult;
24
+ /** Make sure a document loads latex-kit.sty, right before \begin{document}. */
25
+ export declare function ensureLatexKitPackage(tex: string): string;
package/codemod.js ADDED
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.camelSegment = camelSegment;
4
+ exports.convertPlaceholders = convertPlaceholders;
5
+ exports.ensureLatexKitPackage = ensureLatexKitPackage;
6
+ const path_1 = require("./path");
7
+ /** LEGAL_NAME → legalName, COMPANY → company, already camelCase → unchanged. */
8
+ function camelSegment(seg) {
9
+ const s = seg.replace(/\\_/g, '_');
10
+ if (!s.includes('_') && s !== s.toUpperCase())
11
+ return s;
12
+ const parts = s.toLowerCase().split('_').filter(Boolean);
13
+ return parts.map((p, i) => (i === 0 ? p : p[0].toUpperCase() + p.slice(1))).join('');
14
+ }
15
+ // @GROUP@FIELD@ with letters, digits and underscores (possibly escaped as \_ by pandoc)
16
+ const LEGACY = /@([A-Za-z](?:[A-Za-z0-9_]|\\_)*)@([A-Za-z](?:[A-Za-z0-9_]|\\_)*)@/g;
17
+ // {{ path }} as typed, or \{\{ path \}\} as pandoc escapes it
18
+ const MUSTACHE = /(?:\{\{|\\\{\\\{)\s*([^{}\\]*(?:\\_[^{}\\]*)*?)\s*(?:\}\}|\\\}\\\})/g;
19
+ function lineAt(text, offset) {
20
+ let n = 1;
21
+ for (let i = 0; i < offset; i++)
22
+ if (text.charCodeAt(i) === 10)
23
+ n++;
24
+ return n;
25
+ }
26
+ /**
27
+ * Turn placeholder tokens from older templates or Word documents into
28
+ * `\field{…}`: `@GROUP@FIELD@` (the legacy generator's tokens) and
29
+ * `{{ path }}` (common in Word/Markdown templates, also after pandoc
30
+ * escaped it). Anything that cannot become a valid path is left alone and
31
+ * reported.
32
+ */
33
+ function convertPlaceholders(tex) {
34
+ const converted = [];
35
+ const skipped = [];
36
+ let out = tex.replace(LEGACY, (whole, group, field, offset) => {
37
+ const path = `${camelSegment(group)}.${camelSegment(field)}`;
38
+ const item = { from: whole, to: `\\field{${path}}`, line: lineAt(tex, offset) };
39
+ if (!(0, path_1.isPath)(path)) {
40
+ skipped.push(item);
41
+ return whole;
42
+ }
43
+ converted.push(item);
44
+ return item.to;
45
+ });
46
+ const before = out;
47
+ out = out.replace(MUSTACHE, (whole, inner, offset) => {
48
+ const path = inner.replace(/\\_/g, '_').trim();
49
+ const item = { from: whole, to: `\\field{${path}}`, line: lineAt(before, offset) };
50
+ if (!(0, path_1.isPath)(path)) {
51
+ skipped.push(item);
52
+ return whole;
53
+ }
54
+ converted.push(item);
55
+ return item.to;
56
+ });
57
+ return { tex: out, converted, skipped };
58
+ }
59
+ /** Make sure a document loads latex-kit.sty, right before \begin{document}. */
60
+ function ensureLatexKitPackage(tex) {
61
+ if (/\\usepackage\s*(?:\[[^\]]*\])?\s*\{[^}]*\blatex-kit\b[^}]*\}/.test(tex))
62
+ return tex;
63
+ const at = tex.indexOf('\\begin{document}');
64
+ if (at === -1)
65
+ return tex;
66
+ return `${tex.slice(0, at)}\\usepackage{latex-kit}\n${tex.slice(at)}`;
67
+ }
package/compile.d.ts ADDED
@@ -0,0 +1,74 @@
1
+ import { Expr } from './condition';
2
+ import { Diagnostic, Location } from './diagnostics';
3
+ import { FieldSpec } from './filters';
4
+ /**
5
+ * The template language's macros and how many {…} arguments each takes.
6
+ * Bare names keep templates readable; \snippet (not \partial, which is the
7
+ * math ∂) and \clauseref (not \ref) avoid LaTeX's own commands. \clause
8
+ * inserts a numbered clause from the clause library; \clauseref prints its number.
9
+ */
10
+ export declare const MACROS: {
11
+ readonly field: 1;
12
+ readonly raw: 1;
13
+ readonly when: 2;
14
+ readonly otherwise: 1;
15
+ readonly each: 3;
16
+ readonly sep: 1;
17
+ readonly snippet: 1;
18
+ readonly docid: 0;
19
+ readonly clause: 1;
20
+ readonly clauseref: 1;
21
+ };
22
+ export type MacroName = keyof typeof MACROS;
23
+ export type Node = {
24
+ kind: 'text';
25
+ text: string;
26
+ } | {
27
+ kind: 'field';
28
+ spec: FieldSpec;
29
+ raw: boolean;
30
+ source: string;
31
+ loc: Location;
32
+ } | {
33
+ kind: 'when';
34
+ cond: Expr;
35
+ source: string;
36
+ then: Node[];
37
+ else?: Node[];
38
+ loc: Location;
39
+ } | {
40
+ kind: 'each';
41
+ path: string;
42
+ name: string;
43
+ body: Node[];
44
+ loc: Location;
45
+ } | {
46
+ kind: 'sep';
47
+ body: Node[];
48
+ loc: Location;
49
+ } | {
50
+ kind: 'snippet';
51
+ name: string;
52
+ loc: Location;
53
+ } | {
54
+ kind: 'docid';
55
+ loc: Location;
56
+ } | {
57
+ kind: 'clause';
58
+ id: string;
59
+ loc: Location;
60
+ } | {
61
+ kind: 'clauseref';
62
+ id: string;
63
+ loc: Location;
64
+ };
65
+ export interface CompiledTemplate {
66
+ file: string;
67
+ text: string;
68
+ nodes: Node[];
69
+ /** Syntax problems found while compiling. */
70
+ diagnostics: Diagnostic[];
71
+ }
72
+ /** `parts/header`, `nda/confidentiality`: relative, no `..`, no empty segments. */
73
+ export declare function isRelativeName(name: string): boolean;
74
+ export declare function compileTemplate(text: string, file: string): CompiledTemplate;