@latex-kit/schema 0.0.0-stage → 0.2.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/LICENSE +23 -0
- package/README.md +106 -2
- package/docid.d.ts +19 -0
- package/docid.js +63 -0
- package/esm/docid.d.ts +19 -0
- package/esm/docid.js +57 -0
- package/esm/index.d.ts +7 -0
- package/esm/index.js +7 -0
- package/esm/load.d.ts +9 -0
- package/esm/load.js +56 -0
- package/esm/record.d.ts +25 -0
- package/esm/record.js +31 -0
- package/esm/ref.d.ts +26 -0
- package/esm/ref.js +79 -0
- package/esm/schema.d.ts +36 -0
- package/esm/schema.js +55 -0
- package/esm/types.d.ts +88 -0
- package/esm/types.js +49 -0
- package/index.d.ts +7 -0
- package/index.js +25 -0
- package/load.d.ts +9 -0
- package/load.js +62 -0
- package/package.json +46 -4
- package/record.d.ts +25 -0
- package/record.js +36 -0
- package/ref.d.ts +26 -0
- package/ref.js +87 -0
- package/schema.d.ts +36 -0
- package/schema.js +63 -0
- package/types.d.ts +88 -0
- package/types.js +52 -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,107 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @latex-kit/schema
|
|
2
2
|
|
|
3
|
-
|
|
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/schema">
|
|
15
|
+
<img height="20" src="https://img.shields.io/npm/v/@latex-kit/schema.svg"/>
|
|
16
|
+
</a>
|
|
17
|
+
</p>
|
|
18
|
+
|
|
19
|
+
<p align="center">Typed data for latex-kit documents: zod schemas, shared types, references and document IDs.</p>
|
|
20
|
+
|
|
21
|
+
## Installation
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
npm install @latex-kit/schema
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Everything here is also exported from `latex-kit`, so a project usually
|
|
28
|
+
imports from there.
|
|
29
|
+
|
|
30
|
+
## Schemas
|
|
31
|
+
|
|
32
|
+
Each template can have a `schema.ts` next to its `template.tex`. The default
|
|
33
|
+
export is a zod schema for the document's data; `meta` is optional.
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
// templates/nda/schema.ts
|
|
37
|
+
import { ISODate, Party, z } from 'latex-kit';
|
|
38
|
+
|
|
39
|
+
export const meta = { docIdPrefix: 'NDA' };
|
|
40
|
+
|
|
41
|
+
export default z.object({
|
|
42
|
+
effectiveDate: ISODate,
|
|
43
|
+
discloser: Party,
|
|
44
|
+
recipient: Party,
|
|
45
|
+
termMonths: z.number().int().positive(),
|
|
46
|
+
mutual: z.boolean().default(true),
|
|
47
|
+
});
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Shared types: `ISODate`, `Money`, `Address`, `Signer`, `Person`,
|
|
51
|
+
`Organization`, `Party`, `Localized` (`{ en: "…", ja: "…" }`).
|
|
52
|
+
|
|
53
|
+
## Records and references
|
|
54
|
+
|
|
55
|
+
A document record names its template and holds the data. JSON, YAML,
|
|
56
|
+
TypeScript and JavaScript all work.
|
|
57
|
+
|
|
58
|
+
```json
|
|
59
|
+
{
|
|
60
|
+
"template": "nda",
|
|
61
|
+
"docId": "NDA-20261125-8K2M4Q7Z",
|
|
62
|
+
"locale": "en-US",
|
|
63
|
+
"data": {
|
|
64
|
+
"effectiveDate": "2026-11-25",
|
|
65
|
+
"discloser": { "$ref": "orgs/example-widgets" },
|
|
66
|
+
"recipient": { "$ref": "orgs/placeholder-labs" },
|
|
67
|
+
"termMonths": 24
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
`{ "$ref": "orgs/example-widgets" }` (or `ref('orgs/example-widgets')` in
|
|
73
|
+
TypeScript) is replaced by `data/orgs/example-widgets.json|yaml|ts`, so a
|
|
74
|
+
company or person is written once and used everywhere. References resolve
|
|
75
|
+
recursively; cycles and paths outside `data/` are errors.
|
|
76
|
+
|
|
77
|
+
## Document IDs
|
|
78
|
+
|
|
79
|
+
`mintDocId({ prefix, epoch })` makes `NDA-20261125-8K2M4Q7Z` (40 random
|
|
80
|
+
bits). latex-kit mints one on a document's first successful final build and
|
|
81
|
+
writes it into the record (JSON or YAML; TypeScript records are never
|
|
82
|
+
edited: you are told the line to add). Re-renders reuse it, and
|
|
83
|
+
`latex-kit check` fails if two records share one.
|
|
84
|
+
|
|
85
|
+
## API
|
|
86
|
+
|
|
87
|
+
| Function | |
|
|
88
|
+
|---|---|
|
|
89
|
+
| `loadFile(file)` | JSON, YAML, or a TS/JS module's default export |
|
|
90
|
+
| `resolveRefs(value, { dataDir })` | Replace every `$ref`; returns the files read |
|
|
91
|
+
| `loadDocument(file, { dataDir })` | Read and check a record, resolve its references |
|
|
92
|
+
| `loadTemplateSchema(file)` | `{ schema, meta }` from a `schema.ts` |
|
|
93
|
+
| `validate(schema, value)` | `{ ok, value }` or `{ ok: false, issues: [{ path, message }] }` |
|
|
94
|
+
| `toJsonSchema(schema)` | JSON Schema of the data as written in records |
|
|
95
|
+
| `documentJsonSchema(name, json)` | Schema for a whole record, for editor autocomplete |
|
|
96
|
+
| `generateTypes(name, json)` | TypeScript declarations (via schema-typescript) |
|
|
97
|
+
| `mintDocId`, `writeDocId` | Create and store document IDs |
|
|
98
|
+
|
|
99
|
+
## Credits
|
|
100
|
+
|
|
101
|
+
**🛠 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).**
|
|
102
|
+
|
|
103
|
+
## Disclaimer
|
|
104
|
+
|
|
105
|
+
AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
|
|
106
|
+
|
|
107
|
+
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/docid.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A new document ID: `PREFIX-YYYYMMDD-XXXXXXXX` (8 random Crockford base-32
|
|
3
|
+
* characters, 40 bits). Minted once, then stored on the record so every
|
|
4
|
+
* re-render reuses it.
|
|
5
|
+
*/
|
|
6
|
+
export declare function mintDocId(options: {
|
|
7
|
+
prefix: string;
|
|
8
|
+
epoch: number;
|
|
9
|
+
random?: (n: number) => Buffer;
|
|
10
|
+
}): string;
|
|
11
|
+
export declare class DocIdWriteError extends Error {
|
|
12
|
+
name: string;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Store a minted ID in a JSON or YAML record, right after `template`.
|
|
16
|
+
* TypeScript/JavaScript records are code, so they are never rewritten: the
|
|
17
|
+
* error tells you the line to add.
|
|
18
|
+
*/
|
|
19
|
+
export declare function writeDocId(file: string, docId: string): void;
|
package/docid.js
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DocIdWriteError = void 0;
|
|
4
|
+
exports.mintDocId = mintDocId;
|
|
5
|
+
exports.writeDocId = writeDocId;
|
|
6
|
+
const crypto_1 = require("crypto");
|
|
7
|
+
const fs_1 = require("fs");
|
|
8
|
+
const path_1 = require("path");
|
|
9
|
+
const yaml_1 = require("yaml");
|
|
10
|
+
const CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
|
|
11
|
+
/**
|
|
12
|
+
* A new document ID: `PREFIX-YYYYMMDD-XXXXXXXX` (8 random Crockford base-32
|
|
13
|
+
* characters, 40 bits). Minted once, then stored on the record so every
|
|
14
|
+
* re-render reuses it.
|
|
15
|
+
*/
|
|
16
|
+
function mintDocId(options) {
|
|
17
|
+
const prefix = options.prefix.toUpperCase().replace(/[^A-Z0-9]+/g, '-').replace(/^-|-$/g, '') || 'DOC';
|
|
18
|
+
const date = new Date(options.epoch * 1000).toISOString().slice(0, 10).replace(/-/g, '');
|
|
19
|
+
const bytes = (options.random ?? crypto_1.randomBytes)(8);
|
|
20
|
+
let suffix = '';
|
|
21
|
+
for (let i = 0; i < 8; i++)
|
|
22
|
+
suffix += CROCKFORD[bytes[i] & 31];
|
|
23
|
+
return `${prefix}-${date}-${suffix}`;
|
|
24
|
+
}
|
|
25
|
+
class DocIdWriteError extends Error {
|
|
26
|
+
name = 'DocIdWriteError';
|
|
27
|
+
}
|
|
28
|
+
exports.DocIdWriteError = DocIdWriteError;
|
|
29
|
+
/**
|
|
30
|
+
* Store a minted ID in a JSON or YAML record, right after `template`.
|
|
31
|
+
* TypeScript/JavaScript records are code, so they are never rewritten: the
|
|
32
|
+
* error tells you the line to add.
|
|
33
|
+
*/
|
|
34
|
+
function writeDocId(file, docId) {
|
|
35
|
+
const ext = (0, path_1.extname)(file).toLowerCase();
|
|
36
|
+
const text = (0, fs_1.readFileSync)(file, 'utf8');
|
|
37
|
+
if (ext === '.json') {
|
|
38
|
+
const obj = JSON.parse(text);
|
|
39
|
+
const indent = /\n([ \t]+)"/.exec(text)?.[1] ?? ' ';
|
|
40
|
+
const out = {};
|
|
41
|
+
let placed = false;
|
|
42
|
+
for (const [k, v] of Object.entries(obj)) {
|
|
43
|
+
if (k === 'docId')
|
|
44
|
+
continue;
|
|
45
|
+
out[k] = v;
|
|
46
|
+
if (k === 'template') {
|
|
47
|
+
out.docId = docId;
|
|
48
|
+
placed = true;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
if (!placed)
|
|
52
|
+
out.docId = docId;
|
|
53
|
+
(0, fs_1.writeFileSync)(file, JSON.stringify(out, null, indent) + '\n');
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
if (ext === '.yaml' || ext === '.yml') {
|
|
57
|
+
const doc = (0, yaml_1.parseDocument)(text);
|
|
58
|
+
doc.set('docId', docId);
|
|
59
|
+
(0, fs_1.writeFileSync)(file, doc.toString());
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
throw new DocIdWriteError(`${file} is code, so latex-kit will not edit it. Add this line to the record: docId: '${docId}'`);
|
|
63
|
+
}
|
package/esm/docid.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A new document ID: `PREFIX-YYYYMMDD-XXXXXXXX` (8 random Crockford base-32
|
|
3
|
+
* characters, 40 bits). Minted once, then stored on the record so every
|
|
4
|
+
* re-render reuses it.
|
|
5
|
+
*/
|
|
6
|
+
export declare function mintDocId(options: {
|
|
7
|
+
prefix: string;
|
|
8
|
+
epoch: number;
|
|
9
|
+
random?: (n: number) => Buffer;
|
|
10
|
+
}): string;
|
|
11
|
+
export declare class DocIdWriteError extends Error {
|
|
12
|
+
name: string;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Store a minted ID in a JSON or YAML record, right after `template`.
|
|
16
|
+
* TypeScript/JavaScript records are code, so they are never rewritten: the
|
|
17
|
+
* error tells you the line to add.
|
|
18
|
+
*/
|
|
19
|
+
export declare function writeDocId(file: string, docId: string): void;
|
package/esm/docid.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { randomBytes } from 'crypto';
|
|
2
|
+
import { readFileSync, writeFileSync } from 'fs';
|
|
3
|
+
import { extname } from 'path';
|
|
4
|
+
import { parseDocument } from 'yaml';
|
|
5
|
+
const CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
|
|
6
|
+
/**
|
|
7
|
+
* A new document ID: `PREFIX-YYYYMMDD-XXXXXXXX` (8 random Crockford base-32
|
|
8
|
+
* characters, 40 bits). Minted once, then stored on the record so every
|
|
9
|
+
* re-render reuses it.
|
|
10
|
+
*/
|
|
11
|
+
export function mintDocId(options) {
|
|
12
|
+
const prefix = options.prefix.toUpperCase().replace(/[^A-Z0-9]+/g, '-').replace(/^-|-$/g, '') || 'DOC';
|
|
13
|
+
const date = new Date(options.epoch * 1000).toISOString().slice(0, 10).replace(/-/g, '');
|
|
14
|
+
const bytes = (options.random ?? randomBytes)(8);
|
|
15
|
+
let suffix = '';
|
|
16
|
+
for (let i = 0; i < 8; i++)
|
|
17
|
+
suffix += CROCKFORD[bytes[i] & 31];
|
|
18
|
+
return `${prefix}-${date}-${suffix}`;
|
|
19
|
+
}
|
|
20
|
+
export class DocIdWriteError extends Error {
|
|
21
|
+
name = 'DocIdWriteError';
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Store a minted ID in a JSON or YAML record, right after `template`.
|
|
25
|
+
* TypeScript/JavaScript records are code, so they are never rewritten: the
|
|
26
|
+
* error tells you the line to add.
|
|
27
|
+
*/
|
|
28
|
+
export function writeDocId(file, docId) {
|
|
29
|
+
const ext = extname(file).toLowerCase();
|
|
30
|
+
const text = readFileSync(file, 'utf8');
|
|
31
|
+
if (ext === '.json') {
|
|
32
|
+
const obj = JSON.parse(text);
|
|
33
|
+
const indent = /\n([ \t]+)"/.exec(text)?.[1] ?? ' ';
|
|
34
|
+
const out = {};
|
|
35
|
+
let placed = false;
|
|
36
|
+
for (const [k, v] of Object.entries(obj)) {
|
|
37
|
+
if (k === 'docId')
|
|
38
|
+
continue;
|
|
39
|
+
out[k] = v;
|
|
40
|
+
if (k === 'template') {
|
|
41
|
+
out.docId = docId;
|
|
42
|
+
placed = true;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
if (!placed)
|
|
46
|
+
out.docId = docId;
|
|
47
|
+
writeFileSync(file, JSON.stringify(out, null, indent) + '\n');
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
if (ext === '.yaml' || ext === '.yml') {
|
|
51
|
+
const doc = parseDocument(text);
|
|
52
|
+
doc.set('docId', docId);
|
|
53
|
+
writeFileSync(file, doc.toString());
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
throw new DocIdWriteError(`${file} is code, so latex-kit will not edit it. Add this line to the record: docId: '${docId}'`);
|
|
57
|
+
}
|
package/esm/index.d.ts
ADDED
package/esm/index.js
ADDED
package/esm/load.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export declare const DATA_EXTENSIONS: string[];
|
|
2
|
+
export declare class LoadError extends Error {
|
|
3
|
+
readonly file: string;
|
|
4
|
+
constructor(message: string, file: string);
|
|
5
|
+
}
|
|
6
|
+
/** Load a TypeScript or JavaScript module and return all its exports. */
|
|
7
|
+
export declare function loadModule(file: string): Promise<Record<string, unknown>>;
|
|
8
|
+
/** Load a data file: JSON, YAML, or the default export of a TS/JS module. */
|
|
9
|
+
export declare function loadFile(file: string): Promise<unknown>;
|
package/esm/load.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { readFileSync } from 'fs';
|
|
2
|
+
import { createJiti } from 'jiti';
|
|
3
|
+
import { extname, join } from 'path';
|
|
4
|
+
import { parse as parseYaml } from 'yaml';
|
|
5
|
+
export const DATA_EXTENSIONS = ['.json', '.yaml', '.yml', '.ts', '.mts', '.cts', '.js', '.mjs', '.cjs'];
|
|
6
|
+
const MODULE_EXTENSIONS = ['.ts', '.mts', '.cts', '.js', '.mjs', '.cjs'];
|
|
7
|
+
export class LoadError extends Error {
|
|
8
|
+
file;
|
|
9
|
+
constructor(message, file) {
|
|
10
|
+
super(message);
|
|
11
|
+
this.file = file;
|
|
12
|
+
this.name = 'LoadError';
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
let jiti = null;
|
|
16
|
+
function loader() {
|
|
17
|
+
// fsCache off: never write a transpile cache into the user's project
|
|
18
|
+
jiti ??= createJiti(join(process.cwd(), 'latex-kit.js'), { fsCache: false, moduleCache: false, interopDefault: false });
|
|
19
|
+
return jiti;
|
|
20
|
+
}
|
|
21
|
+
/** Load a TypeScript or JavaScript module and return all its exports. */
|
|
22
|
+
export async function loadModule(file) {
|
|
23
|
+
try {
|
|
24
|
+
return (await loader().import(file));
|
|
25
|
+
}
|
|
26
|
+
catch (e) {
|
|
27
|
+
throw new LoadError(`could not load ${file}: ${e.message}`, file);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
/** Load a data file: JSON, YAML, or the default export of a TS/JS module. */
|
|
31
|
+
export async function loadFile(file) {
|
|
32
|
+
const ext = extname(file).toLowerCase();
|
|
33
|
+
if (MODULE_EXTENSIONS.includes(ext)) {
|
|
34
|
+
const mod = await loadModule(file);
|
|
35
|
+
if (!('default' in mod))
|
|
36
|
+
throw new LoadError(`${file} has no default export`, file);
|
|
37
|
+
return mod.default;
|
|
38
|
+
}
|
|
39
|
+
let text;
|
|
40
|
+
try {
|
|
41
|
+
text = readFileSync(file, 'utf8');
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
throw new LoadError(`cannot read ${file}`, file);
|
|
45
|
+
}
|
|
46
|
+
try {
|
|
47
|
+
if (ext === '.json')
|
|
48
|
+
return JSON.parse(text);
|
|
49
|
+
if (ext === '.yaml' || ext === '.yml')
|
|
50
|
+
return parseYaml(text, { prettyErrors: true });
|
|
51
|
+
}
|
|
52
|
+
catch (e) {
|
|
53
|
+
throw new LoadError(`${file}: ${e.message}`, file);
|
|
54
|
+
}
|
|
55
|
+
throw new LoadError(`unsupported data file type ${ext} (use ${DATA_EXTENSIONS.join(', ')})`, file);
|
|
56
|
+
}
|
package/esm/record.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
/** The file that describes one document: which template, its ID, its data. */
|
|
3
|
+
export declare const DocumentRecord: z.ZodObject<{
|
|
4
|
+
$schema: z.ZodOptional<z.ZodString>;
|
|
5
|
+
template: z.ZodString;
|
|
6
|
+
docId: z.ZodOptional<z.ZodString>;
|
|
7
|
+
locale: z.ZodOptional<z.ZodString>;
|
|
8
|
+
data: z.ZodUnknown;
|
|
9
|
+
}, z.core.$strict>;
|
|
10
|
+
export type DocumentRecord = z.infer<typeof DocumentRecord>;
|
|
11
|
+
export interface LoadedDocument {
|
|
12
|
+
file: string;
|
|
13
|
+
record: DocumentRecord;
|
|
14
|
+
/** `data` with every reference resolved. */
|
|
15
|
+
data: unknown;
|
|
16
|
+
/** Shared record files the document read through references. */
|
|
17
|
+
refFiles: string[];
|
|
18
|
+
}
|
|
19
|
+
export declare class RecordError extends Error {
|
|
20
|
+
readonly file: string;
|
|
21
|
+
constructor(message: string, file: string);
|
|
22
|
+
}
|
|
23
|
+
export declare function loadDocument(file: string, options: {
|
|
24
|
+
dataDir: string;
|
|
25
|
+
}): Promise<LoadedDocument>;
|
package/esm/record.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { loadFile } from './load';
|
|
3
|
+
import { resolveRefs } from './ref';
|
|
4
|
+
/** The file that describes one document: which template, its ID, its data. */
|
|
5
|
+
export const DocumentRecord = z
|
|
6
|
+
.object({
|
|
7
|
+
$schema: z.string().optional(),
|
|
8
|
+
template: z.string().min(1),
|
|
9
|
+
docId: z.string().min(1).optional(),
|
|
10
|
+
locale: z.string().optional(),
|
|
11
|
+
data: z.unknown(),
|
|
12
|
+
})
|
|
13
|
+
.strict();
|
|
14
|
+
export class RecordError extends Error {
|
|
15
|
+
file;
|
|
16
|
+
constructor(message, file) {
|
|
17
|
+
super(message);
|
|
18
|
+
this.file = file;
|
|
19
|
+
this.name = 'RecordError';
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
export async function loadDocument(file, options) {
|
|
23
|
+
const raw = await loadFile(file);
|
|
24
|
+
const parsed = DocumentRecord.safeParse(raw);
|
|
25
|
+
if (!parsed.success) {
|
|
26
|
+
const msg = parsed.error.issues.map((i) => `${i.path.join('.') || 'record'}: ${i.message}`).join('; ');
|
|
27
|
+
throw new RecordError(`${file}: not a document record (${msg}). Expected { template, docId?, locale?, data }`, file);
|
|
28
|
+
}
|
|
29
|
+
const { value, files } = await resolveRefs(parsed.data.data ?? {}, { dataDir: options.dataDir });
|
|
30
|
+
return { file, record: parsed.data, data: value, refFiles: files };
|
|
31
|
+
}
|
package/esm/ref.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/** A pointer to a shared record: `{ "$ref": "people/avery" }`. */
|
|
2
|
+
export interface Ref {
|
|
3
|
+
$ref: string;
|
|
4
|
+
}
|
|
5
|
+
/** Point at a shared record in the data folder, e.g. `ref('people/avery')`. */
|
|
6
|
+
export declare function ref(id: string): Ref;
|
|
7
|
+
export declare function isRef(value: unknown): value is Ref;
|
|
8
|
+
export declare class RefError extends Error {
|
|
9
|
+
readonly at: string;
|
|
10
|
+
constructor(message: string, at: string);
|
|
11
|
+
}
|
|
12
|
+
export interface ResolveOptions {
|
|
13
|
+
/** Folder that holds shared records: `<dataDir>/<collection>/<id>.json`. */
|
|
14
|
+
dataDir: string;
|
|
15
|
+
load?: (file: string) => Promise<unknown>;
|
|
16
|
+
}
|
|
17
|
+
/** Find the file for `people/avery` (or `people:avery`). */
|
|
18
|
+
export declare function refFile(id: string, dataDir: string): string | null;
|
|
19
|
+
/**
|
|
20
|
+
* Replace every `{ "$ref": "collection/id" }` with the record it names,
|
|
21
|
+
* recursively. Returns the resolved value and every file it read.
|
|
22
|
+
*/
|
|
23
|
+
export declare function resolveRefs(value: unknown, options: ResolveOptions): Promise<{
|
|
24
|
+
value: unknown;
|
|
25
|
+
files: string[];
|
|
26
|
+
}>;
|
package/esm/ref.js
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { existsSync } from 'fs';
|
|
2
|
+
import { isAbsolute, join, relative, resolve } from 'path';
|
|
3
|
+
import { DATA_EXTENSIONS, loadFile } from './load';
|
|
4
|
+
/** Point at a shared record in the data folder, e.g. `ref('people/avery')`. */
|
|
5
|
+
export function ref(id) {
|
|
6
|
+
return { $ref: id };
|
|
7
|
+
}
|
|
8
|
+
export function isRef(value) {
|
|
9
|
+
return (!!value &&
|
|
10
|
+
typeof value === 'object' &&
|
|
11
|
+
!Array.isArray(value) &&
|
|
12
|
+
Object.keys(value).length === 1 &&
|
|
13
|
+
typeof value.$ref === 'string');
|
|
14
|
+
}
|
|
15
|
+
/** A plain `{}` object, also when it was created in another realm (vm, jest). */
|
|
16
|
+
function isPlainObject(v) {
|
|
17
|
+
if (Object.prototype.toString.call(v) !== '[object Object]')
|
|
18
|
+
return false;
|
|
19
|
+
const proto = Object.getPrototypeOf(v);
|
|
20
|
+
return proto === null || Object.getPrototypeOf(proto) === null;
|
|
21
|
+
}
|
|
22
|
+
export class RefError extends Error {
|
|
23
|
+
at;
|
|
24
|
+
constructor(message, at) {
|
|
25
|
+
super(message);
|
|
26
|
+
this.at = at;
|
|
27
|
+
this.name = 'RefError';
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
/** Find the file for `people/avery` (or `people:avery`). */
|
|
31
|
+
export function refFile(id, dataDir) {
|
|
32
|
+
const norm = id.replace(':', '/');
|
|
33
|
+
if (!/^[A-Za-z0-9_-]+(\/[A-Za-z0-9_.-]+)+$/.test(norm) || norm.split('/').includes('..')) {
|
|
34
|
+
throw new RefError(`invalid reference "${id}" (use collection/id, like people/avery)`, id);
|
|
35
|
+
}
|
|
36
|
+
const base = resolve(dataDir, norm);
|
|
37
|
+
const rel = relative(resolve(dataDir), base);
|
|
38
|
+
if (rel.startsWith('..') || isAbsolute(rel))
|
|
39
|
+
throw new RefError(`reference "${id}" leaves the data folder`, id);
|
|
40
|
+
for (const ext of DATA_EXTENSIONS) {
|
|
41
|
+
if (existsSync(base + ext))
|
|
42
|
+
return base + ext;
|
|
43
|
+
}
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Replace every `{ "$ref": "collection/id" }` with the record it names,
|
|
48
|
+
* recursively. Returns the resolved value and every file it read.
|
|
49
|
+
*/
|
|
50
|
+
export async function resolveRefs(value, options) {
|
|
51
|
+
const load = options.load ?? loadFile;
|
|
52
|
+
const files = new Set();
|
|
53
|
+
const cache = new Map();
|
|
54
|
+
const walk = async (v, path, stack) => {
|
|
55
|
+
if (isRef(v)) {
|
|
56
|
+
const id = v.$ref.replace(':', '/');
|
|
57
|
+
if (stack.includes(id))
|
|
58
|
+
throw new RefError(`reference cycle: ${[...stack, id].join(' → ')}`, path);
|
|
59
|
+
const file = refFile(id, options.dataDir);
|
|
60
|
+
if (!file)
|
|
61
|
+
throw new RefError(`${path}: no record for "${v.$ref}" in ${join(options.dataDir, id)}.{json,yaml,ts,…}`, path);
|
|
62
|
+
files.add(file);
|
|
63
|
+
if (!cache.has(file))
|
|
64
|
+
cache.set(file, await load(file));
|
|
65
|
+
return walk(cache.get(file), path, [...stack, id]);
|
|
66
|
+
}
|
|
67
|
+
if (Array.isArray(v))
|
|
68
|
+
return Promise.all(v.map((x, i) => walk(x, `${path}.${i}`, stack)));
|
|
69
|
+
if (isPlainObject(v)) {
|
|
70
|
+
const out = {};
|
|
71
|
+
for (const [k, x] of Object.entries(v))
|
|
72
|
+
out[k] = await walk(x, path ? `${path}.${k}` : k, stack);
|
|
73
|
+
return out;
|
|
74
|
+
}
|
|
75
|
+
return v;
|
|
76
|
+
};
|
|
77
|
+
const resolved = await walk(value, '', []);
|
|
78
|
+
return { value: resolved, files: [...files] };
|
|
79
|
+
}
|
package/esm/schema.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
export type JsonSchema = Record<string, unknown>;
|
|
3
|
+
/** What a template's schema.ts may export besides its default schema. */
|
|
4
|
+
export interface TemplateMeta {
|
|
5
|
+
/** Prefix for minted document IDs, e.g. "NDA". Default: the template name. */
|
|
6
|
+
docIdPrefix?: string;
|
|
7
|
+
/** Default locale for records that do not set one. */
|
|
8
|
+
locale?: string;
|
|
9
|
+
/** TeX engine for this template. Default: lualatex. */
|
|
10
|
+
engine?: 'lualatex' | 'xelatex' | 'pdflatex';
|
|
11
|
+
title?: string;
|
|
12
|
+
}
|
|
13
|
+
export interface TemplateSchema {
|
|
14
|
+
schema: z.ZodType;
|
|
15
|
+
meta: TemplateMeta;
|
|
16
|
+
}
|
|
17
|
+
export declare function isZodSchema(value: unknown): value is z.ZodType;
|
|
18
|
+
/** Load `templates/<name>/schema.ts`: a default-exported zod schema and optional `meta`. */
|
|
19
|
+
export declare function loadTemplateSchema(file: string): Promise<TemplateSchema>;
|
|
20
|
+
export interface Issue {
|
|
21
|
+
path: string;
|
|
22
|
+
message: string;
|
|
23
|
+
}
|
|
24
|
+
export declare function validate(schema: z.ZodType, value: unknown): {
|
|
25
|
+
ok: true;
|
|
26
|
+
value: unknown;
|
|
27
|
+
} | {
|
|
28
|
+
ok: false;
|
|
29
|
+
issues: Issue[];
|
|
30
|
+
};
|
|
31
|
+
/** JSON Schema of the data, as the record files are written (before defaults/transforms). */
|
|
32
|
+
export declare function toJsonSchema(schema: z.ZodType): JsonSchema;
|
|
33
|
+
/** JSON Schema for a whole document record of one template, for editor autocomplete. */
|
|
34
|
+
export declare function documentJsonSchema(template: string, data: JsonSchema): JsonSchema;
|
|
35
|
+
/** TypeScript declarations for a template's data, named after the template. */
|
|
36
|
+
export declare function generateTypes(name: string, data: JsonSchema): string;
|
package/esm/schema.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { generateTypeScript } from 'schema-typescript';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { loadModule } from './load';
|
|
4
|
+
export function isZodSchema(value) {
|
|
5
|
+
return !!value && typeof value === 'object' && typeof value.safeParse === 'function' && '_zod' in value;
|
|
6
|
+
}
|
|
7
|
+
/** Load `templates/<name>/schema.ts`: a default-exported zod schema and optional `meta`. */
|
|
8
|
+
export async function loadTemplateSchema(file) {
|
|
9
|
+
const mod = await loadModule(file);
|
|
10
|
+
const schema = mod.default;
|
|
11
|
+
if (!isZodSchema(schema)) {
|
|
12
|
+
throw new Error(`${file}: the default export must be a zod schema, e.g. export default z.object({ … })`);
|
|
13
|
+
}
|
|
14
|
+
return { schema, meta: mod.meta ?? {} };
|
|
15
|
+
}
|
|
16
|
+
export function validate(schema, value) {
|
|
17
|
+
const r = schema.safeParse(value);
|
|
18
|
+
if (r.success)
|
|
19
|
+
return { ok: true, value: r.data };
|
|
20
|
+
return {
|
|
21
|
+
ok: false,
|
|
22
|
+
issues: r.error.issues.map((i) => ({ path: i.path.map(String).join('.') || '(root)', message: i.message })),
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
/** JSON Schema of the data, as the record files are written (before defaults/transforms). */
|
|
26
|
+
export function toJsonSchema(schema) {
|
|
27
|
+
return z.toJSONSchema(schema, { io: 'input', unrepresentable: 'any' });
|
|
28
|
+
}
|
|
29
|
+
/** JSON Schema for a whole document record of one template, for editor autocomplete. */
|
|
30
|
+
export function documentJsonSchema(template, data) {
|
|
31
|
+
const { $schema, $defs, ...dataSchema } = data;
|
|
32
|
+
return {
|
|
33
|
+
$schema: $schema ?? 'https://json-schema.org/draft/2020-12/schema',
|
|
34
|
+
title: `${template} document`,
|
|
35
|
+
type: 'object',
|
|
36
|
+
properties: {
|
|
37
|
+
$schema: { type: 'string' },
|
|
38
|
+
template: { const: template },
|
|
39
|
+
docId: { type: 'string', description: 'Minted on the first final build; never reuse one.' },
|
|
40
|
+
locale: { type: 'string', description: 'BCP 47 language tag, e.g. en-US or ja-JP.' },
|
|
41
|
+
data: dataSchema,
|
|
42
|
+
},
|
|
43
|
+
required: ['template', 'data'],
|
|
44
|
+
additionalProperties: false,
|
|
45
|
+
...($defs ? { $defs } : {}),
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
/** TypeScript declarations for a template's data, named after the template. */
|
|
49
|
+
export function generateTypes(name, data) {
|
|
50
|
+
const title = name.replace(/(^|[-_ /])(\w)/g, (_m, _s, c) => c.toUpperCase()) + 'Data';
|
|
51
|
+
return generateTypeScript({ ...data, title }, {
|
|
52
|
+
useSingleQuotes: true,
|
|
53
|
+
strictTypeSafety: true,
|
|
54
|
+
});
|
|
55
|
+
}
|