@latex-kit/template 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esm/clause.js ADDED
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Read a clause file's header: the leading `%` comment lines.
3
+ *
4
+ * % title: Confidentiality
5
+ * % version: 3
6
+ */
7
+ export function parseClauseHeader(text) {
8
+ const meta = {};
9
+ for (const line of text.split('\n')) {
10
+ const t = line.trim();
11
+ if (t === '')
12
+ continue;
13
+ if (!t.startsWith('%'))
14
+ break;
15
+ const m = /^%\s*(title|version)\s*:\s*(.*?)\s*$/i.exec(t);
16
+ if (m)
17
+ meta[m[1].toLowerCase()] = m[2];
18
+ }
19
+ return meta;
20
+ }
21
+ export const clauseLabel = (id) => `clause:${id}`;
@@ -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/esm/codemod.js ADDED
@@ -0,0 +1,62 @@
1
+ import { isPath } from './path';
2
+ /** LEGAL_NAME → legalName, COMPANY → company, already camelCase → unchanged. */
3
+ export function camelSegment(seg) {
4
+ const s = seg.replace(/\\_/g, '_');
5
+ if (!s.includes('_') && s !== s.toUpperCase())
6
+ return s;
7
+ const parts = s.toLowerCase().split('_').filter(Boolean);
8
+ return parts.map((p, i) => (i === 0 ? p : p[0].toUpperCase() + p.slice(1))).join('');
9
+ }
10
+ // @GROUP@FIELD@ with letters, digits and underscores (possibly escaped as \_ by pandoc)
11
+ const LEGACY = /@([A-Za-z](?:[A-Za-z0-9_]|\\_)*)@([A-Za-z](?:[A-Za-z0-9_]|\\_)*)@/g;
12
+ // {{ path }} as typed, or \{\{ path \}\} as pandoc escapes it
13
+ const MUSTACHE = /(?:\{\{|\\\{\\\{)\s*([^{}\\]*(?:\\_[^{}\\]*)*?)\s*(?:\}\}|\\\}\\\})/g;
14
+ function lineAt(text, offset) {
15
+ let n = 1;
16
+ for (let i = 0; i < offset; i++)
17
+ if (text.charCodeAt(i) === 10)
18
+ n++;
19
+ return n;
20
+ }
21
+ /**
22
+ * Turn placeholder tokens from older templates or Word documents into
23
+ * `\field{…}`: `@GROUP@FIELD@` (the legacy generator's tokens) and
24
+ * `{{ path }}` (common in Word/Markdown templates, also after pandoc
25
+ * escaped it). Anything that cannot become a valid path is left alone and
26
+ * reported.
27
+ */
28
+ export function convertPlaceholders(tex) {
29
+ const converted = [];
30
+ const skipped = [];
31
+ let out = tex.replace(LEGACY, (whole, group, field, offset) => {
32
+ const path = `${camelSegment(group)}.${camelSegment(field)}`;
33
+ const item = { from: whole, to: `\\field{${path}}`, line: lineAt(tex, offset) };
34
+ if (!isPath(path)) {
35
+ skipped.push(item);
36
+ return whole;
37
+ }
38
+ converted.push(item);
39
+ return item.to;
40
+ });
41
+ const before = out;
42
+ out = out.replace(MUSTACHE, (whole, inner, offset) => {
43
+ const path = inner.replace(/\\_/g, '_').trim();
44
+ const item = { from: whole, to: `\\field{${path}}`, line: lineAt(before, offset) };
45
+ if (!isPath(path)) {
46
+ skipped.push(item);
47
+ return whole;
48
+ }
49
+ converted.push(item);
50
+ return item.to;
51
+ });
52
+ return { tex: out, converted, skipped };
53
+ }
54
+ /** Make sure a document loads latex-kit.sty, right before \begin{document}. */
55
+ export function ensureLatexKitPackage(tex) {
56
+ if (/\\usepackage\s*(?:\[[^\]]*\])?\s*\{[^}]*\blatex-kit\b[^}]*\}/.test(tex))
57
+ return tex;
58
+ const at = tex.indexOf('\\begin{document}');
59
+ if (at === -1)
60
+ return tex;
61
+ return `${tex.slice(0, at)}\\usepackage{latex-kit}\n${tex.slice(at)}`;
62
+ }
package/esm/compile.d.ts CHANGED
@@ -4,7 +4,10 @@ import { FieldSpec } from './filters';
4
4
  /**
5
5
  * The template language's macros and how many {…} arguments each takes.
6
6
  * Bare names keep templates readable; \snippet (not \partial, which is the
7
- * math ∂) and \clauseref (not \ref) avoid LaTeX's own commands.
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
+ * \signature prints a party's signature block; \component calls a TypeScript
10
+ * component with a value.
8
11
  */
