briyah 2.0.17 → 2.0.19
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/dist-sdk/server/src/ai/agent-config.d.ts +4 -0
- package/dist-sdk/server/src/ai/agent-store.service.js +4 -0
- package/dist-sdk/server/src/ai/agent.d.ts +7 -0
- package/dist-sdk/server/src/ai/agent.js +7 -0
- package/dist-sdk/server/src/app/balance.service.js +1 -1
- package/dist-sdk/server/src/app/usage-context.d.ts +19 -1
- package/dist-sdk/server/src/app/usage-context.js +21 -4
- package/dist-sdk/server/src/app.service.d.ts +2 -0
- package/dist-sdk/server/src/app.service.js +2 -0
- package/dist-sdk/server/src/data/query-validation.d.ts +9 -1
- package/dist-sdk/server/src/data/query-validation.js +9 -5
- package/dist-sdk/server/src/data/run-query.d.ts +14 -0
- package/dist-sdk/server/src/data/run-query.js +39 -0
- package/dist-sdk/server/src/documents/document-conversion.d.ts +27 -9
- package/dist-sdk/server/src/documents/document-conversion.js +131 -10
- package/dist-sdk/server/src/documents/html-data.d.ts +49 -0
- package/dist-sdk/server/src/documents/html-data.js +120 -0
- package/dist-sdk/server/src/documents/html-template.d.ts +108 -0
- package/dist-sdk/server/src/documents/html-template.js +332 -0
- package/dist-sdk/server/src/documents/library/document.types.d.ts +64 -0
- package/dist-sdk/server/src/documents/library/document.types.js +6 -0
- package/dist-sdk/server/src/documents/library/html-template-guide.builder.d.ts +13 -0
- package/dist-sdk/server/src/documents/library/html-template-guide.builder.js +185 -0
- package/dist-sdk/server/src/documents/template-mapping.d.ts +203 -0
- package/dist-sdk/server/src/documents/template-mapping.js +452 -0
- package/dist-sdk/server/src/room/room.d.ts +2 -1
- package/dist-sdk/server/src/room/room.js +7 -3
- package/dist-sdk/server/src/sdk/index.d.ts +12 -3
- package/dist-sdk/server/src/sdk/index.js +28 -2
- package/dist-sdk/server/src/tools/core/document.tools.d.ts +22 -0
- package/dist-sdk/server/src/tools/core/document.tools.js +20 -6
- package/dist-sdk/server/src/tools/core/html-template.tools.d.ts +31 -0
- package/dist-sdk/server/src/tools/core/html-template.tools.js +494 -0
- package/dist-sdk/server/src/tools/core/index.js +2 -0
- package/package.json +1 -1
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The data an HTML page carries in `<script type="application/json">` blocks.
|
|
3
|
+
*
|
|
4
|
+
* A modern page often draws everything it shows — charts, tables, slides — from
|
|
5
|
+
* data embedded in it, and shows almost no text of its own. Reading such a page
|
|
6
|
+
* means reading its data (`convertHtml`), and making another like it means
|
|
7
|
+
* replacing its data and keeping its code (`html-template.ts`). Both start here.
|
|
8
|
+
*/
|
|
9
|
+
/** One JSON data block in a page. */
|
|
10
|
+
export interface HtmlDataBlock {
|
|
11
|
+
/** The script's id, or '' when it has none. */
|
|
12
|
+
id: string;
|
|
13
|
+
/** What a person or an agent calls it: the id, or "data block N". */
|
|
14
|
+
label: string;
|
|
15
|
+
/** The script's type attribute, lower-cased. */
|
|
16
|
+
type: string;
|
|
17
|
+
/** Where the block's content starts and ends in the page, so it can be replaced exactly. */
|
|
18
|
+
contentStart: number;
|
|
19
|
+
contentEnd: number;
|
|
20
|
+
/** The content as written. */
|
|
21
|
+
text: string;
|
|
22
|
+
/** The parsed data; undefined when the content is not valid JSON. */
|
|
23
|
+
value?: unknown;
|
|
24
|
+
}
|
|
25
|
+
/** The value of one attribute in a tag's attribute text, or ''. */
|
|
26
|
+
export declare function htmlAttribute(attributes: string, name: string): string;
|
|
27
|
+
/** Whether a script type attribute marks data rather than code. */
|
|
28
|
+
export declare function isDataScriptType(type: string): boolean;
|
|
29
|
+
/** Every non-empty JSON data block in a page, in page order. */
|
|
30
|
+
export declare function findDataBlocks(html: string): HtmlDataBlock[];
|
|
31
|
+
/** Every script in a page that holds code, as attributes and content. */
|
|
32
|
+
export declare function findCodeScripts(html: string): {
|
|
33
|
+
attributes: string;
|
|
34
|
+
body: string;
|
|
35
|
+
}[];
|
|
36
|
+
/** The page with every script removed. */
|
|
37
|
+
export declare function withoutScripts(html: string): string;
|
|
38
|
+
/**
|
|
39
|
+
* JSON laid out for reading and searching: an object's keys one per line, to two
|
|
40
|
+
* levels, and a list of records one record per line. A record is never broken
|
|
41
|
+
* across lines, so a chunk holds whole records; and the layout adds little to the
|
|
42
|
+
* size, where fully indented JSON would double it.
|
|
43
|
+
*/
|
|
44
|
+
export declare function readableJson(value: unknown, depth?: number): string;
|
|
45
|
+
/**
|
|
46
|
+
* The shape of some JSON in one line: `{ meta: {client, title, …}, claims: [131 × {id, n, …}] }`.
|
|
47
|
+
* Top-level keys are described; anything deeper is named by its keys.
|
|
48
|
+
*/
|
|
49
|
+
export declare function describeShape(value: unknown, depth?: number): string;
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* The data an HTML page carries in `<script type="application/json">` blocks.
|
|
4
|
+
*
|
|
5
|
+
* A modern page often draws everything it shows — charts, tables, slides — from
|
|
6
|
+
* data embedded in it, and shows almost no text of its own. Reading such a page
|
|
7
|
+
* means reading its data (`convertHtml`), and making another like it means
|
|
8
|
+
* replacing its data and keeping its code (`html-template.ts`). Both start here.
|
|
9
|
+
*/
|
|
10
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
11
|
+
exports.htmlAttribute = htmlAttribute;
|
|
12
|
+
exports.isDataScriptType = isDataScriptType;
|
|
13
|
+
exports.findDataBlocks = findDataBlocks;
|
|
14
|
+
exports.findCodeScripts = findCodeScripts;
|
|
15
|
+
exports.withoutScripts = withoutScripts;
|
|
16
|
+
exports.readableJson = readableJson;
|
|
17
|
+
exports.describeShape = describeShape;
|
|
18
|
+
/** A `<script>` whose type says it holds data rather than code: application/json, application/ld+json, … */
|
|
19
|
+
const DATA_SCRIPT_TYPE = /^application\/(?:[\w.-]+\+)?json$/;
|
|
20
|
+
/**
|
|
21
|
+
* Every script in a page. A script's content ends at the first "</script" —
|
|
22
|
+
* HTML's own rule — so this finds each one exactly, however much code is in it.
|
|
23
|
+
*/
|
|
24
|
+
const SCRIPT = /<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi;
|
|
25
|
+
/** The value of one attribute in a tag's attribute text, or ''. */
|
|
26
|
+
function htmlAttribute(attributes, name) {
|
|
27
|
+
const match = attributes.match(new RegExp(`(?:^|\\s)${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, 'i'));
|
|
28
|
+
return match ? (match[1] ?? match[2] ?? match[3] ?? '') : '';
|
|
29
|
+
}
|
|
30
|
+
/** Whether a script type attribute marks data rather than code. */
|
|
31
|
+
function isDataScriptType(type) {
|
|
32
|
+
return DATA_SCRIPT_TYPE.test((type || '').trim().toLowerCase());
|
|
33
|
+
}
|
|
34
|
+
/** Every non-empty JSON data block in a page, in page order. */
|
|
35
|
+
function findDataBlocks(html) {
|
|
36
|
+
const blocks = [];
|
|
37
|
+
for (const match of html.matchAll(SCRIPT)) {
|
|
38
|
+
const [whole, attributes, body] = match;
|
|
39
|
+
const type = htmlAttribute(attributes, 'type').toLowerCase();
|
|
40
|
+
if (!isDataScriptType(type) || !body.trim()) {
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
const contentStart = match.index + whole.indexOf('>') + 1;
|
|
44
|
+
let value;
|
|
45
|
+
try {
|
|
46
|
+
value = JSON.parse(body);
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
value = undefined;
|
|
50
|
+
}
|
|
51
|
+
const id = htmlAttribute(attributes, 'id');
|
|
52
|
+
blocks.push({
|
|
53
|
+
id,
|
|
54
|
+
label: id || `data block ${blocks.length + 1}`,
|
|
55
|
+
type,
|
|
56
|
+
contentStart,
|
|
57
|
+
contentEnd: contentStart + body.length,
|
|
58
|
+
text: body.trim(),
|
|
59
|
+
value,
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
return blocks;
|
|
63
|
+
}
|
|
64
|
+
/** Every script in a page that holds code, as attributes and content. */
|
|
65
|
+
function findCodeScripts(html) {
|
|
66
|
+
return [...html.matchAll(SCRIPT)]
|
|
67
|
+
.filter(([, attributes]) => !isDataScriptType(htmlAttribute(attributes, 'type')))
|
|
68
|
+
.map(([, attributes, body]) => ({ attributes, body }));
|
|
69
|
+
}
|
|
70
|
+
/** The page with every script removed. */
|
|
71
|
+
function withoutScripts(html) {
|
|
72
|
+
return html.replace(SCRIPT, '');
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* JSON laid out for reading and searching: an object's keys one per line, to two
|
|
76
|
+
* levels, and a list of records one record per line. A record is never broken
|
|
77
|
+
* across lines, so a chunk holds whole records; and the layout adds little to the
|
|
78
|
+
* size, where fully indented JSON would double it.
|
|
79
|
+
*/
|
|
80
|
+
function readableJson(value, depth = 0) {
|
|
81
|
+
const indent = ' '.repeat(depth);
|
|
82
|
+
if (Array.isArray(value)) {
|
|
83
|
+
if (!value.length || value.every((item) => item === null || typeof item !== 'object')) {
|
|
84
|
+
return JSON.stringify(value);
|
|
85
|
+
}
|
|
86
|
+
return `[\n${value.map((item) => `${indent} ${JSON.stringify(item)}`).join(',\n')}\n${indent}]`;
|
|
87
|
+
}
|
|
88
|
+
if (value && typeof value === 'object') {
|
|
89
|
+
const entries = Object.entries(value);
|
|
90
|
+
if (!entries.length || depth >= 2) {
|
|
91
|
+
return JSON.stringify(value);
|
|
92
|
+
}
|
|
93
|
+
return `{\n${entries
|
|
94
|
+
.map(([key, item]) => `${indent} ${JSON.stringify(key)}: ${readableJson(item, depth + 1)}`)
|
|
95
|
+
.join(',\n')}\n${indent}}`;
|
|
96
|
+
}
|
|
97
|
+
return JSON.stringify(value) ?? 'null';
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* The shape of some JSON in one line: `{ meta: {client, title, …}, claims: [131 × {id, n, …}] }`.
|
|
101
|
+
* Top-level keys are described; anything deeper is named by its keys.
|
|
102
|
+
*/
|
|
103
|
+
function describeShape(value, depth = 0) {
|
|
104
|
+
const keysOf = (object, limit) => {
|
|
105
|
+
const keys = Object.keys(object);
|
|
106
|
+
return keys.slice(0, limit).join(', ') + (keys.length > limit ? ', …' : '');
|
|
107
|
+
};
|
|
108
|
+
if (Array.isArray(value)) {
|
|
109
|
+
return value.length ? `[${value.length} × ${describeShape(value[0], depth + 1)}]` : '[]';
|
|
110
|
+
}
|
|
111
|
+
if (value && typeof value === 'object') {
|
|
112
|
+
if (depth >= 1) {
|
|
113
|
+
return `{${keysOf(value, 10)}}`;
|
|
114
|
+
}
|
|
115
|
+
const entries = Object.entries(value);
|
|
116
|
+
const shown = entries.slice(0, 25).map(([key, item]) => `${key}: ${describeShape(item, depth + 1)}`);
|
|
117
|
+
return `{ ${shown.join(', ')}${entries.length > 25 ? ', …' : ''} }`;
|
|
118
|
+
}
|
|
119
|
+
return value === null ? 'null' : typeof value;
|
|
120
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Making a new HTML page from one that draws everything from an embedded data
|
|
3
|
+
* block — a template — by replacing its data and keeping its code.
|
|
4
|
+
*
|
|
5
|
+
* An agent never rewrites a template: its scripts and styles can be hundreds of
|
|
6
|
+
* kilobytes, and one changed character can break them. It names the data to
|
|
7
|
+
* change, path by path, and this copies the page with exactly that data replaced.
|
|
8
|
+
* Whatever it does not name keeps the template's value, so reference data — map
|
|
9
|
+
* shapes, labels, configuration — carries over untouched.
|
|
10
|
+
*
|
|
11
|
+
* Every change is compared with the template's value at the same path, because
|
|
12
|
+
* the commonest mistake is a near miss the page's code will not survive: a number
|
|
13
|
+
* given as a string, a record missing a field the code reads. Those come back as
|
|
14
|
+
* warnings rather than refusals; the agent knows whether a difference is
|
|
15
|
+
* deliberate.
|
|
16
|
+
*/
|
|
17
|
+
import { HtmlDataBlock } from './html-data';
|
|
18
|
+
/** One step of a path: an object key or an array index. */
|
|
19
|
+
type PathStep = string | number;
|
|
20
|
+
/** One change to a template's data: the value to put at a path. */
|
|
21
|
+
export interface TemplateChange {
|
|
22
|
+
/** `meta.client`, `claims`, `lines[0].title`, `states["PR (Puerto Rico)"]`; `$` for the whole block. */
|
|
23
|
+
path: string;
|
|
24
|
+
value: unknown;
|
|
25
|
+
}
|
|
26
|
+
export interface TemplateFill {
|
|
27
|
+
/** The block to change, by label. Optional when the page has exactly one. */
|
|
28
|
+
block?: string;
|
|
29
|
+
changes: TemplateChange[];
|
|
30
|
+
/** A new `<title>` for the page. */
|
|
31
|
+
title?: string;
|
|
32
|
+
}
|
|
33
|
+
export interface TemplateFillResult {
|
|
34
|
+
html: string;
|
|
35
|
+
/** The block that was changed. */
|
|
36
|
+
block: string;
|
|
37
|
+
/** Near misses worth checking: type changes, record fields missing or added, a new field. */
|
|
38
|
+
warnings: string[];
|
|
39
|
+
/** The template's top-level keys no change touched — each should be data that is the same for any client. */
|
|
40
|
+
untouched: string[];
|
|
41
|
+
}
|
|
42
|
+
/** A page section of an array, for reading a long list a part at a time. */
|
|
43
|
+
export interface TemplateDataPage {
|
|
44
|
+
total: number;
|
|
45
|
+
offset: number;
|
|
46
|
+
items: unknown[];
|
|
47
|
+
nextOffset?: number;
|
|
48
|
+
}
|
|
49
|
+
/** Thrown for a fill that cannot be applied at all. The message is written for the agent. */
|
|
50
|
+
export declare class TemplateError extends Error {
|
|
51
|
+
constructor(message: string);
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Parses a path into steps.
|
|
55
|
+
*
|
|
56
|
+
* @throws {TemplateError} For a path that cannot be read
|
|
57
|
+
*/
|
|
58
|
+
export declare function parseTemplatePath(path: string): PathStep[];
|
|
59
|
+
export declare function formatPath(steps: PathStep[]): string;
|
|
60
|
+
/**
|
|
61
|
+
* The value at a path.
|
|
62
|
+
*
|
|
63
|
+
* @throws {TemplateError} When the path leads nowhere, naming where it stopped
|
|
64
|
+
*/
|
|
65
|
+
export declare function valueAtPath(root: unknown, path: string): unknown;
|
|
66
|
+
/**
|
|
67
|
+
* A part of the data for reading: the value at a path, or a page of it when it is a list.
|
|
68
|
+
*
|
|
69
|
+
* @throws {TemplateError} When the path leads nowhere
|
|
70
|
+
*/
|
|
71
|
+
export declare function readTemplateData(root: unknown, path: string, options?: {
|
|
72
|
+
offset?: number;
|
|
73
|
+
limit?: number;
|
|
74
|
+
}): unknown;
|
|
75
|
+
/**
|
|
76
|
+
* JSON safe to put inside a `<script>` element: nothing in a value can end the
|
|
77
|
+
* element or start a comment, and the two line separators JavaScript once
|
|
78
|
+
* rejected in strings are escaped.
|
|
79
|
+
*/
|
|
80
|
+
export declare function scriptSafeJson(value: unknown): string;
|
|
81
|
+
/** The template's data, parsed, for the block a caller means. */
|
|
82
|
+
export declare function templateData(html: string, block?: string): {
|
|
83
|
+
block: HtmlDataBlock;
|
|
84
|
+
value: unknown;
|
|
85
|
+
};
|
|
86
|
+
/**
|
|
87
|
+
* A copy of the page with the named data replaced. Nothing else in the page changes.
|
|
88
|
+
*
|
|
89
|
+
* @throws {TemplateError} For a page with no such block, a block that is not JSON, or a
|
|
90
|
+
* path into something that is not there
|
|
91
|
+
*/
|
|
92
|
+
export declare function applyTemplateChanges(html: string, fill: TemplateFill): TemplateFillResult;
|
|
93
|
+
/**
|
|
94
|
+
* Applies one change to the data, in place, and returns the data — a new value
|
|
95
|
+
* only when the change replaced the whole of it (`$`). Warnings are added to
|
|
96
|
+
* `warnings`, and the top-level key the change fell under to `touched`.
|
|
97
|
+
*
|
|
98
|
+
* @throws {TemplateError} For a change with no path or value, or a path into nothing
|
|
99
|
+
*/
|
|
100
|
+
export declare function applyChange(data: unknown, change: TemplateChange, warnings: string[], touched: Set<string>): unknown;
|
|
101
|
+
/** The page with a data block's content replaced by `data`, and optionally a new `<title>`. */
|
|
102
|
+
export declare function writeTemplateData(html: string, block: HtmlDataBlock, data: unknown, title?: string): {
|
|
103
|
+
html: string;
|
|
104
|
+
warnings: string[];
|
|
105
|
+
};
|
|
106
|
+
/** The template's top-level keys no change touched. */
|
|
107
|
+
export declare function untouchedKeys(templateValue: unknown, touched: Set<string>): string[];
|
|
108
|
+
export {};
|
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.TemplateError = void 0;
|
|
4
|
+
exports.parseTemplatePath = parseTemplatePath;
|
|
5
|
+
exports.formatPath = formatPath;
|
|
6
|
+
exports.valueAtPath = valueAtPath;
|
|
7
|
+
exports.readTemplateData = readTemplateData;
|
|
8
|
+
exports.scriptSafeJson = scriptSafeJson;
|
|
9
|
+
exports.templateData = templateData;
|
|
10
|
+
exports.applyTemplateChanges = applyTemplateChanges;
|
|
11
|
+
exports.applyChange = applyChange;
|
|
12
|
+
exports.writeTemplateData = writeTemplateData;
|
|
13
|
+
exports.untouchedKeys = untouchedKeys;
|
|
14
|
+
/**
|
|
15
|
+
* Making a new HTML page from one that draws everything from an embedded data
|
|
16
|
+
* block — a template — by replacing its data and keeping its code.
|
|
17
|
+
*
|
|
18
|
+
* An agent never rewrites a template: its scripts and styles can be hundreds of
|
|
19
|
+
* kilobytes, and one changed character can break them. It names the data to
|
|
20
|
+
* change, path by path, and this copies the page with exactly that data replaced.
|
|
21
|
+
* Whatever it does not name keeps the template's value, so reference data — map
|
|
22
|
+
* shapes, labels, configuration — carries over untouched.
|
|
23
|
+
*
|
|
24
|
+
* Every change is compared with the template's value at the same path, because
|
|
25
|
+
* the commonest mistake is a near miss the page's code will not survive: a number
|
|
26
|
+
* given as a string, a record missing a field the code reads. Those come back as
|
|
27
|
+
* warnings rather than refusals; the agent knows whether a difference is
|
|
28
|
+
* deliberate.
|
|
29
|
+
*/
|
|
30
|
+
const html_data_1 = require("./html-data");
|
|
31
|
+
/** Thrown for a fill that cannot be applied at all. The message is written for the agent. */
|
|
32
|
+
class TemplateError extends Error {
|
|
33
|
+
constructor(message) {
|
|
34
|
+
super(message);
|
|
35
|
+
this.name = 'TemplateError';
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
exports.TemplateError = TemplateError;
|
|
39
|
+
/**
|
|
40
|
+
* Parses a path into steps.
|
|
41
|
+
*
|
|
42
|
+
* @throws {TemplateError} For a path that cannot be read
|
|
43
|
+
*/
|
|
44
|
+
function parseTemplatePath(path) {
|
|
45
|
+
const text = (path ?? '').trim();
|
|
46
|
+
if (text === '' || text === '$') {
|
|
47
|
+
return [];
|
|
48
|
+
}
|
|
49
|
+
const steps = [];
|
|
50
|
+
let rest = text.startsWith('$') ? text.slice(1) : text;
|
|
51
|
+
const step = /^(?:\.?([^.[\]"]+)|\[(\d+)\]|\["((?:[^"\\]|\\.)*)"\])/;
|
|
52
|
+
while (rest.length) {
|
|
53
|
+
const match = rest.match(step);
|
|
54
|
+
if (!match) {
|
|
55
|
+
throw new TemplateError(`"${path}" is not a path this can read. Write keys with dots and indexes in brackets: ` +
|
|
56
|
+
'`meta.client`, `lines[0].title`, or `states["PR (Puerto Rico)"]` for a key with spaces or dots.');
|
|
57
|
+
}
|
|
58
|
+
steps.push(match[1] !== undefined ? match[1].trim() : match[2] !== undefined ? Number(match[2]) : JSON.parse(`"${match[3]}"`));
|
|
59
|
+
rest = rest.slice(match[0].length);
|
|
60
|
+
}
|
|
61
|
+
return steps;
|
|
62
|
+
}
|
|
63
|
+
function formatPath(steps) {
|
|
64
|
+
if (!steps.length) {
|
|
65
|
+
return '$';
|
|
66
|
+
}
|
|
67
|
+
return steps
|
|
68
|
+
.map((step, index) => typeof step === 'number'
|
|
69
|
+
? `[${step}]`
|
|
70
|
+
: /^[A-Za-z_$][\w$-]*$/.test(step)
|
|
71
|
+
? `${index ? '.' : ''}${step}`
|
|
72
|
+
: `[${JSON.stringify(step)}]`)
|
|
73
|
+
.join('');
|
|
74
|
+
}
|
|
75
|
+
function kindOf(value) {
|
|
76
|
+
if (value === null)
|
|
77
|
+
return 'null';
|
|
78
|
+
if (Array.isArray(value))
|
|
79
|
+
return 'list';
|
|
80
|
+
return typeof value === 'object' ? 'object' : typeof value;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* The value at a path.
|
|
84
|
+
*
|
|
85
|
+
* @throws {TemplateError} When the path leads nowhere, naming where it stopped
|
|
86
|
+
*/
|
|
87
|
+
function valueAtPath(root, path) {
|
|
88
|
+
let current = root;
|
|
89
|
+
const steps = parseTemplatePath(path);
|
|
90
|
+
steps.forEach((step, index) => {
|
|
91
|
+
const here = formatPath(steps.slice(0, index));
|
|
92
|
+
if (typeof step === 'number') {
|
|
93
|
+
if (!Array.isArray(current)) {
|
|
94
|
+
throw new TemplateError(`"${here}" is ${kindOf(current) === 'object' ? 'an object' : `a ${kindOf(current)}`}, not a list, so it has no [${step}].`);
|
|
95
|
+
}
|
|
96
|
+
if (step >= current.length) {
|
|
97
|
+
throw new TemplateError(`"${here}" has ${current.length} item(s); [${step}] is past the end.`);
|
|
98
|
+
}
|
|
99
|
+
current = current[step];
|
|
100
|
+
}
|
|
101
|
+
else {
|
|
102
|
+
if (!current || typeof current !== 'object' || Array.isArray(current)) {
|
|
103
|
+
throw new TemplateError(`"${here}" is a ${kindOf(current)}, not an object, so it has no "${step}".`);
|
|
104
|
+
}
|
|
105
|
+
if (!(step in current)) {
|
|
106
|
+
const keys = Object.keys(current);
|
|
107
|
+
throw new TemplateError(`"${formatPath(steps.slice(0, index + 1))}" is not in the data. "${here}" has: ${keys.join(', ')}.`);
|
|
108
|
+
}
|
|
109
|
+
current = current[step];
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
return current;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* A part of the data for reading: the value at a path, or a page of it when it is a list.
|
|
116
|
+
*
|
|
117
|
+
* @throws {TemplateError} When the path leads nowhere
|
|
118
|
+
*/
|
|
119
|
+
function readTemplateData(root, path, options = {}) {
|
|
120
|
+
const value = valueAtPath(root, path);
|
|
121
|
+
if (!Array.isArray(value)) {
|
|
122
|
+
return value;
|
|
123
|
+
}
|
|
124
|
+
const offset = Math.max(0, Math.floor(options.offset ?? 0));
|
|
125
|
+
const limit = Math.max(1, Math.floor(options.limit ?? 10));
|
|
126
|
+
const items = value.slice(offset, offset + limit);
|
|
127
|
+
const page = { total: value.length, offset, items };
|
|
128
|
+
if (offset + items.length < value.length) {
|
|
129
|
+
page.nextOffset = offset + items.length;
|
|
130
|
+
}
|
|
131
|
+
return page;
|
|
132
|
+
}
|
|
133
|
+
/** The keys a list of records has, gathered from its first few records. */
|
|
134
|
+
function recordKeys(list) {
|
|
135
|
+
const records = list.filter((item) => item && typeof item === 'object' && !Array.isArray(item)).slice(0, 5);
|
|
136
|
+
if (!records.length) {
|
|
137
|
+
return null;
|
|
138
|
+
}
|
|
139
|
+
return [...new Set(records.flatMap((record) => Object.keys(record)))];
|
|
140
|
+
}
|
|
141
|
+
function quoteList(keys, limit = 8) {
|
|
142
|
+
return keys.slice(0, limit).map((key) => `"${key}"`).join(', ') + (keys.length > limit ? `, and ${keys.length - limit} more` : '');
|
|
143
|
+
}
|
|
144
|
+
/** How a new value differs from the template's at the same path, as warnings. */
|
|
145
|
+
function compare(path, before, after) {
|
|
146
|
+
const was = kindOf(before);
|
|
147
|
+
const now = kindOf(after);
|
|
148
|
+
if (was !== now && was !== 'null' && now !== 'null') {
|
|
149
|
+
return [`"${path}" was a ${was} in the template (${(0, html_data_1.describeShape)(before)}); you gave a ${now}. The page's code may not read it.`];
|
|
150
|
+
}
|
|
151
|
+
if (Array.isArray(before) && Array.isArray(after)) {
|
|
152
|
+
const keys = recordKeys(before);
|
|
153
|
+
if (!keys) {
|
|
154
|
+
return [];
|
|
155
|
+
}
|
|
156
|
+
const missing = new Map();
|
|
157
|
+
const added = new Map();
|
|
158
|
+
for (const item of after) {
|
|
159
|
+
if (!item || typeof item !== 'object' || Array.isArray(item)) {
|
|
160
|
+
return [`"${path}" held records (${quoteList(keys)}) in the template; you gave a list of ${kindOf(item)}s.`];
|
|
161
|
+
}
|
|
162
|
+
for (const key of keys)
|
|
163
|
+
if (!(key in item))
|
|
164
|
+
missing.set(key, (missing.get(key) ?? 0) + 1);
|
|
165
|
+
for (const key of Object.keys(item))
|
|
166
|
+
if (!keys.includes(key))
|
|
167
|
+
added.set(key, (added.get(key) ?? 0) + 1);
|
|
168
|
+
}
|
|
169
|
+
const warnings = [];
|
|
170
|
+
if (missing.size) {
|
|
171
|
+
warnings.push(`In "${path}", ${quoteList([...missing.keys()])} ${missing.size === 1 ? 'is' : 'are'} missing from some or all of your ` +
|
|
172
|
+
`${after.length} record(s); the template's records all have them, and the page's code may read them.`);
|
|
173
|
+
}
|
|
174
|
+
if (added.size) {
|
|
175
|
+
warnings.push(`In "${path}", your records add ${quoteList([...added.keys()])}, which the template's records do not have.`);
|
|
176
|
+
}
|
|
177
|
+
return warnings;
|
|
178
|
+
}
|
|
179
|
+
if (was === 'object' && now === 'object') {
|
|
180
|
+
const beforeKeys = Object.keys(before);
|
|
181
|
+
const afterKeys = Object.keys(after);
|
|
182
|
+
const missing = beforeKeys.filter((key) => !afterKeys.includes(key));
|
|
183
|
+
const added = afterKeys.filter((key) => !beforeKeys.includes(key));
|
|
184
|
+
const warnings = [];
|
|
185
|
+
if (missing.length)
|
|
186
|
+
warnings.push(`"${path}" lost ${quoteList(missing)}, which the template has.`);
|
|
187
|
+
if (added.length)
|
|
188
|
+
warnings.push(`"${path}" gained ${quoteList(added)}, which the template does not have.`);
|
|
189
|
+
return warnings;
|
|
190
|
+
}
|
|
191
|
+
return [];
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* JSON safe to put inside a `<script>` element: nothing in a value can end the
|
|
195
|
+
* element or start a comment, and the two line separators JavaScript once
|
|
196
|
+
* rejected in strings are escaped.
|
|
197
|
+
*/
|
|
198
|
+
function scriptSafeJson(value) {
|
|
199
|
+
return JSON.stringify(value)
|
|
200
|
+
.replace(/</g, '\\u003c')
|
|
201
|
+
.replace(/>/g, '\\u003e')
|
|
202
|
+
.replace(/\u2028/g, '\\u2028')
|
|
203
|
+
.replace(/\u2029/g, '\\u2029');
|
|
204
|
+
}
|
|
205
|
+
function escapeText(text) {
|
|
206
|
+
return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
207
|
+
}
|
|
208
|
+
/** The data block a fill means. */
|
|
209
|
+
function chooseBlock(blocks, wanted) {
|
|
210
|
+
const labels = blocks.map((block) => block.label);
|
|
211
|
+
if (!blocks.length) {
|
|
212
|
+
throw new TemplateError('This page has no JSON data block, so it is not a template that can be filled.');
|
|
213
|
+
}
|
|
214
|
+
if (wanted) {
|
|
215
|
+
const block = blocks.find((candidate) => candidate.label === wanted || candidate.id === wanted);
|
|
216
|
+
if (!block) {
|
|
217
|
+
throw new TemplateError(`There is no data block "${wanted}". This page has: ${labels.join(', ')}.`);
|
|
218
|
+
}
|
|
219
|
+
return block;
|
|
220
|
+
}
|
|
221
|
+
if (blocks.length > 1) {
|
|
222
|
+
throw new TemplateError(`This page has ${blocks.length} data blocks (${labels.join(', ')}); say which with block.`);
|
|
223
|
+
}
|
|
224
|
+
return blocks[0];
|
|
225
|
+
}
|
|
226
|
+
/** The template's data, parsed, for the block a caller means. */
|
|
227
|
+
function templateData(html, block) {
|
|
228
|
+
const chosen = chooseBlock((0, html_data_1.findDataBlocks)(html), block);
|
|
229
|
+
if (chosen.value === undefined) {
|
|
230
|
+
throw new TemplateError(`The data block "${chosen.label}" is not valid JSON, so it cannot be read or filled.`);
|
|
231
|
+
}
|
|
232
|
+
return { block: chosen, value: chosen.value };
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* A copy of the page with the named data replaced. Nothing else in the page changes.
|
|
236
|
+
*
|
|
237
|
+
* @throws {TemplateError} For a page with no such block, a block that is not JSON, or a
|
|
238
|
+
* path into something that is not there
|
|
239
|
+
*/
|
|
240
|
+
function applyTemplateChanges(html, fill) {
|
|
241
|
+
const { block, value } = templateData(html, fill.block);
|
|
242
|
+
if (!fill.changes?.length && fill.title === undefined) {
|
|
243
|
+
throw new TemplateError('There are no changes to make. Give each change as { "path": …, "value": … }.');
|
|
244
|
+
}
|
|
245
|
+
let data = structuredClone(value);
|
|
246
|
+
const warnings = [];
|
|
247
|
+
const touched = new Set();
|
|
248
|
+
for (const change of fill.changes ?? []) {
|
|
249
|
+
data = applyChange(data, change, warnings, touched);
|
|
250
|
+
}
|
|
251
|
+
const written = writeTemplateData(html, block, data, fill.title);
|
|
252
|
+
return {
|
|
253
|
+
html: written.html,
|
|
254
|
+
block: block.label,
|
|
255
|
+
warnings: [...warnings, ...written.warnings],
|
|
256
|
+
untouched: untouchedKeys(value, touched),
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* Applies one change to the data, in place, and returns the data — a new value
|
|
261
|
+
* only when the change replaced the whole of it (`$`). Warnings are added to
|
|
262
|
+
* `warnings`, and the top-level key the change fell under to `touched`.
|
|
263
|
+
*
|
|
264
|
+
* @throws {TemplateError} For a change with no path or value, or a path into nothing
|
|
265
|
+
*/
|
|
266
|
+
function applyChange(data, change, warnings, touched) {
|
|
267
|
+
if (!change || typeof change.path !== 'string') {
|
|
268
|
+
throw new TemplateError('Each change needs a "path" (text) and a "value".');
|
|
269
|
+
}
|
|
270
|
+
if (!('value' in change) || change.value === undefined) {
|
|
271
|
+
throw new TemplateError(`The change to "${change.path}" has no "value". To empty a list, give [].`);
|
|
272
|
+
}
|
|
273
|
+
const steps = parseTemplatePath(change.path);
|
|
274
|
+
const path = formatPath(steps);
|
|
275
|
+
if (!steps.length) {
|
|
276
|
+
warnings.push(...compare(path, data, change.value));
|
|
277
|
+
const whole = structuredClone(change.value);
|
|
278
|
+
Object.keys(whole ?? {}).forEach((key) => touched.add(key));
|
|
279
|
+
return whole;
|
|
280
|
+
}
|
|
281
|
+
const parentPath = formatPath(steps.slice(0, -1));
|
|
282
|
+
const parent = valueAtPath(data, parentPath);
|
|
283
|
+
const last = steps[steps.length - 1];
|
|
284
|
+
if (typeof last === 'number') {
|
|
285
|
+
if (!Array.isArray(parent)) {
|
|
286
|
+
throw new TemplateError(`"${parentPath}" is not a list, so it has no [${last}].`);
|
|
287
|
+
}
|
|
288
|
+
if (last > parent.length) {
|
|
289
|
+
throw new TemplateError(`"${parentPath}" has ${parent.length} item(s); you can change [0] to [${parent.length - 1}] or add [${parent.length}].`);
|
|
290
|
+
}
|
|
291
|
+
warnings.push(...compare(path, last < parent.length ? parent[last] : parent[0], change.value));
|
|
292
|
+
parent[last] = structuredClone(change.value);
|
|
293
|
+
}
|
|
294
|
+
else {
|
|
295
|
+
if (!parent || typeof parent !== 'object' || Array.isArray(parent)) {
|
|
296
|
+
throw new TemplateError(`"${parentPath}" is a ${kindOf(parent)}, not an object, so it has no "${last}".`);
|
|
297
|
+
}
|
|
298
|
+
if (last in parent) {
|
|
299
|
+
warnings.push(...compare(path, parent[last], change.value));
|
|
300
|
+
}
|
|
301
|
+
else {
|
|
302
|
+
warnings.push(`"${path}" is a new field; the template has no such field, so its code will not read it.`);
|
|
303
|
+
}
|
|
304
|
+
parent[last] = structuredClone(change.value);
|
|
305
|
+
}
|
|
306
|
+
const top = steps[0];
|
|
307
|
+
if (typeof top === 'string')
|
|
308
|
+
touched.add(top);
|
|
309
|
+
return data;
|
|
310
|
+
}
|
|
311
|
+
/** The page with a data block's content replaced by `data`, and optionally a new `<title>`. */
|
|
312
|
+
function writeTemplateData(html, block, data, title) {
|
|
313
|
+
const warnings = [];
|
|
314
|
+
let page = html.slice(0, block.contentStart) + scriptSafeJson(data) + html.slice(block.contentEnd);
|
|
315
|
+
if (title !== undefined) {
|
|
316
|
+
const titleTag = /<title\b[^>]*>[\s\S]*?<\/title\s*>/i;
|
|
317
|
+
if (titleTag.test(page)) {
|
|
318
|
+
const text = escapeText(title);
|
|
319
|
+
page = page.replace(titleTag, (tag) => tag.replace(/>[\s\S]*?</, () => `>${text}<`));
|
|
320
|
+
}
|
|
321
|
+
else {
|
|
322
|
+
warnings.push('The page has no <title>, so the title was not set.');
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
return { html: page, warnings };
|
|
326
|
+
}
|
|
327
|
+
/** The template's top-level keys no change touched. */
|
|
328
|
+
function untouchedKeys(templateValue, touched) {
|
|
329
|
+
return templateValue && typeof templateValue === 'object' && !Array.isArray(templateValue)
|
|
330
|
+
? Object.keys(templateValue).filter((key) => !touched.has(key))
|
|
331
|
+
: [];
|
|
332
|
+
}
|