@grethel-labs/excaliplant 0.1.4 → 0.3.5

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 (35) hide show
  1. package/CHANGELOG.md +100 -0
  2. package/README.md +32 -14
  3. package/SECURITY.md +71 -0
  4. package/THIRD_PARTY_NOTICES.md +29 -0
  5. package/bin/excaliplant.mjs +263 -0
  6. package/index.mjs +50 -18
  7. package/package.json +35 -7
  8. package/src/layout/elk_layout.mjs +141 -19
  9. package/src/layout/sequence_layout.mjs +56 -30
  10. package/src/layout/sizing.mjs +71 -11
  11. package/src/model/diagram.mjs +321 -64
  12. package/src/parser/component_context.mjs +115 -31
  13. package/src/parser/engine.mjs +67 -42
  14. package/src/parser/plantuml.mjs +145 -22
  15. package/src/parser/plugins/component/connections.mjs +29 -4
  16. package/src/parser/plugins/component/containers.mjs +8 -3
  17. package/src/parser/plugins/component/notes.mjs +25 -9
  18. package/src/parser/plugins/component/preamble.mjs +8 -0
  19. package/src/parser/plugins/component/shapes.mjs +36 -7
  20. package/src/parser/plugins/sequence/messages.mjs +8 -2
  21. package/src/parser/plugins/sequence/notes.mjs +30 -2
  22. package/src/parser/plugins/sequence/participants.mjs +6 -1
  23. package/src/parser/plugins/sequence/preamble.mjs +4 -0
  24. package/src/parser/sequence_context.mjs +76 -9
  25. package/src/parser/utils.mjs +154 -32
  26. package/src/render/canvas_svg.mjs +34 -12
  27. package/src/render/excalidraw.mjs +847 -276
  28. package/src/render/png.mjs +10 -2
  29. package/src/render/rng.mjs +52 -0
  30. package/src/render/schema.mjs +35 -0
  31. package/src/render/sequence_render.mjs +213 -83
  32. package/src/render/svg.mjs +152 -51
  33. package/src/style/colors.mjs +63 -2
  34. package/src/style/font.mjs +44 -21
  35. package/src/style/text.mjs +73 -11
