@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.
Files changed (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +8 -2
  3. package/dist/archive.d.ts +147 -0
  4. package/dist/archive.js +765 -0
  5. package/dist/base64.d.ts +24 -0
  6. package/dist/base64.js +52 -0
  7. package/dist/cbor.d.ts +39 -0
  8. package/dist/cbor.js +244 -0
  9. package/dist/csv.d.ts +38 -0
  10. package/dist/csv.js +130 -0
  11. package/dist/der.d.ts +67 -0
  12. package/dist/der.js +221 -0
  13. package/dist/glob.d.ts +64 -0
  14. package/dist/glob.js +218 -0
  15. package/dist/hex.d.ts +17 -0
  16. package/dist/hex.js +30 -0
  17. package/dist/http.d.ts +46 -0
  18. package/dist/http.js +102 -0
  19. package/dist/json5.d.ts +46 -0
  20. package/dist/json5.js +291 -0
  21. package/dist/media-types.d.ts +28 -0
  22. package/dist/media-types.js +121 -0
  23. package/dist/mod.d.ts +39 -0
  24. package/dist/mod.js +31 -0
  25. package/dist/png.d.ts +124 -0
  26. package/dist/png.js +607 -0
  27. package/dist/semver.d.ts +94 -0
  28. package/dist/semver.js +331 -0
  29. package/dist/toml.d.ts +51 -0
  30. package/dist/toml.js +583 -0
  31. package/dist/ts-literal.d.ts +62 -0
  32. package/dist/ts-literal.js +173 -0
  33. package/dist/xml.d.ts +73 -0
  34. package/dist/xml.js +282 -0
  35. package/dist/yaml.d.ts +44 -0
  36. package/dist/yaml.js +706 -0
  37. package/package.json +118 -4
  38. package/src/archive.ts +831 -0
  39. package/src/base64.ts +51 -0
  40. package/src/cbor.ts +235 -0
  41. package/src/csv.ts +132 -0
  42. package/src/der.ts +224 -0
  43. package/src/glob.ts +210 -0
  44. package/src/hex.ts +28 -0
  45. package/src/http.ts +104 -0
  46. package/src/json5.ts +267 -0
  47. package/src/media-types.ts +127 -0
  48. package/src/mod.ts +102 -0
  49. package/src/png.ts +625 -0
  50. package/src/semver.ts +373 -0
  51. package/src/toml.ts +525 -0
  52. package/src/ts-literal.ts +183 -0
  53. package/src/xml.ts +291 -0
  54. package/src/yaml.ts +616 -0
package/src/toml.ts ADDED
@@ -0,0 +1,525 @@
1
+ // Spec: 0001-formats FR-003
2
+ /**
3
+ * TOML 1.0.0 (https://toml.io/en/v1.0.0), read and written with no outside package (commons 0001-formats FR-003). The reader
4
+ * takes the whole language (bare, quoted and dotted keys; tables, arrays of tables and inline tables; the four kinds of string; decimal,
5
+ * hexadecimal, octal and binary integers; floats with `inf` and `nan`; the four kinds of date and time) and holds to its rules: no key or
6
+ * table defined twice, an inline table or a static array never extended, a table made by dotted keys never reopened by a header. It
7
+ * gives a typed `TomlTable`, or the line and column where the text stops being TOML. An integer outside JavaScript's safe range is refused
8
+ * rather than rounded. A date or time stays as its text, with its kind. The writer gives TOML the reader reads back as the same table.
9
+ * Replaces `@std/toml` in erga.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * import { parseToml } from "./toml.ts";
14
+ * parseToml('[server]\nhost = "127.0.0.1"\nports = [8000, 8001]\n');
15
+ * // { kind: "ok", value: { server: { host: "127.0.0.1", ports: [8000, 8001] } } }
16
+ * ```
17
+ *
18
+ * @module
19
+ */
20
+ import { err, ok, type Result } from "@intellectual-frontiers/core";
21
+
22
+ /** A date, a time, or both, as TOML wrote it (a space between date and time made `T`), with which of the four it is. */
23
+ export type TomlDateTime = {
24
+ readonly kind: "offset-date-time" | "local-date-time" | "local-date" | "local-time";
25
+ readonly text: string;
26
+ };
27
+
28
+ /** A TOML value. */
29
+ export type TomlValue = string | number | boolean | TomlDateTime | readonly TomlValue[] | TomlTable;
30
+
31
+ /** A TOML table: its keys in the order they were defined. */
32
+ export type TomlTable = { readonly [key: string]: TomlValue };
33
+
34
+ /** Where a text stops being TOML, and why. Lines and columns count from 1. */
35
+ export type TomlError = { readonly kind: "toml"; readonly line: number; readonly column: number; readonly message: string };
36
+
37
+ /** A TOML error as one line: `3:14: expected a value`. */
38
+ export function formatTomlError(e: TomlError): string {
39
+ return `${e.line}:${e.column}: ${e.message}`;
40
+ }
41
+
42
+ /** Whether a TOML value is a date or time. */
43
+ export function isTomlDateTime(v: TomlValue): v is TomlDateTime {
44
+ return (
45
+ typeof v === "object" &&
46
+ !Array.isArray(v) &&
47
+ Object.keys(v).length === 2 &&
48
+ "kind" in v &&
49
+ "text" in v &&
50
+ typeof v["text"] === "string" &&
51
+ typeof v["kind"] === "string" &&
52
+ /^(offset-date-time|local-date-time|local-date|local-time)$/.test(v["kind"])
53
+ );
54
+ }
55
+
56
+ /** Whether a TOML value is a table (not an array, not a date or time). */
57
+ export function isTomlTable(v: TomlValue): v is TomlTable {
58
+ return typeof v === "object" && !Array.isArray(v) && !isTomlDateTime(v);
59
+ }
60
+
61
+ class Stop extends Error {
62
+ readonly at: number;
63
+ constructor(at: number, message: string) {
64
+ super(message);
65
+ this.at = at;
66
+ }
67
+ }
68
+
69
+ type Mutable = Record<string, TomlValue>;
70
+
71
+ const BARE = /^[A-Za-z0-9_-]+/;
72
+ const ESCAPES: Readonly<Record<string, string>> = { b: "\b", t: "\t", n: "\n", f: "\f", r: "\r", '"': '"', "\\": "\\" };
73
+ const CONTROL = new RegExp(`[${String.fromCharCode(0)}-${String.fromCharCode(8, 10)}-${String.fromCharCode(31, 127)}]`);
74
+ const DATE = /^(\d{4})-(\d{2})-(\d{2})/;
75
+ const TIME = /^(\d{2}):(\d{2}):(\d{2})(\.\d+)?/;
76
+ const OFFSET = /^(?:[Zz]|[+-](\d{2}):(\d{2}))/;
77
+
78
+ function validDate(y: number, m: number, d: number): boolean {
79
+ if (m < 1 || m > 12 || d < 1) return false;
80
+ const days = [31, (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0 ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][m - 1] ?? 0;
81
+ return d <= days;
82
+ }
83
+
84
+ /** TOML text read as a table, or where and why it is not TOML. */
85
+ export function parseToml(text: string): Result<TomlTable, TomlError> {
86
+ let i = 0;
87
+ const root: Mutable = {};
88
+ /** Tables a header defined; tables a header made on its way; tables dotted keys made; inline tables and static arrays; arrays of tables. */
89
+ const defined = new Set<object>();
90
+ const byHeader = new Set<object>();
91
+ const byDots = new Set<object>();
92
+ const frozen = new Set<object>();
93
+ const tableArrays = new Set<object>();
94
+ const fail = (message: string, at = i): never => {
95
+ throw new Stop(at, message);
96
+ };
97
+ const peek = (n = 0): string => text[i + n] ?? "";
98
+ const blank = (): void => {
99
+ while (peek() === " " || peek() === "\t") i++;
100
+ };
101
+ const comment = (): void => {
102
+ if (peek() !== "#") return;
103
+ while (i < text.length && peek() !== "\n" && !(peek() === "\r" && peek(1) === "\n")) {
104
+ if (CONTROL.test(peek()) && peek() !== "\t") fail("no control character in a comment");
105
+ i++;
106
+ }
107
+ };
108
+ const newline = (): boolean => {
109
+ if (peek() === "\n") {
110
+ i++;
111
+ return true;
112
+ }
113
+ if (peek() === "\r" && peek(1) === "\n") {
114
+ i += 2;
115
+ return true;
116
+ }
117
+ return false;
118
+ };
119
+ const endOfLine = (): void => {
120
+ blank();
121
+ comment();
122
+ if (i < text.length && !newline()) fail("the end of the line");
123
+ };
124
+ /** Space, comments and line breaks, as an array allows between its values. */
125
+ const gap = (): void => {
126
+ for (;;) {
127
+ blank();
128
+ comment();
129
+ if (!newline()) return;
130
+ }
131
+ };
132
+ const hexChar = (n: number): string => {
133
+ const h = text.slice(i, i + n);
134
+ if (h.length !== n || !/^[0-9a-fA-F]+$/.test(h)) fail(`${n} hexadecimal digits`);
135
+ const cp = Number.parseInt(h, 16);
136
+ if (cp > 0x10ffff || (cp >= 0xd800 && cp <= 0xdfff)) fail("a Unicode scalar value", i - 2);
137
+ i += n;
138
+ return String.fromCodePoint(cp);
139
+ };
140
+ const escape = (): string => {
141
+ const c = peek();
142
+ i++;
143
+ const simple = ESCAPES[c];
144
+ if (simple !== undefined) return simple;
145
+ if (c === "u") return hexChar(4);
146
+ if (c === "U") return hexChar(8);
147
+ return fail(`a known escape, not \\${c}`, i - 2);
148
+ };
149
+ const basic = (): string => {
150
+ i++;
151
+ let out = "";
152
+ for (;;) {
153
+ const c = peek();
154
+ if (c === "" || c === "\n" || c === "\r") fail("the closing quote of a string");
155
+ i++;
156
+ if (c === '"') return out;
157
+ if (c === "\\") out += escape();
158
+ else if (CONTROL.test(c)) fail("no control character in a string", i - 1);
159
+ else out += c;
160
+ }
161
+ };
162
+ const literal = (): string => {
163
+ i++;
164
+ const start = i;
165
+ for (;;) {
166
+ const c = peek();
167
+ if (c === "" || c === "\n" || c === "\r") fail("the closing quote of a string");
168
+ if (c === "'") break;
169
+ if (CONTROL.test(c)) fail("no control character in a string");
170
+ i++;
171
+ }
172
+ const s = text.slice(start, i);
173
+ i++;
174
+ return s;
175
+ };
176
+ const multiline = (quote: '"' | "'"): string => {
177
+ i += 3;
178
+ newline();
179
+ let out = "";
180
+ for (;;) {
181
+ if (i >= text.length) fail("the closing quotes of a multi-line string");
182
+ if (text.startsWith(quote.repeat(3), i)) {
183
+ let n = 3;
184
+ while (peek(n) === quote && n < 5) n++;
185
+ out += quote.repeat(n - 3);
186
+ i += n;
187
+ return out;
188
+ }
189
+ const c = peek();
190
+ if (newline()) {
191
+ out += "\n";
192
+ continue;
193
+ }
194
+ if (quote === '"' && c === "\\") {
195
+ let j = i + 1;
196
+ while (text[j] === " " || text[j] === "\t") j++;
197
+ if (text[j] === "\n" || (text[j] === "\r" && text[j + 1] === "\n")) {
198
+ i = j;
199
+ while (newline() || peek() === " " || peek() === "\t") if (peek() === " " || peek() === "\t") i++;
200
+ continue;
201
+ }
202
+ i++;
203
+ out += escape();
204
+ continue;
205
+ }
206
+ if (CONTROL.test(c) && c !== "\t") fail("no control character in a string");
207
+ out += c;
208
+ i++;
209
+ }
210
+ };
211
+ const key = (): string => {
212
+ const c = peek();
213
+ if (c === '"') return text.startsWith('"""', i) ? fail("a key on one line") : basic();
214
+ if (c === "'") return text.startsWith("'''", i) ? fail("a key on one line") : literal();
215
+ const m = BARE.exec(text.slice(i));
216
+ if (m === null) return fail("a key");
217
+ i += m[0].length;
218
+ return m[0];
219
+ };
220
+ const dottedKey = (): string[] => {
221
+ const parts = [key()];
222
+ for (;;) {
223
+ blank();
224
+ if (peek() !== ".") return parts;
225
+ i++;
226
+ blank();
227
+ parts.push(key());
228
+ }
229
+ };
230
+ const dateTime = (): TomlDateTime | undefined => {
231
+ const start = i;
232
+ const rest = text.slice(i);
233
+ const d = DATE.exec(rest);
234
+ if (d !== null) {
235
+ if (!validDate(Number(d[1]), Number(d[2]), Number(d[3]))) fail("a real date", start);
236
+ i += d[0].length;
237
+ const sep = peek();
238
+ const t = sep === "T" || sep === "t" || sep === " " ? TIME.exec(text.slice(i + 1)) : null;
239
+ if (t === null) return { kind: "local-date", text: d[0] };
240
+ i += 1;
241
+ time(t, start);
242
+ const o = OFFSET.exec(text.slice(i));
243
+ if (o !== null) {
244
+ if (o[1] !== undefined && (Number(o[1]) > 23 || Number(o[2]) > 59)) fail("a real offset");
245
+ i += o[0].length;
246
+ return { kind: "offset-date-time", text: `${d[0]}T${text.slice(start + 11, i)}` };
247
+ }
248
+ return { kind: "local-date-time", text: `${d[0]}T${text.slice(start + 11, i)}` };
249
+ }
250
+ const t = TIME.exec(rest);
251
+ if (t === null) return undefined;
252
+ time(t, start);
253
+ return { kind: "local-time", text: t[0] };
254
+ };
255
+ const time = (t: RegExpExecArray, start: number): void => {
256
+ if (Number(t[1]) > 23 || Number(t[2]) > 59 || Number(t[3]) > 60) fail("a real time", start);
257
+ i += t[0].length;
258
+ };
259
+ const number = (): number => {
260
+ const start = i;
261
+ const rest = text.slice(i);
262
+ const special = /^([+-]?)(inf|nan)/.exec(rest);
263
+ if (special !== null) {
264
+ i += special[0].length;
265
+ return special[2] === "nan" ? Number.NaN : special[1] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY;
266
+ }
267
+ const radix = /^0(?:x([0-9A-Fa-f](?:_?[0-9A-Fa-f])*)|o([0-7](?:_?[0-7])*)|b([01](?:_?[01])*))/.exec(rest);
268
+ if (radix !== null) {
269
+ i += radix[0].length;
270
+ const [digits, base] = radix[1] !== undefined ? [radix[1], 16] : radix[2] !== undefined ? [radix[2], 8] : [radix[3] ?? "", 2];
271
+ const n = Number.parseInt(digits.replaceAll("_", ""), base);
272
+ if (!Number.isSafeInteger(n)) fail("an integer JavaScript holds exactly (at most 2^53 - 1)", start);
273
+ return n;
274
+ }
275
+ const dec = /^[+-]?(?:0|[1-9](?:_?\d)*)(\.\d(?:_?\d)*)?([eE][+-]?\d(?:_?\d)*)?/.exec(rest);
276
+ if (dec === null) return fail("a value");
277
+ i += dec[0].length;
278
+ const n = Number(dec[0].replaceAll("_", ""));
279
+ if (dec[1] === undefined && dec[2] === undefined && !Number.isSafeInteger(n))
280
+ fail("an integer JavaScript holds exactly (at most 2^53 - 1)", start);
281
+ return n;
282
+ };
283
+ const value = (depth: number): TomlValue => {
284
+ if (depth > 256) fail("less nesting (more than 256 levels)");
285
+ const c = peek();
286
+ let v: TomlValue;
287
+ if (text.startsWith('"""', i)) v = multiline('"');
288
+ else if (text.startsWith("'''", i)) v = multiline("'");
289
+ else if (c === '"') v = basic();
290
+ else if (c === "'") v = literal();
291
+ else if (text.startsWith("true", i)) {
292
+ i += 4;
293
+ v = true;
294
+ } else if (text.startsWith("false", i)) {
295
+ i += 5;
296
+ v = false;
297
+ } else if (c === "[") v = array(depth);
298
+ else if (c === "{") v = inline(depth);
299
+ else v = dateTime() ?? number();
300
+ const after = peek();
301
+ if (!(after === "" || /[ \t\r\n#,\]}]/.test(after))) fail("the end of the value");
302
+ return v;
303
+ };
304
+ const array = (depth: number): TomlValue[] => {
305
+ i++;
306
+ const out: TomlValue[] = [];
307
+ for (;;) {
308
+ gap();
309
+ if (peek() === "]") {
310
+ i++;
311
+ frozen.add(out);
312
+ return out;
313
+ }
314
+ out.push(value(depth + 1));
315
+ gap();
316
+ if (peek() === ",") i++;
317
+ else if (peek() !== "]") fail("a comma or ]");
318
+ }
319
+ };
320
+ const inline = (depth: number): Mutable => {
321
+ i++;
322
+ const table: Mutable = {};
323
+ blank();
324
+ if (peek() === "}") {
325
+ i++;
326
+ frozen.add(table);
327
+ return table;
328
+ }
329
+ for (;;) {
330
+ blank();
331
+ const keyAt = i;
332
+ const path = dottedKey();
333
+ blank();
334
+ if (peek() !== "=") fail("=");
335
+ i++;
336
+ blank();
337
+ assign(table, path, value(depth + 1), keyAt, true);
338
+ blank();
339
+ if (peek() === ",") {
340
+ i++;
341
+ blank();
342
+ if (peek() === "}") fail("a key after the comma (no trailing comma in an inline table)");
343
+ continue;
344
+ }
345
+ if (peek() === "}") {
346
+ i++;
347
+ frozen.add(table);
348
+ return table;
349
+ }
350
+ fail("a comma or }");
351
+ }
352
+ };
353
+ const isTable = (v: TomlValue | undefined): v is Mutable =>
354
+ v !== undefined && typeof v === "object" && !Array.isArray(v) && !isTomlDateTime(v);
355
+ const define = (t: Mutable, k: string, v: TomlValue): void => {
356
+ Object.defineProperty(t, k, { value: v, enumerable: true, writable: true, configurable: true });
357
+ };
358
+ const assign = (table: Mutable, path: readonly string[], v: TomlValue, at: number, inInline: boolean): void => {
359
+ let t = table;
360
+ for (const k of path.slice(0, -1)) {
361
+ const next = Object.hasOwn(t, k) ? t[k] : undefined;
362
+ if (next === undefined) {
363
+ const made: Mutable = {};
364
+ define(t, k, made);
365
+ byDots.add(made);
366
+ if (inInline) frozen.add(made);
367
+ t = made;
368
+ } else if (isTable(next) && byDots.has(next) && !frozen.has(next)) t = next;
369
+ else if (isTable(next) && byDots.has(next) && inInline) t = next;
370
+ else fail(`a key not already defined: ${path.join(".")}`, at);
371
+ }
372
+ const last = path.at(-1) ?? "";
373
+ if (Object.hasOwn(t, last)) fail(`a key not already defined: ${path.join(".")}`, at);
374
+ define(t, last, v);
375
+ };
376
+ const header = (path: readonly string[], array: boolean, at: number): Mutable => {
377
+ let t = root;
378
+ for (const k of path.slice(0, -1)) {
379
+ const next = Object.hasOwn(t, k) ? t[k] : undefined;
380
+ if (next === undefined) {
381
+ const made: Mutable = {};
382
+ define(t, k, made);
383
+ byHeader.add(made);
384
+ t = made;
385
+ } else if (Array.isArray(next) && tableArrays.has(next)) {
386
+ const list: readonly TomlValue[] = next;
387
+ const lastTable = list.at(-1);
388
+ if (!isTable(lastTable)) return fail("a table", at);
389
+ t = lastTable;
390
+ } else if (isTable(next) && !frozen.has(next)) t = next;
391
+ else return fail(`a header that does not extend a value: ${path.join(".")}`, at);
392
+ }
393
+ const last = path.at(-1) ?? "";
394
+ const existing = Object.hasOwn(t, last) ? t[last] : undefined;
395
+ if (array) {
396
+ const made: Mutable = {};
397
+ byHeader.add(made);
398
+ defined.add(made);
399
+ if (existing === undefined) {
400
+ const list: TomlValue[] = [made];
401
+ tableArrays.add(list);
402
+ define(t, last, list);
403
+ } else if (Array.isArray(existing) && tableArrays.has(existing)) (existing as TomlValue[]).push(made);
404
+ else fail(`[[${path.join(".")}]] where a value or table already is`, at);
405
+ return made;
406
+ }
407
+ if (existing === undefined) {
408
+ const made: Mutable = {};
409
+ byHeader.add(made);
410
+ defined.add(made);
411
+ define(t, last, made);
412
+ return made;
413
+ }
414
+ if (isTable(existing) && byHeader.has(existing) && !defined.has(existing)) {
415
+ defined.add(existing);
416
+ return existing;
417
+ }
418
+ return fail(`[${path.join(".")}] defined only once`, at);
419
+ };
420
+ try {
421
+ if (text.startsWith("\ufeff")) i = 1;
422
+ let current = root;
423
+ for (;;) {
424
+ gap();
425
+ if (i >= text.length) return ok(root);
426
+ const at = i;
427
+ if (text.startsWith("[[", i)) {
428
+ i += 2;
429
+ blank();
430
+ const path = dottedKey();
431
+ blank();
432
+ if (!text.startsWith("]]", i)) fail("]]");
433
+ i += 2;
434
+ current = header(path, true, at);
435
+ } else if (peek() === "[") {
436
+ i++;
437
+ blank();
438
+ const path = dottedKey();
439
+ blank();
440
+ if (peek() !== "]") fail("]");
441
+ i++;
442
+ current = header(path, false, at);
443
+ } else {
444
+ const path = dottedKey();
445
+ blank();
446
+ if (peek() !== "=") fail("=");
447
+ i++;
448
+ blank();
449
+ assign(current, path, value(0), at, false);
450
+ }
451
+ endOfLine();
452
+ }
453
+ } catch (e) {
454
+ if (!(e instanceof Stop)) throw e;
455
+ const before = text.slice(0, e.at).split(/\r?\n/);
456
+ return err({ kind: "toml", line: before.length, column: (before.at(-1)?.length ?? 0) + 1, message: `expected ${e.message}` });
457
+ }
458
+ }
459
+
460
+ const BARE_KEY = /^[A-Za-z0-9_-]+$/;
461
+
462
+ /** A key as TOML writes it: bare where it can be, else a basic string. */
463
+ export function tomlKey(k: string): string {
464
+ return BARE_KEY.test(k) ? k : tomlString(k);
465
+ }
466
+
467
+ /** A string as a TOML basic string: `"`, `\` and every control character escaped. */
468
+ export function tomlString(s: string): string {
469
+ let out = '"';
470
+ for (const ch of s) {
471
+ const code = ch.codePointAt(0) ?? 0;
472
+ if (ch === '"') out += '\\"';
473
+ else if (ch === "\\") out += "\\\\";
474
+ else if (ch === "\n") out += "\\n";
475
+ else if (ch === "\t") out += "\\t";
476
+ else if (ch === "\r") out += "\\r";
477
+ else if (code < 0x20 || code === 0x7f) out += `\\u${code.toString(16).padStart(4, "0")}`;
478
+ else out += ch;
479
+ }
480
+ return `${out}"`;
481
+ }
482
+
483
+ function scalar(v: TomlValue): string {
484
+ if (typeof v === "string") return tomlString(v);
485
+ if (typeof v === "boolean") return String(v);
486
+ if (typeof v === "number") {
487
+ if (Number.isNaN(v)) return "nan";
488
+ if (!Number.isFinite(v)) return v > 0 ? "inf" : "-inf";
489
+ if (Object.is(v, -0)) return "-0.0";
490
+ if (Number.isInteger(v) && !Number.isSafeInteger(v)) return v.toExponential();
491
+ return String(v);
492
+ }
493
+ if (Array.isArray(v)) return `[${v.map(scalar).join(", ")}]`;
494
+ if (isTomlDateTime(v)) return v.text;
495
+ const entries = Object.entries(v);
496
+ return entries.length === 0 ? "{}" : `{ ${entries.map(([k, x]) => `${tomlKey(k)} = ${scalar(x)}`).join(", ")} }`;
497
+ }
498
+
499
+ const isTableArray = (v: TomlValue): v is readonly TomlTable[] =>
500
+ Array.isArray(v) && v.length > 0 && v.every((x: TomlValue) => isTomlTable(x));
501
+
502
+ function section(table: TomlTable, path: readonly string[], out: string[]): void {
503
+ const entries = Object.entries(table);
504
+ for (const [k, v] of entries) if (!isTomlTable(v) && !isTableArray(v)) out.push(`${tomlKey(k)} = ${scalar(v)}`);
505
+ for (const [k, v] of entries) {
506
+ const name = [...path, k].map(tomlKey).join(".");
507
+ if (isTomlTable(v)) {
508
+ out.push("", `[${name}]`);
509
+ section(v, [...path, k], out);
510
+ } else if (isTableArray(v)) {
511
+ for (const t of v) {
512
+ out.push("", `[[${name}]]`);
513
+ section(t, [...path, k], out);
514
+ }
515
+ }
516
+ }
517
+ }
518
+
519
+ /** A table as TOML text: plain values first, then each table under its header and each array of tables under `[[...]]`, ending in a line break. */
520
+ export function toToml(table: TomlTable): string {
521
+ const out: string[] = [];
522
+ section(table, [], out);
523
+ while (out[0] === "") out.shift();
524
+ return out.length === 0 ? "" : `${out.join("\n")}\n`;
525
+ }