9
12
  export declare const MACROS: {
10
13
  readonly field: 1;
@@ -15,7 +18,10 @@ export declare const MACROS: {
15
18
  readonly sep: 1;
16
19
  readonly snippet: 1;
17
20
  readonly docid: 0;
21
+ readonly clause: 1;
18
22
  readonly clauseref: 1;
23
+ readonly signature: 1;
24
+ readonly component: 2;
19
25
  };
20
26
  export type MacroName = keyof typeof MACROS;
21
27
  export type Node = {
@@ -51,6 +57,23 @@ export type Node = {
51
57
  } | {
52
58
  kind: 'docid';
53
59
  loc: Location;
60
+ } | {
61
+ kind: 'clause';
62
+ id: string;
63
+ loc: Location;
64
+ } | {
65
+ kind: 'clauseref';
66
+ id: string;
67
+ loc: Location;
68
+ } | {
69
+ kind: 'signature';
70
+ path: string;
71
+ loc: Location;
72
+ } | {
73
+ kind: 'component';
74
+ name: string;
75
+ path: string;
76
+ loc: Location;
54
77
  };
55
78
  export interface CompiledTemplate {
56
79
  file: string;
@@ -59,4 +82,6 @@ export interface CompiledTemplate {
59
82
  /** Syntax problems found while compiling. */
60
83
  diagnostics: Diagnostic[];
61
84
  }
85
+ /** `parts/header`, `nda/confidentiality`: relative, no `..`, no empty segments. */
86
+ export declare function isRelativeName(name: string): boolean;
62
87
  export declare function compileTemplate(text: string, file: string): CompiledTemplate;
package/esm/compile.js CHANGED
@@ -6,7 +6,10 @@ import { isName, isPath } from './path';
6
6
  /**
7
7
  * The template language's macros and how many {…} arguments each takes.
8
8
  * Bare names keep templates readable; \snippet (not \partial, which is the
9
- * math ∂) and \clauseref (not \ref) avoid LaTeX's own commands.
9
+ * math ∂) and \clauseref (not \ref) avoid LaTeX's own commands. \clause
10
+ * inserts a numbered clause from the clause library; \clauseref prints its number.
11
+ * \signature prints a party's signature block; \component calls a TypeScript
12
+ * component with a value.
10
13
  */
11
14
  export const MACROS = {
12
15
  field: 1,
@@ -17,11 +20,18 @@ export const MACROS = {
17
20
  sep: 1,
18
21
  snippet: 1,
19
22
  docid: 0,
23
+ clause: 1,
20
24
  clauseref: 1,
25
+ signature: 1,
26
+ component: 2,
21
27
  };
22
28
  const parser = getParser({
23
29
  macros: Object.fromEntries(Object.entries(MACROS).map(([name, n]) => [name, { signature: Array(n).fill('m').join(' ') }])),
24
30
  });
31
+ /** `parts/header`, `nda/confidentiality`: relative, no `..`, no empty segments. */
32
+ export function isRelativeName(name) {
33
+ return /^[A-Za-z0-9_./-]+$/.test(name) && !name.split('/').some((s) => s === '..' || s === '' || s === '.');
34
+ }
25
35
  /** Find our macros with unified-latex, so comments, verbatim and \verb are skipped. */
26
36
  function findMacros(text) {
27
37
  const out = [];
@@ -200,14 +210,18 @@ export function compileTemplate(text, file) {
200
210
  pos = macroEnd;
201
211
  break;
202
212
  }
203
- case 'snippet': {
213
+ case 'snippet':
214
+ case 'clause': {
204
215
  const name = argText(0);
205
- if (!/^[A-Za-z0-9_\-./]+$/.test(name) || name.split('/').some((s) => s === '..' || s === '')) {
206
- diagnostics.push(diag('error', `\\snippet{${name}}: use a relative name like parts/header`, loc));
216
+ if (!isRelativeName(name)) {
217
+ diagnostics.push(diag('error', `\\${occ.name}{${name}}: use a relative name like ${occ.name === 'clause' ? 'nda/confidentiality' : 'parts/header'}`, loc));
207
218
  }
208
- else {
219
+ else if (occ.name === 'snippet') {
209
220
  nodes.push({ kind: 'snippet', name, loc });
210
221
  }
222
+ else {
223
+ nodes.push({ kind: 'clause', id: name, loc });
224
+ }
211
225
  pos = macroEnd;
212
226
  break;
213
227
  }
@@ -217,10 +231,36 @@ export function compileTemplate(text, file) {
217
231
  pos = text.startsWith('{}', macroEnd) ? macroEnd + 2 : macroEnd;
218
232
  break;
219
233
  }
220
- case 'clauseref':
221
- diagnostics.push(diag('error', '\\clauseref is reserved for the clause library, which is not available yet', loc));
234
+ case 'signature': {
235
+ const path = argText(0);
236
+ if (!isPath(path))
237
+ diagnostics.push(diag('error', `\\signature{${path}}: expected the path of a party, like discloser`, loc));
238
+ else
239
+ nodes.push({ kind: 'signature', path, loc });
240
+ pos = macroEnd;
241
+ break;
242
+ }
243
+ case 'component': {
244
+ const name = argText(0);
245
+ const path = argText(1);
246
+ if (!isRelativeName(name))
247
+ diagnostics.push(diag('error', `\\component{${name}}: use a name like line-items or tables/fees`, loc));
248
+ else if (path !== '' && !isPath(path))
249
+ diagnostics.push(diag('error', `\\component{${name}}{${path}}: invalid path (leave it empty for the whole record)`, loc));
250
+ else
251
+ nodes.push({ kind: 'component', name, path, loc });
222
252
  pos = macroEnd;
223
253
  break;
254
+ }
255
+ case 'clauseref': {
256
+ const id = argText(0);
257
+ if (!isRelativeName(id))
258
+ diagnostics.push(diag('error', `\\clauseref{${id}}: use the clause's name, like nda/confidentiality`, loc));
259
+ else
260
+ nodes.push({ kind: 'clauseref', id, loc });
261
+ pos = macroEnd;
262
+ break;
263
+ }
224
264
  }
225
265
  }
226
266
  catch (e) {
@@ -0,0 +1,29 @@
1
+ import { RawLatex } from '@latex-kit/escape';
2
+ /** What a component gets besides its value. */
3
+ export interface ComponentContext {
4
+ variant: 'draft' | 'blank' | 'final' | 'signed';
5
+ locale: string;
6
+ docId?: string;
7
+ template?: string;
8
+ /** The whole record's data. */
9
+ data: unknown;
10
+ /** The path the template passed (`\component{name}{path}`); '' for the whole record. */
11
+ path: string;
12
+ /**
13
+ * Format a value with the template filters, as `\field` does:
14
+ * `format(1200, 'money:USD')`, `format(d, 'date:long')`. Returns plain
15
+ * text; put it through `tex` (or escapeLatex) like any other value.
16
+ */
17
+ format(value: unknown, filters: string): string;
18
+ /** The signature block `\signature` prints for a party. */
19
+ signature(party: unknown, path?: string): RawLatex;
20
+ /** A red "missing" marker in drafts; an error in final and signed builds. */
21
+ missing(what: string): RawLatex;
22
+ }
23
+ /**
24
+ * A component turns a value into LaTeX: `\component{name}{path}` in a
25
+ * template calls it with the value at `path`. Return `tex`-tagged LaTeX
26
+ * (inserted as is) or a plain string (escaped).
27
+ */
28
+ export type Component = (value: unknown, ctx: ComponentContext) => RawLatex | string | number | null | undefined;
29
+ export declare function isRawLatex(v: unknown): v is RawLatex;
@@ -0,0 +1,5 @@
1
+ import { RawLatex } from '@latex-kit/escape';
2
+ export function isRawLatex(v) {
3
+ return (v instanceof RawLatex ||
4
+ (!!v && typeof v === 'object' && v.constructor?.name === 'RawLatex' && typeof v.value === 'string'));
5
+ }
package/esm/evaluate.d.ts CHANGED
@@ -1,6 +1,9 @@
1
+ import { ClauseUse, LoadedClause } from './clause';
1
2
  import { CompiledTemplate } from './compile';
3
+ import { Component } from './component';
2
4
  import { truthy } from './condition';
3
5
  import { Diagnostic } from './diagnostics';
6
+ import { SignerInfo } from './signature';
4
7
  export type Variant = 'draft' | 'blank' | 'final' | 'signed';
5
8
  export declare const VARIANTS: Variant[];
6
9
  export interface EvaluateOptions {
@@ -17,6 +20,20 @@ export interface EvaluateOptions {
17
20
  allowMissing?: boolean;
18
21
  /** Resolve \snippet{name} from the file that uses it. */
19
22
  loadSnippet?: (name: string, from: string) => CompiledTemplate | null;
23
+ /** Resolve \clause{id} from the clause library. */
24
+ loadClause?: (id: string) => LoadedClause | null;
25
+ /** Components for \component{name}{path}, by name. */
26
+ components?: Record<string, Component>;
27
+ /**
28
+ * Signed builds: a local signature image for a signer, as a path TeX can
29
+ * read, or null to print `/s/ Name`.
30
+ */
31
+ signatureImage?: (signer: SignerInfo) => string | null;
32
+ /** The record's `signed` map: signing date (and image) per party path. */
33
+ signed?: Record<string, {
34
+ date?: string;
35
+ signature?: string;
36
+ }>;
20
37
  }
21
38
  export interface FieldUse {
22
39
  path: string;
@@ -30,6 +47,10 @@ export interface EvaluateResult {
30
47
  diagnostics: Diagnostic[];
31
48
  /** Every field that was filled (or found missing), in document order. */
32
49
  fields: FieldUse[];
50
+ /** Library clauses placed in the document, in order, with versions. */
51
+ clauses: ClauseUse[];
52
+ /** Components the document called, by name. */
53
+ components: string[];
33
54
  }
34
55
  export declare function evaluateTemplate(template: CompiledTemplate, options: EvaluateOptions): EvaluateResult;
35
56
  export { truthy };
package/esm/evaluate.js CHANGED
@@ -1,8 +1,11 @@
1
1
  import { escapeLatex, LatexEscapeError, RawLatex } from '@latex-kit/escape';
2
+ import { clauseLabel } from './clause';
3
+ import { isRawLatex } from './component';
2
4
  import { evaluateCondition, truthy } from './condition';
3
5
  import { diag } from './diagnostics';
4
- import { applyFilters, FilterError, isMissing } from './filters';
6
+ import { applyFilters, FilterError, isMissing, parseFieldSpec } from './filters';
5
7
  import { splitPath } from './path';
8
+ import { signatureBlock, SignatureError } from './signature';
6
9
  export const VARIANTS = ['draft', 'blank', 'final', 'signed'];
7
10
  function own(obj, key) {
8
11
  if (obj === null || typeof obj !== 'object')
@@ -11,9 +14,7 @@ function own(obj, key) {
11
14
  return /^\d+$/.test(key) ? obj[Number(key)] : undefined;
12
15
  return Object.prototype.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
13
16
  }
14
- function isRaw(v) {
15
- return v instanceof RawLatex || (!!v && typeof v === 'object' && v.constructor?.name === 'RawLatex' && typeof v.value === 'string');
16
- }
17
+ const isRaw = isRawLatex;
17
18
  export function evaluateTemplate(template, options) {
18
19
  const variant = options.variant;
19
20
  const locale = options.locale ?? 'en-US';
@@ -22,6 +23,10 @@ export function evaluateTemplate(template, options) {
22
23
  const fields = [];
23
24
  const frames = [];
24
25
  const stack = [template.file];
26
+ const clauses = [];
27
+ const refs = [];
28
+ const usedComponents = new Set();
29
+ const signedPaths = new Set();
25
30
  const lookup = (path) => {
26
31
  const [head, ...rest] = splitPath(path);
27
32
  let value;
@@ -99,6 +104,51 @@ export function evaluateTemplate(template, options) {
99
104
  diagnostics.push(diag('error', `${what} is ${kind}`, loc));
100
105
  return '';
101
106
  };
107
+ const signature = (value, path, loc) => {
108
+ try {
109
+ signedPaths.add(path);
110
+ const signing = options.signed && Object.prototype.hasOwnProperty.call(options.signed, path) ? options.signed[path] : undefined;
111
+ return signatureBlock(value, { variant, locale, path, signing, missing: (what) => missing(what, loc), signatureImage: options.signatureImage });
112
+ }
113
+ catch (e) {
114
+ if (!(e instanceof SignatureError || e instanceof LatexEscapeError))
115
+ throw e;
116
+ diagnostics.push(diag('error', `\\signature{${path}}: ${e.message}`, loc));
117
+ return '';
118
+ }
119
+ };
120
+ /** Call a component (or a TypeScript clause) and turn its result into LaTeX. */
121
+ const callComponent = (fn, value, path, what, loc) => {
122
+ const ctx = {
123
+ variant,
124
+ locale,
125
+ docId: options.docId,
126
+ template: options.template,
127
+ data: options.data,
128
+ path,
129
+ format: (v, filters) => {
130
+ const spec = parseFieldSpec(`value|${filters}`);
131
+ return String(applyFilters(v, spec.filters, { locale }).value ?? '');
132
+ },
133
+ signature: (party, p = path) => new RawLatex(signature(party, p, loc)),
134
+ missing: (w) => new RawLatex(missing(w, loc)),
135
+ };
136
+ try {
137
+ const r = fn(value, ctx);
138
+ if (r === null || r === undefined)
139
+ return '';
140
+ if (isRaw(r))
141
+ return r.value;
142
+ if (typeof r === 'string' || typeof r === 'number')
143
+ return escapeLatex(String(r));
144
+ diagnostics.push(diag('error', `${what} returned ${typeof r}; return tex\`…\` or a string`, loc));
145
+ return '';
146
+ }
147
+ catch (e) {
148
+ diagnostics.push(diag('error', `${what}: ${e.message}`, loc));
149
+ return '';
150
+ }
151
+ };
102
152
  const render = (nodes) => {
103
153
  let out = '';
104
154
  for (const node of nodes) {
@@ -189,11 +239,71 @@ export function evaluateTemplate(template, options) {
189
239
  stack.pop();
190
240
  break;
191
241
  }
242
+ case 'clause': {
243
+ const clause = options.loadClause?.(node.id) ?? null;
244
+ if (!clause) {
245
+ diagnostics.push(diag('error', `clause not found: ${node.id}`, node.loc));
246
+ break;
247
+ }
248
+ if (stack.includes(clause.template.file)) {
249
+ diagnostics.push(diag('error', `clause ${node.id} includes itself`, node.loc));
250
+ break;
251
+ }
252
+ if (clauses.some((c) => c.id === node.id)) {
253
+ diagnostics.push(diag('error', `clause ${node.id} is placed twice`, node.loc));
254
+ break;
255
+ }
256
+ clauses.push({ id: node.id, version: clause.version, file: clause.template.file });
257
+ diagnostics.push(...clause.template.diagnostics);
258
+ out += `\\lkclause{${clause.title ? escapeLatex(clause.title) : ''}}{${clauseLabel(node.id)}}`;
259
+ stack.push(clause.template.file);
260
+ out += render(clause.template.nodes);
261
+ if (clause.render)
262
+ out += callComponent(clause.render, options.data, '', `clause ${node.id}`, node.loc);
263
+ stack.pop();
264
+ break;
265
+ }
266
+ case 'clauseref':
267
+ refs.push({ id: node.id, loc: node.loc });
268
+ out += `\\ref{${clauseLabel(node.id)}}`;
269
+ break;
270
+ case 'signature': {
271
+ const value = variant === 'blank' ? undefined : lookup(node.path);
272
+ fields.push({ path: node.path, ...node.loc, missing: variant !== 'blank' && isMissing(value) });
273
+ out += signature(value, node.path, node.loc);
274
+ break;
275
+ }
276
+ case 'component': {
277
+ const fn = options.components?.[node.name];
278
+ if (!fn) {
279
+ const known = Object.keys(options.components ?? {}).sort();
280
+ diagnostics.push(diag('error', `unknown component ${node.name}${known.length ? ` (known: ${known.join(', ')})` : ''}`, node.loc));
281
+ break;
282
+ }
283
+ usedComponents.add(node.name);
284
+ const value = variant === 'blank' ? undefined : node.path ? lookup(node.path) : options.data;
285
+ if (node.path)
286
+ fields.push({ path: node.path, ...node.loc, missing: variant !== 'blank' && isMissing(value) });
287
+ out += callComponent(fn, value, node.path, `\\component{${node.name}}`, node.loc);
288
+ break;
289
+ }
192
290
  }
193
291
  }
194
292
  return out;
195
293
  };
196
294
  const tex = render(template.nodes);
197
- return { tex, diagnostics, fields };
295
+ // a reference to a clause this document does not contain would print "??"
296
+ for (const r of refs) {
297
+ if (!clauses.some((c) => c.id === r.id)) {
298
+ const msg = `\\clauseref{${r.id}}: clause ${r.id} is not in this document`;
299
+ diagnostics.push(diag(allowMissing ? 'warning' : 'error', msg, r.loc));
300
+ }
301
+ }
302
+ for (const key of Object.keys(options.signed ?? {})) {
303
+ if (!signedPaths.has(key)) {
304
+ diagnostics.push(diag('warning', `signed.${key}: the document has no \\signature{${key}}`, { file: template.file, line: 1, column: 1 }));
305
+ }
306
+ }
307
+ return { tex, diagnostics, fields, clauses, components: [...usedComponents].sort() };
198
308
  }
199
309
  export { truthy };
package/esm/index.d.ts CHANGED
@@ -1,5 +1,8 @@
1
1
  export * from './analyze';
2
+ export * from './clause';
3
+ export * from './codemod';
2
4
  export * from './compile';
5
+ export * from './component';
3
6
  export * from './condition';
4
7
  export * from './diagnostics';
5
8
  export * from './document';
@@ -7,4 +10,5 @@ export * from './evaluate';
7
10
  export * from './filters';
8
11
  export * from './jsonschema';
9
12
  export * from './path';
13
+ export * from './signature';
10
14
  export * from './sty';
package/esm/index.js CHANGED
@@ -1,5 +1,8 @@
1
1
  export * from './analyze';
2
+ export * from './clause';
3
+ export * from './codemod';
2
4
  export * from './compile';
5
+ export * from './component';
3
6
  export * from './condition';
4
7
  export * from './diagnostics';
5
8
  export * from './document';
@@ -7,4 +10,5 @@ export * from './evaluate';
7
10
  export * from './filters';
8
11
  export * from './jsonschema';
9
12
  export * from './path';
13
+ export * from './signature';
10
14
  export * from './sty';
@@ -0,0 +1,36 @@
1
+ /** The signer a signature image is looked up for. */
2
+ export interface SignerInfo {
3
+ name: string;
4
+ /** The signer's `signature` field: an image file name in the signatures folder. */
5
+ image?: string;
6
+ }
7
+ export interface SignatureOptions {
8
+ variant: 'draft' | 'blank' | 'final' | 'signed';
9
+ locale: string;
10
+ /** The data path of the party, for blank labels and messages. */
11
+ path: string;
12
+ /** Text for a missing value: a red marker in drafts, an error otherwise. */
13
+ missing: (what: string) => string;
14
+ /** How this party signed, from the record's `signed` map. */
15
+ signing?: {
16
+ date?: string;
17
+ signature?: string;
18
+ };
19
+ /**
20
+ * Signed builds only: a signature image for this signer, as a path TeX can
21
+ * read, or null to print `/s/ Name`.
22
+ */
23
+ signatureImage?: (signer: SignerInfo) => string | null;
24
+ }
25
+ export declare class SignatureError extends Error {
26
+ name: string;
27
+ }
28
+ /**
29
+ * A signature block for a party: `\lksignature{org}{name}{title}{signature}{date}`.
30
+ *
31
+ * A party with a `signer` (or `kind: organization`) is an organization: its
32
+ * name in bold, then the signer's name and title. Anything else signs for
33
+ * itself. The signed variant prints the signer's local signature image when
34
+ * there is one, else `/s/ Name`, and the date from the record's `signed` map.
35
+ */
36
+ export declare function signatureBlock(value: unknown, o: SignatureOptions): string;
@@ -0,0 +1,54 @@
1
+ import { escapeLatex } from '@latex-kit/escape';
2
+ import { FILTERS } from './filters';
3
+ export class SignatureError extends Error {
4
+ name = 'SignatureError';
5
+ }
6
+ const isObject = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
7
+ const text = (v) => (typeof v === 'string' && v.trim() !== '' ? v : undefined);
8
+ /** Image paths must be plain relative names, so they can never inject LaTeX. */
9
+ const SAFE_IMAGE_PATH = /^[A-Za-z0-9_./-]+$/;
10
+ /**
11
+ * A signature block for a party: `\lksignature{org}{name}{title}{signature}{date}`.
12
+ *
13
+ * A party with a `signer` (or `kind: organization`) is an organization: its
14
+ * name in bold, then the signer's name and title. Anything else signs for
15
+ * itself. The signed variant prints the signer's local signature image when
16
+ * there is one, else `/s/ Name`, and the date from the record's `signed` map.
17
+ */
18
+ export function signatureBlock(value, o) {
19
+ const p = o.path;
20
+ if (o.variant === 'blank') {
21
+ return `\\lksignature{\\lkblank{${p}.name}}{\\lkblank{${p}.signer.name}}{\\lkblank{${p}.signer.title}}{}{}`;
22
+ }
23
+ if (value === undefined || value === null)
24
+ return o.missing(p);
25
+ if (!isObject(value))
26
+ throw new SignatureError(`${p} is not a party (expected an object with a name)`);
27
+ const signerObj = isObject(value.signer) ? value.signer : null;
28
+ const isOrg = !!signerObj || value.kind === 'organization';
29
+ const signer = signerObj ?? (isOrg ? null : value);
30
+ const orgName = isOrg ? text(value.name) : undefined;
31
+ const org = isOrg ? (orgName ? escapeLatex(orgName) : o.missing(`${p}.name`)) : '';
32
+ const signerPath = signerObj ? `${p}.signer` : p;
33
+ const name = signer ? text(signer.name) : undefined;
34
+ const nameTex = name ? escapeLatex(name) : o.missing(isOrg && !signer ? `${p}.signer` : `${signerPath}.name`);
35
+ const title = signer ? text(signer.title) : undefined;
36
+ const titleTex = title ? escapeLatex(title) : '';
37
+ let sign = '';
38
+ let date = '';
39
+ if (o.variant === 'signed' && name) {
40
+ const file = o.signatureImage?.({ name, image: text(o.signing?.signature) ?? text(signer?.signature) }) ?? null;
41
+ if (file) {
42
+ if (!SAFE_IMAGE_PATH.test(file))
43
+ throw new SignatureError(`signature image path "${file}" may only use letters, digits, . _ - and /`);
44
+ sign = `\\lksignatureimage{${file}}`;
45
+ }
46
+ else {
47
+ sign = `/s/~${escapeLatex(name)}`;
48
+ }
49
+ const signed = text(o.signing?.date);
50
+ if (signed)
51
+ date = escapeLatex(String(FILTERS.date.apply(signed, 'long', { locale: o.locale }, {})));
52
+ }
53
+ return `\\lksignature{${org}}{${nameTex}}{${titleTex}}{${sign}}{${date}}`;
54
+ }
package/esm/sty.d.ts CHANGED
@@ -3,4 +3,4 @@
3
3
  * every generated document; `latex-kit sty <dir>` writes it for previewing
4
4
  * templates in an editor.
5
5
  */
6
- export declare const LATEX_KIT_STY = "% latex-kit.sty: support for latex-kit templates.\n%\n% Load it in a template with \\usepackage{latex-kit}. Compiled directly, a\n% template previews as a blank form: every \\field becomes a labelled line.\n% When latex-kit renders a document it passes the `rendered` option and the\n% variant (draft, blank, final, signed); the template macros are gone by then.\n%\n% https://github.com/constructive-io/latex-kit (MIT)\n\\NeedsTeXFormat{LaTeX2e}\n\\ProvidesPackage{latex-kit}[2026/11/25 v0.3 latex-kit template support]\n\n\\newif\\iflk@rendered\n\\newif\\iflk@draft\n\\DeclareOption{rendered}{\\lk@renderedtrue}\n\\DeclareOption{draft}{\\lk@drafttrue}\n\\DeclareOption{blank}{}\n\\DeclareOption{final}{}\n\\DeclareOption{signed}{}\n\\ProcessOptions\\relax\n\n\\RequirePackage{xcolor}\n\\definecolor{lkmeta}{gray}{0.55}\n\\providecommand\\lkstamp{}\n\n% A labelled blank line: \\lkblank{party.name}\n\\newlength\\lkblankwidth\n\\setlength\\lkblankwidth{3.5cm}\n\\newcommand\\lkblank[1]{\\leavevmode\\underline{\\makebox[\\lkblankwidth][l]{\\color{lkmeta}\\tiny\\ttfamily\\detokenize{#1}}}}\n\n% A value the data does not have yet (draft builds only).\n\\newcommand\\lkmissing[1]{\\leavevmode{\\color{red}\\fbox{\\scriptsize\\ttfamily missing: \\detokenize{#1}}}}\n\n\\iflk@draft\n \\RequirePackage{draftwatermark}\n \\SetWatermarkText{DRAFT}\n \\SetWatermarkScale{1}\n \\SetWatermarkColor[gray]{0.9}\n \\RequirePackage{eso-pic}\n \\AddToShipoutPictureFG{%\n \\AtPageLowerLeft{\\raisebox{6mm}{\\hspace{10mm}\\color{lkmeta}\\scriptsize\\ttfamily DRAFT \\lkstamp}}}\n\\fi\n\n\\iflk@rendered\\else\n % Previewing the template itself: show its structure.\n \\newcommand\\field[1]{\\lkblank{#1}}\n \\newcommand\\raw[1]{\\lkblank{#1}}\n \\newcommand\\docid{\\lkblank{docid}}\n \\newcommand\\when[2]{{\\color{lkmeta}\\tiny[if \\detokenize{#1}]}#2}\n \\newcommand\\otherwise[1]{{\\color{lkmeta}\\tiny[otherwise]}#1}\n \\newcommand\\each[3]{{\\color{lkmeta}\\tiny[each \\detokenize{#2} in \\detokenize{#1}]}#3}\n \\newcommand\\sep[1]{#1}\n \\newcommand\\snippet[1]{\\InputIfFileExists{#1}{}{\\lkblank{snippet #1}}}\n \\newcommand\\clauseref[1]{\\lkblank{clause #1}}\n\\fi\n\n\\endinput\n";
6
+ export declare const LATEX_KIT_STY = "% latex-kit.sty: support for latex-kit templates.\n%\n% Load it in a template with \\usepackage{latex-kit}. Compiled directly, a\n% template previews as a blank form: every \\field becomes a labelled line.\n% When latex-kit renders a document it passes the `rendered` option and the\n% variant (draft, blank, final, signed); the template macros are gone by then.\n%\n% https://github.com/constructive-io/latex-kit (MIT)\n\\NeedsTeXFormat{LaTeX2e}\n\\ProvidesPackage{latex-kit}[2026/11/25 v0.4 latex-kit template support]\n\n\\newif\\iflk@rendered\n\\newif\\iflk@draft\n\\DeclareOption{rendered}{\\lk@renderedtrue}\n\\DeclareOption{draft}{\\lk@drafttrue}\n\\DeclareOption{blank}{}\n\\DeclareOption{final}{}\n\\DeclareOption{signed}{}\n\\ProcessOptions\\relax\n\n\\RequirePackage{xcolor}\n\\RequirePackage{graphicx}\n% tables from latex-kit components (table(), line items)\n\\RequirePackage{array,tabularx,booktabs}\n\\definecolor{lkmeta}{gray}{0.55}\n\\providecommand\\lkstamp{}\n\n% A labelled blank line: \\lkblank{party.name}\n\\newlength\\lkblankwidth\n\\setlength\\lkblankwidth{3.5cm}\n\\newcommand\\lkblank[1]{\\leavevmode\\underline{\\makebox[\\lkblankwidth][l]{\\color{lkmeta}\\tiny\\ttfamily\\detokenize{#1}}}}\n\n% A clause from the library: \\lkclause{title}{label}. Numbered like a\n% section; with no title, a bold number. Redefine it to change the style.\n\\providecommand\\lkclause[2]{\\ifx\\relax#1\\relax\\par\\refstepcounter{section}\\label{#2}\\noindent\\textbf{\\thesection.}~\\else\\section{#1}\\label{#2}\\fi}\n\n% A signature block: \\lksignature{organization}{name}{title}{signature}{date}.\n% The organization line is left out when empty (a person signing for\n% themselves). The signature sits on the line: an image or /s/ text in signed\n% builds, nothing otherwise. Two blocks fit side by side with \\hfill.\n\\newlength\\lksignaturewidth\n\\setlength\\lksignaturewidth{0.45\\linewidth}\n\\newlength\\lksignatureheight\n\\setlength\\lksignatureheight{2.2em}\n\\providecommand\\lksignatureimage[1]{\\includegraphics[height=\\lksignatureheight,keepaspectratio]{#1}}\n\\providecommand\\lksignature[5]{%\n \\begin{minipage}[t]{\\lksignaturewidth}\\raggedright\\setlength\\parindent{0pt}%\n \\ifx\\relax#1\\relax\\else\\textbf{#1}\\par\\fi\n \\vspace{\\dimexpr\\lksignatureheight+0.4em\\relax}%\n \\rlap{\\smash{\\raisebox{1pt}{#4}}}\\rule{\\linewidth}{0.4pt}\\par\n #2\\par\n \\ifx\\relax#3\\relax\\else#3\\par\\fi\n \\vspace{0.5em}%\n Date:~\\ifx\\relax#5\\relax\\rule{0.55\\linewidth}{0.4pt}\\else#5\\fi\n \\end{minipage}}\n\n% An exhibit: a new page headed \"Exhibit A\", then its title.\n\\newcounter{lkexhibit}\n\\renewcommand\\thelkexhibit{\\Alph{lkexhibit}}\n\\providecommand\\lkexhibit[2]{%\n \\clearpage\\refstepcounter{lkexhibit}\\label{#2}%\n \\begin{center}{\\large\\bfseries Exhibit \\thelkexhibit}\\ifx\\relax#1\\relax\\else\\\\[0.3em]{\\bfseries #1}\\fi\\end{center}\\par}\n\n% A value the data does not have yet (draft builds only).\n\\newcommand\\lkmissing[1]{\\leavevmode{\\color{red}\\fbox{\\scriptsize\\ttfamily missing: \\detokenize{#1}}}}\n\n\\iflk@draft\n \\RequirePackage{draftwatermark}\n \\SetWatermarkText{DRAFT}\n \\SetWatermarkScale{1}\n \\SetWatermarkColor[gray]{0.9}\n \\RequirePackage{eso-pic}\n \\AddToShipoutPictureFG{%\n \\AtPageLowerLeft{\\raisebox{6mm}{\\hspace{10mm}\\color{lkmeta}\\scriptsize\\ttfamily DRAFT \\lkstamp}}}\n\\fi\n\n\\iflk@rendered\\else\n % Previewing the template itself: show its structure.\n \\newcommand\\field[1]{\\lkblank{#1}}\n \\newcommand\\raw[1]{\\lkblank{#1}}\n \\newcommand\\docid{\\lkblank{docid}}\n \\newcommand\\when[2]{{\\color{lkmeta}\\tiny[if \\detokenize{#1}]}#2}\n \\newcommand\\otherwise[1]{{\\color{lkmeta}\\tiny[otherwise]}#1}\n \\newcommand\\each[3]{{\\color{lkmeta}\\tiny[each \\detokenize{#2} in \\detokenize{#1}]}#3}\n \\newcommand\\sep[1]{#1}\n \\newcommand\\snippet[1]{\\InputIfFileExists{#1}{}{\\lkblank{snippet #1}}}\n \\newcommand\\clause[1]{\\par\\lkblank{clause #1}\\par}\n \\newcommand\\clauseref[1]{\\lkblank{ref #1}}\n \\newcommand\\signature[1]{\\lksignature{\\lkblank{#1.name}}{\\lkblank{#1.signer.name}}{\\lkblank{#1.signer.title}}{}{}}\n \\newcommand\\component[2]{\\par\\lkblank{component #1}\\par}\n\\fi\n\n\\endinput\n";