package/CHANGELOG.md ADDED
@@ -0,0 +1,100 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@grethel-labs/excaliplant` are documented in this
4
+ file. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
5
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [0.3.1] - 2026-05-04
8
+
9
+ ### Fixed
10
+
11
+ - Dependabot PRs now automatically receive `release:patch` labels to ensure the
12
+ release version workflow can process them correctly.
13
+ - Auto-patch dependencies workflow now adds `release:patch` label to created/updated PRs.
14
+ - PR release version workflow detects Dependabot PRs and automatically adds
15
+ `release:patch` label if missing.
16
+ - Type-checking now narrows the component-context container stack via a proper
17
+ discriminated union, fixing strict null/undefined errors surfaced by
18
+ TypeScript 6.x.
19
+ - `declareParticipant` resolves the cached lookup once so its return type is a
20
+ non-nullable `Participant`, satisfying stricter type checking.
21
+ - Docs file-tree script imports `tree-node-cli` namespace-style and picks the
22
+ named export (v3+) or default (v1.x) at runtime, so the docs build works
23
+ across both major versions.
24
+
25
+ ### Added
26
+
27
+ - New `auto-rebase-prs.yml` workflow that automatically rebases open PRs
28
+ when main is updated, and adjusts version numbers if there are conflicts
29
+ from parallel PRs being merged.
30
+
31
+ ## [0.3.0] - 2026-05-04
32
+
33
+ ### Added
34
+
35
+ - Repository-wide editing-agent instructions via `AGENTS.md`, with thin adapter
36
+ files for GitHub Copilot, Claude Code, Gemini CLI, Cursor, Windsurf, Cline,
37
+ and Roo Code. The adapters all point back to `AGENTS.md` so project rules stay
38
+ centralized for future automated editing workflows.
39
+ - A README notice clarifying that the repository was created almost entirely
40
+ with AI assistance and that use remains at the user's own risk under the MIT
41
+ License warranty disclaimer.
42
+
43
+ ## [0.2.1] - 2026-05-03
44
+
45
+ ### Security
46
+
47
+ - `excalidrawJsonToCanvasSvg`: HTML-escape the user-supplied `background`
48
+ option before interpolating it into the canvas `<rect>` `fill`
49
+ attribute. Previously a string like `'" onload="alert(1)'` could
50
+ break out of the attribute and inject arbitrary markup into the
51
+ emitted SVG. The escape uses the same routine as the rest of
52
+ `src/render/svg.mjs` (`escapeAttr`, now exported) and now also
53
+ escapes `>` for defence in depth.
54
+ - `parsePlantUml` gains opt-in resource limits
55
+ (`maxInputBytes`, `maxLines`, `maxNodes`, `maxEdges`) with sensible
56
+ defaults so the library API enforces the same safety bounds as the
57
+ CLI. `renderPlantUml({ limits })` forwards the option.
58
+ - CI permissions are now `contents: read` by default; only the
59
+ PR-docs auto-amend job re-asserts `contents: write`. The release
60
+ workflow additionally runs `typecheck`, `format:check`, an
61
+ `npm audit --omit=dev --audit-level=high`, and a pack + smoke
62
+ install before publishing.
63
+
64
+ ### Fixed
65
+
66
+ - `slug()` keeps Unicode letters and digits instead of replacing
67
+ every non-ASCII character with `_`. Diagrams with German umlauts,
68
+ Japanese identifiers, etc. now resolve their connections correctly.
69
+ - `stripComment()` is now string-aware: an apostrophe inside a
70
+ `"..."` literal no longer truncates the line, so labels like
71
+ `"Bob 's service"` parse intact.
72
+ - Component connections that use bracket / paren / quoted shorthand
73
+ (`[Foo] --> [Bar]`, `(Use case A) --> (Use case B)`) now resolve
74
+ to the matching declared boxes regardless of capitalisation or
75
+ Unicode content.
76
+ - Sequence diagrams interleave notes between messages by declaration
77
+ order. Previously every note was placed below the last message,
78
+ losing temporal context.
79
+
80
+ ### Added
81
+
82
+ - `parsePlantUml(text, { unknownLines: "warn" | "strict" })` for
83
+ diagnostics on lines that no plugin consumed (default behaviour
84
+ remains silent for backwards compatibility).
85
+ - `runEngine({ onUnknownLine })` callback so custom pipelines can
86
+ observe unrecognised input.
87
+ - `DEFAULT_PARSE_LIMITS` is exported from the top-level module and
88
+ from `./parser/plantuml`.
89
+ - `CHANGELOG.md` (this file) and a tightened `pre-commit` hook that
90
+ also runs `npm run typecheck`.
91
+
92
+ ### Changed
93
+
94
+ - `prepublishOnly` now runs `npm test`, `npm run typecheck`,
95
+ `npm run format:check`, and `npm run build` (in addition to the
96
+ existing prepublish guard) before publishing.
97
+
98
+ ## [0.2.0] - 2026-04
99
+
100
+ Initial public release on npm.
package/README.md CHANGED
@@ -1,7 +1,13 @@
1
1
 
2
2
  # excaliplant
3
3
 
4
- > PlantUML → ELK layout → Excalidraw renderer with a plugin-based parser. &nbsp;·&nbsp; **v0.1.4** &nbsp;·&nbsp; 73 tests &nbsp;·&nbsp; MIT
4
+ [![npm](https://img.shields.io/npm/v/@grethel-labs/excaliplant.svg?label=latest)](https://www.npmjs.com/package/@grethel-labs/excaliplant)
5
+ [![downloads](https://img.shields.io/npm/dm/@grethel-labs/excaliplant.svg)](https://www.npmjs.com/package/@grethel-labs/excaliplant)
6
+ [![ci](https://github.com/grethel-labs/excaliplant/actions/workflows/ci.yml/badge.svg)](https://github.com/grethel-labs/excaliplant/actions/workflows/ci.yml)
7
+ [![node](https://img.shields.io/node/v/@grethel-labs/excaliplant.svg)](https://nodejs.org)
8
+ [![license](https://img.shields.io/npm/l/@grethel-labs/excaliplant.svg)](./LICENSE)
9
+
10
+ > PlantUML → ELK layout → Excalidraw renderer with a plugin-based parser. &nbsp;·&nbsp; **v0.3.5** &nbsp;·&nbsp; 86 tests &nbsp;·&nbsp; MIT
5
11
 
6
12
  `@grethel-labs/excaliplant` takes PlantUML source, runs it through a plugin-based
7
13
  parser, lays it out with [ELK](https://github.com/kieler/elkjs), and
@@ -27,6 +33,13 @@ artefacts.
27
33
  > [`docs/README.template.md.njk`](./docs/README.template.md.njk) and
28
34
  > run `npm run build:docs`.
29
35
 
36
+ > **AI-generated project notice:** This repository, including source code,
37
+ > documentation, comments, and generated artefacts, was created almost entirely
38
+ > with AI assistance. The maintainer does not adopt every generated sentence,
39
+ > implementation detail, or artefact as a personal statement, endorsement, or
40
+ > guarantee. Review everything carefully and use the code at your own risk; the
41
+ > MIT License warranty disclaimer applies.
42
+
30
43
  ---
31
44
 
32
45
  ## How to use
@@ -96,7 +109,7 @@ Lower-level entry points are also exported:
96
109
  npm test
97
110
  ```
