@archipen/render 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +22 -2
- package/dist/THIRD-PARTY-NOTICES.txt +81 -0
- package/dist/chunks/env-D14HK4d7.mjs +3 -0
- package/dist/chunks/server-BOCCbETh.mjs +354 -0
- package/dist/chunks/src-79SWTPGl.mjs +12974 -0
- package/dist/chunks/vendorPathsRest-wrCr0LHH.mjs +277 -0
- package/dist/cli.mjs +157 -0
- package/dist/index.mjs +1 -0
- package/dist/server.mjs +1 -0
- package/dist/worker.mjs +36 -0
- package/fonts/InstrumentSans-Regular.ttf +0 -0
- package/fonts/InstrumentSans-SemiBold.ttf +0 -0
- package/fonts/InstrumentSans-Variable.woff2 +0 -0
- package/fonts/OFL.txt +93 -0
- package/index.d.ts +54 -0
- package/package.json +75 -4
- package/vendor-icon-credits.txt +158 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Archipen contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,23 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @archipen/render
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Render [Archipen](https://archipen.dev/) diagrams (`.archipen.json`) to SVG, PNG and PDF without a browser. You can
|
|
4
|
+
use it from the command line, from Node, or as an HTTP server.
|
|
5
|
+
|
|
6
|
+
```sh
|
|
7
|
+
npx @archipen/render export diagram.archipen.json -o diagram.png # or: npm install -g @archipen/render
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
```js
|
|
11
|
+
import { renderPng } from '@archipen/render'
|
|
12
|
+
const png = await renderPng(readFileSync('diagram.archipen.json', 'utf8'), { theme: 'dark', scale: 2 })
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
archipen serve --port 8080 --base-path /tools/archipen-api
|
|
17
|
+
curl -X POST --data-binary @diagram.archipen.json 'localhost:8080/tools/archipen-api/export?format=pdf' -o diagram.pdf
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Node.js 22 or newer. Run `archipen --help` for all options. Full guide: <https://archipen.dev/export>.
|
|
21
|
+
|
|
22
|
+
Fonts: Instrument Sans, SIL Open Font License (`fonts/OFL.txt`). Vendor logos: Simple Icons, credited in
|
|
23
|
+
`vendor-icon-credits.txt`; the logos are trademarks of their owners. Bundled third-party code: `dist/THIRD-PARTY-NOTICES.txt`.
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
@archipen/render: third-party notices
|
|
2
|
+
=====================================
|
|
3
|
+
|
|
4
|
+
This build contains code from the following packages. Their licences are reproduced below.
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
------------------------------------------------------------------------------
|
|
8
|
+
|
|
9
|
+
lucide 1.66.0 (ISC)
|
|
10
|
+
https://github.com/lucide-icons/lucide.git
|
|
11
|
+
|
|
12
|
+
ISC License
|
|
13
|
+
|
|
14
|
+
Copyright (c) 2026 Lucide Icons and Contributors
|
|
15
|
+
|
|
16
|
+
Permission to use, copy, modify, and/or distribute this software for any
|
|
17
|
+
purpose with or without fee is hereby granted, provided that the above
|
|
18
|
+
copyright notice and this permission notice appear in all copies.
|
|
19
|
+
|
|
20
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
|
21
|
+
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
|
22
|
+
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
|
23
|
+
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
|
24
|
+
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
|
25
|
+
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
|
26
|
+
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
|
27
|
+
|
|
28
|
+
---
|
|
29
|
+
|
|
30
|
+
The following Lucide icons are derived from the Feather project:
|
|
31
|
+
|
|
32
|
+
airplay, alert-circle, alert-octagon, alert-triangle, aperture, arrow-down-circle, arrow-down-left, arrow-down-right, arrow-down, arrow-left-circle, arrow-left, arrow-right-circle, arrow-right, arrow-up-circle, arrow-up-left, arrow-up-right, arrow-up, at-sign, calendar, cast, check, chevron-down, chevron-left, chevron-right, chevron-up, chevrons-down, chevrons-left, chevrons-right, chevrons-up, circle, clipboard, clock, code, columns, command, compass, corner-down-left, corner-down-right, corner-left-down, corner-left-up, corner-right-down, corner-right-up, corner-up-left, corner-up-right, crosshair, database, divide-circle, divide-square, dollar-sign, download, external-link, feather, frown, hash, headphones, help-circle, info, italic, key, layout, life-buoy, link-2, link, loader, lock, log-in, log-out, maximize, meh, minimize, minimize-2, minus-circle, minus-square, minus, monitor, moon, more-horizontal, more-vertical, move, music, navigation-2, navigation, octagon, pause-circle, percent, plus-circle, plus-square, plus, power, radio, rss, search, server, share, shopping-bag, sidebar, smartphone, smile, square, table-2, tablet, target, terminal, trash-2, trash, triangle, tv, type, upload, x-circle, x-octagon, x-square, x, zoom-in, zoom-out
|
|
33
|
+
|
|
34
|
+
The MIT License (MIT) (for the icons listed above)
|
|
35
|
+
|
|
36
|
+
Copyright (c) 2013-present Cole Bemis
|
|
37
|
+
|
|
38
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
39
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
40
|
+
in the Software without restriction, including without limitation the rights
|
|
41
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
42
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
43
|
+
furnished to do so, subject to the following conditions:
|
|
44
|
+
|
|
45
|
+
The above copyright notice and this permission notice shall be included in all
|
|
46
|
+
copies or substantial portions of the Software.
|
|
47
|
+
|
|
48
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
49
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
50
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
51
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
52
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
53
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
54
|
+
SOFTWARE.
|
|
55
|
+
|
|
56
|
+
------------------------------------------------------------------------------
|
|
57
|
+
|
|
58
|
+
zod 4.6.7 (MIT)
|
|
59
|
+
git+https://github.com/colinhacks/zod.git
|
|
60
|
+
|
|
61
|
+
MIT License
|
|
62
|
+
|
|
63
|
+
Copyright (c) 2025 Colin McDonnell
|
|
64
|
+
|
|
65
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
66
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
67
|
+
in the Software without restriction, including without limitation the rights
|
|
68
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
69
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
70
|
+
furnished to do so, subject to the following conditions:
|
|
71
|
+
|
|
72
|
+
The above copyright notice and this permission notice shall be included in all
|
|
73
|
+
copies or substantial portions of the Software.
|
|
74
|
+
|
|
75
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
76
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
77
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
78
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
79
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
80
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
81
|
+
SOFTWARE.
|
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
import { o as fileBaseName, r as FORMATS, t as CONTENT_TYPES } from "./src-79SWTPGl.mjs";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import { pathToFileURL } from "node:url";
|
|
4
|
+
import { createServer } from "node:http";
|
|
5
|
+
import { availableParallelism } from "node:os";
|
|
6
|
+
import { Worker } from "node:worker_threads";
|
|
7
|
+
// src/pool.ts
|
|
8
|
+
/** Why a render did not produce a file. */
|
|
9
|
+
var RenderFailure = class extends Error {
|
|
10
|
+
kind;
|
|
11
|
+
issues;
|
|
12
|
+
constructor(kind, message, issues = []) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.kind = kind;
|
|
15
|
+
this.issues = issues;
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* worker.mjs sits in dist/. This module is in dist/ or dist/chunks/ once built,
|
|
20
|
+
* and in src/ when the tests run it (they build first).
|
|
21
|
+
*/
|
|
22
|
+
function defaultWorkerUrl() {
|
|
23
|
+
const url = [
|
|
24
|
+
"./worker.mjs",
|
|
25
|
+
"../worker.mjs",
|
|
26
|
+
"../dist/worker.mjs"
|
|
27
|
+
].map((p) => new URL(p, import.meta.url)).find((u) => existsSync(u));
|
|
28
|
+
if (!url) throw new Error("@archipen/render: dist/worker.mjs not found (run \"npm run build\" in render/)");
|
|
29
|
+
return url;
|
|
30
|
+
}
|
|
31
|
+
var RenderPool = class {
|
|
32
|
+
opts;
|
|
33
|
+
slots = [];
|
|
34
|
+
queue = [];
|
|
35
|
+
nextId = 1;
|
|
36
|
+
closed = false;
|
|
37
|
+
url;
|
|
38
|
+
constructor(opts) {
|
|
39
|
+
this.opts = opts;
|
|
40
|
+
this.url = opts.workerUrl ?? defaultWorkerUrl();
|
|
41
|
+
for (let i = 0; i < Math.max(1, opts.workers); i++) this.slots.push(this.spawn());
|
|
42
|
+
}
|
|
43
|
+
render(raw, format, opts) {
|
|
44
|
+
if (this.closed) return Promise.reject(new RenderFailure("busy", "The server is shutting down"));
|
|
45
|
+
if (this.queue.length >= this.opts.maxQueue) return Promise.reject(new RenderFailure("busy", "The server is busy, try again shortly"));
|
|
46
|
+
return new Promise((resolve, reject) => {
|
|
47
|
+
this.queue.push({
|
|
48
|
+
msg: {
|
|
49
|
+
id: this.nextId++,
|
|
50
|
+
raw,
|
|
51
|
+
format,
|
|
52
|
+
opts
|
|
53
|
+
},
|
|
54
|
+
resolve,
|
|
55
|
+
reject
|
|
56
|
+
});
|
|
57
|
+
this.dispatch();
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
async close() {
|
|
61
|
+
this.closed = true;
|
|
62
|
+
for (const job of this.queue.splice(0)) job.reject(new RenderFailure("busy", "The server is shutting down"));
|
|
63
|
+
await Promise.all(this.slots.map((s) => this.finish(s, new RenderFailure("busy", "The server is shutting down"))));
|
|
64
|
+
}
|
|
65
|
+
spawn() {
|
|
66
|
+
const worker = new Worker(this.url, {
|
|
67
|
+
execArgv: [],
|
|
68
|
+
resourceLimits: { maxOldGenerationSizeMb: 512 }
|
|
69
|
+
});
|
|
70
|
+
worker.unref();
|
|
71
|
+
const slot = { worker };
|
|
72
|
+
worker.on("message", (reply) => {
|
|
73
|
+
const job = slot.job;
|
|
74
|
+
if (!job || job.msg.id !== reply.id) return;
|
|
75
|
+
this.done(slot);
|
|
76
|
+
if (reply.ok) job.resolve(Buffer.from(reply.bytes.buffer, reply.bytes.byteOffset, reply.bytes.byteLength));
|
|
77
|
+
else if (reply.kind === "diagram") job.reject(new RenderFailure("diagram", "Not a valid Archipen file", reply.issues));
|
|
78
|
+
else job.reject(new RenderFailure(reply.kind, reply.message));
|
|
79
|
+
this.dispatch();
|
|
80
|
+
});
|
|
81
|
+
worker.on("error", (e) => this.replace(slot, new RenderFailure("error", `Rendering failed: ${e.message}`)));
|
|
82
|
+
worker.on("exit", () => this.replace(slot, new RenderFailure("error", "Rendering failed")));
|
|
83
|
+
return slot;
|
|
84
|
+
}
|
|
85
|
+
dispatch() {
|
|
86
|
+
for (const slot of this.slots) {
|
|
87
|
+
if (slot.job || !this.queue.length) continue;
|
|
88
|
+
const job = this.queue.shift();
|
|
89
|
+
slot.job = job;
|
|
90
|
+
slot.timer = setTimeout(() => {
|
|
91
|
+
const s = Math.round(this.opts.timeoutMs / 1e3);
|
|
92
|
+
this.replace(slot, new RenderFailure("timeout", `Rendering took longer than ${s} s; the diagram is too complex`));
|
|
93
|
+
}, this.opts.timeoutMs);
|
|
94
|
+
slot.worker.postMessage(job.msg);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
done(slot) {
|
|
98
|
+
clearTimeout(slot.timer);
|
|
99
|
+
slot.job = slot.timer = void 0;
|
|
100
|
+
}
|
|
101
|
+
/** Reject the slot's running job, if any, and stop its worker. */
|
|
102
|
+
finish(slot, err) {
|
|
103
|
+
const job = slot.job;
|
|
104
|
+
this.done(slot);
|
|
105
|
+
job?.reject(err);
|
|
106
|
+
slot.worker.removeAllListeners();
|
|
107
|
+
slot.worker.on("error", () => {});
|
|
108
|
+
return slot.worker.terminate();
|
|
109
|
+
}
|
|
110
|
+
replace(slot, err) {
|
|
111
|
+
const i = this.slots.indexOf(slot);
|
|
112
|
+
if (i < 0) return;
|
|
113
|
+
this.finish(slot, err);
|
|
114
|
+
if (this.closed) return;
|
|
115
|
+
this.slots[i] = this.spawn();
|
|
116
|
+
this.dispatch();
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
// src/server.ts
|
|
120
|
+
/** Server settings from the environment, as documented in docs/hosting.md. Unset ones keep their defaults. */
|
|
121
|
+
function envOptions(env = process.env) {
|
|
122
|
+
const int = (name, min) => {
|
|
123
|
+
const v = env[name];
|
|
124
|
+
if (v === void 0 || v === "") return void 0;
|
|
125
|
+
const n = Number(v);
|
|
126
|
+
if (!Number.isInteger(n) || n < min) throw new Error(`${name} must be a whole number of at least ${min} (got "${v}")`);
|
|
127
|
+
return n;
|
|
128
|
+
};
|
|
129
|
+
return {
|
|
130
|
+
corsOrigin: env.CORS_ORIGIN || void 0,
|
|
131
|
+
workers: int("RENDER_WORKERS", 1),
|
|
132
|
+
maxQueue: int("RENDER_QUEUE", 0),
|
|
133
|
+
renderTimeoutMs: int("RENDER_TIMEOUT_MS", 100),
|
|
134
|
+
maxItems: int("MAX_ITEMS", 1)
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
var MB = 1048576;
|
|
138
|
+
var HttpError = class extends Error {
|
|
139
|
+
status;
|
|
140
|
+
extra;
|
|
141
|
+
constructor(status, message, extra = {}) {
|
|
142
|
+
super(message);
|
|
143
|
+
this.status = status;
|
|
144
|
+
this.extra = extra;
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
/** "/tools/api/" → "/tools/api", "" or "/" → "". Throws on a path without a leading slash. */
|
|
148
|
+
function normalizeBasePath(p) {
|
|
149
|
+
const s = (p ?? "").trim().replace(/\/+$/, "");
|
|
150
|
+
if (s && !s.startsWith("/")) throw new Error(`BASE_PATH must start with "/" (got "${p}")`);
|
|
151
|
+
return s;
|
|
152
|
+
}
|
|
153
|
+
function usage(base) {
|
|
154
|
+
return `Archipen export server
|
|
155
|
+
|
|
156
|
+
POST ${base}/export?format=svg|png|pdf body: diagram JSON (.archipen.json)
|
|
157
|
+
theme=light|dark projection=iso|2d page=<id> (default: all pages; PNG: the first) scale=2 (PNG, max 8) padding=32
|
|
158
|
+
transparent=1 animate=1 (SVG) font=0 (SVG without embedded font)
|
|
159
|
+
GET ${base}/healthz
|
|
160
|
+
|
|
161
|
+
Example:
|
|
162
|
+
curl -X POST --data-binary @diagram.archipen.json '<host>${base}/export?format=png' -o diagram.png
|
|
163
|
+
`;
|
|
164
|
+
}
|
|
165
|
+
var flag = (v) => v !== null && v !== "0" && v !== "false" && v !== "no";
|
|
166
|
+
function numberParam(q, name, min, max) {
|
|
167
|
+
const v = q.get(name);
|
|
168
|
+
if (v === null || v === "") return void 0;
|
|
169
|
+
const n = Number(v);
|
|
170
|
+
if (!Number.isFinite(n) || n < min || n > max) throw new HttpError(400, `${name} must be a number from ${min} to ${max}`);
|
|
171
|
+
return n;
|
|
172
|
+
}
|
|
173
|
+
function parseQuery(q) {
|
|
174
|
+
const format = (q.get("format") ?? "svg").toLowerCase();
|
|
175
|
+
if (!FORMATS.includes(format)) throw new HttpError(400, "format must be svg, png or pdf");
|
|
176
|
+
const theme = q.get("theme") ?? void 0;
|
|
177
|
+
if (theme && theme !== "light" && theme !== "dark") throw new HttpError(400, "theme must be light or dark");
|
|
178
|
+
const projection = q.get("projection") ?? void 0;
|
|
179
|
+
if (projection && projection !== "iso" && projection !== "2d") throw new HttpError(400, "projection must be iso or 2d");
|
|
180
|
+
return {
|
|
181
|
+
format,
|
|
182
|
+
opts: {
|
|
183
|
+
theme,
|
|
184
|
+
projection,
|
|
185
|
+
page: q.get("page") || void 0,
|
|
186
|
+
scale: numberParam(q, "scale", .1, 8),
|
|
187
|
+
padding: numberParam(q, "padding", 0, 1e3),
|
|
188
|
+
background: !flag(q.get("transparent")),
|
|
189
|
+
animate: flag(q.get("animate")),
|
|
190
|
+
embedFont: q.get("font") === null || flag(q.get("font"))
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
async function readBody(req, limit) {
|
|
195
|
+
if (Number(req.headers["content-length"]) > limit) throw new HttpError(413, `Request body is larger than ${Math.round(limit / MB)} MB`);
|
|
196
|
+
const chunks = [];
|
|
197
|
+
let size = 0;
|
|
198
|
+
for await (const chunk of req) {
|
|
199
|
+
size += chunk.length;
|
|
200
|
+
if (size > limit) throw new HttpError(413, `Request body is larger than ${Math.round(limit / MB)} MB`);
|
|
201
|
+
chunks.push(chunk);
|
|
202
|
+
}
|
|
203
|
+
return Buffer.concat(chunks);
|
|
204
|
+
}
|
|
205
|
+
/** "Web shop" → `inline; filename="Web shop.png"; filename*=UTF-8''Web%20shop.png` (ASCII fallback for old clients). */
|
|
206
|
+
function disposition(name) {
|
|
207
|
+
return `inline; filename="${name.replace(/[^\x20-\x7e]/g, "_").replace(/["\\]/g, "_")}"; filename*=UTF-8''${encodeURIComponent(name)}`;
|
|
208
|
+
}
|
|
209
|
+
/** Nodes, zones, edges and texts on all pages of a parsed (not yet validated) diagram. */
|
|
210
|
+
function itemCount(raw) {
|
|
211
|
+
const pages = raw && typeof raw === "object" ? raw.pages : void 0;
|
|
212
|
+
if (!Array.isArray(pages)) return 0;
|
|
213
|
+
const count = (p) => p && typeof p === "object" ? [
|
|
214
|
+
"nodes",
|
|
215
|
+
"zones",
|
|
216
|
+
"edges",
|
|
217
|
+
"texts"
|
|
218
|
+
].reduce((n, k) => n + (Array.isArray(p[k]) ? p[k].length : 0), 0) : 0;
|
|
219
|
+
return pages.reduce((n, p) => n + count(p), 0);
|
|
220
|
+
}
|
|
221
|
+
/** The request handler on its own, e.g. to mount it in an existing server. Call `close()` when done. */
|
|
222
|
+
function createHandler(options = {}) {
|
|
223
|
+
const base = normalizeBasePath(options.basePath);
|
|
224
|
+
const limit = options.maxBodyBytes ?? 5 * MB;
|
|
225
|
+
const cors = options.corsOrigin;
|
|
226
|
+
const maxItems = options.maxItems ?? 1e3;
|
|
227
|
+
const workers = options.workers ?? availableParallelism();
|
|
228
|
+
const pool = new RenderPool({
|
|
229
|
+
workers,
|
|
230
|
+
maxQueue: options.maxQueue ?? workers * 8,
|
|
231
|
+
timeoutMs: options.renderTimeoutMs ?? 2e4,
|
|
232
|
+
workerUrl: options.workerUrl
|
|
233
|
+
});
|
|
234
|
+
const send = (res, status, body, type, headers = {}) => {
|
|
235
|
+
res.writeHead(status, {
|
|
236
|
+
"Content-Type": type,
|
|
237
|
+
"Content-Length": Buffer.byteLength(body),
|
|
238
|
+
...headers
|
|
239
|
+
});
|
|
240
|
+
res.end(body);
|
|
241
|
+
};
|
|
242
|
+
const sendJson = (res, status, data, headers = {}) => send(res, status, JSON.stringify(data), "application/json; charset=utf-8", headers);
|
|
243
|
+
const handler = async (req, res) => {
|
|
244
|
+
res.setHeader("X-Content-Type-Options", "nosniff");
|
|
245
|
+
res.setHeader("Referrer-Policy", "no-referrer");
|
|
246
|
+
if (cors) {
|
|
247
|
+
res.setHeader("Access-Control-Allow-Origin", cors);
|
|
248
|
+
res.setHeader("Vary", "Origin");
|
|
249
|
+
}
|
|
250
|
+
const url = new URL(req.url ?? "/", "http://localhost");
|
|
251
|
+
const path = url.pathname;
|
|
252
|
+
const method = req.method ?? "GET";
|
|
253
|
+
try {
|
|
254
|
+
if (base && path === base) {
|
|
255
|
+
res.writeHead(308, { Location: `${base}/${url.search}` });
|
|
256
|
+
return res.end();
|
|
257
|
+
}
|
|
258
|
+
if (path === `${base}/` && (method === "GET" || method === "HEAD")) return send(res, 200, usage(base), "text/plain; charset=utf-8");
|
|
259
|
+
if (path === `${base}/healthz` && (method === "GET" || method === "HEAD")) return send(res, 200, "ok\n", "text/plain; charset=utf-8", { "Cache-Control": "no-store" });
|
|
260
|
+
if (path === `${base}/export`) {
|
|
261
|
+
if (method === "OPTIONS" && cors) {
|
|
262
|
+
res.writeHead(204, {
|
|
263
|
+
"Access-Control-Allow-Methods": "POST, OPTIONS",
|
|
264
|
+
"Access-Control-Allow-Headers": "Content-Type",
|
|
265
|
+
"Access-Control-Max-Age": "86400"
|
|
266
|
+
});
|
|
267
|
+
return res.end();
|
|
268
|
+
}
|
|
269
|
+
if (method !== "POST") throw new HttpError(405, "Use POST with the diagram JSON as the body", { allow: "POST" });
|
|
270
|
+
const { format, opts } = parseQuery(url.searchParams);
|
|
271
|
+
const body = await readBody(req, limit);
|
|
272
|
+
let raw;
|
|
273
|
+
try {
|
|
274
|
+
raw = JSON.parse(body.toString("utf8"));
|
|
275
|
+
} catch (e) {
|
|
276
|
+
throw new HttpError(400, `Body is not valid JSON: ${e.message}`);
|
|
277
|
+
}
|
|
278
|
+
const items = itemCount(raw);
|
|
279
|
+
if (items > maxItems) throw new HttpError(422, `The diagram has ${items} items; this server renders at most ${maxItems}`);
|
|
280
|
+
const bytes = await pool.render(raw, format, opts);
|
|
281
|
+
const title = typeof raw.name === "string" ? raw.name : "";
|
|
282
|
+
const headers = {
|
|
283
|
+
"Content-Disposition": disposition(`${fileBaseName(title)}.${format}`),
|
|
284
|
+
"Cache-Control": "no-store"
|
|
285
|
+
};
|
|
286
|
+
if (format === "svg") headers["Content-Security-Policy"] = "default-src 'none'; style-src 'unsafe-inline'; font-src data:; img-src data:; sandbox";
|
|
287
|
+
return send(res, 200, bytes, CONTENT_TYPES[format], headers);
|
|
288
|
+
}
|
|
289
|
+
throw new HttpError(404, "Not found");
|
|
290
|
+
} catch (e) {
|
|
291
|
+
if (e instanceof HttpError) {
|
|
292
|
+
const headers = e.status === 405 ? { Allow: String(e.extra.allow) } : {};
|
|
293
|
+
if (e.status === 413) headers.Connection = "close";
|
|
294
|
+
return sendJson(res, e.status, { error: e.message }, headers);
|
|
295
|
+
}
|
|
296
|
+
if (e instanceof RenderFailure) {
|
|
297
|
+
if (e.kind === "diagram") return sendJson(res, 400, {
|
|
298
|
+
error: e.message,
|
|
299
|
+
issues: e.issues
|
|
300
|
+
});
|
|
301
|
+
if (e.kind === "limit" || e.kind === "timeout") return sendJson(res, 422, { error: e.message });
|
|
302
|
+
if (e.kind === "busy") return sendJson(res, 503, { error: e.message }, { "Retry-After": "5" });
|
|
303
|
+
}
|
|
304
|
+
console.error(e);
|
|
305
|
+
return sendJson(res, 500, { error: "Rendering failed" });
|
|
306
|
+
}
|
|
307
|
+
};
|
|
308
|
+
return Object.assign(handler, { close: () => pool.close() });
|
|
309
|
+
}
|
|
310
|
+
/** Start the export server. Resolves once it is listening. */
|
|
311
|
+
async function startServer(options = {}) {
|
|
312
|
+
const base = normalizeBasePath(options.basePath);
|
|
313
|
+
const handler = createHandler({
|
|
314
|
+
...envOptions(),
|
|
315
|
+
...withoutUndefined(options),
|
|
316
|
+
basePath: base
|
|
317
|
+
});
|
|
318
|
+
const server = createServer((req, res) => void handler(req, res));
|
|
319
|
+
server.requestTimeout = 3e4;
|
|
320
|
+
server.headersTimeout = 1e4;
|
|
321
|
+
await new Promise((resolve, reject) => {
|
|
322
|
+
server.once("error", reject);
|
|
323
|
+
server.listen(options.port ?? 8080, options.host, resolve);
|
|
324
|
+
});
|
|
325
|
+
const { port } = server.address();
|
|
326
|
+
return {
|
|
327
|
+
server,
|
|
328
|
+
url: `http://localhost:${port}${base}/`,
|
|
329
|
+
close: async () => {
|
|
330
|
+
await new Promise((resolve, reject) => server.close((err) => err ? reject(err) : resolve()));
|
|
331
|
+
await handler.close();
|
|
332
|
+
}
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
var withoutUndefined = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== void 0));
|
|
336
|
+
/** Start the server and stop it cleanly on SIGTERM/SIGINT (needed as PID 1 in a container). Logs where it listens. */
|
|
337
|
+
async function serve(options) {
|
|
338
|
+
const { url, close } = await startServer(options);
|
|
339
|
+
console.error(`Archipen export server listening on ${url}`);
|
|
340
|
+
const stop = () => {
|
|
341
|
+
close().finally(() => process.exit(0));
|
|
342
|
+
setTimeout(() => process.exit(0), 5e3).unref();
|
|
343
|
+
};
|
|
344
|
+
process.once("SIGTERM", stop);
|
|
345
|
+
process.once("SIGINT", stop);
|
|
346
|
+
}
|
|
347
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) serve({
|
|
348
|
+
port: Number(process.env.PORT || 8080),
|
|
349
|
+
basePath: process.env.BASE_PATH
|
|
350
|
+
}).catch((e) => {
|
|
351
|
+
console.error(`archipen: ${e.message}`);
|
|
352
|
+
process.exit(1);
|
|
353
|
+
});
|
|
354
|
+
export { startServer as a, serve as i, envOptions as n, normalizeBasePath as r, createHandler as t };
|