@enmaq/mdgl 0.2.0 → 0.3.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/README.md +71 -33
- package/UNICODE-LICENSE.txt +39 -0
- package/bin/mdgl-adapter.js +31 -0
- package/bin/mdgl.js +105 -0
- package/dist/adapter.d.ts +7 -0
- package/dist/adapter.js +231 -0
- package/dist/check.d.ts +48 -0
- package/dist/check.js +374 -0
- package/dist/eval.d.ts +53 -0
- package/dist/eval.js +496 -0
- package/dist/index.d.ts +14 -15
- package/dist/index.js +36 -98
- package/dist/parse.d.ts +117 -0
- package/dist/parse.js +424 -0
- package/dist/play.d.ts +44 -0
- package/dist/play.js +153 -0
- package/dist/unicode-tables.d.ts +7 -0
- package/dist/unicode-tables.js +15 -0
- package/dist/unicode.d.ts +12 -0
- package/dist/unicode.js +109 -0
- package/package.json +12 -4
package/README.md
CHANGED
|
@@ -1,49 +1,87 @@
|
|
|
1
|
-
# @enmaq/mdgl (npm
|
|
1
|
+
# @enmaq/mdgl (npm)
|
|
2
2
|
|
|
3
|
-
One npm package for JavaScript and TypeScript.
|
|
4
|
-
`
|
|
5
|
-
|
|
6
|
-
build artifact and is not committed.
|
|
3
|
+
One npm package for JavaScript and TypeScript. TypeScript source is `src/`
|
|
4
|
+
(`parse.ts` syntax, `check.ts` semantics); `npm run build` (`tsc`) compiles it to
|
|
5
|
+
`dist/*.js` (CommonJS) plus `.d.ts`. `dist/` is a build artifact and is not committed.
|
|
7
6
|
|
|
8
|
-
|
|
9
|
-
MDGL parser. It does not pass the conformance suite. The Go module is the
|
|
10
|
-
reference.
|
|
7
|
+
## Status
|
|
11
8
|
|
|
12
|
-
|
|
9
|
+
Implemented: full MDGL 0.1 lexical parsing and semantic checking per `SPEC.md`:
|
|
10
|
+
Go-style quoted escapes, UTF-8 byte columns, finite non-exponent decimals,
|
|
11
|
+
scene/actor/action ordering, actor references, forward parents and cycles, all
|
|
12
|
+
actor and action argument types, duplicates and unknowns with did-you-mean,
|
|
13
|
+
overlapping properties, timing/period/repeat/fallback, and the stage, count and
|
|
14
|
+
text limits. Also implemented: evaluator and terminal-cell renderer (`compile`, `frameNs`,
|
|
15
|
+
`fallbackFrame`; all nine actions, easing, repeat/Done/fallback, parent transforms, text, braille rect/circle,
|
|
16
|
+
wire cube) and the NDJSON conformance adapter (`bin/mdgl-adapter.js`, `handleLine`). Rect/circle follow a coordinator reference profile, not SPEC text.
|
|
17
|
+
The current shared corpus has 86 fixtures (64 normative + 22 non-normative or profile-assumption); all five adapters (Go, Rust, C, TypeScript/JavaScript, Python) passed it in an independent verification on 2026-10-10 UTC, accepted by the coordinator. That is bounded evidence under conformance protocol v1, not a universal SPEC certification.
|
|
18
|
+
Braille lines are quantized to 1e-9, clipped to the stage dot box, then stepped (ceil of the longer span, 1..800), as the SPEC
|
|
19
|
+
rule and the coordinator reference profile state; this reproduces all 24 cube fixtures. No full-conformance claim: rect/circle and cube colour have only
|
|
20
|
+
non-normative reference-profile observable fixtures (`obs_ref_*`), and normative rect/circle coverage is still an open gap.
|
|
21
|
+
The 0.2.0 package was an earlier limited header/resource check.
|
|
13
22
|
|
|
14
|
-
|
|
15
|
-
bytes), each line <= 16 KiB, a single `scene` header with `width` (1..200),
|
|
16
|
-
`height` (1..60) and `fallback`, no unknown/duplicate scene keys, optional
|
|
17
|
-
leading `mdgl 0.1`, scene before actors before actions, <= 64 actors,
|
|
18
|
-
<= 1024 actions.
|
|
19
|
-
|
|
20
|
-
NOT checked: full grammar, actor/action bodies, references, timing, arguments,
|
|
21
|
-
`period`/`repeat`/`fps`/`fallback` values, string limits, rendering, frames.
|
|
22
|
-
JS strings cannot hold invalid UTF-8, so that rule is not applicable.
|
|
23
|
-
|
|
24
|
-
`check(source)` returns `Diag[]` (`{line, col, message}`; also exported as
|
|
25
|
-
`Problem`, with `CheckResult = Diag[]`). An empty array means
|
|
26
|
-
"no limit/header problems found", **not** "valid MDGL". Non-strings throw `TypeError`.
|
|
23
|
+
## API
|
|
27
24
|
|
|
28
25
|
```ts
|
|
29
|
-
import { check } from '@enmaq/mdgl';
|
|
30
|
-
|
|
26
|
+
import { check, parse, parseChecked } from '@enmaq/mdgl';
|
|
27
|
+
check(source); // Diag[] ({line, col, message}); [] means valid; the first entry is the compat diagnostic
|
|
28
|
+
parse(source); // source-located statements, no semantic checks
|
|
29
|
+
parseChecked(source); // { ok: true, doc: {scene, actors, actions} } or { ok: false, diagnostics }
|
|
31
30
|
```
|
|
32
31
|
|
|
33
|
-
|
|
32
|
+
Non-strings throw `TypeError`. Times in the checked model are integer nanoseconds.
|
|
33
|
+
|
|
34
|
+
## Unicode compatibility profile
|
|
34
35
|
|
|
35
|
-
|
|
36
|
-
|
|
36
|
+
Grapheme counting and cell width use pinned Unicode 15.0.0 tables (`src/unicode-tables.ts`, generated by
|
|
37
|
+
`scripts/gen-unicode.js` from the official unicode.org 15.0.0 data; input hashes are in the table header;
|
|
38
|
+
licence in `UNICODE-LICENSE.txt`). This is a compatibility profile, not a new normative MDGL rule. One extended
|
|
39
|
+
grapheme cluster (UAX #29, no GB9c) occupies one cell. `cellRune` emits the first non-mark rune; U+FFFD when the
|
|
40
|
+
cluster is width 2 (East Asian W/F first rune, regional indicators including flag pairs, emoji-style VS16 and
|
|
41
|
+
keycap sequences); a blank only for a cluster made entirely of marks (zero-width format or default-ignorable runes are non-mark and are emitted, still one cell).
|
|
42
|
+
Not modelled: width of ZWJ sequences beyond their first rune, and terminal-specific width tables.
|
|
37
43
|
|
|
38
|
-
##
|
|
44
|
+
## Examples
|
|
45
|
+
|
|
46
|
+
Two runnable examples render one frame of the shared `../examples/text.mdgl` using the public API
|
|
47
|
+
(`check`, `compile`, `frameNs`, `fallbackFrame`):
|
|
39
48
|
|
|
40
49
|
```
|
|
41
|
-
npm install
|
|
50
|
+
npm install
|
|
51
|
+
npm run example:js # builds, then node examples/render.mjs
|
|
52
|
+
npm run example:ts # builds, compiles examples/render.ts, runs it
|
|
53
|
+
node examples/render.mjs ../examples/ui-motion.mdgl --time 2.5 # another scene, absolute seconds
|
|
54
|
+
node examples/render.mjs --fallback # fallback frame (no done flag)
|
|
42
55
|
```
|
|
43
56
|
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
57
|
+
Invalid MDGL prints `file:line:col: message` and exits 1; unreadable files or a bad `--time` exit 2.
|
|
58
|
+
Circle radius is limited to 100 (diameter 200); rect and cube sizes to 200.
|
|
59
|
+
|
|
60
|
+
## Terminal player: `mdgl play FILE`
|
|
61
|
+
|
|
62
|
+
The package installs an `mdgl` command (and the `mdgl-adapter` conformance adapter):
|
|
63
|
+
|
|
64
|
+
```
|
|
65
|
+
npm install @enmaq/mdgl # or: npx -p @enmaq/mdgl mdgl play scene.mdgl
|
|
66
|
+
mdgl play scene.mdgl # animate in the terminal; Ctrl+C stops
|
|
67
|
+
mdgl check scene.mdgl # validate; file:line:col: message on stderr
|
|
68
|
+
mdgl frames scene.mdgl --at 0,1.5 # print frames at absolute seconds
|
|
47
69
|
```
|
|
48
70
|
|
|
49
|
-
|
|
71
|
+
Playback follows the SPEC: frame time is the monotonic elapsed time (late timers drop frames, never
|
|
72
|
+
change state), the scene `fps` sets the rate, only changed cells are rewritten (fg and bg), each
|
|
73
|
+
update is one DEC synchronized-output (mode 2026) chunk, and the cursor is hidden and restored on every exit path. Finite scenes stop
|
|
74
|
+
when the evaluator reports done; infinite repeat runs until interrupted. Cell glyphs are sanitised, so
|
|
75
|
+
a scene can never inject terminal escapes. When stdout is not a terminal, or `NO_COLOR` or
|
|
76
|
+
`MDGL_REDUCED_MOTION` is set to a non-empty value, `play` prints the plain fallback frame once, with no escapes or timers.
|
|
77
|
+
|
|
78
|
+
Exit codes: 0 normal, 1 invalid scene or output error, 2 usage error or unreadable file, 130 Ctrl+C, 143 SIGTERM.
|
|
79
|
+
Limits: the terminal must be at least as wide and tall as the scene (no resize handling); `play` needs an ANSI terminal.
|
|
80
|
+
|
|
81
|
+
Library: `play(scene, {write, clock, onWriteError?, onInterrupt?})` returns `{done, stop}` and does no I/O itself;
|
|
82
|
+
`examples/play.mjs` shows the wiring, and `plainFallback(scene)` gives the redirected-output text.
|
|
83
|
+
|
|
84
|
+
## Development
|
|
85
|
+
|
|
86
|
+
`npm test` builds, type-checks `test/consumer/consumer.ts` and runs the tests,
|
|
87
|
+
including every `.mdgl` file in `../conformance`.
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
UNICODE LICENSE V3
|
|
2
|
+
|
|
3
|
+
COPYRIGHT AND PERMISSION NOTICE
|
|
4
|
+
|
|
5
|
+
Copyright © 1991-2026 Unicode, Inc.
|
|
6
|
+
|
|
7
|
+
NOTICE TO USER: Carefully read the following legal agreement. BY
|
|
8
|
+
DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR
|
|
9
|
+
SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE
|
|
10
|
+
TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT
|
|
11
|
+
DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE.
|
|
12
|
+
|
|
13
|
+
Permission is hereby granted, free of charge, to any person obtaining a
|
|
14
|
+
copy of data files and any associated documentation (the "Data Files") or
|
|
15
|
+
software and any associated documentation (the "Software") to deal in the
|
|
16
|
+
Data Files or Software without restriction, including without limitation
|
|
17
|
+
the rights to use, copy, modify, merge, publish, distribute, and/or sell
|
|
18
|
+
copies of the Data Files or Software, and to permit persons to whom the
|
|
19
|
+
Data Files or Software are furnished to do so, provided that either (a)
|
|
20
|
+
this copyright and permission notice appear with all copies of the Data
|
|
21
|
+
Files or Software, or (b) this copyright and permission notice appear in
|
|
22
|
+
associated Documentation.
|
|
23
|
+
|
|
24
|
+
THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
|
|
25
|
+
KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
26
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
|
|
27
|
+
THIRD PARTY RIGHTS.
|
|
28
|
+
|
|
29
|
+
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE
|
|
30
|
+
BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES,
|
|
31
|
+
OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
|
|
32
|
+
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
|
|
33
|
+
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA
|
|
34
|
+
FILES OR SOFTWARE.
|
|
35
|
+
|
|
36
|
+
Except as contained in this notice, the name of a copyright holder shall
|
|
37
|
+
not be used in advertising or otherwise to promote the sale, use or other
|
|
38
|
+
dealings in these Data Files or Software without prior written
|
|
39
|
+
authorization of the copyright holder.
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
// Newline-delimited JSON conformance adapter (PROTOCOL v1). One response line per request line,
|
|
4
|
+
// processed in order; the final non-empty line without a newline is answered once.
|
|
5
|
+
const { handleLine, invalidUtf8, MAX_REQUEST_LINE } = require('../dist/adapter.js');
|
|
6
|
+
// Fatal decode of the complete line bytes: malformed UTF-8 is rejected, never replaced; a BOM is kept (ignoreBOM) so JSON parsing rejects it.
|
|
7
|
+
const dec = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
|
|
8
|
+
let buf = Buffer.alloc(0), skipping = false;
|
|
9
|
+
const emit = (s) => process.stdout.write(s + '\n');
|
|
10
|
+
function line(b) {
|
|
11
|
+
if (b.length > MAX_REQUEST_LINE) return emit(handleLine('', b.length));
|
|
12
|
+
let text;
|
|
13
|
+
try { text = dec.decode(b); } catch (e) { return emit(invalidUtf8()); }
|
|
14
|
+
emit(handleLine(text, b.length));
|
|
15
|
+
}
|
|
16
|
+
process.stdin.on('data', (chunk) => {
|
|
17
|
+
buf = Buffer.concat([buf, chunk]);
|
|
18
|
+
for (;;) {
|
|
19
|
+
const nl = buf.indexOf(10);
|
|
20
|
+
if (nl < 0) {
|
|
21
|
+
if (buf.length > MAX_REQUEST_LINE && !skipping) { emit(handleLine('', MAX_REQUEST_LINE + 1)); skipping = true; }
|
|
22
|
+
if (skipping) buf = Buffer.alloc(0);
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
const l = buf.subarray(0, nl);
|
|
26
|
+
buf = buf.subarray(nl + 1);
|
|
27
|
+
if (skipping) { skipping = false; continue; }
|
|
28
|
+
line(l);
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
process.stdin.on('end', () => { if (!skipping && buf.length > 0) line(buf); });
|
package/bin/mdgl.js
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
// mdgl command line: check FILE | frames FILE --at t1,t2 | play FILE.
|
|
4
|
+
// Exit codes: 0 ok, 1 invalid scene or output error, 2 usage or unreadable file,
|
|
5
|
+
// 130 interrupted by Ctrl+C (SIGINT), 143 terminated (SIGTERM).
|
|
6
|
+
const fs = require('node:fs');
|
|
7
|
+
const { performance } = require('node:perf_hooks');
|
|
8
|
+
const mdgl = require('../dist/index.js');
|
|
9
|
+
const pkg = require('../package.json');
|
|
10
|
+
|
|
11
|
+
const USAGE = `usage: mdgl <command> [options]
|
|
12
|
+
|
|
13
|
+
commands:
|
|
14
|
+
play FILE play FILE in the terminal (Ctrl+C stops it)
|
|
15
|
+
check FILE validate FILE; prints file:line:col: message and exits 1 if invalid
|
|
16
|
+
frames FILE --at T,T print the frame at each absolute time T (seconds), conformance format
|
|
17
|
+
|
|
18
|
+
play shows the fallback frame once, without escapes or timers, when stdout is not a terminal
|
|
19
|
+
or NO_COLOR or MDGL_REDUCED_MOTION is set to a non-empty value.
|
|
20
|
+
|
|
21
|
+
options:
|
|
22
|
+
-h, --help show this help
|
|
23
|
+
-V, --version show the version
|
|
24
|
+
|
|
25
|
+
exit codes: 0 ok, 1 invalid scene or output error, 2 usage or unreadable file, 130 Ctrl+C
|
|
26
|
+
`;
|
|
27
|
+
const usage = (msg) => { if (msg) process.stderr.write(`mdgl: ${msg}\n`); process.stderr.write(USAGE); process.exitCode = 2; };
|
|
28
|
+
|
|
29
|
+
function load(file) {
|
|
30
|
+
let src;
|
|
31
|
+
try { src = fs.readFileSync(file, 'utf8'); } catch (e) { process.stderr.write(`mdgl: cannot read ${file}\n`); process.exitCode = 2; return null; }
|
|
32
|
+
const r = mdgl.compile(src);
|
|
33
|
+
if (!r.ok) {
|
|
34
|
+
for (const d of r.diagnostics) process.stderr.write(`${file}:${d.line}:${d.col}: ${d.message}\n`);
|
|
35
|
+
process.exitCode = 1;
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
return r.scene;
|
|
39
|
+
}
|
|
40
|
+
/** decimal seconds -> integer nanoseconds, or null */
|
|
41
|
+
function seconds(s) {
|
|
42
|
+
const m = /^([0-9]+)(?:\.([0-9]+))?$/.exec(s);
|
|
43
|
+
if (!m) return null;
|
|
44
|
+
const ns = Number(m[1]) * 1e9 + Number(((m[2] || '') + '000000000').slice(0, 9));
|
|
45
|
+
return Number.isSafeInteger(ns) ? ns : null;
|
|
46
|
+
}
|
|
47
|
+
function writeOut(text) {
|
|
48
|
+
return new Promise((resolve) => {
|
|
49
|
+
const onErr = (e) => { process.stderr.write(`mdgl: write error: ${e && e.code ? e.code : 'failed'}\n`); process.exitCode = 1; resolve(); };
|
|
50
|
+
process.stdout.once('error', onErr);
|
|
51
|
+
process.stdout.write(text, () => { process.stdout.off('error', onErr); resolve(); });
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function play(file) {
|
|
56
|
+
const scene = load(file);
|
|
57
|
+
if (!scene) return;
|
|
58
|
+
const reduced = (process.env.NO_COLOR || '') !== '' || (process.env.MDGL_REDUCED_MOTION || '') !== '';
|
|
59
|
+
if (!process.stdout.isTTY || reduced) { await writeOut(mdgl.plainFallback(scene)); return; }
|
|
60
|
+
const out = process.stdout;
|
|
61
|
+
const handle = mdgl.play(scene, {
|
|
62
|
+
write: (s) => { out.write(s); },
|
|
63
|
+
clock: { now: () => performance.now(), setTimeout: (f, ms) => setTimeout(f, ms), clearTimeout: (h) => clearTimeout(h) },
|
|
64
|
+
onWriteError: (cb) => { out.on('error', cb); return () => out.off('error', cb); },
|
|
65
|
+
onInterrupt: (cb) => {
|
|
66
|
+
const a = () => cb(130), b = () => cb(143);
|
|
67
|
+
process.on('SIGINT', a);
|
|
68
|
+
process.on('SIGTERM', b);
|
|
69
|
+
return () => { process.off('SIGINT', a); process.off('SIGTERM', b); };
|
|
70
|
+
},
|
|
71
|
+
});
|
|
72
|
+
const res = await handle.done;
|
|
73
|
+
// keep a late stream error from crashing during teardown
|
|
74
|
+
out.on('error', () => {});
|
|
75
|
+
if (res.reason === 'write-error') process.stderr.write(`mdgl: write error: ${res.error && res.error.code ? res.error.code : 'failed'}\n`);
|
|
76
|
+
process.exitCode = res.code;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function main(argv) {
|
|
80
|
+
const [cmd, ...rest] = argv;
|
|
81
|
+
if (cmd === undefined) return usage();
|
|
82
|
+
if (cmd === '-h' || cmd === '--help' || cmd === 'help') { process.stdout.write(USAGE); return; }
|
|
83
|
+
if (cmd === '-V' || cmd === '--version') { process.stdout.write(`${pkg.version}\n`); return; }
|
|
84
|
+
if (!['play', 'check', 'frames'].includes(cmd)) return usage(`unknown command ${JSON.stringify(cmd)}`);
|
|
85
|
+
if (rest.includes('-h') || rest.includes('--help')) { process.stdout.write(USAGE); return; }
|
|
86
|
+
const at = rest.indexOf('--at');
|
|
87
|
+
const times = at >= 0 ? rest.splice(at, 2)[1] : undefined;
|
|
88
|
+
const flags = rest.filter((a) => a.startsWith('-'));
|
|
89
|
+
if (flags.length) return usage(`unknown option ${flags[0]}`);
|
|
90
|
+
if (rest.length !== 1) return usage('expected exactly one FILE');
|
|
91
|
+
const file = rest[0];
|
|
92
|
+
if (cmd === 'check') { if (load(file)) process.stdout.write('ok\n'); return; }
|
|
93
|
+
if (cmd === 'frames') {
|
|
94
|
+
if (times === undefined) return usage('frames needs --at T,T');
|
|
95
|
+
const list = times.split(',');
|
|
96
|
+
const ns = list.map(seconds);
|
|
97
|
+
if (ns.includes(null)) return usage('--at takes non-negative decimal seconds');
|
|
98
|
+
const scene = load(file);
|
|
99
|
+
if (!scene) return;
|
|
100
|
+
await writeOut(list.map((t, i) => `@${t}\n${mdgl.frameNs(scene, ns[i]).cells.map((r) => r.map((c) => mdgl.sanitizeRune(c.r)).join('').replace(/ +$/, '')).join('\n')}\n`).join(''));
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
await play(file);
|
|
104
|
+
}
|
|
105
|
+
main(process.argv.slice(2)).catch((e) => { process.stderr.write(`mdgl: ${e && e.message ? e.message : e}\n`); process.exitCode = 1; });
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export declare const MAX_REQUEST_LINE = 2097152;
|
|
2
|
+
/** Exact mathematical integer value of a JSON number lexeme, or null if it is not an integer. */
|
|
3
|
+
export declare function mathInt(lex: string): bigint | null;
|
|
4
|
+
/** bad_request response for a line whose bytes are not valid UTF-8 (the id is unrecoverable). */
|
|
5
|
+
export declare const invalidUtf8: () => string;
|
|
6
|
+
/** Handle one request line (without its newline). Always returns exactly one response line. */
|
|
7
|
+
export declare function handleLine(line: string, lineBytes?: number): string;
|
package/dist/adapter.js
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.invalidUtf8 = exports.MAX_REQUEST_LINE = void 0;
|
|
4
|
+
exports.mathInt = mathInt;
|
|
5
|
+
exports.handleLine = handleLine;
|
|
6
|
+
// Conformance adapter core (PROTOCOL v1): one request line in, one response line out.
|
|
7
|
+
// Pure string -> string; bin/mdgl-adapter.js wires stdin/stdout. JSON numbers are kept as
|
|
8
|
+
// lexemes and validated as exact mathematical integers (9007199254740991.1 rejects).
|
|
9
|
+
const check_1 = require("./check");
|
|
10
|
+
const eval_1 = require("./eval");
|
|
11
|
+
exports.MAX_REQUEST_LINE = 2097152;
|
|
12
|
+
class Bad extends Error {
|
|
13
|
+
}
|
|
14
|
+
function parseJson(t) {
|
|
15
|
+
let i = 0, lone = false, depth = 0;
|
|
16
|
+
const ws = () => { while (i < t.length && (t[i] === ' ' || t[i] === '\t' || t[i] === '\n' || t[i] === '\r'))
|
|
17
|
+
i++; };
|
|
18
|
+
const lit = (w, v) => { if (!t.startsWith(w, i))
|
|
19
|
+
throw new Bad(); i += w.length; return v; };
|
|
20
|
+
const str = () => {
|
|
21
|
+
i++;
|
|
22
|
+
let o = '';
|
|
23
|
+
for (;;) {
|
|
24
|
+
if (i >= t.length)
|
|
25
|
+
throw new Bad();
|
|
26
|
+
const c = t[i];
|
|
27
|
+
if (c === '"') {
|
|
28
|
+
i++;
|
|
29
|
+
return o;
|
|
30
|
+
}
|
|
31
|
+
if (c < ' ')
|
|
32
|
+
throw new Bad();
|
|
33
|
+
if (c !== '\\') {
|
|
34
|
+
o += c;
|
|
35
|
+
i++;
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
const e = t[i + 1];
|
|
39
|
+
const m = { '"': '"', '\\': '\\', '/': '/', b: '\b', f: '\f', n: '\n', r: '\r', t: '\t' };
|
|
40
|
+
if (e in m) {
|
|
41
|
+
o += m[e];
|
|
42
|
+
i += 2;
|
|
43
|
+
}
|
|
44
|
+
else if (e === 'u') {
|
|
45
|
+
const h = t.slice(i + 2, i + 6);
|
|
46
|
+
if (!/^[0-9a-fA-F]{4}$/.test(h))
|
|
47
|
+
throw new Bad();
|
|
48
|
+
const cu = parseInt(h, 16);
|
|
49
|
+
if (cu >= 0xd800 && cu < 0xdc00) {
|
|
50
|
+
const lo = /^\\u([dD][c-fC-F][0-9a-fA-F]{2})/.exec(t.slice(i + 6, i + 12));
|
|
51
|
+
if (lo) {
|
|
52
|
+
o += String.fromCharCode(cu, parseInt(lo[1], 16));
|
|
53
|
+
i += 12;
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
lone = true;
|
|
57
|
+
}
|
|
58
|
+
else if (cu >= 0xdc00 && cu < 0xe000)
|
|
59
|
+
lone = true;
|
|
60
|
+
o += String.fromCharCode(cu);
|
|
61
|
+
i += 6;
|
|
62
|
+
}
|
|
63
|
+
else
|
|
64
|
+
throw new Bad();
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
const val = () => {
|
|
68
|
+
ws();
|
|
69
|
+
const c = t[i];
|
|
70
|
+
if (++depth > 200)
|
|
71
|
+
throw new Bad();
|
|
72
|
+
let r;
|
|
73
|
+
if (c === '{') {
|
|
74
|
+
i++;
|
|
75
|
+
const o = {};
|
|
76
|
+
ws();
|
|
77
|
+
if (t[i] === '}')
|
|
78
|
+
i++;
|
|
79
|
+
else
|
|
80
|
+
for (;;) {
|
|
81
|
+
ws();
|
|
82
|
+
if (t[i] !== '"')
|
|
83
|
+
throw new Bad();
|
|
84
|
+
const k = str();
|
|
85
|
+
ws();
|
|
86
|
+
if (t[i++] !== ':')
|
|
87
|
+
throw new Bad();
|
|
88
|
+
o[k] = val();
|
|
89
|
+
ws();
|
|
90
|
+
if (t[i] === ',') {
|
|
91
|
+
i++;
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
if (t[i++] === '}')
|
|
95
|
+
break;
|
|
96
|
+
throw new Bad();
|
|
97
|
+
}
|
|
98
|
+
r = o;
|
|
99
|
+
}
|
|
100
|
+
else if (c === '[') {
|
|
101
|
+
i++;
|
|
102
|
+
const a = [];
|
|
103
|
+
ws();
|
|
104
|
+
if (t[i] === ']')
|
|
105
|
+
i++;
|
|
106
|
+
else
|
|
107
|
+
for (;;) {
|
|
108
|
+
a.push(val());
|
|
109
|
+
ws();
|
|
110
|
+
if (t[i] === ',') {
|
|
111
|
+
i++;
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
if (t[i++] === ']')
|
|
115
|
+
break;
|
|
116
|
+
throw new Bad();
|
|
117
|
+
}
|
|
118
|
+
r = a;
|
|
119
|
+
}
|
|
120
|
+
else if (c === '"')
|
|
121
|
+
r = str();
|
|
122
|
+
else if (c === 't')
|
|
123
|
+
r = lit('true', true);
|
|
124
|
+
else if (c === 'f')
|
|
125
|
+
r = lit('false', false);
|
|
126
|
+
else if (c === 'n')
|
|
127
|
+
r = lit('null', null);
|
|
128
|
+
else {
|
|
129
|
+
const m = /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/.exec(t.slice(i, i + 4096));
|
|
130
|
+
if (!m)
|
|
131
|
+
throw new Bad();
|
|
132
|
+
i += m[0].length;
|
|
133
|
+
r = { num: m[0] };
|
|
134
|
+
}
|
|
135
|
+
depth--;
|
|
136
|
+
return r;
|
|
137
|
+
};
|
|
138
|
+
const v = val();
|
|
139
|
+
ws();
|
|
140
|
+
if (i !== t.length)
|
|
141
|
+
throw new Bad();
|
|
142
|
+
return { v, lone };
|
|
143
|
+
}
|
|
144
|
+
/** Exact mathematical integer value of a JSON number lexeme, or null if it is not an integer. */
|
|
145
|
+
function mathInt(lex) {
|
|
146
|
+
const m = /^(-?)(\d+)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec(lex);
|
|
147
|
+
if (!m)
|
|
148
|
+
return null;
|
|
149
|
+
const frac = m[3] ?? '';
|
|
150
|
+
const exp = Number(m[4] ?? '0') - frac.length;
|
|
151
|
+
let d = BigInt(m[2] + frac);
|
|
152
|
+
if (d === 0n)
|
|
153
|
+
return 0n;
|
|
154
|
+
if (exp > 400)
|
|
155
|
+
return null; // far beyond any accepted range; treat as out of range by callers
|
|
156
|
+
if (exp >= 0)
|
|
157
|
+
d *= 10n ** BigInt(exp);
|
|
158
|
+
else {
|
|
159
|
+
const p = 10n ** BigInt(-exp);
|
|
160
|
+
if (-exp > 4000 || d % p !== 0n)
|
|
161
|
+
return null;
|
|
162
|
+
d /= p;
|
|
163
|
+
}
|
|
164
|
+
return m[1] ? -d : d;
|
|
165
|
+
}
|
|
166
|
+
const isNum = (v) => typeof v === 'object' && v !== null && !Array.isArray(v) && 'num' in v && typeof v.num === 'string';
|
|
167
|
+
function intIn(v, lo, hi) {
|
|
168
|
+
if (!isNum(v))
|
|
169
|
+
return null;
|
|
170
|
+
const n = mathInt(v.num);
|
|
171
|
+
return n === null || n < lo || n > hi ? null : Number(n);
|
|
172
|
+
}
|
|
173
|
+
const out = (o) => JSON.stringify(o);
|
|
174
|
+
const fail = (id, code, message, extra) => out({ v: 1, id, ok: false, error: { code, message, ...extra } });
|
|
175
|
+
/** bad_request response for a line whose bytes are not valid UTF-8 (the id is unrecoverable). */
|
|
176
|
+
const invalidUtf8 = () => fail(null, 'bad_request', 'request line is not valid UTF-8');
|
|
177
|
+
exports.invalidUtf8 = invalidUtf8;
|
|
178
|
+
/** Handle one request line (without its newline). Always returns exactly one response line. */
|
|
179
|
+
function handleLine(line, lineBytes = line.length) {
|
|
180
|
+
if (lineBytes > exports.MAX_REQUEST_LINE)
|
|
181
|
+
return fail(null, 'bad_request', 'request line too long');
|
|
182
|
+
let top, lone;
|
|
183
|
+
try {
|
|
184
|
+
({ v: top, lone } = parseJson(line));
|
|
185
|
+
}
|
|
186
|
+
catch (e) {
|
|
187
|
+
return fail(null, 'bad_request', line.trim() === '' ? 'blank line' : 'invalid JSON');
|
|
188
|
+
}
|
|
189
|
+
if (typeof top !== 'object' || top === null || Array.isArray(top) || isNum(top))
|
|
190
|
+
return fail(null, 'bad_request', 'request must be a JSON object');
|
|
191
|
+
const o = top;
|
|
192
|
+
const id = typeof o.id === 'string' ? o.id : null;
|
|
193
|
+
if (!isNum(o.v) || mathInt(o.v.num) === null)
|
|
194
|
+
return fail(id, 'bad_request', 'v must be an integer');
|
|
195
|
+
if (mathInt(o.v.num) !== 1n)
|
|
196
|
+
return fail(id, 'unsupported_version', `protocol version ${o.v.num} is not supported`);
|
|
197
|
+
if (id === null)
|
|
198
|
+
return fail(null, 'bad_request', 'id must be a string');
|
|
199
|
+
if (o.op !== 'check' && o.op !== 'frame')
|
|
200
|
+
return fail(id, 'bad_request', 'op must be "check" or "frame"');
|
|
201
|
+
if (typeof o.source !== 'string')
|
|
202
|
+
return fail(id, 'bad_request', 'source must be a string');
|
|
203
|
+
if (lone)
|
|
204
|
+
return fail(id, 'bad_request', 'source contains a lone surrogate');
|
|
205
|
+
let width = 0, height = 0, tNs = 0, fb = false;
|
|
206
|
+
if (o.op === 'frame') {
|
|
207
|
+
const w = intIn(o.width, 1n, 200n), h = intIn(o.height, 1n, 60n);
|
|
208
|
+
if (w === null || h === null)
|
|
209
|
+
return fail(id, 'bad_request', 'width and height must be integers in 1..200 and 1..60');
|
|
210
|
+
width = w;
|
|
211
|
+
height = h;
|
|
212
|
+
if ('fallback' in o && typeof o.fallback !== 'boolean')
|
|
213
|
+
return fail(id, 'bad_request', 'fallback must be a boolean');
|
|
214
|
+
fb = o.fallback === true;
|
|
215
|
+
if (!fb) {
|
|
216
|
+
const t = intIn(o.time_ns, 0n, 9007199254740991n);
|
|
217
|
+
if (t === null)
|
|
218
|
+
return fail(id, 'bad_request', 'time_ns must be an integer in 0..2^53-1');
|
|
219
|
+
tNs = t;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
const r = (0, check_1.parseChecked)(o.source);
|
|
223
|
+
if (o.op === 'check')
|
|
224
|
+
return out({ v: 1, id, ok: true, diagnostics: r.ok ? [] : r.diagnostics });
|
|
225
|
+
if (!r.ok)
|
|
226
|
+
return fail(id, 'invalid_source', 'source has diagnostics', { diagnostics: r.diagnostics });
|
|
227
|
+
const sc = (0, eval_1.compileDocument)(r.doc);
|
|
228
|
+
const f = fb ? (0, eval_1.fallbackFrame)(sc, width, height) : (0, eval_1.frameNs)(sc, tNs, width, height);
|
|
229
|
+
const cells = f.cells.map((row) => row.map((c) => ({ r: c.r, fg: c.fg, bg: c.bg })));
|
|
230
|
+
return out(fb ? { v: 1, id, ok: true, width: f.width, height: f.height, cells } : { v: 1, id, ok: true, width: f.width, height: f.height, cells, done: f.done });
|
|
231
|
+
}
|
package/dist/check.d.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { ActionStmt, ActorStmt, Diag, Document } from './parse';
|
|
2
|
+
export declare const MAX_ACTORS = 64;
|
|
3
|
+
export declare const MAX_ACTIONS = 1024;
|
|
4
|
+
export type Fallback = {
|
|
5
|
+
kind: 'start';
|
|
6
|
+
} | {
|
|
7
|
+
kind: 'end';
|
|
8
|
+
} | {
|
|
9
|
+
kind: 'at';
|
|
10
|
+
ns: number;
|
|
11
|
+
};
|
|
12
|
+
export interface CheckedScene {
|
|
13
|
+
line: number;
|
|
14
|
+
width: number;
|
|
15
|
+
height: number;
|
|
16
|
+
fps: number;
|
|
17
|
+
/** explicit period in ns, if given */
|
|
18
|
+
period?: number;
|
|
19
|
+
/** repeat count; Infinity for `infinite` */
|
|
20
|
+
repeat: number;
|
|
21
|
+
fallback: Fallback;
|
|
22
|
+
/** simple duration in ns: explicit period, else greatest action end */
|
|
23
|
+
duration: number;
|
|
24
|
+
}
|
|
25
|
+
export interface CheckedAction extends ActionStmt {
|
|
26
|
+
beginNs: number;
|
|
27
|
+
endNs: number;
|
|
28
|
+
property: string;
|
|
29
|
+
durNs: number;
|
|
30
|
+
}
|
|
31
|
+
export interface CheckedDocument {
|
|
32
|
+
scene: CheckedScene;
|
|
33
|
+
actors: ActorStmt[];
|
|
34
|
+
actions: CheckedAction[];
|
|
35
|
+
}
|
|
36
|
+
export type ParseResult = {
|
|
37
|
+
ok: true;
|
|
38
|
+
doc: CheckedDocument;
|
|
39
|
+
} | {
|
|
40
|
+
ok: false;
|
|
41
|
+
diagnostics: Diag[];
|
|
42
|
+
};
|
|
43
|
+
/** Check a parsed document; returns the checked model or the first diagnostic. */
|
|
44
|
+
export declare function checkDocument(doc: Document): ParseResult;
|
|
45
|
+
/** Parse and check; returns the checked, source-located scene model or diagnostics. */
|
|
46
|
+
export declare function parseChecked(source: string): ParseResult;
|
|
47
|
+
/** Compat API: `[]` means the source is valid; otherwise the first diagnostic. */
|
|
48
|
+
export declare function check(source: string): Diag[];
|