98
111
 
99
- Ships with **73 tests** across functional, edge-case,
112
+ Ships with **86 tests** across functional, edge-case,
100
113
  security (XSS / ReDoS / prototype-pollution), and self-introspection
101
114
  suites.
102
115
 
@@ -179,10 +192,13 @@ excaliplant
179
192
  │ └── fonts
180
193
  │ ├── Excalifont-Regular.woff2
181
194
  │ └── LICENSE.txt
195
+ ├── bin
196
+ │ └── excaliplant.mjs
182
197
  ├── docs
183
198
  │ ├── ressources
184
199
  │ ├── scripts
185
200
  │ │ ├── build-docs.mjs
201
+ │ │ ├── check-build-manifest.mjs
186
202
  │ │ ├── config.mjs
187
203
  │ │ ├── extract-docs.mjs
188
204
  │ │ ├── file-tree.mjs
@@ -190,6 +206,9 @@ excaliplant
190
206
  │ └── README.template.md.njk
191
207
  ├── scripts
192
208
  │ ├── auto-patch-deps.mjs
209
+ │ ├── bump-release-version.mjs
210
+ │ ├── prepublish-guard.mjs
211
+ │ ├── setup-merge-drivers.mjs
193
212
  │ └── smoke.mjs
194
213
  ├── src
195
214
  │ ├── layout
@@ -211,6 +230,8 @@ excaliplant
211
230
  │ │ ├── canvas_svg.mjs
212
231
  │ │ ├── excalidraw.mjs
213
232
  │ │ ├── png.mjs
233
+ │ │ ├── rng.mjs
234
+ │ │ ├── schema.mjs
214
235
  │ │ ├── sequence_render.mjs
215
236
  │ │ └── svg.mjs
216
237
  │ └── style
@@ -223,8 +244,15 @@ excaliplant
223
244
  │ ├── plantuml.test.mjs
224
245
  │ ├── security.test.mjs
225
246
  │ └── self_introspection.test.mjs
247
+ ├── AGENTS.md
248
+ ├── CHANGELOG.md
249
+ ├── CLAUDE.md
250
+ ├── CONTRIBUTING.md
251
+ ├── GEMINI.md
226
252
  ├── LICENSE
227
253
  ├── README.md
254
+ ├── SECURITY.md
255
+ ├── THIRD_PARTY_NOTICES.md
228
256
  ├── index.mjs
229
257
  ├── package.json
230
258
  ├── tsconfig.json
@@ -271,16 +299,6 @@ PlantUML syntax; that lives entirely in plugins. Block plugins
271
299
  (multi-line notes, class bodies) take exclusive ownership of
272
300
  subsequent lines until they release.
273
301
 
274
- Plugin contract:
275
-
276
- ```js
277
- {
278
- name,
279
- tryStart?(line, ctx): null | { onLine, tryEnd },
280
- tryLine?(line, ctx): boolean,
281
- }
282
- ```
283
-
284
302
  ### render
