@grethel-labs/excaliplant 0.1.0 → 0.1.3

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 CHANGED
@@ -1,22 +1,119 @@
1
+
1
2
  # excaliplant
2
3
 
3
- PlantUML → Excalidraw renderer with a plugin-based parser. Standalone library.
4
+ > PlantUML → ELK layout → Excalidraw renderer with a plugin-based parser.  ·  **v0.1.3**  ·  73 tests  ·  MIT
5
+
6
+ `@grethel-labs/excaliplant` takes PlantUML source, runs it through a plugin-based
7
+ parser, lays it out with [ELK](https://github.com/kieler/elkjs), and
8
+ emits a `.excalidraw` JSON document — opening cleanly in any
9
+ Excalidraw front-end. Optional helpers convert the result to SVG or
10
+ PNG so the same pipeline can also produce static documentation
11
+ artefacts.
12
+
13
+ <table>
14
+ <tr>
15
+ <td align="center" width="50%">
16
+ <a href="docs/ressources/generated/png/modules.png"><img src="docs/ressources/generated/png/modules.png" alt="Module structure" width="380"/></a><br/>
17
+ <sub><b>Module structure</b> — rendered by excaliplant itself</sub>
18
+ </td>
19
+ <td align="center" width="50%">
20
+ <a href="docs/ressources/generated/png/sequence.png"><img src="docs/ressources/generated/png/sequence.png" alt="renderPlantUml flow" width="380"/></a><br/>
21
+ <sub><b>renderPlantUml flow</b> — rendered by excaliplant itself</sub>
22
+ </td>
23
+ </tr>
24
+ </table>
25
+
26
+ > ⚠️ This README is generated. Edit
27
+ > [`docs/README.template.md.njk`](./docs/README.template.md.njk) and
28
+ > run `npm run build:docs`.
29
+
30
+ ---
31
+
32
+ ## How to use
33
+
34
+ ### Install
35
+
36
+ ```sh
37
+ npm install @grethel-labs/excaliplant
38
+ ```
39
+
40
+ `@resvg/resvg-js` is pulled in as a runtime dependency so the SVG and
41
+ PNG export paths work out of the box.
42
+
43
+ ### Render PlantUML to an Excalidraw document
44
+
45
+ ```js
46
+ import { renderPlantUml } from "@grethel-labs/excaliplant";
47
+
48
+ const excalidraw = await renderPlantUml(plantumlText, { sourceLabel: "demo" });
49
+ // → write `excalidraw` to disk as <name>.excalidraw, or hand it to an
50
+ // Excalidraw embed.
51
+ ```
52
+
53
+ ### Render to SVG / PNG
54
+
55
+ The result of `renderPlantUml(...)` is a thenable — you can `await` it
56
+ to get the Excalidraw JSON, or chain `.toSvg()` / `.toPng()` on it to
57
+ get the rasterised diagram in a single line. Both outputs keep the
58
+ hand-drawn Excalidraw look (strokes are produced via `roughjs`, the
59
+ same library Excalidraw uses internally).
60
+
61
+ ```js
62
+ import { renderPlantUml } from "@grethel-labs/excaliplant";
63
+
64
+ const svg = await renderPlantUml(plantumlText).toSvg();
65
+ const png = await renderPlantUml(plantumlText).toPng({ width: 4800 });
66
+ ```
67
+
68
+ The lower-level helpers are still exported if you need them:
69
+
70
+ ```js
71
+ import {
72
+ renderPlantUml,
73
+ excalidrawJsonToCanvasSvg,
74
+ svgToPng,
75
+ } from "@grethel-labs/excaliplant";
76
+
77
+ const doc = await renderPlantUml(plantumlText);
78
+ const svg = excalidrawJsonToCanvasSvg(doc, { width: 1200 });
79
+ const png = svgToPng(svg, { width: 4800 }); // 4× SVG width
80
+ ```
4
81
 
5
- <!-- BEGIN:version -->
6
- **Version:** `0.1.0`
7
- <!-- END:version -->
82
+ Lower-level entry points are also exported:
8
83
 
9
- ## Self-rendered diagrams
84
+ | Export | Purpose |
85
+ | ------------------------------- | ------------------------------------------------ |
86
+ | `parsePlantUml(text)` | PlantUML → `Diagram` model |
87
+ | `layoutDiagram(diagram)` | Sizing + ELK layout + edge routing |
88
+ | `exportDiagram(diagram)` | Diagram → Excalidraw JSON |
89
+ | `excalidrawToSvg(doc)` | Excalidraw JSON → tightly-cropped SVG |
90
+ | `excalidrawJsonToCanvasSvg(…)` | …same, letter-boxed onto a fixed-aspect canvas |
91
+ | `svgToPng(svg)` | Rasterise SVG to PNG (`@resvg/resvg-js`) |
10
92
 
11
- The diagrams below are generated **by excaliplant itself** at build time
12
- (`npm run build:docs`) from PlantUML sources that describe this very
13
- repository. The doc snippets under each image are extracted from the
14
- source code via `@diagram` JSDoc tags.
93
+ ### Run the tests
94
+
95
+ ```sh
96
+ npm test
97
+ ```
98
+
99
+ Ships with **73 tests** across functional, edge-case,
100
+ security (XSS / ReDoS / prototype-pollution), and self-introspection
101
+ suites.
102
+
103
+ ---
104
+
105
+ ## Self-rendered architecture diagrams
106
+
107
+ The diagrams below are produced **by excaliplant itself** at build
108
+ time from PlantUML sources that describe this very repository. The
109
+ text under each image is extracted from the source via `@diagram`
110
+ JSDoc tags.
15
111
 
16
- <!-- BEGIN:diagrams -->
17
112
  ### Module structure
18
113
 
19
- ![Module structure](./docs/modules.svg)
114
+ ![Module structure](docs/ressources/generated/png/modules.png)
115
+
116
+ _Sources: [PlantUML](docs/ressources/generated/puml/modules.puml) · [SVG](docs/ressources/generated/svg/modules.svg)_
20
117
 
21
118
  The module graph reflects how the source is laid out under
22
119
  [`src/`](./src/). Note in particular how the parser is split into a
@@ -25,7 +122,9 @@ each plugin handling one PlantUML construct.
25
122
 
26
123
  ### renderPlantUml flow
27
124
 
28
- ![renderPlantUml flow](./docs/sequence.svg)
125
+ ![renderPlantUml flow](docs/ressources/generated/png/sequence.png)
126
+
127
+ _Sources: [PlantUML](docs/ressources/generated/puml/sequence.puml) · [SVG](docs/ressources/generated/svg/sequence.svg)_
29
128
 
30
129
  The call graph for `renderPlantUml(text)` walks three subsystems:
31
130
 
@@ -42,7 +141,9 @@ The call graph for `renderPlantUml(text)` walks three subsystems:
42
141
 
43
142
  ### Parser plugins
44
143
 
45
- ![Parser plugins](./docs/plugins.svg)
144
+ ![Parser plugins](docs/ressources/generated/png/plugins.png)
145
+
146
+ _Sources: [PlantUML](docs/ressources/generated/puml/plugins.puml) · [SVG](docs/ressources/generated/svg/plugins.svg)_
46
147
 
47
148
  Each parser plugin is a tiny self-contained file that handles ONE
48
149
  PlantUML construct. The engine offers each input line to plugins
@@ -52,12 +153,86 @@ To add support for a new PlantUML keyword, drop a new file in
52
153
  `src/parser/plugins/` and append it to the default array in
53
154
  [`plantuml.mjs`](./src/parser/plantuml.mjs). No engine change required.
54
155
 
55
- <!-- END:diagrams -->
156
+ ## Pipeline
157
+
158
+ ```text
159
+ PlantUML text
160
+ │ parsePlantUml()
161
+ ▼
162
+ Diagram (planes, subplanes, boxes, connections)
163
+ │ layoutDiagram() (sizing → ELK layered + orthogonal routing → chamfer)
164
+ ▼
165
+ Diagram with absolute positions and edge paths
166
+ │ exportDiagram()
167
+ ▼
168
+ Excalidraw JSON
169
+ │ excalidrawJsonToCanvasSvg() (optional)
170
+ ▼
171
+ SVG ── svgToPng() ──▶ PNG (both optional, no headless browser)
172
+ ```
173
+
174
+ ## Repository layout
175
+
176
+ ```text
177
+ excaliplant
178
+ ├── docs
179
+ │ ├── ressources
180
+ │ ├── scripts
181
+ │ │ ├── build-docs.mjs
182
+ │ │ ├── config.mjs
183
+ │ │ ├── extract-docs.mjs
184
+ │ │ ├── file-tree.mjs
185
+ │ │ └── self-diagrams.mjs
186
+ │ └── README.template.md.njk
187
+ ├── scripts
188
+ │ ├── auto-patch-deps.mjs
189
+ │ └── smoke.mjs
190
+ ├── src
191
+ │ ├── layout
192
+ │ │ ├── elk_layout.mjs
193
+ │ │ ├── sequence_layout.mjs
194
+ │ │ └── sizing.mjs
195
+ │ ├── model
196
+ │ │ └── diagram.mjs
197
+ │ ├── parser
198
+ │ │ ├── plugins
199
+ │ │ │ ├── component
200
+ │ │ │ └── sequence
201
+ │ │ ├── component_context.mjs
202
+ │ │ ├── engine.mjs
203
+ │ │ ├── plantuml.mjs
204
+ │ │ ├── sequence_context.mjs
205
+ │ │ └── utils.mjs
206
+ │ ├── render
207
+ │ │ ├── canvas_svg.mjs
208
+ │ │ ├── excalidraw.mjs
209
+ │ │ ├── png.mjs
210
+ │ │ ├── sequence_render.mjs
211
+ │ │ └── svg.mjs
212
+ │ └── style
213
+ │ ├── colors.mjs
214
+ │ └── text.mjs
215
+ ├── tests
216
+ │ ├── edge_cases.test.mjs
217
+ │ ├── functional_more.test.mjs
218
+ │ ├── plantuml.test.mjs
219
+ │ ├── security.test.mjs
220
+ │ └── self_introspection.test.mjs
221
+ ├── LICENSE
222
+ ├── README.md
223
+ ├── index.mjs
224
+ ├── package.json
225
+ ├── tsconfig.json
226
+ └── typedoc.json
227
+ ```
228
+
229
+ Generated artefacts (`docs/ressources/generated/`, `docs/api/`) live
230
+ in `.gitignore` — they are rebuilt by `npm run build:docs` and
231
+ `npm run build:api`.
56
232
 
57
233
  ## Module documentation
58
234
 
59
- <!-- BEGIN:module-docs -->
60
- #### layout
235
+ ### layout
61
236
 
62
237
  Layout chooses positions for every shape and routes every edge.
63
238
  Component / use-case / deployment diagrams flow through ELK
@@ -70,7 +245,7 @@ tabular (lifelines on the X axis, time on the Y axis), so a
70
245
  deterministic ~90-line algorithm produces better, more compact
71
246
  results than a force-directed solver could.
72
247
 
73
- #### model
248
+ ### model
74
249
 
75
250
  Input-agnostic diagram model. Two top-level kinds:
76
251
 
@@ -84,7 +259,7 @@ pipeline; the parser is just one possible source. Callers can
84
259
  also build a `Diagram` programmatically and feed it to
85
260
  `renderDiagram()`.
86
261
 
87
- #### parser/engine
262
+ ### parser/engine
88
263
 
89
264
  A ~50-line line-walker. The engine itself knows nothing about
90
265
  PlantUML syntax; that lives entirely in plugins. Block plugins
@@ -92,6 +267,7 @@ PlantUML syntax; that lives entirely in plugins. Block plugins
92
267
  subsequent lines until they release.
93
268
 
94
269
  Plugin contract:
270
+
95
271
  ```js
96
272
  {
97
273
  name,
@@ -100,7 +276,7 @@ Plugin contract:
100
276
  }
101
277
  ```
102
278
 
103
- #### render
279
+ ### render
104
280
 
105
281
  Emits Excalidraw JSON. Each model shape is dispatched to a
106
282
  dedicated `renderXxx()` function that produces one or more
@@ -110,193 +286,6 @@ that any Excalidraw front-end can open. The companion module
110
286
  [`src/render/svg.mjs`](./src/render/svg.mjs) converts the same
111
287
  JSON to SVG for the build-time documentation pipeline.
112
288
 
113
- <!-- END:module-docs -->
114
-
115
- ## Pipeline
116
-
117
- ```
118
- PlantUML text
119
- │ parsePlantUml()
120
- ▼
121
- Diagram (planes, subplanes, boxes, connections)
122
- │ layoutDiagram() (sizing → ELK layered + orthogonal routing → chamfer)
123
- ▼
124
- Diagram with absolute positions and edge paths
125
- │ exportDiagram()
126
- ▼
127
- Excalidraw JSON
128
- ```
129
-
130
- ## API
131
-
132
- ```js
133
- import { renderPlantUml } from "./index.mjs";
134
-
135
- const excalidraw = await renderPlantUml(plantumlText, { sourceLabel: "demo" });
136
- ```
137
-
138
- Lower-level entry points (`parsePlantUml`, `layoutDiagram`,
139
- `exportDiagram`, `renderDiagram`) are also exported. The model classes
140
- (`Diagram`, `Plane`, `Subplane`, `Box`, `Connection`) are exported for
141
- callers that want to construct shapes programmatically.
142
-
143
- ## Supported PlantUML subset
144
-
145
- ### Component / use-case / deployment diagrams
146
-
147
- ```plantuml
148
- @startuml
149
- title "<free text>"
150
-
151
- ' --- containers (any nest the others) -------------------------------
152
- package "<Title>" as <id> { ... }
153
- frame "<Title>" as <id> { ... }
154
- folder "<Title>" as <id> { ... }
155
- node "<Title>" as <id> { ... }
156
- rectangle "<Title>" as <id> { ... }
157
- together { ... }
158
-
159
- ' --- shapes --------------------------------------------------------
160
- [Title] as <id> [: description]
161
- component "Title" <<stereo>> as <id> [: description]
162
- rectangle "Title" as <id>
163
- actor "Title" as <id> ' or just `actor User`
164
- usecase "Title" as <id> ' or `(Title) as <id>`
165
- database "Title" as <id>
166
- node "Title" as <id> ' (no `{}` → 3-D box shape)
167
- cloud "Title" as <id>
168
- interface "Title" as <id> ' rendered as a small "lollipop" circle
169
- entity "Title" as <id>
170
- class "Title" as <id> { member; member }
171
-
172
- ' --- connections ---------------------------------------------------
173
- a --> b : label ' solid arrow
174
- a <-- b
175
- a <--> b
176
- a -up-> b ' direction hint (up|down|left|right)
177
- a ..> b ' dependency (dashed)
178
- a <|-- b ' inheritance (triangle on parent)
179
- a ..|> b ' realization (dashed + triangle)
180
- a *-- b ' composition (filled diamond)
181
- a o-- b ' aggregation (open diamond)
182
-
183
- ' --- notes ---------------------------------------------------------
184
- note left of <id> : text
185
- note right of <id> : text
186
- note top of <id> : text
187
- note bottom of <id> : text
188
- note "free standing text" as N1
189
- N1 .. <id>
190
-
191
- ' Multi-line text everywhere via \n.
192
- @enduml
193
- ```
194
-
195
- ### Sequence diagrams
196
-
197
- The parser auto-switches to the sequence pipeline as soon as it sees a
198
- `participant`/`boundary`/`control`/`collections`/`queue` keyword.
199
-
200
- ```plantuml
201
- @startuml
202
- title "Login flow"
203
- actor User
204
- participant "Web UI" as ui
205
- participant Auth as auth
206
- database DB
207
-
208
- User -> ui : open page
209
- ui -> auth : login(name, pwd)
210
- auth -> DB : SELECT user
211
- DB --> auth : row ' dashed = reply
212
- auth --> ui : ok\n(token)
213
- ui --> User : show home
214
- auth -> auth : audit ' self-message (loop arrow)
215
-
216
- note right of auth : token has\n5 min ttl
217
- note over ui, auth : TLS only
218
- @enduml
219
- ```
220
-
221
- Sequence diagrams use a separate, deterministic tabular layout (no ELK),
222
- since lifelines + time form a strictly tabular structure.
223
-
224
- ## Architecture
225
-
226
- The parser is built around a tiny line-driven engine plus a list of
227
- self-contained **plugins** (one per PlantUML construct):
228
-
229
- ```
230
- src/parser/
231
- ├── engine.mjs ← ~50 lines, walks lines + dispatches to plugins
232
- ├── utils.mjs ← shared regexes / helpers (slug, classifyArrow, …)
233
- ├── component_context.mjs ← mutable state for component-style parses
234
- ├── sequence_context.mjs ← mutable state for sequence parses
235
- ├── plantuml.mjs ← entry: dispatch + plugin registry
236
- └── plugins/
237
- ├── component/
238
- │ ├── preamble.mjs ← title, closing brace
239
- │ ├── containers.mjs ← package / frame / folder / node / rectangle / together
240
- │ ├── shapes.mjs ← [X], (Y), shape keywords, class { members }
241
- │ ├── connections.mjs ← all arrow flavours
242
- │ └── notes.mjs ← note of, free notes, multi-line note blocks
243
- └── sequence/
244
- ├── preamble.mjs ← title
245
- ├── participants.mjs
246
- ├── messages.mjs
247
- └── notes.mjs ← side / over notes (single + multi-line)
248
- ```
249
-
250
- A plugin is just `{ name, tryLine?(line, ctx), tryStart?(line, ctx) }`
251
- — see `engine.mjs` for the full contract. Block plugins (notes, class
252
- bodies) take over the engine until they decide to release.
253
-
254
- ### Adding a new construct
255
-
256
- 1. Create a new plugin file in `plugins/component/` or `plugins/sequence/`.
257
- 2. Register it in `DEFAULT_COMPONENT_PLUGINS` / `DEFAULT_SEQUENCE_PLUGINS`
258
- in `plantuml.mjs`. Order matters only when several plugins might match
259
- the same line.
260
-
261
- ### Injecting plugins from outside
262
-
263
- Without forking, callers can append their own plugins:
289
+ ## License
264
290
 
265
- ```js
266
- parsePlantUml(src, {
267
- plugins: {
268
- component: [...DEFAULT_COMPONENT_PLUGINS, myCustomPlugin],
269
- },
270
- });
271
- ```
272
-
273
- ## Dependencies
274
-
275
- - [`elkjs`](https://www.npmjs.com/package/elkjs) — Eclipse Layout Kernel
276
- (port to JS). Provides hierarchical layered layout + orthogonal edge
277
- routing.
278
- - Excalidraw is consumed via its **file-format API**: this lib emits
279
- the JSON document that any Excalidraw front-end can open. We do not
280
- bundle the Excalidraw React component (47 MB, browser/DOM-bound;
281
- not usable in Node).
282
-
283
- ### Why not delegate parsing / rendering to a third-party library?
284
-
285
- We evaluated:
286
-
287
- | Candidate | Outcome |
288
- |---|---|
289
- | `plantuml-parser` (Enteee) | Drops `title`, `note`, `actor`/`database`/`cloud`/`entity`/`rectangle` shape declarations, sequence participants, and `-up->` direction hints — too lossy to replace our parser without re-introducing the same regex code as a "supplementary scanner". |
290
- | `@excalidraw/excalidraw` | 47 MB React component, depends on `window` / `canvas`. Not usable in a Node library. |
291
- | `@excalidraw/utils` | 96 MB, same DOM dependencies. Not usable. |
292
- | `@excalidraw/mermaid-to-excalidraw` | Mermaid-only input; doesn't expose a generic skeleton API. |
293
-
294
- So instead we make our **own** parser easy to extend (plugin
295
- architecture above) and our renderer talks to Excalidraw via its
296
- documented JSON file format.
297
-
298
- ## Tests
299
-
300
- ```sh
301
- npm test
302
- ```
291
+ MIT © grethel-labs
package/index.mjs CHANGED
@@ -49,41 +49,118 @@
49
49
  import { parsePlantUml } from "./src/parser/plantuml.mjs";
50
50
  import { layoutDiagram } from "./src/layout/elk_layout.mjs";
51
51
  import { exportDiagram } from "./src/render/excalidraw.mjs";
52
+ import { excalidrawToSvg } from "./src/render/svg.mjs";
53
+ import { excalidrawJsonToCanvasSvg } from "./src/render/canvas_svg.mjs";
54
+ import { svgToPng } from "./src/render/png.mjs";
52
55
 
53
56
  export { parsePlantUml } from "./src/parser/plantuml.mjs";
54
57
  export { layoutDiagram } from "./src/layout/elk_layout.mjs";
55
58
  export { exportDiagram } from "./src/render/excalidraw.mjs";
59
+ export { excalidrawToSvg } from "./src/render/svg.mjs";
60
+ export {
61
+ excalidrawJsonToCanvasSvg,
62
+ DEFAULT_CANVAS_WIDTH,
63
+ DEFAULT_ASPECT_RATIO,
64
+ } from "./src/render/canvas_svg.mjs";
65
+ export { svgToPng } from "./src/render/png.mjs";
56
66
  export {
57
67
  Box, Connection, Diagram, Plane, Subplane,
58
68
  Participant, Message, SequenceDiagram, SequenceNote,
59
69
  SHAPES,
60
70
  } from "./src/model/diagram.mjs";
61
71
 
72
+ /**
73
+ * Chainable result returned by `renderPlantUml` / `renderDiagram`.
74
+ *
75
+ * Awaiting the result yields the Excalidraw JSON document, so existing
76
+ * callers (`const doc = await renderPlantUml(text)`) keep working.
77
+ *
78
+ * On top of that, the result exposes `.toSvg()` and `.toPng()` so a
79
+ * caller can write:
80
+ *
81
+ * ```js
82
+ * const r = renderPlantUml(text);
83
+ * const svg = await r.toSvg();
84
+ * const png = await r.toPng({ width: 4800 });
85
+ * ```
86
+ *
87
+ * Both helpers lazily await the underlying document — so calling
88
+ * `toSvg()` / `toPng()` directly on the unawaited result works too.
89
+ */
90
+ export class RenderResult {
91
+ /** @param {Promise<object>} docPromise */
92
+ constructor(docPromise) {
93
+ this._doc = docPromise;
94
+ }
95
+
96
+ /** Thenable: `await result` yields the Excalidraw JSON document. */
97
+ then(onFulfilled, onRejected) {
98
+ return this._doc.then(onFulfilled, onRejected);
99
+ }
100
+
101
+ /**
102
+ * Letter-boxed sketchy SVG.
103
+ *
104
+ * @param {object} [opts] Forwarded to `excalidrawJsonToCanvasSvg`,
105
+ * plus `{ canvas: false }` to skip the letter-boxing and get the
106
+ * tightly-cropped SVG instead.
107
+ * @returns {Promise<string>}
108
+ */
109
+ async toSvg(opts = {}) {
110
+ const doc = await this._doc;
111
+ if (opts.canvas === false) return excalidrawToSvg(doc, opts);
112
+ return excalidrawJsonToCanvasSvg(doc, opts);
113
+ }
114
+
115
+ /**
116
+ * Sketchy PNG. Renders the SVG (which already carries the
117
+ * Excalidraw-style wobble via roughjs) and rasterises with resvg.
118
+ *
119
+ * @param {object} [opts] Forwarded to `svgToPng` and the SVG step.
120
+ * @returns {Promise<Buffer>}
121
+ */
122
+ async toPng(opts = {}) {
123
+ const svg = await this.toSvg(opts);
124
+ return svgToPng(svg, opts);
125
+ }
126
+ }
127
+
62
128
  /**
63
129
  * Render a PlantUML source string to an Excalidraw JSON document.
64
130
  *
131
+ * The return value is a thenable {@link RenderResult}: `await` it for
132
+ * the Excalidraw JSON, or call `.toSvg()` / `.toPng()` on it to get
133
+ * the rasterised diagram in one chained call.
134
+ *
65
135
  * @param {string} plantuml PlantUML text (see src/parser/plantuml.mjs
66
136
  * for the supported subset).
67
137
  * @param {object} [opts]
68
138
  * @param {string} [opts.sourceLabel] Forwarded to the renderer's
69
139
  * appState.name.
70
- * @returns {Promise<object>} Excalidraw JSON.
140
+ * @returns {RenderResult} Thenable wrapping the Excalidraw
141
+ * JSON document.
71
142
  */
72
- export async function renderPlantUml(plantuml, opts = {}) {
73
- const diagram = parsePlantUml(plantuml);
74
- await layoutDiagram(diagram);
75
- return exportDiagram(diagram, {
76
- sourceLabel: opts.sourceLabel ?? diagram.title ?? "",
77
- });
143
+ export function renderPlantUml(plantuml, opts = {}) {
144
+ return new RenderResult((async () => {
145
+ const diagram = parsePlantUml(plantuml);
146
+ await layoutDiagram(diagram);
147
+ return exportDiagram(diagram, {
148
+ sourceLabel: opts.sourceLabel ?? diagram.title ?? "",
149
+ });
150
+ })());
78
151
  }
79
152
 
80
153
  /**
81
154
  * Render an already-built Diagram model. Useful for callers that want
82
155
  * to bypass the PlantUML parser and feed shapes programmatically.
156
+ *
157
+ * @returns {RenderResult}
83
158
  */
84
- export async function renderDiagram(diagram, opts = {}) {
85
- await layoutDiagram(diagram);
86
- return exportDiagram(diagram, {
87
- sourceLabel: opts.sourceLabel ?? diagram.title ?? "",
88
- });
159
+ export function renderDiagram(diagram, opts = {}) {
160
+ return new RenderResult((async () => {
161
+ await layoutDiagram(diagram);
162
+ return exportDiagram(diagram, {
163
+ sourceLabel: opts.sourceLabel ?? diagram.title ?? "",
164
+ });
165
+ })());
89
166
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@grethel-labs/excaliplant",
3
- "version": "0.1.0",
3
+ "version": "0.1.3",
4
4
  "description": "PlantUML → ELK layout → Excalidraw renderer with a plugin-based parser.",
5
5
  "type": "module",
6
6
  "main": "index.mjs",
@@ -15,11 +15,14 @@
15
15
  "./parser/plantuml": "./src/parser/plantuml.mjs",
16
16
  "./layout": "./src/layout/elk_layout.mjs",
17
17
  "./render": "./src/render/excalidraw.mjs",
18
+ "./render/svg": "./src/render/svg.mjs",
19
+ "./render/canvas-svg": "./src/render/canvas_svg.mjs",
20
+ "./render/png": "./src/render/png.mjs",
18
21
  "./model": "./src/model/diagram.mjs"
19
22
  },
20
23
  "scripts": {
21
- "test": "node --test tests/*.test.mjs",
22
- "build:docs": "node scripts/build-docs.mjs",
24
+ "test": "node --test tests/edge_cases.test.mjs tests/functional_more.test.mjs tests/plantuml.test.mjs tests/security.test.mjs tests/self_introspection.test.mjs",
25
+ "build:docs": "node docs/scripts/build-docs.mjs",
23
26
  "build:api": "typedoc",
24
27
  "build": "npm run build:docs && npm run build:api",
25
28
  "prepublishOnly": "npm test && npm run build"
@@ -41,13 +44,17 @@
41
44
  "access": "public"
42
45
  },
43
46
  "dependencies": {
44
- "elkjs": "^0.9.3"
47
+ "@resvg/resvg-js": "^2.6.2",
48
+ "elkjs": "^0.11.1",
49
+ "roughjs": "^4.6.6"
45
50
  },
46
51
  "engines": {
47
52
  "node": ">=18"
48
53
  },
49
54
  "license": "MIT",
50
55
  "devDependencies": {
56
+ "nunjucks": "^3.2.4",
57
+ "tree-node-cli": "^1.6.0",
51
58
  "typedoc": "^0.28.19"
52
59
  }
53
60
  }
@@ -12,6 +12,7 @@
12
12
  * subsequent lines until they release.
13
13
  *
14
14
  * Plugin contract:
15
+ *
15
16
  * ```js
16
17
  * {
17
18
  * name,
@@ -0,0 +1,70 @@
1
+ // Canvas-letterboxed SVG export.
2
+ //
3
+ // Wraps the plain `excalidrawToSvg` output in a fixed-aspect canvas
4
+ // so multiple diagrams render at the same proportions (useful when
5
+ // embedding several PNGs side-by-side in a document).
6
+ //
7
+ // This is part of the optional rendering API. The plain SVG path has
8
+ // no extra runtime dependencies; the PNG path
9
+ // (`./png.mjs`) needs `@resvg/resvg-js` to be installed.
10
+
11
+ import { excalidrawToSvg } from "./svg.mjs";
12
+
13
+ export const DEFAULT_CANVAS_WIDTH = 1200;
14
+ export const DEFAULT_ASPECT_RATIO = { w: 4, h: 3 };
15
+
16
+ /**
17
+ * Convert an Excalidraw JSON document to an SVG that has been
18
+ * letter-boxed onto a fixed-aspect canvas.
19
+ *
20
+ * @param {object} doc Excalidraw JSON document.
21
+ * @param {object} [opts]
22
+ * @param {{w:number,h:number}} [opts.aspect] Canvas aspect ratio.
23
+ * @param {number} [opts.width] Canvas width in px.
24
+ * @param {string} [opts.background] Canvas background fill.
25
+ * @param {number} [opts.padding] Inner SVG padding.
26
+ * @returns {string} A canvas-sized SVG document.
27
+ */
28
+ export function excalidrawJsonToCanvasSvg(doc, opts = {}) {
29
+ const aspect = opts.aspect ?? DEFAULT_ASPECT_RATIO;
30
+ const width = opts.width ?? DEFAULT_CANVAS_WIDTH;
31
+ const height = Math.round((width * aspect.h) / aspect.w);
32
+ const background = opts.background ?? "#ffffff";
33
+ const padding = opts.padding ?? 16;
34
+
35
+ const inner = excalidrawToSvg(doc, { padding });
36
+ const innerVb = parseViewBox(inner);
37
+ if (!innerVb) return blankCanvas(width, height, background);
38
+
39
+ const scale = Math.min(width / innerVb.w, height / innerVb.h);
40
+ const drawnW = innerVb.w * scale;
41
+ const drawnH = innerVb.h * scale;
42
+ const offsetX = (width - drawnW) / 2;
43
+ const offsetY = (height - drawnH) / 2;
44
+
45
+ const innerBody = inner.replace(/^<svg[^>]*>/, "").replace(/<\/svg>\s*$/, "");
46
+
47
+ return [
48
+ `<svg xmlns="http://www.w3.org/2000/svg" `
49
+ + `width="${width}" height="${height}" `
50
+ + `viewBox="0 0 ${width} ${height}">`,
51
+ `<rect width="${width}" height="${height}" fill="${background}"/>`,
52
+ `<g transform="translate(${offsetX} ${offsetY}) scale(${scale}) `
53
+ + `translate(${-innerVb.x} ${-innerVb.y})">`,
54
+ innerBody,
55
+ `</g>`,
56
+ `</svg>`,
57
+ ].join("");
58
+ }
59
+
60
+ function parseViewBox(svgText) {
61
+ const m = svgText.match(/viewBox="([-\d.]+)\s+([-\d.]+)\s+([-\d.]+)\s+([-\d.]+)"/);
62
+ if (!m) return null;
63
+ return { x: +m[1], y: +m[2], w: +m[3], h: +m[4] };
64
+ }
65
+
66
+ function blankCanvas(w, h, bg) {
67
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" `
68
+ + `viewBox="0 0 ${w} ${h}">`
69
+ + `<rect width="${w}" height="${h}" fill="${bg}"/></svg>`;
70
+ }
@@ -0,0 +1,28 @@
1
+ // PNG rasterisation for SVGs produced by `./svg.mjs` or
2
+ // `./canvas_svg.mjs`.
3
+ //
4
+ // Uses `@resvg/resvg-js` (a runtime dependency of this package). No
5
+ // headless browser is involved.
6
+
7
+ import { Resvg } from "@resvg/resvg-js";
8
+
9
+ const DEFAULT_PNG_WIDTH = 4800; // 4× the default 1200 SVG canvas.
10
+
11
+ /**
12
+ * Rasterise an SVG document to PNG.
13
+ *
14
+ * @param {string} svgText
15
+ * @param {object} [opts]
16
+ * @param {number} [opts.width=4800] Output PNG width in px.
17
+ * @param {string} [opts.background="#ffffff"]
18
+ * @returns {Buffer} PNG bytes.
19
+ */
20
+ export function svgToPng(svgText, opts = {}) {
21
+ const width = opts.width ?? DEFAULT_PNG_WIDTH;
22
+ const resvg = new Resvg(svgText, {
23
+ fitTo: { mode: "width", value: width },
24
+ background: opts.background ?? "#ffffff",
25
+ font: { loadSystemFonts: true },
26
+ });
27
+ return resvg.render().asPng();
28
+ }
@@ -1,27 +1,26 @@
1
1
  // Convert an Excalidraw JSON document to a self-contained SVG string.
2
2
  //
3
3
  // The Excalidraw renderer emits a flat list of elements with absolute
4
- // positions; SVG needs the same. We translate the subset we actually
5
- // produce: rectangle, ellipse, line, arrow, text. Roughness is dropped
6
- // (we render geometric primitives — readable in README, no rough-style
7
- // wobble needed).
4
+ // positions; we translate the subset we actually produce: rectangle,
5
+ // ellipse, line, arrow, text. Strokes are routed through `roughjs`
6
+ // (the same library Excalidraw uses internally) so the exported SVG
7
+ // inherits the recognisable hand-drawn wobble — and since the PNG
8
+ // path rasterises this very SVG, the PNG keeps the look too.
8
9
  //
9
- // This exists to give the build pipeline a Node-only path from
10
- // PlantUML → SVG without spinning up a headless browser.
10
+ // The roughjs Generator is dependency-free at runtime: it produces
11
+ // SVG path commands as strings, no DOM required.
12
+
13
+ import rough from "roughjs";
11
14
 
12
15
  const FONT_FAMILY = "Helvetica, Arial, sans-serif";
16
+ const ROUGHNESS = 1; // Excalidraw's default roughness.
17
+ const BOWING = 1;
18
+ const FILL_WEIGHT = 0; // 0 → roughjs picks a sensible default.
19
+
20
+ const generator = rough.generator();
13
21
 
14
- /**
15
- * @param {object} doc Excalidraw JSON document.
16
- * @param {object} [opts]
17
- * @param {number} [opts.padding=16] Extra margin around content.
18
- * @param {string} [opts.background] Document background colour.
19
- * @returns {string} SVG markup.
20
- */
21
22
  /**
22
23
  * Convert an Excalidraw JSON document to a stand-alone SVG string.
23
- * Used by the build-time documentation pipeline
24
- * ({@link ../../scripts/build-docs.mjs}).
25
24
  *
26
25
  * @param {object} doc The Excalidraw JSON document.
27
26
  * @param {object} [opts]
@@ -76,39 +75,146 @@ function computeBounds(elements) {
76
75
 
77
76
  function renderOne(el) {
78
77
  switch (el.type) {
79
- case "rectangle": return svgRect(el);
80
- case "ellipse": return svgEllipse(el);
81
- case "line": return svgPolyline(el, false);
82
- case "arrow": return svgPolyline(el, true);
78
+ case "rectangle": return roughRect(el);
79
+ case "ellipse": return roughEllipse(el);
80
+ case "line": return roughPolyline(el, false);
81
+ case "arrow": return roughPolyline(el, true);
83
82
  case "text": return svgText(el);
84
83
  default: return null;
85
84
  }
86
85
  }
87
86
 
88
- function svgRect(el) {
89
- const fill = colorOrNone(el.backgroundColor);
87
+ // ── roughjs helpers ───────────────────────────────────────────────────────
88
+
89
+ // Pull a deterministic seed off each Excalidraw element so re-rendering
90
+ // the same JSON document yields the same wobble. Excalidraw assigns
91
+ // `seed` to every element; if it's missing we fall back to a hash of
92
+ // the element's id so output is still deterministic per-document.
93
+ function seedFor(el) {
94
+ if (typeof el.seed === "number") return el.seed % 2_147_483_647;
95
+ if (el.id) {
96
+ let h = 0;
97
+ for (const c of String(el.id)) h = (h * 31 + c.charCodeAt(0)) | 0;
98
+ return Math.abs(h) % 2_147_483_647;
99
+ }
100
+ return 1;
101
+ }
102
+
103
+ function roughOpts(el) {
104
+ return {
105
+ seed: seedFor(el),
106
+ roughness: ROUGHNESS,
107
+ bowing: BOWING,
108
+ stroke: el.strokeColor || "#000",
109
+ strokeWidth: el.strokeWidth || 1.5,
110
+ fill: undefined,
111
+ fillStyle: "solid",
112
+ fillWeight: FILL_WEIGHT,
113
+ disableMultiStroke: false,
114
+ };
115
+ }
116
+
117
+ function dasharray(el) {
118
+ if (el.strokeStyle === "dashed") return "8 4";
119
+ if (el.strokeStyle === "dotted") return "1.5 6";
120
+ return null;
121
+ }
122
+
123
+ function drawableToSvg(drawable, el) {
124
+ // roughjs returns one or more `OpSet`s. We render path-typed sets
125
+ // as <path> elements. fillSketch/fillPath sets get the fill colour;
126
+ // path sets get the stroke colour.
90
127
  const stroke = el.strokeColor || "#000";
91
- const rx = el.roundness ? 6 : 0;
92
- return `<rect x="${el.x}" y="${el.y}" width="${el.width}" height="${el.height}" rx="${rx}" ry="${rx}" fill="${escapeAttr(fill)}" stroke="${escapeAttr(stroke)}" stroke-width="${el.strokeWidth || 1.5}"/>`;
128
+ const strokeWidth = el.strokeWidth || 1.5;
129
+ const dash = dasharray(el);
130
+ const dashAttr = dash ? ` stroke-dasharray="${dash}"` : "";
131
+
132
+ const out = [];
133
+ for (const set of drawable.sets) {
134
+ const d = generator.opsToPath(set);
135
+ if (!d) continue;
136
+ if (set.type === "fillPath" || set.type === "fillSketch") {
137
+ const fill = el.backgroundColor && el.backgroundColor !== "transparent"
138
+ ? el.backgroundColor : null;
139
+ if (!fill) continue;
140
+ out.push(
141
+ `<path d="${d}" fill="${escapeAttr(fill)}" stroke="none"/>`,
142
+ );
143
+ } else if (set.type === "path") {
144
+ out.push(
145
+ `<path d="${d}" fill="none" stroke="${escapeAttr(stroke)}" `
146
+ + `stroke-width="${strokeWidth}" stroke-linecap="round" `
147
+ + `stroke-linejoin="round"${dashAttr}/>`,
148
+ );
149
+ }
150
+ }
151
+ return out.join("");
152
+ }
153
+
154
+ function roughRect(el) {
155
+ const fill = colorOrNone(el.backgroundColor);
156
+ // Solid fill underneath. roughjs' fill modes look noisy on small
157
+ // shapes, and Excalidraw's own export uses solid fills + sketchy
158
+ // outlines, so we mirror that.
159
+ const fillSvg = fill !== "none"
160
+ ? `<path d="${rectPath(el)}" fill="${escapeAttr(fill)}" stroke="none"/>`
161
+ : "";
162
+ const drawable = generator.rectangle(
163
+ el.x, el.y, el.width, el.height, roughOpts(el),
164
+ );
165
+ return fillSvg + drawableToSvg(drawable, el);
93
166
  }
94
167
 
95
- function svgEllipse(el) {
168
+ function rectPath(el) {
169
+ const r = el.roundness ? Math.min(8, el.width / 4, el.height / 4) : 0;
170
+ if (!r) {
171
+ return `M${el.x},${el.y} h${el.width} v${el.height} h${-el.width} z`;
172
+ }
173
+ const x = el.x, y = el.y, w = el.width, h = el.height;
174
+ return [
175
+ `M${x + r},${y}`,
176
+ `h${w - 2 * r}`,
177
+ `a${r},${r} 0 0 1 ${r},${r}`,
178
+ `v${h - 2 * r}`,
179
+ `a${r},${r} 0 0 1 ${-r},${r}`,
180
+ `h${-(w - 2 * r)}`,
181
+ `a${r},${r} 0 0 1 ${-r},${-r}`,
182
+ `v${-(h - 2 * r)}`,
183
+ `a${r},${r} 0 0 1 ${r},${-r}`,
184
+ "z",
185
+ ].join(" ");
186
+ }
187
+
188
+ function roughEllipse(el) {
96
189
  const cx = el.x + el.width / 2;
97
190
  const cy = el.y + el.height / 2;
98
- const rx = el.width / 2;
99
- const ry = el.height / 2;
100
191
  const fill = colorOrNone(el.backgroundColor);
101
- const stroke = el.strokeColor || "#000";
102
- return `<ellipse cx="${cx}" cy="${cy}" rx="${rx}" ry="${ry}" fill="${escapeAttr(fill)}" stroke="${escapeAttr(stroke)}" stroke-width="${el.strokeWidth || 1.5}"/>`;
192
+ const fillSvg = fill !== "none"
193
+ ? `<ellipse cx="${cx}" cy="${cy}" rx="${el.width / 2}" `
194
+ + `ry="${el.height / 2}" fill="${escapeAttr(fill)}" stroke="none"/>`
195
+ : "";
196
+ const drawable = generator.ellipse(cx, cy, el.width, el.height, roughOpts(el));
197
+ return fillSvg + drawableToSvg(drawable, el);
103
198
  }
104
199
 
105
- function svgPolyline(el, withArrow) {
106
- const pts = (el.points || []).map(([dx, dy]) => `${el.x + dx},${el.y + dy}`).join(" ");
107
- const stroke = el.strokeColor || "#000";
108
- const dash = el.strokeStyle === "dashed" ? `stroke-dasharray="6 4"` : "";
109
- const startMarker = withArrow && el.startArrowhead ? markerForArrowhead(el.startArrowhead, "start") : "";
110
- const endMarker = withArrow && el.endArrowhead ? markerForArrowhead(el.endArrowhead, "end") : "";
111
- return `<polyline points="${pts}" fill="none" stroke="${escapeAttr(stroke)}" stroke-width="${el.strokeWidth || 1.5}" ${dash} ${startMarker} ${endMarker}/>`;
200
+ function roughPolyline(el, withArrow) {
201
+ const pts = (el.points || []).map(([dx, dy]) => [el.x + dx, el.y + dy]);
202
+ if (pts.length < 2) return "";
203
+ const drawable = generator.linearPath(pts, roughOpts(el));
204
+ let body = drawableToSvg(drawable, el);
205
+
206
+ // Arrowheads: keep the same marker-based mechanism, but apply it to
207
+ // a thin invisible <polyline> so the marker ends up at the geometric
208
+ // endpoint (not a wobble-jittered endpoint of the rough path).
209
+ if (withArrow && (el.startArrowhead || el.endArrowhead)) {
210
+ const polyPts = pts.map(([x, y]) => `${x},${y}`).join(" ");
211
+ const startMarker = el.startArrowhead
212
+ ? ` marker-start="url(#m_${el.startArrowhead}_start)"` : "";
213
+ const endMarker = el.endArrowhead
214
+ ? ` marker-end="url(#m_${el.endArrowhead}_end)"` : "";
215
+ body += `<polyline points="${polyPts}" fill="none" stroke="${escapeAttr(el.strokeColor || "#000")}" stroke-width="0" stroke-opacity="0"${startMarker}${endMarker}/>`;
216
+ }
217
+ return body;
112
218
  }
113
219
 
114
220
  function svgText(el) {
@@ -118,26 +224,19 @@ function svgText(el) {
118
224
  const lines = String(el.text ?? "").split("\n");
119
225
  const align = el.textAlign || "left";
120
226
  const anchor = align === "center" ? "middle" : align === "right" ? "end" : "start";
121
- // Excalidraw text x is the box's left edge; baseline depends on align.
122
227
  let xRef = el.x;
123
228
  if (align === "center") xRef = el.x + (el.width || 0) / 2;
124
229
  else if (align === "right") xRef = el.x + (el.width || 0);
125
- const yTop = el.y + fs; // first baseline
230
+ const yTop = el.y + fs;
126
231
  const tspans = lines.map((l, i) =>
127
232
  `<tspan x="${xRef}" dy="${i === 0 ? 0 : lineHeight}">${escapeText(l)}</tspan>`,
128
233
  ).join("");
129
234
  return `<text x="${xRef}" y="${yTop}" fill="${escapeAttr(fill)}" font-size="${fs}" text-anchor="${anchor}">${tspans}</text>`;
130
235
  }
131
236
 
132
- // Arrowhead helpers --------------------------------------------------------
133
-
134
- function markerForArrowhead(kind, end) {
135
- const id = `m_${kind}_${end}`;
136
- return `marker-${end}="url(#${id})"`;
137
- }
237
+ // ── arrowheads ────────────────────────────────────────────────────────────
138
238
 
139
239
  function arrowheadDefs() {
140
- // Inline definitions so each generated SVG is self-contained.
141
240
  return `<defs>
142
241
  <marker id="m_arrow_end" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto"><path d="M0,0 L10,5 L0,10 z" fill="#000"/></marker>
143
242
  <marker id="m_arrow_start" viewBox="0 0 10 10" refX="1" refY="5" markerWidth="8" markerHeight="8" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" fill="#000"/></marker>
@@ -152,7 +251,7 @@ function arrowheadDefs() {
152
251
  </defs>`;
153
252
  }
154
253
 
155
- // Misc helpers -------------------------------------------------------------
254
+ // ── misc ──────────────────────────────────────────────────────────────────
156
255
 
157
256
  function colorOrNone(c) {
158
257
  if (!c || c === "transparent") return "none";