nerdgram1337 0.0.0-stage → 1.1.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.
@@ -0,0 +1,471 @@
1
+ // server/src/frontMatter.ts
2
+ import { Document, isMap, isSeq, parseDocument } from "yaml";
3
+ var MERMAID_THEMES = [
4
+ "default",
5
+ "neutral",
6
+ "dark",
7
+ "forest",
8
+ "base",
9
+ "neo",
10
+ "neo-dark",
11
+ "redux",
12
+ "redux-dark",
13
+ "redux-color",
14
+ "redux-dark-color"
15
+ ];
16
+ var MERMAID_LOOKS = ["classic", "handDrawn", "neo"];
17
+ var MERMAID_LAYOUTS = ["elk", "dagre"];
18
+ var FLOWCHART_CURVES = [
19
+ "basis",
20
+ "bumpX",
21
+ "bumpY",
22
+ "cardinal",
23
+ "catmullRom",
24
+ "linear",
25
+ "monotoneX",
26
+ "monotoneY",
27
+ "natural",
28
+ "step",
29
+ "stepAfter",
30
+ "stepBefore"
31
+ ];
32
+ var ELK_NODE_PLACEMENTS = [
33
+ "SIMPLE",
34
+ "NETWORK_SIMPLEX",
35
+ "LINEAR_SEGMENTS",
36
+ "BRANDES_KOEPF"
37
+ ];
38
+ var FALLBACK_THEME = "dark";
39
+ var DEFAULT_FONT_FAMILY = '"IBM Plex Sans", system-ui, sans-serif';
40
+ var NERDGRAM = "nerdgram";
41
+ var SECURE_CONFIG_KEYS = /* @__PURE__ */ new Set([
42
+ "secure",
43
+ "securityLevel",
44
+ "startOnLoad",
45
+ "maxTextSize",
46
+ "suppressErrorRendering",
47
+ "maxEdges"
48
+ ]);
49
+ var whitespace = /\s/;
50
+ function isLineBreak(char) {
51
+ return char === "\n" || char === "\r";
52
+ }
53
+ function lastLineBreakInWhitespaceRun(text, from) {
54
+ let index = -1;
55
+ for (let i = from; i < text.length && whitespace.test(text[i] ?? ""); i += 1) {
56
+ if (isLineBreak(text[i])) index = i;
57
+ }
58
+ return index;
59
+ }
60
+ function matchFrontMatter(text) {
61
+ let cursor = 0;
62
+ while (cursor < text.length && whitespace.test(text[cursor] ?? "") && !isLineBreak(text[cursor])) {
63
+ cursor += 1;
64
+ }
65
+ const indent = text.slice(0, cursor);
66
+ if (!text.startsWith("---", cursor)) return null;
67
+ const openingEnds = [];
68
+ for (let i = cursor + 3; i < text.length && whitespace.test(text[i] ?? ""); i += 1) {
69
+ if (isLineBreak(text[i])) openingEnds.push(i);
70
+ }
71
+ if (openingEnds.length === 0) return null;
72
+ const closingFence = `${indent}---`;
73
+ const closingEnd = (index) => isLineBreak(text[index]) && text.startsWith(closingFence, index + 1) ? lastLineBreakInWhitespaceRun(text, index + 1 + closingFence.length) : -1;
74
+ const earliestBodyStart = (openingEnds[0] ?? 0) + 1;
75
+ let lastClosingFence = -1;
76
+ for (let i = earliestBodyStart; i < text.length; i += 1) {
77
+ if (closingEnd(i) !== -1) lastClosingFence = i;
78
+ }
79
+ if (lastClosingFence === -1) return null;
80
+ let openingEnd = openingEnds[0] ?? 0;
81
+ for (const candidate of openingEnds) {
82
+ if (candidate < lastClosingFence) openingEnd = candidate;
83
+ }
84
+ const bodyStart = openingEnd + 1;
85
+ for (let i = bodyStart; i <= lastClosingFence; i += 1) {
86
+ const matchEnd = closingEnd(i);
87
+ if (matchEnd !== -1) {
88
+ return { indent, body: text.slice(bodyStart, i), length: matchEnd + 1 };
89
+ }
90
+ }
91
+ return null;
92
+ }
93
+ function isPlainObject(value) {
94
+ return typeof value === "object" && value !== null && !Array.isArray(value);
95
+ }
96
+ function deepMerge(base, overlay) {
97
+ const out = { ...base };
98
+ for (const [key, value] of Object.entries(overlay)) {
99
+ const previous = out[key];
100
+ if (isPlainObject(previous) && isPlainObject(value)) {
101
+ out[key] = deepMerge(previous, value);
102
+ } else {
103
+ out[key] = value;
104
+ }
105
+ }
106
+ return out;
107
+ }
108
+ function asString(value) {
109
+ if (typeof value === "string") return value;
110
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
111
+ return null;
112
+ }
113
+ function asTags(value) {
114
+ if (!Array.isArray(value)) return [];
115
+ const tags = [];
116
+ for (const item of value) {
117
+ const text = asString(item)?.trim();
118
+ if (text && !tags.includes(text)) tags.push(text);
119
+ }
120
+ return tags;
121
+ }
122
+ function scalarRecord(value) {
123
+ if (!isPlainObject(value)) return {};
124
+ const out = {};
125
+ for (const [key, item] of Object.entries(value)) {
126
+ if (item == null || typeof item === "string" || typeof item === "number" || typeof item === "boolean") {
127
+ out[key] = item;
128
+ }
129
+ }
130
+ return out;
131
+ }
132
+ function yamlText(match) {
133
+ const normalized = match.body.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
134
+ if (!match.indent) return normalized;
135
+ return normalized.split("\n").map((line) => line.startsWith(match.indent) ? line.slice(match.indent.length) : line).join("\n");
136
+ }
137
+ function firstErrorLine(error) {
138
+ const line = error.linePos?.[0]?.line;
139
+ return typeof line === "number" && line > 0 ? line : 1;
140
+ }
141
+ function parseInitArgs(raw) {
142
+ if (!raw) return { value: {}, error: null };
143
+ const attempts = raw.includes("'") ? [raw, raw.replace(/'/g, '"')] : [raw];
144
+ let last = "The init directive is not JSON.";
145
+ for (const attempt of attempts) {
146
+ try {
147
+ const value = JSON.parse(attempt);
148
+ if (!isPlainObject(value)) {
149
+ return { value: null, error: "The init directive must be a JSON object." };
150
+ }
151
+ return { value, error: null };
152
+ } catch (err) {
153
+ last = err instanceof Error ? err.message : last;
154
+ }
155
+ }
156
+ return { value: null, error: last };
157
+ }
158
+ function findInitDirectives(text) {
159
+ const hits = [];
160
+ let cursor = 0;
161
+ while (cursor < text.length) {
162
+ const start = text.indexOf("%%{", cursor);
163
+ if (start === -1) break;
164
+ let index = start + 3;
165
+ while (index < text.length && whitespace.test(text[index] ?? "")) index += 1;
166
+ const word = /^[A-Za-z]+/.exec(text.slice(index));
167
+ if (!word) {
168
+ cursor = start + 3;
169
+ continue;
170
+ }
171
+ index += word[0].length;
172
+ while (index < text.length && whitespace.test(text[index] ?? "")) index += 1;
173
+ if (text[index] === ":") {
174
+ index += 1;
175
+ while (index < text.length && whitespace.test(text[index] ?? "")) index += 1;
176
+ }
177
+ const close = text.indexOf("}%%", index);
178
+ if (close === -1) break;
179
+ const end = close + 3;
180
+ const name = word[0].toLowerCase();
181
+ if (name === "init" || name === "initialize") {
182
+ const parsed = parseInitArgs(text.slice(index, close).trim());
183
+ hits.push({ start, end, value: parsed.value, error: parsed.error });
184
+ }
185
+ cursor = end;
186
+ }
187
+ return hits;
188
+ }
189
+ function emptyDocument() {
190
+ return {
191
+ hasFrontMatter: false,
192
+ malformed: false,
193
+ error: null,
194
+ errorLine: null,
195
+ body: "",
196
+ title: null,
197
+ description: "",
198
+ notes: "",
199
+ tags: [],
200
+ category: "",
201
+ theme: null,
202
+ look: null,
203
+ layout: null,
204
+ displayMode: null,
205
+ fontFamily: null,
206
+ handDrawnSeed: null,
207
+ themeCSS: null,
208
+ themeVariables: {},
209
+ flowchartCurve: null,
210
+ elk: {},
211
+ config: {},
212
+ initConfig: {},
213
+ hasLegacyInit: false,
214
+ initError: null,
215
+ cacheKey: ""
216
+ };
217
+ }
218
+ function fnv1a(text) {
219
+ let hash = 2166136261;
220
+ for (let i = 0; i < text.length; i += 1) {
221
+ hash ^= text.charCodeAt(i);
222
+ hash = Math.imul(hash, 16777619);
223
+ }
224
+ return (hash >>> 0).toString(16).padStart(8, "0");
225
+ }
226
+ function cacheKeyFor(source) {
227
+ return `${fnv1a(source)}:${source.length}`;
228
+ }
229
+ function readConfig(data) {
230
+ const config = isPlainObject(data.config) ? data.config : {};
231
+ const flowchart = isPlainObject(config.flowchart) ? config.flowchart : {};
232
+ const seed = config.handDrawnSeed;
233
+ return {
234
+ config,
235
+ theme: asString(config.theme),
236
+ look: asString(config.look),
237
+ layout: asString(config.layout),
238
+ fontFamily: asString(config.fontFamily),
239
+ handDrawnSeed: typeof seed === "number" && Number.isFinite(seed) ? seed : null,
240
+ themeCSS: asString(config.themeCSS),
241
+ themeVariables: scalarRecord(config.themeVariables),
242
+ flowchartCurve: asString(flowchart.curve),
243
+ elk: scalarRecord(config.elk)
244
+ };
245
+ }
246
+ function withInits(document, body, source) {
247
+ const hits = findInitDirectives(body);
248
+ const failed = hits.find((hit) => hit.error);
249
+ let initConfig = {};
250
+ if (!failed) {
251
+ for (const hit of hits) {
252
+ if (hit.value) initConfig = deepMerge(initConfig, hit.value);
253
+ }
254
+ }
255
+ const next = {
256
+ ...document,
257
+ body,
258
+ hasLegacyInit: hits.length > 0,
259
+ initError: failed?.error ?? null,
260
+ initConfig
261
+ };
262
+ next.cacheKey = cacheKeyFor(source);
263
+ return next;
264
+ }
265
+ function parseDiagram(source) {
266
+ const text = source.startsWith("\uFEFF") ? source.slice(1) : source;
267
+ const match = matchFrontMatter(text);
268
+ if (!match) return withInits({ ...emptyDocument(), body: text }, text, text);
269
+ const doc = parseDocument(yamlText(match), { schema: "core", prettyErrors: false });
270
+ const body = text.slice(match.length);
271
+ if (doc.errors.length > 0) {
272
+ const error = doc.errors[0];
273
+ const message = error?.message.split("\n")[0]?.trim() || "The YAML front matter could not be parsed.";
274
+ return withInits(
275
+ {
276
+ ...emptyDocument(),
277
+ hasFrontMatter: true,
278
+ malformed: true,
279
+ error: message,
280
+ errorLine: error ? firstErrorLine(error) : 1,
281
+ body
282
+ },
283
+ body,
284
+ text
285
+ );
286
+ }
287
+ const raw = doc.toJS();
288
+ if (raw != null && !isPlainObject(raw)) {
289
+ return withInits(
290
+ {
291
+ ...emptyDocument(),
292
+ hasFrontMatter: true,
293
+ malformed: true,
294
+ error: "Front matter must be a YAML mapping of keys.",
295
+ errorLine: 1,
296
+ body
297
+ },
298
+ body,
299
+ text
300
+ );
301
+ }
302
+ const data = raw ?? {};
303
+ const nerdgram = isPlainObject(data[NERDGRAM]) ? data[NERDGRAM] : {};
304
+ const config = readConfig(data);
305
+ const titleText = asString(data.title);
306
+ const title = titleText && titleText.trim() ? titleText : null;
307
+ const parsed = {
308
+ ...emptyDocument(),
309
+ hasFrontMatter: true,
310
+ body,
311
+ title,
312
+ description: asString(nerdgram.description) ?? "",
313
+ notes: asString(nerdgram.notes) ?? "",
314
+ tags: asTags(nerdgram.tags),
315
+ category: (asString(nerdgram.category) ?? "").trim(),
316
+ displayMode: asString(data.displayMode),
317
+ ...config
318
+ };
319
+ return withInits(parsed, body, text);
320
+ }
321
+ function diagramConfigKey(body) {
322
+ for (const line of body.split(/\r?\n/)) {
323
+ const trimmed = line.trim();
324
+ if (!trimmed || trimmed.startsWith("%%")) continue;
325
+ const word = trimmed.split(/\s+/)[0]?.toLowerCase() ?? "";
326
+ if (word === "graph" || word === "flowchart" || word === "flowchart-elk") return "flowchart";
327
+ if (word === "sequencediagram") return "sequence";
328
+ if (word === "classdiagram") return "class";
329
+ if (word === "statediagram" || word === "statediagram-v2") return "state";
330
+ if (word === "erdiagram") return "er";
331
+ if (word === "gantt") return "gantt";
332
+ if (word === "journey") return "journey";
333
+ if (word === "pie") return "pie";
334
+ if (word === "mindmap") return "mindmap";
335
+ if (word === "timeline") return "timeline";
336
+ if (word === "gitgraph") return "gitGraph";
337
+ if (word === "c4context" || word === "c4container" || word === "c4component") return "c4";
338
+ if (word === "quadrantchart") return "quadrantChart";
339
+ if (word === "requirementdiagram") return "requirement";
340
+ if (word === "xychart-beta" || word === "xychart") return "xyChart";
341
+ if (word === "block-beta" || word === "block") return "block";
342
+ if (word === "sankey-beta" || word === "sankey") return "sankey";
343
+ if (word === "packet-beta" || word === "packet") return "packet";
344
+ if (word === "kanban") return "kanban";
345
+ if (word === "architecture-beta" || word === "architecture") return "architecture";
346
+ return null;
347
+ }
348
+ return null;
349
+ }
350
+ function appearance(config, body, key) {
351
+ const sectionName = diagramConfigKey(body);
352
+ const section = sectionName && isPlainObject(config[sectionName]) ? config[sectionName] : null;
353
+ const scoped = section ? asString(section[key]) : null;
354
+ if (scoped) return scoped;
355
+ return asString(config[key]) ?? void 0;
356
+ }
357
+ function diagramInitConfig(source, fallbackTheme = FALLBACK_THEME) {
358
+ const parsed = parseDiagram(source);
359
+ const effective = parsed.malformed ? {} : deepMerge(parsed.config, parsed.initConfig);
360
+ const init = {};
361
+ for (const [key, value] of Object.entries(effective)) {
362
+ if (SECURE_CONFIG_KEYS.has(key) || key.startsWith("__")) continue;
363
+ init[key] = value;
364
+ }
365
+ init.startOnLoad = false;
366
+ init.securityLevel = "loose";
367
+ init.suppressErrorRendering = true;
368
+ init.theme = appearance(effective, parsed.body, "theme") ?? fallbackTheme;
369
+ const look = appearance(effective, parsed.body, "look");
370
+ if (look) init.look = look;
371
+ else delete init.look;
372
+ const layout = appearance(effective, parsed.body, "layout");
373
+ if (layout) init.layout = layout;
374
+ else delete init.layout;
375
+ const fontFamily = asString(effective.fontFamily);
376
+ init.fontFamily = fontFamily || DEFAULT_FONT_FAMILY;
377
+ return init;
378
+ }
379
+
380
+ // server/src/parseError.ts
381
+ function locateParseError(error, source) {
382
+ const hash = readHash(error);
383
+ const loc = hash?.loc;
384
+ const shift = frontMatterLineShift(source);
385
+ if (loc && typeof loc.first_line === "number" && loc.first_line > 0) {
386
+ const line2 = loc.first_line + shift;
387
+ const column2 = typeof loc.first_column === "number" && loc.first_column >= 0 ? loc.first_column + 1 : 1;
388
+ const span2 = spanFor(source, line2, column2, loc);
389
+ return { ...span2, message: plainMessage(line2, column2, hash?.token) };
390
+ }
391
+ const message = error instanceof Error ? error.message : String(error);
392
+ const lineMatch = message.match(/Parse error on line (\d+)/i) ?? message.match(/\bline\s+(\d+)\b/i);
393
+ const line = (lineMatch ? Math.max(1, Number(lineMatch[1])) : 1) + shift;
394
+ const column = caretColumn(message, source, line);
395
+ const span = spanFor(source, line, column, null);
396
+ return { ...span, message: plainMessage(line, column, void 0) };
397
+ }
398
+ function isMermaidEnvironmentError(error) {
399
+ const message = error instanceof Error ? error.message : String(error);
400
+ return /DOMPurify|document is not defined|window is not defined|CSSStyleSheet is not defined/i.test(message);
401
+ }
402
+ function frontMatterLineShift(source) {
403
+ const front = matchFrontMatter(source);
404
+ if (!front || front.length <= 0) return 0;
405
+ const prefix = source.slice(0, front.length);
406
+ let lines = 0;
407
+ for (let i = 0; i < prefix.length; i += 1) {
408
+ if (prefix[i] === "\n") lines += 1;
409
+ }
410
+ return lines;
411
+ }
412
+ function readHash(error) {
413
+ if (!error || typeof error !== "object" || !("hash" in error)) return null;
414
+ const hash = error.hash;
415
+ if (!hash || typeof hash !== "object") return null;
416
+ const record = hash;
417
+ return { loc: record.loc, token: typeof record.token === "string" ? record.token : void 0 };
418
+ }
419
+ function spanFor(source, line, column, loc) {
420
+ const lines = source.split(/\n/);
421
+ const index = Math.min(Math.max(line - 1, 0), Math.max(lines.length - 1, 0));
422
+ let lineStart = 0;
423
+ for (let i = 0; i < index; i += 1) lineStart += (lines[i]?.length ?? 0) + 1;
424
+ const lineText = (lines[index] ?? "").replace(/\r$/, "");
425
+ const from = lineStart + Math.min(Math.max(column - 1, 0), lineText.length);
426
+ let to = lineStart + lineText.length;
427
+ if (loc && loc.last_line === loc.first_line && typeof loc.last_column === "number" && typeof loc.first_column === "number" && loc.last_column > loc.first_column) {
428
+ to = lineStart + Math.min(loc.last_column, lineText.length);
429
+ }
430
+ if (to <= from) to = Math.min(lineStart + lineText.length, from + 1);
431
+ if (to <= from) to = from + 1;
432
+ return { line: index + 1, column: from - lineStart + 1, from, to };
433
+ }
434
+ function caretColumn(message, source, line) {
435
+ const lines = message.split(/\n/);
436
+ const caret = lines.find((item) => /^\s*-+\^/.test(item) || /^\s*\^+$/.test(item));
437
+ if (!caret) return 1;
438
+ const mark = caret.lastIndexOf("^");
439
+ if (mark < 0) return 1;
440
+ const sourceLine = source.split(/\n/)[line - 1] ?? "";
441
+ if (sourceLine.length <= mark) return mark + 1;
442
+ return 1;
443
+ }
444
+ function plainMessage(line, column, token) {
445
+ const where = `Line ${line}, column ${column}`;
446
+ const found = foundPhrase(token);
447
+ if (!found) return `${where}: this isn't valid Mermaid.`;
448
+ return `${where}: this isn't valid Mermaid. The parser stopped at ${found}.`;
449
+ }
450
+ function foundPhrase(token) {
451
+ if (!token) return null;
452
+ const name = token.replace(/^'+|'+$/g, "").toUpperCase();
453
+ if (name === "EOF") return "the end of the diagram";
454
+ if (name === "NEWLINE" || name === "NL") return "the end of the line";
455
+ if (name === "INVALID") return "text Mermaid doesn't accept here";
456
+ return null;
457
+ }
458
+
459
+ export {
460
+ MERMAID_THEMES,
461
+ MERMAID_LOOKS,
462
+ MERMAID_LAYOUTS,
463
+ FLOWCHART_CURVES,
464
+ ELK_NODE_PLACEMENTS,
465
+ matchFrontMatter,
466
+ parseDiagram,
467
+ diagramConfigKey,
468
+ diagramInitConfig,
469
+ locateParseError,
470
+ isMermaidEnvironmentError
471
+ };