285
303
 
286
304
  Emits Excalidraw JSON. Each model shape is dispatched to a
@@ -288,8 +306,8 @@ dedicated `renderXxx()` function that produces one or more
288
306
  Excalidraw primitive elements (rectangle, ellipse, line, arrow,
289
307
  text). The output document is a stand-alone `.excalidraw` file
290
308
  that any Excalidraw front-end can open. The companion module
291
- [`src/render/svg.mjs`](./src/render/svg.mjs) converts the same
292
- JSON to SVG for the build-time documentation pipeline.
309
+ `src/render/svg.mjs` converts the same JSON to SVG for the
310
+ build-time documentation pipeline.
293
311
 
294
312
  ## License
295
313
 
package/SECURITY.md ADDED
@@ -0,0 +1,71 @@
1
+ # Security policy
2
+
3
+ `@grethel-labs/excaliplant` parses untrusted PlantUML text and emits
4
+ Excalidraw JSON / SVG / PNG. We treat the parser surface as a trust
5
+ boundary and ship a dedicated security test suite
6
+ ([`tests/security.test.mjs`](tests/security.test.mjs)) covering XSS,
7
+ ReDoS, prototype pollution, deeply nested input, oversized input, null
8
+ bytes, RTL override / zero-width characters, surrogate pairs, and
9
+ filesystem isolation.
10
+
11
+ ## Supported versions
12
+
13
+ We support **the latest published minor** on npm. Older lines do not
14
+ receive backports.
15
+
16
+ | Version | Supported |
17
+ | ------- | ------------------ |
18
+ | `0.2.x` | :white_check_mark: |
19
+ | `0.1.x` | :x: |
20
+
21
+ ## Reporting a vulnerability
22
+
23
+ Please **do not** open a public issue.
24
+
25
+ 1. Use GitHub's [private vulnerability reporting](https://github.com/grethel-labs/excaliplant/security/advisories/new).
26
+ 2. Include a minimal PlantUML reproducer if possible.
27
+
28
+ We aim to acknowledge reports within 5 working days and to ship a
29
+ patched release within 30 days for confirmed high/critical issues.
30
+
31
+ ## Disclosure policy
32
+
33
+ - Confirmed vulnerabilities are tracked as GitHub Security Advisories.
34
+ - A CVE is requested for any issue with a CVSS ≥ 7.0.
35
+ - Fixes ship as a patch release on npm; the advisory is published
36
+ simultaneously.
37
+
38
+ ## Hardening recommendations for consumers
39
+
40
+ - Treat `renderPlantUml(input)` like any other untrusted-input parser.
41
+ Run it inside a worker / isolated process if your input source is
42
+ hostile.
43
+ - The SVG output **inlines the Excalifont woff2** as a `data:` URL.
44
+ Some sandboxing environments restrict data URLs in fonts; if that
45
+ applies, post-process the SVG to drop the `<style>` block.
46
+ - The PNG path uses `@resvg/resvg-js` which executes as native code
47
+ (Rust → N-API). Keep that dependency on `npm audit` watch.
48
+
49
+ ## Built-in hardening
50
+
51
+ These limits are enforced automatically and don't need to be enabled:
52
+
53
+ - **CLI stdin / file input cap**: `bin/excaliplant.mjs` rejects input
54
+ larger than `--max-input-bytes` (default 10 MiB, ceiling 200 MiB).
55
+ - **Render-width bounds**: PNG and canvas-SVG widths are clamped to
56
+ `[16, 16000]` px to bound `@resvg/resvg-js` memory.
57
+ - **Stack-trace gating**: the CLI prints a one-line error by default.
58
+ Set `DEBUG=1` to opt back into full stack traces.
59
+ - **No install scripts**: the npm package declares no
60
+ `pre/install/postinstall` hooks; nothing executes at `npm install`
61
+ time beyond the bundled JS being placed on disk.
62
+ - **Provenance**: releases are published with `npm publish
63
+ --provenance`. Consumers can verify the package origin via
64
+ `npm audit signatures`.
65
+ - **Pinned third-party Actions**: `softprops/action-gh-release` and
66
+ `peaceiris/actions-gh-pages` are pinned by commit SHA in
67
+ `.github/workflows/release.yml`.
68
+ - **Auto-patch dependency PRs require human review**: the
69
+ `auto-patch-deps` workflow opens a PR but no longer auto-merges, so
70
+ a malicious patch release that passes audit/tests still cannot land
71
+ on `main` without an approving review.
@@ -0,0 +1,29 @@
1
+ # Third-party notices
2
+
3
+ This package bundles or depends on the following third-party works.
4
+
5
+ ---
6
+
7
+ ## Excalifont (Latin subset, woff2)
8
+
9
+ - Path: [`assets/fonts/Excalifont-Regular.woff2`](assets/fonts/Excalifont-Regular.woff2)
10
+ - Upstream: <https://github.com/excalidraw/excalidraw>
11
+ - License: SIL Open Font License 1.1 (OFL-1.1)
12
+ - Reproduction of the OFL notice is bundled alongside the binary at
13
+ [`assets/fonts/LICENSE.txt`](assets/fonts/LICENSE.txt).
14
+
15
+ The font is embedded into exported SVG / PNG documents as a `data:`
16
+ URL so they render with the same hand-drawn Excalidraw look in any
17
+ context (GitHub README rendering, sandboxed `<img>` hosts, …).
18
+
19
+ ---
20
+
21
+ ## Runtime dependencies
22
+
23
+ | Package | License | Purpose |
24
+ | ----------------- | ------- | --------------------------------- |
25
+ | `elkjs` | EPL-2.0 | Layered + orthogonal graph layout |
26
+ | `@resvg/resvg-js` | MPL-2.0 | SVG → PNG rasterisation |
27
+ | `roughjs` | MIT | Hand-drawn stroke generation |
28
+
29
+ Run `npm ls --omit=dev` for the resolved versions in your install.
@@ -0,0 +1,263 @@
1
+ #!/usr/bin/env node
2
+ // excaliplant CLI.
3
+ //
4
+ // Usage:
5
+ // excaliplant [--svg|--png|--excalidraw] [-o <out>] [--width N] [<input>]
6
+ //
7
+ // If <input> is omitted, PlantUML is read from stdin.
8
+ // If -o is omitted, output is written to stdout (binary for PNG).
9
+ //
10
+ // Examples:
11
+ // excaliplant diagram.puml # excalidraw → stdout
12
+ // excaliplant -o diagram.excalidraw diagram.puml
13
+ // excaliplant --svg diagram.puml > out.svg
14
+ // cat diagram.puml | excaliplant --png -o out.png --width 4800
15
+
16
+ import { readFile, writeFile } from "node:fs/promises";
17
+ import { renderPlantUml } from "../index.mjs";
18
+
19
+ // Hard limits to keep the CLI from being weaponised as a memory bomb.
20
+ const DEFAULT_MAX_INPUT_BYTES = 10 * 1024 * 1024; // 10 MiB of PlantUML
21
+ const MAX_INPUT_BYTES_CEILING = 200 * 1024 * 1024; // hard ceiling for --max-input-bytes
22
+ const MAX_RENDER_WIDTH = 16000; // PNG/SVG canvas width upper bound
23
+ const MIN_RENDER_WIDTH = 16;
24
+
25
+ const HELP = `excaliplant — PlantUML → Excalidraw / SVG / PNG renderer.
26
+
27
+ Usage:
28
+ excaliplant [options] [<input>]
29
+
30
+ Options:
31
+ --excalidraw Emit Excalidraw JSON (default).
32
+ --svg Emit a sketchy SVG.
33
+ --png Emit a sketchy PNG.
34
+ -o, --out <f> Write to file <f> instead of stdout.
35
+ --width <n> PNG width (default 4800) / SVG canvas width (default 1200).
36
+ Clamped to [${MIN_RENDER_WIDTH}, ${MAX_RENDER_WIDTH}].
37
+ --label <s> Source label written to appState.name.
38
+ --no-canvas For --svg: emit a tightly-cropped SVG without the 4:3 letterbox.
39
+ --rng-seed <n> Override the deterministic seed (use --rng-seed=random for non-determinism).
40
+ --max-input-bytes <N>
41
+ Reject stdin/file input larger than N bytes
42
+ (default ${DEFAULT_MAX_INPUT_BYTES}, ceiling ${MAX_INPUT_BYTES_CEILING}).
43
+ -h, --help Show this message.
44
+ -v, --version Show package version.
45
+
46
+ Exit codes:
47
+ 0 success
48
+ 1 input error (oversized, parse error, render failure)
49
+ 2 CLI argument error
50
+ 64 unexpected internal error
51
+
52
+ Set DEBUG=1 to print full stack traces on failure.
53
+ `;
54
+
55
+ /**
56
+ * Print a one-line error and exit with the given code.
57
+ * @param {number} code
58
+ * @param {string} msg
59
+ * @internal
60
+ */
61
+ function die(code, msg) {
62
+ process.stderr.write(`excaliplant: ${msg}\n`);
63
+ process.exit(code);
64
+ }
65
+
66
+ /**
67
+ * Parse a CLI argument that must be a positive integer.
68
+ * @param {string} raw
69
+ * @param {string} flag
70
+ * @returns {number}
71
+ * @internal
72
+ */
73
+ function parsePositiveInt(raw, flag) {
74
+ const n = Number(raw);
75
+ if (!Number.isFinite(n) || !Number.isInteger(n) || n <= 0) {
76
+ die(2, `${flag} expects a positive integer (got ${JSON.stringify(raw)})`);
77
+ }
78
+ return n;
79
+ }
80
+
81
+ /**
82
+ * Parse `process.argv.slice(2)` into a normalised options object.
83
+ * Validates ranges and exits with code 2 on bad input.
84
+ * @param {string[]} argv
85
+ * @returns {object}
86
+ * @internal
87
+ */
88
+ function parseArgs(argv) {
89
+ const opts = { format: "excalidraw", canvas: true, maxInputBytes: DEFAULT_MAX_INPUT_BYTES };
90
+ const positional = [];
91
+ for (let i = 0; i < argv.length; i++) {
92
+ const a = argv[i];
93
+ switch (a) {
94
+ case "--excalidraw":
95
+ opts.format = "excalidraw";
96
+ break;
97
+ case "--svg":
98
+ opts.format = "svg";
99
+ break;
100
+ case "--png":
101
+ opts.format = "png";
102
+ break;
103
+ case "-o":
104
+ case "--out":
105
+ opts.out = argv[++i];
106
+ break;
107
+ case "--width": {
108
+ const w = parsePositiveInt(argv[++i], "--width");
109
+ if (w < MIN_RENDER_WIDTH || w > MAX_RENDER_WIDTH) {
110
+ die(2, `--width out of range [${MIN_RENDER_WIDTH}, ${MAX_RENDER_WIDTH}] (got ${w})`);
111
+ }
112
+ opts.width = w;
113
+ break;
114
+ }
115
+ case "--label":
116
+ opts.label = argv[++i];
117
+ break;
118
+ case "--no-canvas":
119
+ opts.canvas = false;
120
+ break;
121
+ case "--rng-seed":
122
+ opts.rngSeed = argv[++i];
123
+ break;
124
+ case "--max-input-bytes": {
125
+ const n = parsePositiveInt(argv[++i], "--max-input-bytes");
126
+ if (n > MAX_INPUT_BYTES_CEILING) {
127
+ die(2, `--max-input-bytes exceeds ceiling ${MAX_INPUT_BYTES_CEILING}`);
128
+ }
129
+ opts.maxInputBytes = n;
130
+ break;
131
+ }
132
+ case "-h":
133
+ case "--help":
134
+ opts.help = true;
135
+ break;
136
+ case "-v":
137
+ case "--version":
138
+ opts.versionFlag = true;
139
+ break;
140
+ default:
141
+ if (a.startsWith("-")) die(2, `unknown option: ${a}`);
142
+ positional.push(a);
143
+ }
144
+ }
145
+ if (positional.length > 1) die(2, "expected at most one positional <input> path");
146
+ opts.input = positional[0];
147
+ return opts;
148
+ }
149
+
150
+ /**
151
+ * Read the PlantUML source either from the named file or from stdin,
152
+ * enforcing the configured byte cap.
153
+ * @param {string|undefined} file
154
+ * @param {number} maxBytes
155
+ * @returns {Promise<string>}
156
+ * @internal
157
+ */
158
+ async function readInput(file, maxBytes) {
159
+ if (file) {
160
+ // Stat first so we don't load multi-GB files into memory.
161
+ const { stat } = await import("node:fs/promises");
162
+ const st = await stat(file);
163
+ if (st.size > maxBytes) {
164
+ die(
165
+ 1,
166
+ `input file ${file} is ${st.size} bytes, exceeds limit ${maxBytes} (raise with --max-input-bytes)`,
167
+ );
168
+ }
169
+ return readFile(file, "utf8");
170
+ }
171
+ return new Promise((resolve, reject) => {
172
+ let total = 0;
173
+ const chunks = [];
174
+ process.stdin.on("data", (chunk) => {
175
+ total += chunk.length;
176
+ if (total > maxBytes) {
177
+ process.stdin.destroy();
178
+ reject(
179
+ new Error(
180
+ `stdin exceeded ${maxBytes} bytes (raise with --max-input-bytes); aborted at ${total}`,
181
+ ),
182
+ );
183
+ return;
184
+ }
185
+ chunks.push(chunk);
186
+ });
187
+ process.stdin.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
188
+ process.stdin.on("error", reject);
189
+ });
190
+ }
191
+
192
+ /**
193
+ * CLI entry point. Wired into `bin/excaliplant.mjs` shebang.
194
+ * @returns {Promise<void>}
195
+ * @internal
196
+ */
197
+ async function main() {
198
+ const opts = parseArgs(process.argv.slice(2));
199
+ if (opts.help) {
200
+ process.stdout.write(HELP);
201
+ return;
202
+ }
203
+ if (opts.versionFlag) {
204
+ const { readFile: rf } = await import("node:fs/promises");
205
+ const url = new URL("../package.json", import.meta.url);
206
+ const pkg = JSON.parse(await rf(url, "utf8"));
207
+ process.stdout.write(`${pkg.version}\n`);
208
+ return;
209
+ }
210
+
211
+ let text;
212
+ try {
213
+ text = await readInput(opts.input, opts.maxInputBytes);
214
+ } catch (e) {
215
+ die(1, e?.message || String(e));
216
+ }
217
+
218
+ // Build deterministic / overridable RNG.
219
+ let rng;
220
+ if (opts.rngSeed === "random") {
221
+ rng = Math.random;
222
+ } else if (opts.rngSeed != null) {
223
+ const { createSeededRng } = await import("../src/render/rng.mjs");
224
+ rng = createSeededRng(Number(opts.rngSeed) >>> 0);
225
+ }
226
+
227
+ const result = renderPlantUml(text, {
228
+ sourceLabel: opts.label ?? opts.input ?? "stdin",
229
+ rng,
230
+ });
231
+
232
+ let payload;
233
+ if (opts.format === "excalidraw") {
234
+ const doc = await result;
235
+ payload = JSON.stringify(doc, null, 2);
236
+ } else if (opts.format === "svg") {
237
+ const svgOpts = { canvas: opts.canvas };
238
+ if (opts.width) svgOpts.width = opts.width;
239
+ payload = await result.toSvg(svgOpts);
240
+ } else if (opts.format === "png") {
241
+ const pngOpts = {};
242
+ if (opts.width) pngOpts.width = opts.width;
243
+ payload = await result.toPng(pngOpts);
244
+ }
245
+
246
+ if (opts.out) {
247
+ await writeFile(opts.out, payload);
248
+ } else if (opts.format === "png") {
249
+ process.stdout.write(payload);
250
+ } else {
251
+ process.stdout.write(`${payload}\n`);
252
+ }
253
+ }
254
+
255
+ main().catch((e) => {
256
+ if (process.env.DEBUG) {
257
+ console.error(e?.stack || e);
258
+ } else {
259
+ console.error(`excaliplant: ${e?.message || e}`);
260
+ console.error(" (set DEBUG=1 to see the full stack trace)");
261
+ }
262
+ process.exit(64);
263
+ });