nerdgram1337 0.0.0-stage → 1.2.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/LICENSE +21 -0
- package/README.md +51 -2
- package/bin/nerdgram.js +35 -0
- package/dist/chunk-5EV3XFVE.js +322 -0
- package/dist/chunk-EGA2UGTF.js +1966 -0
- package/dist/chunk-KO565WWM.js +471 -0
- package/dist/cli.js +723 -0
- package/package.json +48 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ryan Thomas Huff
|
|
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,52 @@
|
|
|
1
|
-
#
|
|
1
|
+
# nerdgram1337
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
`nerdgram` is the command-line client for [NerdGram1337](https://github.com/NetworkNerd1337/NerdGram1337), a local app for [Mermaid](https://mermaid.js.org/) diagrams. The npm package name is `nerdgram1337`. The command it installs is `nerdgram`.
|
|
4
|
+
|
|
5
|
+
List, search, and edit diagrams on a NerdGram server that is already running. `lint` and `render` of a `.mmd` file that is already on disk do not need the server.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
Node.js 20 or newer, and npm 10 or newer.
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npm install -g nerdgram1337
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npx nerdgram1337 --help
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
`npm install -g` puts `nerdgram` on your `PATH`. `npx` runs that command without a global install. The package is public.
|
|
20
|
+
|
|
21
|
+
The install also downloads Mermaid and Puppeteer's chrome-headless-shell. Offline `lint` uses Mermaid's parser. Offline `render` uses that shell, which is the large part of the download. Commands that only call the API do not launch it.
|
|
22
|
+
|
|
23
|
+
## Use
|
|
24
|
+
|
|
25
|
+
`NERDGRAM_URL` defaults to `http://127.0.0.1:8787`. `NERDGRAM_TOKEN` is an automation token from Settings in the app. `--url` and `--token` override those. `--json` prints one JSON object. The process exits `1` when the command fails.
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
export NERDGRAM_URL=http://127.0.0.1:8787
|
|
29
|
+
export NERDGRAM_TOKEN=ng_your_token
|
|
30
|
+
|
|
31
|
+
nerdgram --help
|
|
32
|
+
nerdgram list
|
|
33
|
+
nerdgram search Atlanta
|
|
34
|
+
nerdgram get Welcome.mmd -o Welcome.mmd
|
|
35
|
+
nerdgram put Notes.mmd ./Notes.mmd
|
|
36
|
+
nerdgram lint Welcome.mmd
|
|
37
|
+
nerdgram diff Welcome.mmd --from current --to current --format md
|
|
38
|
+
nerdgram baseline Welcome.mmd --name "Baseline"
|
|
39
|
+
nerdgram replace CORE-SW1 ATL-CORE-01 --dry-run
|
|
40
|
+
nerdgram replace CORE-SW1 ATL-CORE-01 --yes
|
|
41
|
+
nerdgram render Welcome.mmd -o Welcome.svg
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
`render` of a local `.mmd` file does not need a server. `--server` sends it to the API instead. `lint` of a local file does not need a server either. `lint` exits `1` when a diagnostic is an error.
|
|
45
|
+
|
|
46
|
+
The app still has to be reachable for every other command. A token does not make it safe to publish port 8787. The server is a single-user app with no login. Keep it on loopback.
|
|
47
|
+
|
|
48
|
+
The full command list and the release notes are in the [repository README](https://github.com/NetworkNerd1337/NerdGram1337#command-line-tool).
|
|
49
|
+
|
|
50
|
+
## License
|
|
51
|
+
|
|
52
|
+
MIT © Ryan Thomas Huff
|
package/bin/nerdgram.js
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { spawnSync } from "node:child_process";
|
|
3
|
+
import { existsSync } from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
|
|
7
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
8
|
+
|
|
9
|
+
// A checkout uses the server build so local edits apply without a pack.
|
|
10
|
+
// A registry install has only the bundled program under dist/.
|
|
11
|
+
const checkout = [
|
|
12
|
+
process.env.NERDGRAM_CLI,
|
|
13
|
+
path.resolve(here, "../../server/dist/cli.js"),
|
|
14
|
+
path.resolve(here, "../server/dist/cli.js"),
|
|
15
|
+
].filter((file) => typeof file === "string" && file.length > 0);
|
|
16
|
+
|
|
17
|
+
const bundled = path.resolve(here, "../dist/cli.js");
|
|
18
|
+
const imageCli = "/app/server/dist/cli.js";
|
|
19
|
+
const target =
|
|
20
|
+
checkout.find((file) => existsSync(file)) ??
|
|
21
|
+
(existsSync(bundled) ? bundled : existsSync(imageCli) ? imageCli : undefined);
|
|
22
|
+
|
|
23
|
+
if (!target) {
|
|
24
|
+
console.error(
|
|
25
|
+
"nerdgram could not find its program. From a checkout, run npm run build, then node server/dist/cli.js. From npm, reinstall nerdgram1337.",
|
|
26
|
+
);
|
|
27
|
+
process.exit(1);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const result = spawnSync(process.execPath, [target, ...process.argv.slice(2)], { stdio: "inherit" });
|
|
31
|
+
if (result.error) {
|
|
32
|
+
console.error(result.error.message);
|
|
33
|
+
process.exit(1);
|
|
34
|
+
}
|
|
35
|
+
process.exit(result.status ?? 1);
|
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
import {
|
|
2
|
+
diagramInitConfig,
|
|
3
|
+
locateParseError
|
|
4
|
+
} from "./chunk-KO565WWM.js";
|
|
5
|
+
|
|
6
|
+
// server/src/renderDiagram.ts
|
|
7
|
+
import { createRequire } from "node:module";
|
|
8
|
+
import puppeteer from "puppeteer";
|
|
9
|
+
|
|
10
|
+
// server/src/paths.ts
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
import { fileURLToPath } from "node:url";
|
|
13
|
+
var __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
14
|
+
var REPO_ROOT = path.resolve(__dirname, "../..");
|
|
15
|
+
|
|
16
|
+
// server/src/storage.ts
|
|
17
|
+
function httpFail(status, message, code, details) {
|
|
18
|
+
return Object.assign(new Error(message), { status, code, details });
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// server/src/thumbnails.ts
|
|
22
|
+
import * as cheerio from "cheerio";
|
|
23
|
+
|
|
24
|
+
// server/src/svgImage.ts
|
|
25
|
+
function svgForImage(svg) {
|
|
26
|
+
if (!/xlink:/i.test(svg) || /xmlns:xlink\s*=/i.test(svg)) return svg;
|
|
27
|
+
return svg.replace(/<svg\b/i, '<svg xmlns:xlink="http://www.w3.org/1999/xlink"');
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// server/src/thumbnails.ts
|
|
31
|
+
var URL_ATTRS = /* @__PURE__ */ new Set(["href", "xlink:href", "src"]);
|
|
32
|
+
function decodeUrl(value) {
|
|
33
|
+
return value.replace(/&#x([0-9a-f]+);/gi, (_, hex) => {
|
|
34
|
+
const code = Number.parseInt(hex, 16);
|
|
35
|
+
return Number.isFinite(code) ? String.fromCodePoint(code) : "";
|
|
36
|
+
}).replace(/&#(\d+);/g, (_, num) => {
|
|
37
|
+
const code = Number.parseInt(num, 10);
|
|
38
|
+
return Number.isFinite(code) ? String.fromCodePoint(code) : "";
|
|
39
|
+
}).replace(/[\u0000-\u0020]+/g, "").trim().toLowerCase();
|
|
40
|
+
}
|
|
41
|
+
function isDangerousUrl(value) {
|
|
42
|
+
const decoded = decodeUrl(value);
|
|
43
|
+
return decoded.startsWith("javascript:") || decoded.startsWith("vbscript:") || decoded.startsWith("data:text/html") || decoded.startsWith("data:application/xhtml");
|
|
44
|
+
}
|
|
45
|
+
function sanitizeThumbnailSvg(svg) {
|
|
46
|
+
const trimmed = svg.trim();
|
|
47
|
+
if (!trimmed) return svg;
|
|
48
|
+
let changed = false;
|
|
49
|
+
const $ = cheerio.load(trimmed, { xml: true });
|
|
50
|
+
$("*").each((_, el) => {
|
|
51
|
+
if (el.type !== "tag" && el.type !== "script") return;
|
|
52
|
+
const name = el.name.toLowerCase();
|
|
53
|
+
if (name === "script" || name === "iframe" || name === "object" || name === "embed" || name === "link" || name === "meta" || name === "base") {
|
|
54
|
+
$(el).remove();
|
|
55
|
+
changed = true;
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
const attribs = el.attribs;
|
|
59
|
+
for (const [attr, raw] of Object.entries(attribs)) {
|
|
60
|
+
const lower = attr.toLowerCase();
|
|
61
|
+
const value = raw ?? "";
|
|
62
|
+
if (lower.startsWith("on")) {
|
|
63
|
+
$(el).removeAttr(attr);
|
|
64
|
+
changed = true;
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
if (URL_ATTRS.has(lower) || lower.endsWith(":href")) {
|
|
68
|
+
if (isDangerousUrl(value)) {
|
|
69
|
+
$(el).removeAttr(attr);
|
|
70
|
+
changed = true;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
if (lower === "style" && /javascript\s*:|expression\s*\(|behavior\s*:|-moz-binding|@import/i.test(value)) {
|
|
74
|
+
$(el).removeAttr(attr);
|
|
75
|
+
changed = true;
|
|
76
|
+
}
|
|
77
|
+
if ((name === "set" || name === "animate" || name === "animatetransform") && lower === "attributename" && (value.toLowerCase().startsWith("on") || value.toLowerCase() === "href" || value.toLowerCase().endsWith(":href"))) {
|
|
78
|
+
$(el).remove();
|
|
79
|
+
changed = true;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
});
|
|
83
|
+
const structured = changed ? $.xml().trim() : trimmed;
|
|
84
|
+
const swept = structured.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, "").replace(/<script\b[^>]*\/?>/gi, "").replace(/\s+on[a-z]+\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/gi, "").replace(
|
|
85
|
+
/(\s(?:href|xlink:href|src)\s*=\s*)(["'])\s*(?:javascript|vbscript):[^"']*\2/gi,
|
|
86
|
+
"$1$2#$2"
|
|
87
|
+
);
|
|
88
|
+
const cleaned = swept === svg || swept === trimmed ? svg : swept;
|
|
89
|
+
return svgForImage(cleaned);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// server/src/renderDiagram.ts
|
|
93
|
+
var require2 = createRequire(import.meta.url);
|
|
94
|
+
var MAX_RENDER_SOURCE_CHARS = 512 * 1024;
|
|
95
|
+
var MAX_RENDER_SVG_CHARS = 2e6;
|
|
96
|
+
var DARK_BACKGROUND = "#1b1e27";
|
|
97
|
+
var LIGHT_BACKGROUND = "#ffffff";
|
|
98
|
+
var browserPromise = null;
|
|
99
|
+
var chain = Promise.resolve();
|
|
100
|
+
function enqueue(task) {
|
|
101
|
+
const run = chain.then(task, task);
|
|
102
|
+
chain = run.then(
|
|
103
|
+
() => void 0,
|
|
104
|
+
() => void 0
|
|
105
|
+
);
|
|
106
|
+
return run;
|
|
107
|
+
}
|
|
108
|
+
function mermaidScript() {
|
|
109
|
+
return require2.resolve("mermaid/dist/mermaid.min.js");
|
|
110
|
+
}
|
|
111
|
+
function wantsNoSandbox() {
|
|
112
|
+
return process.env.NERDGRAM_INSTALL === "docker" || process.env.NERDGRAM_CHROME_NO_SANDBOX === "1";
|
|
113
|
+
}
|
|
114
|
+
async function launchBrowser() {
|
|
115
|
+
const args = ["--disable-dev-shm-usage", "--no-first-run", "--disable-gpu"];
|
|
116
|
+
if (wantsNoSandbox()) args.push("--no-sandbox", "--disable-setuid-sandbox");
|
|
117
|
+
try {
|
|
118
|
+
return await puppeteer.launch({ headless: "shell", args });
|
|
119
|
+
} catch (err) {
|
|
120
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
121
|
+
if (wantsNoSandbox() || !/sandbox|namespace|zygote/i.test(message)) {
|
|
122
|
+
throw httpFail(503, "The diagram renderer could not start.", "renderer");
|
|
123
|
+
}
|
|
124
|
+
return puppeteer.launch({
|
|
125
|
+
headless: "shell",
|
|
126
|
+
args: [...args, "--no-sandbox", "--disable-setuid-sandbox"]
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
async function browser() {
|
|
131
|
+
if (!browserPromise) {
|
|
132
|
+
browserPromise = launchBrowser().catch((err) => {
|
|
133
|
+
browserPromise = null;
|
|
134
|
+
throw err;
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
const current = await browserPromise;
|
|
138
|
+
if (!current.connected) {
|
|
139
|
+
browserPromise = null;
|
|
140
|
+
return browser();
|
|
141
|
+
}
|
|
142
|
+
return current;
|
|
143
|
+
}
|
|
144
|
+
async function closeRenderer() {
|
|
145
|
+
const pending = browserPromise;
|
|
146
|
+
browserPromise = null;
|
|
147
|
+
if (!pending) return;
|
|
148
|
+
try {
|
|
149
|
+
const current = await pending;
|
|
150
|
+
await current.close();
|
|
151
|
+
} catch {
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
function assertSource(source) {
|
|
155
|
+
if (typeof source !== "string") throw httpFail(400, "source must be a string", "invalid");
|
|
156
|
+
if (source.includes("\0")) throw httpFail(400, "source is not valid text", "invalid");
|
|
157
|
+
if (!source.trim()) throw httpFail(400, "source is empty", "invalid");
|
|
158
|
+
if (source.length > MAX_RENDER_SOURCE_CHARS) {
|
|
159
|
+
throw httpFail(400, "source is too large", "invalid");
|
|
160
|
+
}
|
|
161
|
+
return source;
|
|
162
|
+
}
|
|
163
|
+
function assertBackground(value, theme) {
|
|
164
|
+
if (value == null || value === "") {
|
|
165
|
+
return typeof theme === "string" && theme.toLowerCase().includes("dark") ? DARK_BACKGROUND : LIGHT_BACKGROUND;
|
|
166
|
+
}
|
|
167
|
+
if (typeof value !== "string" || !/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/.test(value)) {
|
|
168
|
+
throw httpFail(400, "background must be a hex color", "invalid");
|
|
169
|
+
}
|
|
170
|
+
return value;
|
|
171
|
+
}
|
|
172
|
+
function plainError(err) {
|
|
173
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
174
|
+
return message.replace(/\s+/g, " ").trim().slice(0, 400) || "Mermaid could not render that diagram.";
|
|
175
|
+
}
|
|
176
|
+
async function draw(page, source, background) {
|
|
177
|
+
const init = diagramInitConfig(source);
|
|
178
|
+
init.startOnLoad = false;
|
|
179
|
+
init.securityLevel = "strict";
|
|
180
|
+
init.suppressErrorRendering = true;
|
|
181
|
+
const config = JSON.parse(JSON.stringify(init));
|
|
182
|
+
await page.setContent(
|
|
183
|
+
"<!doctype html><html><head><meta charset='utf-8'></head><body style='margin:0'><div id='out'></div></body></html>",
|
|
184
|
+
{ waitUntil: "domcontentloaded" }
|
|
185
|
+
);
|
|
186
|
+
await page.addScriptTag({ path: mermaidScript() });
|
|
187
|
+
const drawn = await page.evaluate(
|
|
188
|
+
async (code, mermaidConfig, fill) => {
|
|
189
|
+
const api = window.mermaid;
|
|
190
|
+
if (!api) return { ok: false, message: "Mermaid did not load", loc: null, token: void 0 };
|
|
191
|
+
document.body.style.background = fill;
|
|
192
|
+
api.initialize(mermaidConfig);
|
|
193
|
+
try {
|
|
194
|
+
const rendered = await api.render("nerdgram-render", code);
|
|
195
|
+
return { ok: true, svg: rendered.svg };
|
|
196
|
+
} catch (err) {
|
|
197
|
+
const hash = err && typeof err === "object" && "hash" in err ? err.hash : void 0;
|
|
198
|
+
const loc = hash?.loc;
|
|
199
|
+
return {
|
|
200
|
+
ok: false,
|
|
201
|
+
message: err instanceof Error ? err.message : String(err),
|
|
202
|
+
loc: loc && typeof loc.first_line === "number" ? {
|
|
203
|
+
first_line: loc.first_line,
|
|
204
|
+
last_line: typeof loc.last_line === "number" ? loc.last_line : void 0,
|
|
205
|
+
first_column: typeof loc.first_column === "number" ? loc.first_column : void 0,
|
|
206
|
+
last_column: typeof loc.last_column === "number" ? loc.last_column : void 0
|
|
207
|
+
} : null,
|
|
208
|
+
token: typeof hash?.token === "string" ? hash.token : void 0
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
},
|
|
212
|
+
source,
|
|
213
|
+
config,
|
|
214
|
+
background
|
|
215
|
+
);
|
|
216
|
+
if (!drawn.ok) {
|
|
217
|
+
const parsed = drawn.loc != null || /parse error on line/i.test(drawn.message);
|
|
218
|
+
if (!parsed) throw httpFail(400, plainError(drawn.message), "invalid");
|
|
219
|
+
const located = locateParseError(
|
|
220
|
+
{ message: drawn.message, hash: { loc: drawn.loc ?? void 0, token: drawn.token } },
|
|
221
|
+
source
|
|
222
|
+
);
|
|
223
|
+
throw httpFail(400, located.message, "invalid");
|
|
224
|
+
}
|
|
225
|
+
return drawn.svg;
|
|
226
|
+
}
|
|
227
|
+
async function rasterize(page, svg, background) {
|
|
228
|
+
await page.setViewport({ width: 1600, height: 1200, deviceScaleFactor: 2 });
|
|
229
|
+
await page.setContent(
|
|
230
|
+
`<!doctype html><html><head><meta charset="utf-8"></head><body style="margin:0;background:${background}"><div id="frame" style="display:inline-block;background:${background};padding:16px"></div></body></html>`,
|
|
231
|
+
{ waitUntil: "domcontentloaded" }
|
|
232
|
+
);
|
|
233
|
+
await page.evaluate((markup, fill) => {
|
|
234
|
+
const frame2 = document.getElementById("frame");
|
|
235
|
+
if (!frame2) throw new Error("Missing frame");
|
|
236
|
+
frame2.innerHTML = markup;
|
|
237
|
+
frame2.style.background = fill;
|
|
238
|
+
const svgEl = frame2.querySelector("svg");
|
|
239
|
+
if (!svgEl) return;
|
|
240
|
+
const viewBox = svgEl.viewBox?.baseVal;
|
|
241
|
+
if (viewBox && viewBox.width > 0 && viewBox.height > 0) {
|
|
242
|
+
svgEl.setAttribute("width", String(viewBox.width));
|
|
243
|
+
svgEl.setAttribute("height", String(viewBox.height));
|
|
244
|
+
}
|
|
245
|
+
}, svg, background);
|
|
246
|
+
const frame = await page.$("#frame");
|
|
247
|
+
if (!frame) throw httpFail(500, "The diagram renderer did not produce a PNG.", "renderer");
|
|
248
|
+
const png = await frame.screenshot({ type: "png", omitBackground: false });
|
|
249
|
+
return Buffer.from(png);
|
|
250
|
+
}
|
|
251
|
+
async function renderOnce(input) {
|
|
252
|
+
const source = assertSource(input.source);
|
|
253
|
+
if (input.format !== "svg" && input.format !== "png") {
|
|
254
|
+
throw httpFail(400, "format must be svg or png", "invalid");
|
|
255
|
+
}
|
|
256
|
+
const theme = diagramInitConfig(source).theme;
|
|
257
|
+
const background = assertBackground(input.background, theme);
|
|
258
|
+
const current = await browser();
|
|
259
|
+
const page = await current.newPage();
|
|
260
|
+
page.setDefaultTimeout(2e4);
|
|
261
|
+
try {
|
|
262
|
+
let svg;
|
|
263
|
+
try {
|
|
264
|
+
svg = await draw(page, source, background);
|
|
265
|
+
} catch (err) {
|
|
266
|
+
throw httpFail(400, plainError(err), "invalid");
|
|
267
|
+
}
|
|
268
|
+
const cleaned = sanitizeThumbnailSvg(svg).trim();
|
|
269
|
+
if (!cleaned.includes("<svg") || /syntax error/i.test(cleaned) || cleaned.length > MAX_RENDER_SVG_CHARS) {
|
|
270
|
+
throw httpFail(400, "Mermaid could not render that diagram.", "invalid");
|
|
271
|
+
}
|
|
272
|
+
if (/<script[\s>/]/i.test(cleaned)) {
|
|
273
|
+
throw httpFail(400, "Rendered SVG was rejected.", "invalid");
|
|
274
|
+
}
|
|
275
|
+
if (input.format === "svg") {
|
|
276
|
+
return { format: "svg", contentType: "image/svg+xml; charset=utf-8", body: Buffer.from(cleaned, "utf8") };
|
|
277
|
+
}
|
|
278
|
+
const png = await rasterize(page, cleaned, background);
|
|
279
|
+
if (png.length < 32 || png.subarray(0, 8).toString("hex") !== "89504e470d0a1a0a") {
|
|
280
|
+
throw httpFail(500, "The diagram renderer did not produce a PNG.", "renderer");
|
|
281
|
+
}
|
|
282
|
+
return { format: "png", contentType: "image/png", body: png };
|
|
283
|
+
} finally {
|
|
284
|
+
await page.close().catch(() => void 0);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
function renderDiagram(input) {
|
|
288
|
+
return enqueue(() => renderOnce(input));
|
|
289
|
+
}
|
|
290
|
+
function createRateLimiter(options) {
|
|
291
|
+
const buckets = /* @__PURE__ */ new Map();
|
|
292
|
+
return {
|
|
293
|
+
take(id) {
|
|
294
|
+
const now = Date.now();
|
|
295
|
+
const recent = (buckets.get(id) ?? []).filter((stamp) => now - stamp < options.windowMs);
|
|
296
|
+
if (recent.length >= options.limit) {
|
|
297
|
+
const retryAfterSec = Math.max(1, Math.ceil((recent[0] + options.windowMs - now) / 1e3));
|
|
298
|
+
buckets.set(id, recent);
|
|
299
|
+
return { ok: false, retryAfterSec };
|
|
300
|
+
}
|
|
301
|
+
recent.push(now);
|
|
302
|
+
buckets.set(id, recent);
|
|
303
|
+
return { ok: true };
|
|
304
|
+
}
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
function defaultRenderRate() {
|
|
308
|
+
const limit = Number(process.env.NERDGRAM_RENDER_LIMIT ?? 30);
|
|
309
|
+
const windowMs = Number(process.env.NERDGRAM_RENDER_WINDOW_MS ?? 6e4);
|
|
310
|
+
return {
|
|
311
|
+
limit: Number.isInteger(limit) && limit > 0 ? limit : 30,
|
|
312
|
+
windowMs: Number.isInteger(windowMs) && windowMs >= 1e3 ? windowMs : 6e4
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
export {
|
|
316
|
+
MAX_RENDER_SOURCE_CHARS,
|
|
317
|
+
MAX_RENDER_SVG_CHARS,
|
|
318
|
+
closeRenderer,
|
|
319
|
+
createRateLimiter,
|
|
320
|
+
defaultRenderRate,
|
|
321
|
+
renderDiagram
|
|
322
|
+
};
|