@intellectual-frontiers/formats 0.0.0-stage → 0.1.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 +21 -0
- package/README.md +8 -2
- package/dist/archive.d.ts +147 -0
- package/dist/archive.js +765 -0
- package/dist/base64.d.ts +24 -0
- package/dist/base64.js +52 -0
- package/dist/cbor.d.ts +39 -0
- package/dist/cbor.js +244 -0
- package/dist/csv.d.ts +38 -0
- package/dist/csv.js +130 -0
- package/dist/der.d.ts +67 -0
- package/dist/der.js +221 -0
- package/dist/glob.d.ts +64 -0
- package/dist/glob.js +218 -0
- package/dist/hex.d.ts +17 -0
- package/dist/hex.js +30 -0
- package/dist/http.d.ts +46 -0
- package/dist/http.js +102 -0
- package/dist/json5.d.ts +46 -0
- package/dist/json5.js +291 -0
- package/dist/media-types.d.ts +28 -0
- package/dist/media-types.js +121 -0
- package/dist/mod.d.ts +39 -0
- package/dist/mod.js +31 -0
- package/dist/png.d.ts +124 -0
- package/dist/png.js +607 -0
- package/dist/semver.d.ts +94 -0
- package/dist/semver.js +331 -0
- package/dist/toml.d.ts +51 -0
- package/dist/toml.js +583 -0
- package/dist/ts-literal.d.ts +62 -0
- package/dist/ts-literal.js +173 -0
- package/dist/xml.d.ts +73 -0
- package/dist/xml.js +282 -0
- package/dist/yaml.d.ts +44 -0
- package/dist/yaml.js +706 -0
- package/package.json +118 -4
- package/src/archive.ts +831 -0
- package/src/base64.ts +51 -0
- package/src/cbor.ts +235 -0
- package/src/csv.ts +132 -0
- package/src/der.ts +224 -0
- package/src/glob.ts +210 -0
- package/src/hex.ts +28 -0
- package/src/http.ts +104 -0
- package/src/json5.ts +267 -0
- package/src/media-types.ts +127 -0
- package/src/mod.ts +102 -0
- package/src/png.ts +625 -0
- package/src/semver.ts +373 -0
- package/src/toml.ts +525 -0
- package/src/ts-literal.ts +183 -0
- package/src/xml.ts +291 -0
- package/src/yaml.ts +616 -0
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
// Spec: 0001-formats FR-006
|
|
2
|
+
/**
|
|
3
|
+
* Data as TypeScript object literals, for files a program writes for people to read and edit (keys bare where they are identifiers, strings
|
|
4
|
+
* in double quotes, two-space indentation and trailing commas), and the reader of exactly that subset, which never runs the file, so a past
|
|
5
|
+
* version from `git show` can be read safely (commons 0001-formats FR-006); the writer takes any type shaped as JSON (FR-063).
|
|
6
|
+
* Taken from Stolos's `src/archon/core/ts-literal.ts`; the reader returns a `Result` instead of throwing.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```ts
|
|
10
|
+
* import { parseTsLiteral, tsLiteral } from "./ts-literal.ts";
|
|
11
|
+
* const text = tsLiteral({ timezone: "America/New_York", "otel-ui": true });
|
|
12
|
+
* parseTsLiteral(text); // { kind: "ok", value: { value: { timezone: "America/New_York", "otel-ui": true }, end: text.length } }
|
|
13
|
+
* ```
|
|
14
|
+
*
|
|
15
|
+
* @module
|
|
16
|
+
*/
|
|
17
|
+
import { err, ok } from "@intellectual-frontiers/core";
|
|
18
|
+
/** A key that needs no quotes: an identifier (letters, digits, `_`, `$`; not starting with a digit). */
|
|
19
|
+
export const BARE_KEY = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
20
|
+
/** A key as TypeScript writes it: bare where it can be, else a double-quoted string. */
|
|
21
|
+
export function tsKey(key) {
|
|
22
|
+
return BARE_KEY.test(key) ? key : JSON.stringify(key);
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* A value as a TypeScript literal, indented for `depth` (two spaces each). It takes any value whose type is shaped as JSON (FR-063), an
|
|
26
|
+
* interface with no index signature included, and refuses at compile time a value holding a function, a `Date`, a `bigint` or another
|
|
27
|
+
* type JSON has not. Objects and arrays span lines (empty ones stay `{}` and `[]`); properties that are `undefined` are left out, as
|
|
28
|
+
* `JSON.stringify` leaves them out. A number that is not finite is written `null`, as JSON writes it. (The check is on the parameter,
|
|
29
|
+
* `T & LiteralShape<T>`, because TypeScript refuses `T extends LiteralShape<T>` as a circular constraint.)
|
|
30
|
+
*/
|
|
31
|
+
export function tsLiteral(value, depth = 0) {
|
|
32
|
+
return write(value, depth);
|
|
33
|
+
}
|
|
34
|
+
// The type parameter of `tsLiteral` already holds the value to JSON's shape; here it is walked as what it is at run time.
|
|
35
|
+
function write(value, depth) {
|
|
36
|
+
const pad = " ".repeat(depth + 1);
|
|
37
|
+
const end = " ".repeat(depth);
|
|
38
|
+
if (value === null || value === undefined)
|
|
39
|
+
return "null";
|
|
40
|
+
if (Array.isArray(value)) {
|
|
41
|
+
const items = value;
|
|
42
|
+
if (items.length === 0)
|
|
43
|
+
return "[]";
|
|
44
|
+
return `[\n${items.map((v) => `${pad}${write(v, depth + 1)},\n`).join("")}${end}]`;
|
|
45
|
+
}
|
|
46
|
+
if (typeof value === "object") {
|
|
47
|
+
const entries = Object.entries(value).filter((e) => e[1] !== undefined);
|
|
48
|
+
if (entries.length === 0)
|
|
49
|
+
return "{}";
|
|
50
|
+
return `{\n${entries.map(([k, v]) => `${pad}${tsKey(k)}: ${write(v, depth + 1)},\n`).join("")}${end}}`;
|
|
51
|
+
}
|
|
52
|
+
if (typeof value === "string")
|
|
53
|
+
return JSON.stringify(value);
|
|
54
|
+
if (typeof value === "number")
|
|
55
|
+
return Number.isFinite(value) ? JSON.stringify(value) : "null";
|
|
56
|
+
if (typeof value === "boolean")
|
|
57
|
+
return String(value);
|
|
58
|
+
return "null";
|
|
59
|
+
}
|
|
60
|
+
class Stop extends Error {
|
|
61
|
+
at;
|
|
62
|
+
expected;
|
|
63
|
+
constructor(at, expected) {
|
|
64
|
+
super(`not a literal at ${at}: expected ${expected}`);
|
|
65
|
+
this.at = at;
|
|
66
|
+
this.expected = expected;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* The value of a literal {@link tsLiteral} wrote, starting at `start`, and where it ended: objects with bare or quoted keys, arrays,
|
|
71
|
+
* double-quoted strings, numbers, `true`, `false` and `null`, with trailing commas and `//` comments. Anything else is an error.
|
|
72
|
+
*/
|
|
73
|
+
export function parseTsLiteral(text, start = 0) {
|
|
74
|
+
let i = start;
|
|
75
|
+
const ws = () => {
|
|
76
|
+
for (;;) {
|
|
77
|
+
while (i < text.length && /\s/.test(text[i] ?? ""))
|
|
78
|
+
i++;
|
|
79
|
+
if (!text.startsWith("//", i))
|
|
80
|
+
return;
|
|
81
|
+
while (i < text.length && text[i] !== "\n")
|
|
82
|
+
i++;
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
const fail = (expected) => {
|
|
86
|
+
throw new Stop(i, expected);
|
|
87
|
+
};
|
|
88
|
+
const str = () => {
|
|
89
|
+
const m = /^"(?:[^"\\\n]|\\.)*"/.exec(text.slice(i));
|
|
90
|
+
if (m === null)
|
|
91
|
+
return fail("a complete string");
|
|
92
|
+
i += m[0].length;
|
|
93
|
+
const s = JSON.parse(m[0]);
|
|
94
|
+
return typeof s === "string" ? s : fail("a string");
|
|
95
|
+
};
|
|
96
|
+
const value = () => {
|
|
97
|
+
ws();
|
|
98
|
+
const c = text[i];
|
|
99
|
+
if (c === "{") {
|
|
100
|
+
i++;
|
|
101
|
+
const o = {};
|
|
102
|
+
for (;;) {
|
|
103
|
+
ws();
|
|
104
|
+
if (text[i] === "}") {
|
|
105
|
+
i++;
|
|
106
|
+
return o;
|
|
107
|
+
}
|
|
108
|
+
let k;
|
|
109
|
+
if (text[i] === '"')
|
|
110
|
+
k = str();
|
|
111
|
+
else {
|
|
112
|
+
const m = /^[A-Za-z_$][A-Za-z0-9_$]*/.exec(text.slice(i));
|
|
113
|
+
if (m === null)
|
|
114
|
+
return fail("a key");
|
|
115
|
+
k = m[0];
|
|
116
|
+
i += k.length;
|
|
117
|
+
}
|
|
118
|
+
ws();
|
|
119
|
+
if (text[i] !== ":")
|
|
120
|
+
fail("a colon");
|
|
121
|
+
i++;
|
|
122
|
+
Object.defineProperty(o, k, { value: value(), enumerable: true, writable: true, configurable: true });
|
|
123
|
+
ws();
|
|
124
|
+
if (text[i] === ",")
|
|
125
|
+
i++;
|
|
126
|
+
else if (text[i] !== "}")
|
|
127
|
+
fail("a comma or }");
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
if (c === "[") {
|
|
131
|
+
i++;
|
|
132
|
+
const a = [];
|
|
133
|
+
for (;;) {
|
|
134
|
+
ws();
|
|
135
|
+
if (text[i] === "]") {
|
|
136
|
+
i++;
|
|
137
|
+
return a;
|
|
138
|
+
}
|
|
139
|
+
a.push(value());
|
|
140
|
+
ws();
|
|
141
|
+
if (text[i] === ",")
|
|
142
|
+
i++;
|
|
143
|
+
else if (text[i] !== "]")
|
|
144
|
+
fail("a comma or ]");
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
if (c === '"')
|
|
148
|
+
return str();
|
|
149
|
+
const m = /^(-?\d+(\.\d+)?([eE][+-]?\d+)?|true|false|null)/.exec(text.slice(i));
|
|
150
|
+
if (m === null)
|
|
151
|
+
return fail("a value");
|
|
152
|
+
i += m[0].length;
|
|
153
|
+
const v = JSON.parse(m[0]);
|
|
154
|
+
return typeof v === "number" || typeof v === "boolean" || v === null ? v : fail("a value");
|
|
155
|
+
};
|
|
156
|
+
try {
|
|
157
|
+
const v = value();
|
|
158
|
+
return ok({ value: v, end: i });
|
|
159
|
+
}
|
|
160
|
+
catch (e) {
|
|
161
|
+
if (e instanceof Stop)
|
|
162
|
+
return err({ kind: "literal", at: e.at, expected: e.expected });
|
|
163
|
+
throw e;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
/** The value of `export const <name>[: Type] = <literal>;` in a file {@link tsLiteral} wrote, or why it cannot be read. */
|
|
167
|
+
export function exportedLiteral(source, name) {
|
|
168
|
+
const m = new RegExp(`export const ${name}(?:\\s*:\\s*[A-Za-z_$][\\w$.<>, \\[\\]]*)?\\s*=\\s*`).exec(source);
|
|
169
|
+
if (m === null)
|
|
170
|
+
return err({ kind: "literal", at: 0, expected: `export const ${name}` });
|
|
171
|
+
const r = parseTsLiteral(source, m.index + m[0].length);
|
|
172
|
+
return r.kind === "ok" ? ok(r.value.value) : r;
|
|
173
|
+
}
|
package/dist/xml.d.ts
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* XML as a typed tree of elements and text, written with every value escaped (no document is a template of values) and read with no
|
|
3
|
+
* outside package (commons 0001-formats FR-004). The reader takes elements, attributes in either quote, the five named entities
|
|
4
|
+
* and character references, CDATA, comments, processing instructions and the XML declaration, checks that every element is closed by its
|
|
5
|
+
* own name, and refuses a document type with an internal subset, so no entity is ever expanded (no "billion laughs", no external entity).
|
|
6
|
+
* Names are kept as written (`dc:title`); the finders match a name with or without its prefix. Taken from erga's `lib/ts/xml`, whose
|
|
7
|
+
* reader was `@std/xml`.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```ts
|
|
11
|
+
* import { el, readXml, textOf, writeXml } from "./xml.js";
|
|
12
|
+
* const doc = writeXml(el("note", [el("to", ["Ada & Charles"])], [["lang", "en"]]));
|
|
13
|
+
* // '<?xml version="1.0" encoding="UTF-8"?>\n<note lang="en"><to>Ada & Charles</to></note>'
|
|
14
|
+
* const back = readXml(doc);
|
|
15
|
+
* if (back.kind === "ok") textOf(back.value); // "Ada & Charles"
|
|
16
|
+
* ```
|
|
17
|
+
*
|
|
18
|
+
* @module
|
|
19
|
+
*/
|
|
20
|
+
import { type Result } from "@intellectual-frontiers/core";
|
|
21
|
+
/** An element: its name as written, its attributes in order, and its children. */
|
|
22
|
+
export type XmlElement = {
|
|
23
|
+
readonly kind: "element";
|
|
24
|
+
readonly name: string;
|
|
25
|
+
readonly attributes: readonly (readonly [string, string])[];
|
|
26
|
+
readonly children: readonly XmlNode[];
|
|
27
|
+
};
|
|
28
|
+
/** Text, its entities and references already replaced. */
|
|
29
|
+
export type XmlText = {
|
|
30
|
+
readonly kind: "text";
|
|
31
|
+
readonly text: string;
|
|
32
|
+
};
|
|
33
|
+
/** A node of an XML document. */
|
|
34
|
+
export type XmlNode = XmlElement | XmlText;
|
|
35
|
+
/** What an element may be given as a child: a node, or a value written as text; `undefined` gives nothing. */
|
|
36
|
+
export type XmlChild = XmlNode | string | number | boolean | undefined;
|
|
37
|
+
/** An element. */
|
|
38
|
+
export declare function el(name: string, children?: readonly XmlChild[], attributes?: readonly (readonly [string, string])[]): XmlElement;
|
|
39
|
+
/** An element holding one value, or nothing where the value is absent. */
|
|
40
|
+
export declare function leaf(name: string, value: string | number | boolean | undefined): XmlElement | undefined;
|
|
41
|
+
/** A value as XML text or an attribute's value: `&`, `<`, `>`, `"` and `'` escaped, and the characters XML 1.0 forbids removed. */
|
|
42
|
+
export declare function escapeXml(s: string): string;
|
|
43
|
+
/** A node as XML text, with no declaration. */
|
|
44
|
+
export declare function writeNode(n: XmlNode): string;
|
|
45
|
+
/** A whole document: the XML declaration, then its root. */
|
|
46
|
+
export declare function writeXml(root: XmlElement): string;
|
|
47
|
+
/** Where a text stops being XML this reader takes, and why. Lines and columns count from 1. */
|
|
48
|
+
export type XmlError = {
|
|
49
|
+
readonly kind: "xml";
|
|
50
|
+
readonly line: number;
|
|
51
|
+
readonly column: number;
|
|
52
|
+
readonly message: string;
|
|
53
|
+
};
|
|
54
|
+
/** How to read: whether text that is only white space between elements is kept (it is dropped by default). */
|
|
55
|
+
export type ReadXmlOptions = {
|
|
56
|
+
readonly keepWhitespace?: boolean;
|
|
57
|
+
};
|
|
58
|
+
/** A document read: its root element; or where and why it is not XML this reader takes. */
|
|
59
|
+
export declare function readXml(text: string, options?: ReadXmlOptions): Result<XmlElement, XmlError>;
|
|
60
|
+
/** An XML error as one line: `3:14: expected a name`. */
|
|
61
|
+
export declare function formatXmlError(e: XmlError): string;
|
|
62
|
+
/** A name without its prefix: `title` for `dc:title`. */
|
|
63
|
+
export declare function localName(name: string): string;
|
|
64
|
+
/** The child elements of a node named `name` (with or without a prefix). */
|
|
65
|
+
export declare function children(n: XmlNode, name: string): readonly XmlElement[];
|
|
66
|
+
/** The first child element named `name`. */
|
|
67
|
+
export declare function child(n: XmlNode, name: string): XmlElement | undefined;
|
|
68
|
+
/** Every element below a node named `name`, in document order. */
|
|
69
|
+
export declare function descendants(n: XmlNode, name: string): readonly XmlElement[];
|
|
70
|
+
/** All the text a node holds. */
|
|
71
|
+
export declare function textOf(n: XmlNode | undefined): string;
|
|
72
|
+
/** An attribute's value, by its name with or without a prefix. */
|
|
73
|
+
export declare function attribute(n: XmlNode | undefined, name: string): string | undefined;
|
package/dist/xml.js
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
// Spec: 0001-formats FR-004
|
|
2
|
+
/**
|
|
3
|
+
* XML as a typed tree of elements and text, written with every value escaped (no document is a template of values) and read with no
|
|
4
|
+
* outside package (commons 0001-formats FR-004). The reader takes elements, attributes in either quote, the five named entities
|
|
5
|
+
* and character references, CDATA, comments, processing instructions and the XML declaration, checks that every element is closed by its
|
|
6
|
+
* own name, and refuses a document type with an internal subset, so no entity is ever expanded (no "billion laughs", no external entity).
|
|
7
|
+
* Names are kept as written (`dc:title`); the finders match a name with or without its prefix. Taken from erga's `lib/ts/xml`, whose
|
|
8
|
+
* reader was `@std/xml`.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```ts
|
|
12
|
+
* import { el, readXml, textOf, writeXml } from "./xml.ts";
|
|
13
|
+
* const doc = writeXml(el("note", [el("to", ["Ada & Charles"])], [["lang", "en"]]));
|
|
14
|
+
* // '<?xml version="1.0" encoding="UTF-8"?>\n<note lang="en"><to>Ada & Charles</to></note>'
|
|
15
|
+
* const back = readXml(doc);
|
|
16
|
+
* if (back.kind === "ok") textOf(back.value); // "Ada & Charles"
|
|
17
|
+
* ```
|
|
18
|
+
*
|
|
19
|
+
* @module
|
|
20
|
+
*/
|
|
21
|
+
import { absurd, err, ok } from "@intellectual-frontiers/core";
|
|
22
|
+
const asNodes = (c) => c === undefined ? [] : typeof c === "object" ? [c] : [{ kind: "text", text: String(c) }];
|
|
23
|
+
/** An element. */
|
|
24
|
+
export function el(name, children = [], attributes = []) {
|
|
25
|
+
return { kind: "element", name, attributes, children: children.flatMap(asNodes) };
|
|
26
|
+
}
|
|
27
|
+
/** An element holding one value, or nothing where the value is absent. */
|
|
28
|
+
export function leaf(name, value) {
|
|
29
|
+
return value === undefined ? undefined : el(name, [value]);
|
|
30
|
+
}
|
|
31
|
+
const FORBIDDEN = new RegExp(`[${String.fromCharCode(0)}-${String.fromCharCode(8)}${String.fromCharCode(11, 12)}${String.fromCharCode(14)}-${String.fromCharCode(31)}\\ufffe\\uffff]`, "g");
|
|
32
|
+
/** A value as XML text or an attribute's value: `&`, `<`, `>`, `"` and `'` escaped, and the characters XML 1.0 forbids removed. */
|
|
33
|
+
export function escapeXml(s) {
|
|
34
|
+
return s
|
|
35
|
+
.replace(FORBIDDEN, "")
|
|
36
|
+
.replaceAll("&", "&")
|
|
37
|
+
.replaceAll("<", "<")
|
|
38
|
+
.replaceAll(">", ">")
|
|
39
|
+
.replaceAll('"', """)
|
|
40
|
+
.replaceAll("'", "'");
|
|
41
|
+
}
|
|
42
|
+
/** A node as XML text, with no declaration. */
|
|
43
|
+
export function writeNode(n) {
|
|
44
|
+
switch (n.kind) {
|
|
45
|
+
case "text":
|
|
46
|
+
return escapeXml(n.text);
|
|
47
|
+
case "element": {
|
|
48
|
+
const attrs = n.attributes.map(([k, v]) => ` ${k}="${escapeXml(v)}"`).join("");
|
|
49
|
+
return n.children.length === 0 ? `<${n.name}${attrs}/>` : `<${n.name}${attrs}>${n.children.map(writeNode).join("")}</${n.name}>`;
|
|
50
|
+
}
|
|
51
|
+
default:
|
|
52
|
+
return absurd(n);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/** A whole document: the XML declaration, then its root. */
|
|
56
|
+
export function writeXml(root) {
|
|
57
|
+
return `<?xml version="1.0" encoding="UTF-8"?>\n${writeNode(root)}`;
|
|
58
|
+
}
|
|
59
|
+
class Stop extends Error {
|
|
60
|
+
at;
|
|
61
|
+
constructor(at, message) {
|
|
62
|
+
super(message);
|
|
63
|
+
this.at = at;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
const NAME_START = /[:A-Z_a-z\p{L}\p{Nl}]/u;
|
|
67
|
+
const NAME_PART = /[-.0-9:A-Z_a-z\p{L}\p{Nl}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\u00b7]/u;
|
|
68
|
+
const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
|
|
69
|
+
/** A document read: its root element; or where and why it is not XML this reader takes. */
|
|
70
|
+
export function readXml(text, options = {}) {
|
|
71
|
+
let i = text.startsWith("\ufeff") ? 1 : 0;
|
|
72
|
+
const fail = (message, at = i) => {
|
|
73
|
+
throw new Stop(at, message);
|
|
74
|
+
};
|
|
75
|
+
const space = () => {
|
|
76
|
+
while (/[ \t\r\n]/.test(text[i] ?? ""))
|
|
77
|
+
i++;
|
|
78
|
+
};
|
|
79
|
+
const expect = (s) => {
|
|
80
|
+
if (!text.startsWith(s, i))
|
|
81
|
+
fail(`expected ${JSON.stringify(s)}`);
|
|
82
|
+
i += s.length;
|
|
83
|
+
};
|
|
84
|
+
const charAt = (at) => {
|
|
85
|
+
const cp = text.codePointAt(at);
|
|
86
|
+
return cp === undefined ? "" : String.fromCodePoint(cp);
|
|
87
|
+
};
|
|
88
|
+
const name = () => {
|
|
89
|
+
const start = i;
|
|
90
|
+
if (!NAME_START.test(charAt(i)))
|
|
91
|
+
fail("expected a name");
|
|
92
|
+
while (i < text.length && NAME_PART.test(charAt(i)))
|
|
93
|
+
i += charAt(i).length;
|
|
94
|
+
return text.slice(start, i);
|
|
95
|
+
};
|
|
96
|
+
const decode = (raw, at) => raw.replace(/&([^;&]*);?/g, (whole, ref, offset) => {
|
|
97
|
+
if (!whole.endsWith(";"))
|
|
98
|
+
fail("an entity reference that ends with ;", at + offset);
|
|
99
|
+
const named = ENTITIES[ref];
|
|
100
|
+
if (named !== undefined)
|
|
101
|
+
return named;
|
|
102
|
+
const m = /^#(?:x([0-9a-fA-F]+)|([0-9]+))$/.exec(ref);
|
|
103
|
+
const code = m === null ? Number.NaN : m[1] !== undefined ? Number.parseInt(m[1], 16) : Number(m[2]);
|
|
104
|
+
if (!Number.isInteger(code) || code < 1 || code > 0x10ffff)
|
|
105
|
+
fail(`a known entity or a character reference, not &${ref};`, at + offset);
|
|
106
|
+
return String.fromCodePoint(code);
|
|
107
|
+
});
|
|
108
|
+
const misc = () => {
|
|
109
|
+
for (;;) {
|
|
110
|
+
space();
|
|
111
|
+
if (text.startsWith("<!--", i)) {
|
|
112
|
+
const end = text.indexOf("-->", i + 4);
|
|
113
|
+
if (end < 0)
|
|
114
|
+
fail("a comment that is closed");
|
|
115
|
+
i = end + 3;
|
|
116
|
+
}
|
|
117
|
+
else if (text.startsWith("<?", i)) {
|
|
118
|
+
const end = text.indexOf("?>", i + 2);
|
|
119
|
+
if (end < 0)
|
|
120
|
+
fail("a processing instruction that is closed");
|
|
121
|
+
i = end + 2;
|
|
122
|
+
}
|
|
123
|
+
else if (text.startsWith("<!DOCTYPE", i)) {
|
|
124
|
+
const end = text.indexOf(">", i);
|
|
125
|
+
if (end < 0)
|
|
126
|
+
fail("a document type that is closed");
|
|
127
|
+
if (text.slice(i, end).includes("["))
|
|
128
|
+
fail("a document type with no internal subset (no entity is expanded)");
|
|
129
|
+
i = end + 1;
|
|
130
|
+
}
|
|
131
|
+
else
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
const element = (depth) => {
|
|
136
|
+
if (depth > 512)
|
|
137
|
+
fail("less nesting (more than 512 levels)");
|
|
138
|
+
expect("<");
|
|
139
|
+
const tag = name();
|
|
140
|
+
const attributes = [];
|
|
141
|
+
for (;;) {
|
|
142
|
+
const before = i;
|
|
143
|
+
space();
|
|
144
|
+
if (text.startsWith("/>", i)) {
|
|
145
|
+
i += 2;
|
|
146
|
+
return { kind: "element", name: tag, attributes, children: [] };
|
|
147
|
+
}
|
|
148
|
+
if (text[i] === ">") {
|
|
149
|
+
i++;
|
|
150
|
+
break;
|
|
151
|
+
}
|
|
152
|
+
if (i === before)
|
|
153
|
+
fail("white space before an attribute");
|
|
154
|
+
const keyAt = i;
|
|
155
|
+
const key = name();
|
|
156
|
+
if (attributes.some(([k]) => k === key))
|
|
157
|
+
fail(`the attribute ${key} only once`, keyAt);
|
|
158
|
+
space();
|
|
159
|
+
expect("=");
|
|
160
|
+
space();
|
|
161
|
+
const quote = text[i];
|
|
162
|
+
if (quote !== '"' && quote !== "'")
|
|
163
|
+
fail("a quoted attribute value");
|
|
164
|
+
const end = text.indexOf(quote ?? "", i + 1);
|
|
165
|
+
if (end < 0)
|
|
166
|
+
fail("a closing quote");
|
|
167
|
+
const raw = text.slice(i + 1, end);
|
|
168
|
+
if (raw.includes("<"))
|
|
169
|
+
fail("no < in an attribute value", i + 1 + raw.indexOf("<"));
|
|
170
|
+
attributes.push([key, decode(raw, i + 1).replace(/[\t\n\r]/g, " ")]);
|
|
171
|
+
i = end + 1;
|
|
172
|
+
}
|
|
173
|
+
const children = [];
|
|
174
|
+
let buffer = "";
|
|
175
|
+
let whitespaceOnly = true;
|
|
176
|
+
const flush = () => {
|
|
177
|
+
if (buffer !== "" && (options.keepWhitespace === true || !whitespaceOnly))
|
|
178
|
+
children.push({ kind: "text", text: buffer });
|
|
179
|
+
buffer = "";
|
|
180
|
+
whitespaceOnly = true;
|
|
181
|
+
};
|
|
182
|
+
for (;;) {
|
|
183
|
+
if (i >= text.length)
|
|
184
|
+
fail(`the end tag </${tag}>`);
|
|
185
|
+
if (text.startsWith("</", i)) {
|
|
186
|
+
flush();
|
|
187
|
+
i += 2;
|
|
188
|
+
const at = i;
|
|
189
|
+
const closing = name();
|
|
190
|
+
if (closing !== tag)
|
|
191
|
+
fail(`</${tag}>, not </${closing}>`, at);
|
|
192
|
+
space();
|
|
193
|
+
expect(">");
|
|
194
|
+
return { kind: "element", name: tag, attributes, children };
|
|
195
|
+
}
|
|
196
|
+
if (text.startsWith("<![CDATA[", i)) {
|
|
197
|
+
const end = text.indexOf("]]>", i + 9);
|
|
198
|
+
if (end < 0)
|
|
199
|
+
fail("a CDATA section that is closed");
|
|
200
|
+
buffer += text.slice(i + 9, end);
|
|
201
|
+
whitespaceOnly = false;
|
|
202
|
+
i = end + 3;
|
|
203
|
+
}
|
|
204
|
+
else if (text.startsWith("<!--", i)) {
|
|
205
|
+
const end = text.indexOf("-->", i + 4);
|
|
206
|
+
if (end < 0)
|
|
207
|
+
fail("a comment that is closed");
|
|
208
|
+
i = end + 3;
|
|
209
|
+
}
|
|
210
|
+
else if (text.startsWith("<?", i)) {
|
|
211
|
+
const end = text.indexOf("?>", i + 2);
|
|
212
|
+
if (end < 0)
|
|
213
|
+
fail("a processing instruction that is closed");
|
|
214
|
+
i = end + 2;
|
|
215
|
+
}
|
|
216
|
+
else if (text[i] === "<") {
|
|
217
|
+
flush();
|
|
218
|
+
children.push(element(depth + 1));
|
|
219
|
+
}
|
|
220
|
+
else {
|
|
221
|
+
const next = text.indexOf("<", i);
|
|
222
|
+
const end = next < 0 ? text.length : next;
|
|
223
|
+
const raw = text.slice(i, end);
|
|
224
|
+
const decoded = decode(raw, i);
|
|
225
|
+
if (!/^[ \t\r\n]*$/.test(decoded))
|
|
226
|
+
whitespaceOnly = false;
|
|
227
|
+
buffer += decoded;
|
|
228
|
+
i = end;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
};
|
|
232
|
+
try {
|
|
233
|
+
misc();
|
|
234
|
+
if (text[i] !== "<")
|
|
235
|
+
fail("a root element");
|
|
236
|
+
const root = element(0);
|
|
237
|
+
misc();
|
|
238
|
+
if (i < text.length)
|
|
239
|
+
fail("nothing after the root element");
|
|
240
|
+
return ok(root);
|
|
241
|
+
}
|
|
242
|
+
catch (e) {
|
|
243
|
+
if (!(e instanceof Stop))
|
|
244
|
+
throw e;
|
|
245
|
+
const before = text.slice(0, e.at).split(/\r\n|[\n\r]/);
|
|
246
|
+
return err({ kind: "xml", line: before.length, column: (before.at(-1)?.length ?? 0) + 1, message: e.message });
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
/** An XML error as one line: `3:14: expected a name`. */
|
|
250
|
+
export function formatXmlError(e) {
|
|
251
|
+
return `${e.line}:${e.column}: ${e.message}`;
|
|
252
|
+
}
|
|
253
|
+
/** A name without its prefix: `title` for `dc:title`. */
|
|
254
|
+
export function localName(name) {
|
|
255
|
+
const at = name.indexOf(":");
|
|
256
|
+
return at < 0 ? name : name.slice(at + 1);
|
|
257
|
+
}
|
|
258
|
+
const named = (n, name) => n.kind === "element" && (n.name === name || localName(n.name) === name);
|
|
259
|
+
/** The child elements of a node named `name` (with or without a prefix). */
|
|
260
|
+
export function children(n, name) {
|
|
261
|
+
return n.kind === "element" ? n.children.filter((c) => named(c, name)) : [];
|
|
262
|
+
}
|
|
263
|
+
/** The first child element named `name`. */
|
|
264
|
+
export function child(n, name) {
|
|
265
|
+
return children(n, name)[0];
|
|
266
|
+
}
|
|
267
|
+
/** Every element below a node named `name`, in document order. */
|
|
268
|
+
export function descendants(n, name) {
|
|
269
|
+
if (n.kind !== "element")
|
|
270
|
+
return [];
|
|
271
|
+
return n.children.flatMap((c) => [...(named(c, name) ? [c] : []), ...descendants(c, name)]);
|
|
272
|
+
}
|
|
273
|
+
/** All the text a node holds. */
|
|
274
|
+
export function textOf(n) {
|
|
275
|
+
if (n === undefined)
|
|
276
|
+
return "";
|
|
277
|
+
return n.kind === "text" ? n.text : n.children.map(textOf).join("");
|
|
278
|
+
}
|
|
279
|
+
/** An attribute's value, by its name with or without a prefix. */
|
|
280
|
+
export function attribute(n, name) {
|
|
281
|
+
return n?.kind === "element" ? n.attributes.find(([k]) => k === name || localName(k) === name)?.[1] : undefined;
|
|
282
|
+
}
|
package/dist/yaml.d.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* YAML 1.2 for data (commons 0001-formats FR-002), read and written with no outside package. The reader takes what data files,
|
|
3
|
+
* front matter and configuration use: block mappings and sequences (a sequence may sit at its key's indentation, and a mapping may begin
|
|
4
|
+
* on a sequence's dash), flow collections over several lines, plain scalars folded over several lines, single- and double-quoted scalars
|
|
5
|
+
* with every escape of YAML 1.2, literal and folded block scalars with their chomping and indentation indicators, comments and one
|
|
6
|
+
* document between `---` and `...`. Plain scalars resolve by the core schema (null, booleans, integers in decimal, octal and hexadecimal,
|
|
7
|
+
* floats with `.inf` and `.nan`) or, with the failsafe schema, stay text. It refuses, with the line and column and the reason, what makes
|
|
8
|
+
* data ambiguous or unsafe to read: anchors and aliases (and so no "billion laughs"), tags, complex keys, directives, more than one
|
|
9
|
+
* document, a key given twice and a tab used for indentation. The writer gives block YAML that the reader reads back as the same value.
|
|
10
|
+
* Replaces `@std/yaml` in erga.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```ts
|
|
14
|
+
* import { parseYaml, toYaml } from "./yaml.js";
|
|
15
|
+
* parseYaml("name: skill\ntags: [a, b]\nsteps:\n - run: build\n times: 2\n");
|
|
16
|
+
* // { kind: "ok", value: { name: "skill", tags: ["a", "b"], steps: [{ run: "build", times: 2 }] } }
|
|
17
|
+
* toYaml({ name: "skill", on: true }); // "name: skill\non: true\n" (YAML 1.2: "on" is only text)
|
|
18
|
+
* ```
|
|
19
|
+
*
|
|
20
|
+
* @module
|
|
21
|
+
*/
|
|
22
|
+
import type { Json } from "./json5.js";
|
|
23
|
+
import { type Result } from "@intellectual-frontiers/core";
|
|
24
|
+
/** Where a text stops being YAML this reader takes, and why. Lines and columns count from 1. */
|
|
25
|
+
export type YamlError = {
|
|
26
|
+
readonly kind: "yaml";
|
|
27
|
+
readonly line: number;
|
|
28
|
+
readonly column: number;
|
|
29
|
+
readonly message: string;
|
|
30
|
+
};
|
|
31
|
+
/** A YAML error as one line: `3:14: anchors and aliases are not read`. */
|
|
32
|
+
export declare function formatYamlError(e: YamlError): string;
|
|
33
|
+
/** How plain scalars resolve: by YAML 1.2's core schema (the default), or all as text (failsafe). */
|
|
34
|
+
export type YamlOptions = {
|
|
35
|
+
readonly schema?: "core" | "failsafe";
|
|
36
|
+
};
|
|
37
|
+
/** A plain scalar resolved by YAML 1.2's core schema. */
|
|
38
|
+
export declare function resolveCore(s: string): Json;
|
|
39
|
+
/** A YAML text read as a JSON value (an empty document is `null`), or where and why it is not YAML this reader takes. */
|
|
40
|
+
export declare function parseYaml(text: string, options?: YamlOptions): Result<Json, YamlError>;
|
|
41
|
+
/** Whether text can be written as a plain scalar and read back as the same text by the core schema. */
|
|
42
|
+
export declare function isPlainSafe(s: string): boolean;
|
|
43
|
+
/** A value as block YAML, ending in a line break: mappings and sequences by indentation, text plain where it reads back the same, else double-quoted. */
|
|
44
|
+
export declare function toYaml(value: Json): string;
|