cms-renderer 0.6.7 → 0.6.9
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/dist/lib/block-renderer.d.ts +3 -1
- package/dist/lib/block-renderer.js +42 -5
- package/dist/lib/block-renderer.js.map +1 -1
- package/dist/lib/block-toolbar.js +42 -3
- package/dist/lib/block-toolbar.js.map +1 -1
- package/dist/lib/client-editable-block.js +51 -5
- package/dist/lib/client-editable-block.js.map +1 -1
- package/dist/lib/custom-schemas.js.map +1 -1
- package/dist/lib/markdown-utils.d.ts +0 -7
- package/dist/lib/markdown-utils.js +300 -9
- package/dist/lib/markdown-utils.js.map +1 -1
- package/dist/lib/parametric-route.js +131 -7
- package/dist/lib/parametric-route.js.map +1 -1
- package/dist/lib/renderer.js +131 -7
- package/dist/lib/renderer.js.map +1 -1
- package/dist/lib/types.d.ts +32 -1
- package/dist/lib/types.js.map +1 -1
- package/package.json +2 -2
- package/styles/docs-markdown.css +15 -15
|
@@ -153,13 +153,6 @@ declare const parseMarkdown: typeof parseMarkdownV3;
|
|
|
153
153
|
* @returns true if no XSS patterns detected
|
|
154
154
|
*/
|
|
155
155
|
declare function isSafeMarkdown(content: string): boolean;
|
|
156
|
-
/**
|
|
157
|
-
* Estimates the word count of markdown content.
|
|
158
|
-
* Useful for content length limits and reading time estimates.
|
|
159
|
-
*
|
|
160
|
-
* @param content - Markdown string to count
|
|
161
|
-
* @returns Estimated word count
|
|
162
|
-
*/
|
|
163
156
|
declare function estimateWordCount(content: string): number;
|
|
164
157
|
/**
|
|
165
158
|
* Estimates reading time for markdown content.
|
|
@@ -1,6 +1,246 @@
|
|
|
1
1
|
// lib/markdown-utils.ts
|
|
2
2
|
import { mdToJSON } from "md4w";
|
|
3
3
|
|
|
4
|
+
// lib/markdown-sanitize.ts
|
|
5
|
+
var DANGEROUS_SCHEMES = ["javascript:", "vbscript:", "data:"];
|
|
6
|
+
var HTML_URL_ATTRIBUTES = [
|
|
7
|
+
"href",
|
|
8
|
+
"src",
|
|
9
|
+
"action",
|
|
10
|
+
"formaction",
|
|
11
|
+
"cite",
|
|
12
|
+
"background",
|
|
13
|
+
"poster",
|
|
14
|
+
"xlink:href"
|
|
15
|
+
];
|
|
16
|
+
function isHtmlWhitespace(ch) {
|
|
17
|
+
return ch === " " || ch === " " || ch === "\n" || ch === "\r" || ch === "\f" || ch === "\v";
|
|
18
|
+
}
|
|
19
|
+
function neutralizeDangerousSchemesInUrl(url) {
|
|
20
|
+
let result = url;
|
|
21
|
+
let lower = result.toLowerCase();
|
|
22
|
+
for (const scheme of DANGEROUS_SCHEMES) {
|
|
23
|
+
const lowerScheme = scheme.toLowerCase();
|
|
24
|
+
let index = lower.indexOf(lowerScheme);
|
|
25
|
+
while (index !== -1) {
|
|
26
|
+
const atUrlStart = index === 0;
|
|
27
|
+
const afterSeparator = index > 0 && (isHtmlWhitespace(result.charAt(index - 1)) || result.charAt(index - 1) === '"');
|
|
28
|
+
if (atUrlStart || afterSeparator) {
|
|
29
|
+
result = `${result.slice(0, index)}removed:${result.slice(index + scheme.length)}`;
|
|
30
|
+
lower = result.toLowerCase();
|
|
31
|
+
index = lower.indexOf(lowerScheme, index + "removed:".length);
|
|
32
|
+
} else {
|
|
33
|
+
index = lower.indexOf(lowerScheme, index + 1);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return result;
|
|
38
|
+
}
|
|
39
|
+
function stripScriptTags(content) {
|
|
40
|
+
let result = content;
|
|
41
|
+
let lower = result.toLowerCase();
|
|
42
|
+
let searchFrom = 0;
|
|
43
|
+
while (searchFrom < lower.length) {
|
|
44
|
+
const start = lower.indexOf("<script", searchFrom);
|
|
45
|
+
if (start === -1) break;
|
|
46
|
+
const closeStart = lower.indexOf("</script", start);
|
|
47
|
+
if (closeStart === -1) {
|
|
48
|
+
searchFrom = start + 1;
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
let end = lower.indexOf(">", closeStart);
|
|
52
|
+
if (end === -1) {
|
|
53
|
+
searchFrom = start + 1;
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
end += 1;
|
|
57
|
+
result = result.slice(0, start) + result.slice(end);
|
|
58
|
+
lower = result.toLowerCase();
|
|
59
|
+
searchFrom = start;
|
|
60
|
+
}
|
|
61
|
+
return result;
|
|
62
|
+
}
|
|
63
|
+
function replaceUrlInParenGroup(content, openParen, closeParen) {
|
|
64
|
+
const url = content.slice(openParen + 1, closeParen);
|
|
65
|
+
const sanitized = neutralizeDangerousSchemesInUrl(url);
|
|
66
|
+
if (sanitized === url) {
|
|
67
|
+
return { content, nextIndex: closeParen + 1 };
|
|
68
|
+
}
|
|
69
|
+
return {
|
|
70
|
+
content: content.slice(0, openParen + 1) + sanitized + content.slice(closeParen),
|
|
71
|
+
nextIndex: openParen + sanitized.length + 1
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
function neutralizeMarkdownLinkAndImageDestinations(content) {
|
|
75
|
+
let result = content;
|
|
76
|
+
let index = 0;
|
|
77
|
+
while (index < result.length) {
|
|
78
|
+
const isImage = result.startsWith("![", index);
|
|
79
|
+
const marker = isImage ? "![" : "[";
|
|
80
|
+
const markerIndex = isImage ? index : result.indexOf("[", index);
|
|
81
|
+
if (markerIndex === -1) break;
|
|
82
|
+
if (!isImage && result.startsWith("![", markerIndex)) {
|
|
83
|
+
index = markerIndex + 2;
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
const bracketStart = isImage ? markerIndex + 2 : markerIndex + 1;
|
|
87
|
+
const closeBracket = result.indexOf("]", bracketStart);
|
|
88
|
+
if (closeBracket === -1) {
|
|
89
|
+
index = markerIndex + marker.length;
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
const openParen = result.indexOf("(", closeBracket);
|
|
93
|
+
if (openParen !== closeBracket + 1) {
|
|
94
|
+
index = markerIndex + marker.length;
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
const closeParen = result.indexOf(")", openParen);
|
|
98
|
+
if (closeParen === -1) {
|
|
99
|
+
index = markerIndex + marker.length;
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
const replaced = replaceUrlInParenGroup(result, openParen, closeParen);
|
|
103
|
+
result = replaced.content;
|
|
104
|
+
index = replaced.nextIndex;
|
|
105
|
+
}
|
|
106
|
+
return result;
|
|
107
|
+
}
|
|
108
|
+
function readHtmlAttributeValue(content, valueStart) {
|
|
109
|
+
let end = valueStart;
|
|
110
|
+
while (end < content.length && isHtmlWhitespace(content.charAt(end))) {
|
|
111
|
+
end += 1;
|
|
112
|
+
}
|
|
113
|
+
const quote = content.charAt(end);
|
|
114
|
+
if (quote === '"' || quote === "'") {
|
|
115
|
+
end += 1;
|
|
116
|
+
while (end < content.length && content.charAt(end) !== quote) {
|
|
117
|
+
end += 1;
|
|
118
|
+
}
|
|
119
|
+
if (end < content.length) end += 1;
|
|
120
|
+
return end;
|
|
121
|
+
}
|
|
122
|
+
while (end < content.length) {
|
|
123
|
+
const ch = content.charAt(end);
|
|
124
|
+
if (isHtmlWhitespace(ch) || ch === ">") break;
|
|
125
|
+
end += 1;
|
|
126
|
+
}
|
|
127
|
+
return end;
|
|
128
|
+
}
|
|
129
|
+
function findHtmlAttribute(_content, lower, attrName, from) {
|
|
130
|
+
const needle = attrName.toLowerCase();
|
|
131
|
+
let i = from;
|
|
132
|
+
while (i < lower.length) {
|
|
133
|
+
const idx = lower.indexOf(needle, i);
|
|
134
|
+
if (idx === -1) return -1;
|
|
135
|
+
const before = idx > 0 ? lower.charAt(idx - 1) : "";
|
|
136
|
+
if (idx > 0 && !isHtmlWhitespace(before) && before !== "<" && before !== "/") {
|
|
137
|
+
i = idx + 1;
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
let after = idx + needle.length;
|
|
141
|
+
while (after < lower.length && isHtmlWhitespace(lower.charAt(after))) {
|
|
142
|
+
after += 1;
|
|
143
|
+
}
|
|
144
|
+
if (lower.charAt(after) === "=") return idx;
|
|
145
|
+
i = idx + 1;
|
|
146
|
+
}
|
|
147
|
+
return -1;
|
|
148
|
+
}
|
|
149
|
+
function neutralizeHtmlUrlAttributes(content) {
|
|
150
|
+
let result = content;
|
|
151
|
+
let lower = result.toLowerCase();
|
|
152
|
+
for (const attr of HTML_URL_ATTRIBUTES) {
|
|
153
|
+
let searchFrom = 0;
|
|
154
|
+
while (searchFrom < lower.length) {
|
|
155
|
+
const attrIndex = findHtmlAttribute(result, lower, attr, searchFrom);
|
|
156
|
+
if (attrIndex === -1) break;
|
|
157
|
+
let valueStart = attrIndex + attr.length;
|
|
158
|
+
while (valueStart < lower.length && isHtmlWhitespace(lower.charAt(valueStart))) {
|
|
159
|
+
valueStart += 1;
|
|
160
|
+
}
|
|
161
|
+
if (lower.charAt(valueStart) !== "=") {
|
|
162
|
+
searchFrom = attrIndex + 1;
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
valueStart += 1;
|
|
166
|
+
while (valueStart < result.length && isHtmlWhitespace(result.charAt(valueStart))) {
|
|
167
|
+
valueStart += 1;
|
|
168
|
+
}
|
|
169
|
+
const valueEnd = readHtmlAttributeValue(result, valueStart);
|
|
170
|
+
const rawValue = result.slice(valueStart, valueEnd);
|
|
171
|
+
const quote = rawValue.charAt(0) === '"' || rawValue.charAt(0) === "'" ? rawValue.charAt(0) : null;
|
|
172
|
+
const innerStart = quote ? 1 : 0;
|
|
173
|
+
const innerEnd = quote && rawValue.charAt(rawValue.length - 1) === quote ? rawValue.length - 1 : rawValue.length;
|
|
174
|
+
const url = rawValue.slice(innerStart, innerEnd);
|
|
175
|
+
const sanitized = neutralizeDangerousSchemesInUrl(url);
|
|
176
|
+
const wrapped = quote ? `${quote}${sanitized}${quote}` : sanitized;
|
|
177
|
+
if (sanitized !== url) {
|
|
178
|
+
result = result.slice(0, valueStart) + wrapped + result.slice(valueEnd);
|
|
179
|
+
lower = result.toLowerCase();
|
|
180
|
+
}
|
|
181
|
+
searchFrom = valueStart + (sanitized !== url ? wrapped.length : rawValue.length);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
return result;
|
|
185
|
+
}
|
|
186
|
+
function stripEventHandlersFromTag(tag) {
|
|
187
|
+
let result = tag;
|
|
188
|
+
let lower = result.toLowerCase();
|
|
189
|
+
let searchFrom = 0;
|
|
190
|
+
while (searchFrom < lower.length) {
|
|
191
|
+
let eventStart = -1;
|
|
192
|
+
for (let j = searchFrom; j < lower.length; j++) {
|
|
193
|
+
if (lower.charAt(j) !== "o" || !lower.startsWith("on", j)) continue;
|
|
194
|
+
if (j > 0 && !isHtmlWhitespace(lower.charAt(j - 1))) continue;
|
|
195
|
+
let nameEnd = j + 2;
|
|
196
|
+
while (nameEnd < lower.length) {
|
|
197
|
+
const ch = lower.charAt(nameEnd);
|
|
198
|
+
if (!(ch >= "a" && ch <= "z" || ch >= "0" && ch <= "9" || ch === "-")) break;
|
|
199
|
+
nameEnd += 1;
|
|
200
|
+
}
|
|
201
|
+
let eqIndex = nameEnd;
|
|
202
|
+
while (eqIndex < lower.length && isHtmlWhitespace(lower.charAt(eqIndex))) {
|
|
203
|
+
eqIndex += 1;
|
|
204
|
+
}
|
|
205
|
+
if (lower.charAt(eqIndex) !== "=" || nameEnd - j < 3) continue;
|
|
206
|
+
eventStart = j;
|
|
207
|
+
break;
|
|
208
|
+
}
|
|
209
|
+
if (eventStart === -1) break;
|
|
210
|
+
const valueEnd = readHtmlAttributeValue(result, lower.indexOf("=", eventStart) + 1);
|
|
211
|
+
result = result.slice(0, eventStart) + result.slice(valueEnd);
|
|
212
|
+
lower = result.toLowerCase();
|
|
213
|
+
searchFrom = eventStart;
|
|
214
|
+
}
|
|
215
|
+
return result;
|
|
216
|
+
}
|
|
217
|
+
function stripInlineEventHandlers(content) {
|
|
218
|
+
let result = content;
|
|
219
|
+
let i = 0;
|
|
220
|
+
while (i < result.length) {
|
|
221
|
+
const tagStart = result.indexOf("<", i);
|
|
222
|
+
if (tagStart === -1) break;
|
|
223
|
+
if (result.startsWith("<!--", tagStart)) {
|
|
224
|
+
const commentEnd = result.indexOf("-->", tagStart);
|
|
225
|
+
i = commentEnd === -1 ? result.length : commentEnd + 3;
|
|
226
|
+
continue;
|
|
227
|
+
}
|
|
228
|
+
const tagEnd = result.indexOf(">", tagStart);
|
|
229
|
+
if (tagEnd === -1) break;
|
|
230
|
+
const tag = result.slice(tagStart, tagEnd + 1);
|
|
231
|
+
const sanitizedTag = stripEventHandlersFromTag(tag);
|
|
232
|
+
result = result.slice(0, tagStart) + sanitizedTag + result.slice(tagEnd + 1);
|
|
233
|
+
i = tagStart + sanitizedTag.length;
|
|
234
|
+
}
|
|
235
|
+
return result;
|
|
236
|
+
}
|
|
237
|
+
function sanitizeMarkdownContent(content) {
|
|
238
|
+
let sanitized = stripScriptTags(content);
|
|
239
|
+
sanitized = neutralizeMarkdownLinkAndImageDestinations(sanitized);
|
|
240
|
+
sanitized = neutralizeHtmlUrlAttributes(sanitized);
|
|
241
|
+
return stripInlineEventHandlers(sanitized);
|
|
242
|
+
}
|
|
243
|
+
|
|
4
244
|
// lib/result.ts
|
|
5
245
|
function ok(value) {
|
|
6
246
|
return { ok: true, value };
|
|
@@ -23,7 +263,7 @@ var XSS_PATTERNS = [
|
|
|
23
263
|
/javascript:/i,
|
|
24
264
|
/on\w+\s*=/i,
|
|
25
265
|
// onclick=, onerror=, etc.
|
|
26
|
-
|
|
266
|
+
/\bdata:/i,
|
|
27
267
|
// data: URIs can be dangerous
|
|
28
268
|
/vbscript:/i
|
|
29
269
|
];
|
|
@@ -52,13 +292,7 @@ function detectXssPattern(content) {
|
|
|
52
292
|
return null;
|
|
53
293
|
}
|
|
54
294
|
function sanitizeContent(content) {
|
|
55
|
-
|
|
56
|
-
sanitized = sanitized.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, "");
|
|
57
|
-
sanitized = sanitized.replace(/javascript:/gi, "removed:");
|
|
58
|
-
sanitized = sanitized.replace(/vbscript:/gi, "removed:");
|
|
59
|
-
sanitized = sanitized.replace(/\bon\w+\s*=\s*["'][^"']*["']/gi, "");
|
|
60
|
-
sanitized = sanitized.replace(/\bon\w+\s*=\s*\S+/gi, "");
|
|
61
|
-
return sanitized;
|
|
295
|
+
return sanitizeMarkdownContent(content);
|
|
62
296
|
}
|
|
63
297
|
function parseMarkdownV3(content, options = {}) {
|
|
64
298
|
const { maxLength = DEFAULT_MAX_LENGTH, sanitize = true, allowEmpty = false } = options;
|
|
@@ -120,8 +354,65 @@ var parseMarkdown = parseMarkdownV3;
|
|
|
120
354
|
function isSafeMarkdown(content) {
|
|
121
355
|
return detectXssPattern(content) === null;
|
|
122
356
|
}
|
|
357
|
+
var MAX_ESTIMATE_LENGTH = 5e5;
|
|
358
|
+
function stripFencedCodeBlocks(text) {
|
|
359
|
+
let result = text;
|
|
360
|
+
let start = result.indexOf("```");
|
|
361
|
+
while (start !== -1) {
|
|
362
|
+
const end = result.indexOf("```", start + 3);
|
|
363
|
+
if (end === -1) break;
|
|
364
|
+
result = result.slice(0, start) + result.slice(end + 3);
|
|
365
|
+
start = result.indexOf("```");
|
|
366
|
+
}
|
|
367
|
+
return result;
|
|
368
|
+
}
|
|
369
|
+
function stripInlineCodeSpans(text) {
|
|
370
|
+
let result = text;
|
|
371
|
+
let start = result.indexOf("`");
|
|
372
|
+
while (start !== -1) {
|
|
373
|
+
const end = result.indexOf("`", start + 1);
|
|
374
|
+
if (end === -1) break;
|
|
375
|
+
result = result.slice(0, start) + result.slice(end + 1);
|
|
376
|
+
start = result.indexOf("`");
|
|
377
|
+
}
|
|
378
|
+
return result;
|
|
379
|
+
}
|
|
380
|
+
function stripMarkdownImages(text) {
|
|
381
|
+
let result = text;
|
|
382
|
+
let index = result.indexOf("![");
|
|
383
|
+
while (index !== -1) {
|
|
384
|
+
const closeBracket = result.indexOf("]", index + 2);
|
|
385
|
+
const openParen = closeBracket !== -1 ? result.indexOf("(", closeBracket) : -1;
|
|
386
|
+
const closeParen = openParen !== -1 ? result.indexOf(")", openParen) : -1;
|
|
387
|
+
if (closeBracket === -1 || openParen === -1 || closeParen === -1) break;
|
|
388
|
+
result = result.slice(0, index) + result.slice(closeParen + 1);
|
|
389
|
+
index = result.indexOf("![");
|
|
390
|
+
}
|
|
391
|
+
return result;
|
|
392
|
+
}
|
|
393
|
+
function convertMarkdownLinksToText(text) {
|
|
394
|
+
let result = text;
|
|
395
|
+
let index = result.indexOf("[");
|
|
396
|
+
while (index !== -1) {
|
|
397
|
+
const closeBracket = result.indexOf("]", index + 1);
|
|
398
|
+
const openParen = closeBracket !== -1 ? result.indexOf("(", closeBracket) : -1;
|
|
399
|
+
const closeParen = openParen !== -1 ? result.indexOf(")", openParen) : -1;
|
|
400
|
+
if (closeBracket === -1 || openParen === -1 || closeParen === -1) break;
|
|
401
|
+
const label = result.slice(index + 1, closeBracket);
|
|
402
|
+
result = result.slice(0, index) + label + result.slice(closeParen + 1);
|
|
403
|
+
index = result.indexOf("[", index + label.length);
|
|
404
|
+
}
|
|
405
|
+
return result;
|
|
406
|
+
}
|
|
123
407
|
function estimateWordCount(content) {
|
|
124
|
-
const
|
|
408
|
+
const bounded = content.length > MAX_ESTIMATE_LENGTH ? content.slice(0, MAX_ESTIMATE_LENGTH) : content;
|
|
409
|
+
let plainText = bounded;
|
|
410
|
+
plainText = plainText.replace(/#+\s/g, "");
|
|
411
|
+
plainText = stripFencedCodeBlocks(plainText);
|
|
412
|
+
plainText = stripInlineCodeSpans(plainText);
|
|
413
|
+
plainText = stripMarkdownImages(plainText);
|
|
414
|
+
plainText = convertMarkdownLinksToText(plainText);
|
|
415
|
+
plainText = plainText.replace(/\*\*|__|~~/g, "");
|
|
125
416
|
const words = plainText.trim().split(/\s+/).filter(Boolean);
|
|
126
417
|
return words.length;
|
|
127
418
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../lib/markdown-utils.ts","../../lib/result.ts"],"sourcesContent":["/**\n * Markdown Parsing Utilities\n *\n * Three implementations showing the tradeoffs between simple and more\n * defensive parsing:\n * - v1 (Naive): Direct call, crashes on bad input\n * - v2 (Defensive): Try-catch with null fallback\n * - v3 (Robust): Result type, validation, lightweight sanitization\n *\n * The default export points to the v3 implementation.\n */\n\nimport type { MDTree } from 'md4w';\nimport { mdToJSON } from 'md4w';\n\nimport { err, ok, type Result } from './result';\n\n// -----------------------------------------------------------------------------\n// Types\n// -----------------------------------------------------------------------------\n\n/**\n * Error codes for markdown parsing failures.\n */\nexport const ParseErrorCode = {\n INVALID_INPUT: 'INVALID_INPUT',\n EMPTY_CONTENT: 'EMPTY_CONTENT',\n PARSE_FAILED: 'PARSE_FAILED',\n CONTENT_TOO_LONG: 'CONTENT_TOO_LONG',\n NESTED_TOO_DEEP: 'NESTED_TOO_DEEP',\n} as const;\n\nexport type ParseErrorCode = (typeof ParseErrorCode)[keyof typeof ParseErrorCode];\n\n/**\n * Structured error for markdown parsing failures.\n */\nexport interface ParseError {\n code: ParseErrorCode;\n message: string;\n cause?: Error;\n}\n\n/**\n * Options for robust markdown parsing.\n */\nexport interface ParseOptions {\n /**\n * Maximum content length in characters.\n * @default 500000 (500KB of text, ~100K words)\n */\n maxLength?: number;\n\n /**\n * Whether to run a lightweight string-based sanitization pass before parsing.\n * @default true\n */\n sanitize?: boolean;\n\n /**\n * Whether to allow empty content.\n * @default false\n */\n allowEmpty?: boolean;\n}\n\n// -----------------------------------------------------------------------------\n// Constants\n// -----------------------------------------------------------------------------\n\nconst DEFAULT_MAX_LENGTH = 500_000; // 500KB of text\n\n/**\n * Patterns that indicate potential XSS attempts in markdown.\n * These are checked in raw content before parsing.\n */\nconst XSS_PATTERNS = [\n /<script\\b/i,\n /javascript:/i,\n /on\\w+\\s*=/i, // onclick=, onerror=, etc.\n /data:/i, // data: URIs can be dangerous\n /vbscript:/i,\n] as const;\n\n// -----------------------------------------------------------------------------\n// V1: Naive Implementation\n// -----------------------------------------------------------------------------\n\n/**\n * Naive markdown parser - crashes on bad input.\n *\n * DO NOT USE IN PRODUCTION. This is for demonstration only.\n *\n * Problems:\n * - No input validation\n * - No error handling\n * - Will crash the entire app on malformed input\n * - No protection against XSS\n * - No content limits\n *\n * @example\n * ```ts\n * // This crashes if content is null, undefined, or malformed\n * const ast = parseMarkdownV1(userInput);\n * ```\n */\nexport function parseMarkdownV1(content: string): MDTree {\n return mdToJSON(content);\n}\n\n// -----------------------------------------------------------------------------\n// V2: Defensive Implementation\n// -----------------------------------------------------------------------------\n\n/**\n * Defensive markdown parser - catches errors but loses context.\n *\n * Better than v1 but still problematic:\n * - Returns null on any error (loses error details)\n * - Caller can't distinguish between empty content and parse failure\n * - Still no XSS protection\n * - Still no content limits\n *\n * @example\n * ```ts\n * const ast = parseMarkdownV2(userInput);\n * if (!ast) {\n * // What went wrong? We don't know.\n * return <ErrorFallback />;\n * }\n * ```\n */\nexport function parseMarkdownV2(content: string): MDTree | null {\n try {\n // Basic null check\n if (content == null) {\n return null;\n }\n return mdToJSON(content);\n } catch {\n return null;\n }\n}\n\n// -----------------------------------------------------------------------------\n// V3: Robust Implementation\n// -----------------------------------------------------------------------------\n\n/**\n * Creates a ParseError with the given code and message.\n */\nfunction createParseError(code: ParseErrorCode, message: string, cause?: Error): ParseError {\n return { code, message, cause };\n}\n\n/**\n * Checks content for potential XSS patterns.\n * Returns the first matched pattern or null if clean.\n */\nfunction detectXssPattern(content: string): RegExp | null {\n for (const pattern of XSS_PATTERNS) {\n if (pattern.test(content)) {\n return pattern;\n }\n }\n return null;\n}\n\n/**\n * Sanitizes content by removing dangerous patterns.\n * This is a lightweight, string-based sanitizer and not a full HTML sanitizer.\n */\nfunction sanitizeContent(content: string): string {\n let sanitized = content;\n\n // Remove script tags\n sanitized = sanitized.replace(/<script\\b[^<]*(?:(?!<\\/script>)<[^<]*)*<\\/script>/gi, '');\n\n // Remove javascript: and vbscript: URLs\n sanitized = sanitized.replace(/javascript:/gi, 'removed:');\n sanitized = sanitized.replace(/vbscript:/gi, 'removed:');\n\n // Remove event handlers (onclick, onerror, etc.)\n sanitized = sanitized.replace(/\\bon\\w+\\s*=\\s*[\"'][^\"']*[\"']/gi, '');\n sanitized = sanitized.replace(/\\bon\\w+\\s*=\\s*\\S+/gi, '');\n\n return sanitized;\n}\n\n/**\n * Robust markdown parser with explicit error handling and lightweight sanitization.\n *\n * Features:\n * - Input validation with specific error codes\n * - Result type for explicit error handling\n * - XSS pattern detection and optional lightweight sanitization\n * - Content length limits\n * - Preserves error context for debugging\n *\n * @param content - Markdown string to parse\n * @param options - Parsing options\n * @returns Result containing the AST or a structured error\n *\n * @example\n * ```ts\n * const result = parseMarkdownV3(userInput);\n *\n * if (!result.ok) {\n * switch (result.error.code) {\n * case 'INVALID_INPUT':\n * return <InvalidInputError message={result.error.message} />;\n * case 'CONTENT_TOO_LONG':\n * return <ContentTooLongError />;\n * case 'PARSE_FAILED':\n * console.error('Parse error:', result.error.cause);\n * return <ParseError />;\n * default:\n * return <GenericError />;\n * }\n * }\n *\n * return <MarkdownRenderer ast={result.value} />;\n * ```\n */\nexport function parseMarkdownV3(\n content: string,\n options: ParseOptions = {}\n): Result<MDTree, ParseError> {\n const { maxLength = DEFAULT_MAX_LENGTH, sanitize = true, allowEmpty = false } = options;\n\n // 1. Validate input type\n if (content === null || content === undefined) {\n return err(\n createParseError(\n ParseErrorCode.INVALID_INPUT,\n `Content must be a string, received ${content === null ? 'null' : 'undefined'}`\n )\n );\n }\n\n if (typeof content !== 'string') {\n return err(\n createParseError(\n ParseErrorCode.INVALID_INPUT,\n `Content must be a string, received ${typeof content}`\n )\n );\n }\n\n // 2. Handle empty content\n const trimmed = content.trim();\n if (trimmed.length === 0 && !allowEmpty) {\n return err(\n createParseError(ParseErrorCode.EMPTY_CONTENT, 'Content is empty or contains only whitespace')\n );\n }\n\n // 3. Check content length\n if (content.length > maxLength) {\n return err(\n createParseError(\n ParseErrorCode.CONTENT_TOO_LONG,\n `Content exceeds maximum length of ${maxLength.toLocaleString()} characters ` +\n `(received ${content.length.toLocaleString()})`\n )\n );\n }\n\n // 4. Check for XSS patterns\n const xssPattern = detectXssPattern(content);\n if (xssPattern) {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n `[parseMarkdownV3] XSS pattern detected: ${xssPattern.toString()}`,\n sanitize ? 'Content will be sanitized.' : 'Sanitization is disabled!'\n );\n }\n }\n\n // 5. Optionally sanitize content\n const processedContent = sanitize ? sanitizeContent(content) : content;\n\n // 6. Parse markdown with error handling\n try {\n const ast = mdToJSON(processedContent);\n return ok(ast);\n } catch (error) {\n const cause = error instanceof Error ? error : new Error(String(error));\n return err(\n createParseError(\n ParseErrorCode.PARSE_FAILED,\n `Failed to parse markdown: ${cause.message}`,\n cause\n )\n );\n }\n}\n\n// -----------------------------------------------------------------------------\n// Default Export\n// -----------------------------------------------------------------------------\n\n/**\n * Default markdown parser.\n *\n * This is an alias for `parseMarkdownV3`, the most defensive implementation\n * in this module.\n *\n * @example\n * ```ts\n * import { parseMarkdown } from '@/lib/markdown-utils';\n *\n * const result = parseMarkdown(content);\n * if (!result.ok) {\n * // Handle error with full context\n * console.error(`[${result.error.code}] ${result.error.message}`);\n * return null;\n * }\n * return result.value;\n * ```\n */\nexport const parseMarkdown = parseMarkdownV3;\n\n// -----------------------------------------------------------------------------\n// Utility Functions\n// -----------------------------------------------------------------------------\n\n/**\n * Checks if content is safe markdown (no XSS patterns detected).\n *\n * @param content - Markdown string to check\n * @returns true if no XSS patterns detected\n */\nexport function isSafeMarkdown(content: string): boolean {\n return detectXssPattern(content) === null;\n}\n\n/**\n * Estimates the word count of markdown content.\n * Useful for content length limits and reading time estimates.\n *\n * @param content - Markdown string to count\n * @returns Estimated word count\n */\nexport function estimateWordCount(content: string): number {\n // Remove markdown syntax for more accurate count\n const plainText = content\n .replace(/#+\\s/g, '') // Remove headings\n .replace(/```[\\s\\S]*?```/g, '') // Remove fenced code blocks (must precede backtick-stripping)\n .replace(/`[^`]+`/g, '') // Remove inline code spans (must precede backtick-stripping)\n .replace(/!\\[([^\\]]*)\\]\\([^)]+\\)/g, '') // Remove images (must precede link regex)\n .replace(/\\[([^\\]]+)\\]\\([^)]+\\)/g, '$1') // Convert links to text\n .replace(/\\*\\*|__|~~/g, ''); // Remove remaining bold/italic/strikethrough markers\n\n const words = plainText.trim().split(/\\s+/).filter(Boolean);\n return words.length;\n}\n\n/**\n * Estimates reading time for markdown content.\n *\n * @param content - Markdown string\n * @param wordsPerMinute - Reading speed (default 200 WPM)\n * @returns Reading time in minutes\n */\nexport function estimateReadingTime(content: string, wordsPerMinute = 200): number {\n const wordCount = estimateWordCount(content);\n return Math.ceil(wordCount / wordsPerMinute);\n}\n","/**\n * Result Type Utilities\n *\n * Go-style error handling with discriminated union types.\n * Provides type-safe success/error handling without exceptions.\n *\n * @example\n * ```ts\n * const [err, data] = await handle(async () => {\n * const response = await fetch(url);\n * if (!response.ok) throw new Error(`HTTP ${response.status}`);\n * return response.json();\n * });\n *\n * if (err) {\n * console.error('Failed:', err.message);\n * return { error: err.message };\n * }\n * return { data };\n * ```\n */\n\n// -----------------------------------------------------------------------------\n// Result Type\n// -----------------------------------------------------------------------------\n\n/**\n * A discriminated union representing either success or failure.\n *\n * @template T - The success value type\n * @template E - The error type (defaults to Error)\n *\n * @example\n * ```ts\n * function divide(a: number, b: number): Result<number, string> {\n * if (b === 0) return err('Division by zero');\n * return ok(a / b);\n * }\n *\n * const result = divide(10, 2);\n * if (isOk(result)) {\n * console.log('Result:', result.value); // 5\n * } else {\n * console.error('Error:', result.error);\n * }\n * ```\n */\nexport type Result<T, E = Error> = { ok: true; value: T } | { ok: false; error: E };\n\n// -----------------------------------------------------------------------------\n// Constructors\n// -----------------------------------------------------------------------------\n\n/**\n * Creates a success Result.\n *\n * @param value - The success value\n * @returns A success Result containing the value\n *\n * @example\n * ```ts\n * const result = ok(42);\n * // { ok: true, value: 42 }\n * ```\n */\nexport function ok<T>(value: T): Result<T, never> {\n return { ok: true, value };\n}\n\n/**\n * Creates a failure Result.\n *\n * @param error - The error value\n * @returns A failure Result containing the error\n *\n * @example\n * ```ts\n * const result = err(new Error('Something went wrong'));\n * // { ok: false, error: Error('Something went wrong') }\n * ```\n */\nexport function err<E>(error: E): Result<never, E> {\n return { ok: false, error };\n}\n\n// -----------------------------------------------------------------------------\n// Type Guards\n// -----------------------------------------------------------------------------\n\n/**\n * Type guard to check if a Result is successful.\n *\n * @param result - The Result to check\n * @returns true if the Result is a success\n *\n * @example\n * ```ts\n * const result = fetchData();\n * if (isOk(result)) {\n * // TypeScript knows result.value exists here\n * console.log(result.value);\n * }\n * ```\n */\nexport function isOk<T, E>(result: Result<T, E>): result is { ok: true; value: T } {\n return result.ok === true;\n}\n\n/**\n * Type guard to check if a Result is a failure.\n *\n * @param result - The Result to check\n * @returns true if the Result is a failure\n *\n * @example\n * ```ts\n * const result = fetchData();\n * if (isErr(result)) {\n * // TypeScript knows result.error exists here\n * console.error(result.error);\n * }\n * ```\n */\nexport function isErr<T, E>(result: Result<T, E>): result is { ok: false; error: E } {\n return result.ok === false;\n}\n\n// -----------------------------------------------------------------------------\n// Extractors\n// -----------------------------------------------------------------------------\n\n/**\n * Extracts the value from a Result, throwing if it's an error.\n *\n * @param result - The Result to unwrap\n * @returns The success value\n * @throws The error if Result is a failure\n *\n * @example\n * ```ts\n * const result = ok(42);\n * const value = unwrap(result); // 42\n *\n * const errorResult = err(new Error('fail'));\n * const value2 = unwrap(errorResult); // throws Error('fail')\n * ```\n */\nexport function unwrap<T, E>(result: Result<T, E>): T {\n if (isOk(result)) {\n return result.value;\n }\n throw result.error;\n}\n\n/**\n * Extracts the value from a Result, returning a default on error.\n *\n * @param result - The Result to unwrap\n * @param defaultValue - The value to return if Result is an error\n * @returns The success value or the default value\n *\n * @example\n * ```ts\n * const result = err(new Error('fail'));\n * const value = unwrapOr(result, 0); // 0\n *\n * const okResult = ok(42);\n * const value2 = unwrapOr(okResult, 0); // 42\n * ```\n */\nexport function unwrapOr<T, E>(result: Result<T, E>, defaultValue: T): T {\n if (isOk(result)) {\n return result.value;\n }\n return defaultValue;\n}\n\n/**\n * Extracts the value from a Result, computing a default on error.\n *\n * @param result - The Result to unwrap\n * @param fn - Function to compute the default value from the error\n * @returns The success value or the computed default\n *\n * @example\n * ```ts\n * const result = err(new Error('not found'));\n * const value = unwrapOrElse(result, (e) => {\n * console.error('Error:', e.message);\n * return [];\n * });\n * ```\n */\nexport function unwrapOrElse<T, E>(result: Result<T, E>, fn: (error: E) => T): T {\n if (isOk(result)) {\n return result.value;\n }\n return fn(result.error);\n}\n\n// -----------------------------------------------------------------------------\n// Transformers\n// -----------------------------------------------------------------------------\n\n/**\n * Maps a successful Result's value.\n *\n * @param result - The Result to map\n * @param fn - Function to transform the value\n * @returns A new Result with the transformed value, or the original error\n *\n * @example\n * ```ts\n * const result = ok(5);\n * const doubled = map(result, (n) => n * 2); // ok(10)\n *\n * const errorResult = err('fail');\n * const still = map(errorResult, (n) => n * 2); // err('fail')\n * ```\n */\nexport function map<T, U, E>(result: Result<T, E>, fn: (value: T) => U): Result<U, E> {\n if (isOk(result)) {\n return ok(fn(result.value));\n }\n return result;\n}\n\n/**\n * Maps a failed Result's error.\n *\n * @param result - The Result to map\n * @param fn - Function to transform the error\n * @returns A new Result with the transformed error, or the original value\n *\n * @example\n * ```ts\n * const result = err('not found');\n * const mapped = mapErr(result, (e) => new Error(e)); // err(Error('not found'))\n * ```\n */\nexport function mapErr<T, E, F>(result: Result<T, E>, fn: (error: E) => F): Result<T, F> {\n if (isErr(result)) {\n return err(fn(result.error));\n }\n return result;\n}\n\n/**\n * Chains Result-returning operations.\n *\n * @param result - The Result to chain from\n * @param fn - Function that returns a new Result\n * @returns The chained Result\n *\n * @example\n * ```ts\n * function parse(input: string): Result<number, string> {\n * const n = parseInt(input, 10);\n * return isNaN(n) ? err('not a number') : ok(n);\n * }\n *\n * function double(n: number): Result<number, string> {\n * return ok(n * 2);\n * }\n *\n * const result = flatMap(parse('5'), double); // ok(10)\n * const fail = flatMap(parse('abc'), double); // err('not a number')\n * ```\n */\nexport function flatMap<T, U, E>(\n result: Result<T, E>,\n fn: (value: T) => Result<U, E>\n): Result<U, E> {\n if (isOk(result)) {\n return fn(result.value);\n }\n return result;\n}\n\n// -----------------------------------------------------------------------------\n// Async Helpers\n// -----------------------------------------------------------------------------\n\n/**\n * Wraps a Promise in a Result type.\n *\n * @param promise - The Promise to wrap\n * @returns A Promise that resolves to a Result\n *\n * @example\n * ```ts\n * const result = await fromPromise(fetch('/api/data'));\n * if (isErr(result)) {\n * console.error('Fetch failed:', result.error);\n * return;\n * }\n * const response = result.value;\n * ```\n */\nexport async function fromPromise<T>(promise: Promise<T>): Promise<Result<T, Error>> {\n try {\n const value = await promise;\n return ok(value);\n } catch (error) {\n return err(error instanceof Error ? error : new Error(String(error)));\n }\n}\n\n/**\n * Wraps a throwing function in a Result type.\n *\n * @param fn - The function to wrap\n * @returns A Result containing the return value or the thrown error\n *\n * @example\n * ```ts\n * const result = tryCatch(() => JSON.parse(input));\n * if (isErr(result)) {\n * console.error('Invalid JSON:', result.error);\n * return null;\n * }\n * return result.value;\n * ```\n */\nexport function tryCatch<T>(fn: () => T): Result<T, Error> {\n try {\n return ok(fn());\n } catch (error) {\n return err(error instanceof Error ? error : new Error(String(error)));\n }\n}\n\n/**\n * Wraps an async function in a Result type.\n *\n * @param fn - The async function to wrap\n * @returns A Promise that resolves to a Result\n *\n * @example\n * ```ts\n * const result = await tryCatchAsync(async () => {\n * const response = await fetch('/api/data');\n * if (!response.ok) throw new Error(`HTTP ${response.status}`);\n * return response.json();\n * });\n * ```\n */\nexport async function tryCatchAsync<T>(fn: () => Promise<T>): Promise<Result<T, Error>> {\n try {\n const value = await fn();\n return ok(value);\n } catch (error) {\n return err(error instanceof Error ? error : new Error(String(error)));\n }\n}\n\n// -----------------------------------------------------------------------------\n// Tuple Helpers (Go-style)\n// -----------------------------------------------------------------------------\n\n/**\n * Go-style tuple for error handling: [error, value]\n *\n * @example\n * ```ts\n * const [err, data] = await handle(fetchData);\n * if (err) {\n * console.error(err);\n * return;\n * }\n * console.log(data);\n * ```\n */\nexport type GoTuple<T, E = Error> = [E, undefined] | [undefined, T];\n\n/**\n * Converts a Result to a Go-style tuple.\n *\n * @param result - The Result to convert\n * @returns A tuple of [error, value]\n *\n * @example\n * ```ts\n * const result = await fetchData();\n * const [err, data] = toTuple(result);\n * ```\n */\nexport function toTuple<T, E>(result: Result<T, E>): GoTuple<T, E> {\n if (isOk(result)) {\n return [undefined, result.value];\n }\n return [result.error, undefined];\n}\n\n/**\n * Wraps an async function and returns a Go-style tuple.\n *\n * @param fn - The async function to wrap\n * @returns A Promise that resolves to [error, value] tuple\n *\n * @example\n * ```ts\n * const [err, data] = await handle(async () => {\n * const res = await fetch('/api/users');\n * if (!res.ok) throw new Error(`HTTP ${res.status}`);\n * return res.json();\n * });\n *\n * if (err) {\n * console.error('Failed to fetch users:', err.message);\n * return [];\n * }\n * return data;\n * ```\n */\nexport async function handle<T>(fn: () => Promise<T>): Promise<GoTuple<T, Error>> {\n try {\n const value = await fn();\n return [undefined, value];\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n return [err, undefined];\n }\n}\n\n/**\n * Wraps a synchronous function and returns a Go-style tuple.\n *\n * @param fn - The function to wrap\n * @returns A tuple of [error, value]\n *\n * @example\n * ```ts\n * const [err, parsed] = handleSync(() => JSON.parse(input));\n * if (err) {\n * console.error('Invalid JSON:', err.message);\n * return null;\n * }\n * return parsed;\n * ```\n */\nexport function handleSync<T>(fn: () => T): GoTuple<T, Error> {\n try {\n const value = fn();\n return [undefined, value];\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n return [err, undefined];\n }\n}\n"],"mappings":";AAaA,SAAS,gBAAgB;;;ACoDlB,SAAS,GAAM,OAA4B;AAChD,SAAO,EAAE,IAAI,MAAM,MAAM;AAC3B;AAcO,SAAS,IAAO,OAA4B;AACjD,SAAO,EAAE,IAAI,OAAO,MAAM;AAC5B;;;AD3DO,IAAM,iB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EAAE;AAE5B,QAAM,QAAQ,UAAU,KAAK,EAAE,MAAM,KAAK,EAAE,OAAO,OAAO;AAC1D,SAAO,MAAM;AACf;AASO,SAAS,oBAAoB,SAAiB,iBAAiB,KAAa;AACjF,QAAM,YAAY,kBAAkB,OAAO;AAC3C,SAAO,KAAK,KAAK,YAAY,cAAc;AAC7C;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../lib/markdown-utils.ts","../../lib/markdown-sanitize.ts","../../lib/result.ts"],"sourcesContent":["/**\n * Markdown Parsing Utilities\n *\n * Three implementations showing the tradeoffs between simple and more\n * defensive parsing:\n * - v1 (Naive): Direct call, crashes on bad input\n * - v2 (Defensive): Try-catch with null fallback\n * - v3 (Robust): Result type, validation, lightweight sanitization\n *\n * The default export points to the v3 implementation.\n */\n\nimport type { MDTree } from 'md4w';\nimport { mdToJSON } from 'md4w';\n\nimport { sanitizeMarkdownContent } from './markdown-sanitize';\nimport { err, ok, type Result } from './result';\n\n// -----------------------------------------------------------------------------\n// Types\n// -----------------------------------------------------------------------------\n\n/**\n * Error codes for markdown parsing failures.\n */\nexport const ParseErrorCode = {\n INVALID_INPUT: 'INVALID_INPUT',\n EMPTY_CONTENT: 'EMPTY_CONTENT',\n PARSE_FAILED: 'PARSE_FAILED',\n CONTENT_TOO_LONG: 'CONTENT_TOO_LONG',\n NESTED_TOO_DEEP: 'NESTED_TOO_DEEP',\n} as const;\n\nexport type ParseErrorCode = (typeof ParseErrorCode)[keyof typeof ParseErrorCode];\n\n/**\n * Structured error for markdown parsing failures.\n */\nexport interface ParseError {\n code: ParseErrorCode;\n message: string;\n cause?: Error;\n}\n\n/**\n * Options for robust markdown parsing.\n */\nexport interface ParseOptions {\n /**\n * Maximum content length in characters.\n * @default 500000 (500KB of text, ~100K words)\n */\n maxLength?: number;\n\n /**\n * Whether to run a lightweight string-based sanitization pass before parsing.\n * @default true\n */\n sanitize?: boolean;\n\n /**\n * Whether to allow empty content.\n * @default false\n */\n allowEmpty?: boolean;\n}\n\n// -----------------------------------------------------------------------------\n// Constants\n// -----------------------------------------------------------------------------\n\nconst DEFAULT_MAX_LENGTH = 500_000; // 500KB of text\n\n/**\n * Patterns that indicate potential XSS attempts in markdown.\n * These are checked in raw content before parsing.\n */\nconst XSS_PATTERNS = [\n /<script\\b/i,\n /javascript:/i,\n /on\\w+\\s*=/i, // onclick=, onerror=, etc.\n /\\bdata:/i, // data: URIs can be dangerous\n /vbscript:/i,\n] as const;\n\n// -----------------------------------------------------------------------------\n// V1: Naive Implementation\n// -----------------------------------------------------------------------------\n\n/**\n * Naive markdown parser - crashes on bad input.\n *\n * DO NOT USE IN PRODUCTION. This is for demonstration only.\n *\n * Problems:\n * - No input validation\n * - No error handling\n * - Will crash the entire app on malformed input\n * - No protection against XSS\n * - No content limits\n *\n * @example\n * ```ts\n * // This crashes if content is null, undefined, or malformed\n * const ast = parseMarkdownV1(userInput);\n * ```\n */\nexport function parseMarkdownV1(content: string): MDTree {\n return mdToJSON(content);\n}\n\n// -----------------------------------------------------------------------------\n// V2: Defensive Implementation\n// -----------------------------------------------------------------------------\n\n/**\n * Defensive markdown parser - catches errors but loses context.\n *\n * Better than v1 but still problematic:\n * - Returns null on any error (loses error details)\n * - Caller can't distinguish between empty content and parse failure\n * - Still no XSS protection\n * - Still no content limits\n *\n * @example\n * ```ts\n * const ast = parseMarkdownV2(userInput);\n * if (!ast) {\n * // What went wrong? We don't know.\n * return <ErrorFallback />;\n * }\n * ```\n */\nexport function parseMarkdownV2(content: string): MDTree | null {\n try {\n // Basic null check\n if (content == null) {\n return null;\n }\n return mdToJSON(content);\n } catch {\n return null;\n }\n}\n\n// -----------------------------------------------------------------------------\n// V3: Robust Implementation\n// -----------------------------------------------------------------------------\n\n/**\n * Creates a ParseError with the given code and message.\n */\nfunction createParseError(code: ParseErrorCode, message: string, cause?: Error): ParseError {\n return { code, message, cause };\n}\n\n/**\n * Checks content for potential XSS patterns.\n * Returns the first matched pattern or null if clean.\n */\nfunction detectXssPattern(content: string): RegExp | null {\n for (const pattern of XSS_PATTERNS) {\n if (pattern.test(content)) {\n return pattern;\n }\n }\n return null;\n}\n\n/**\n * Sanitizes content by removing dangerous patterns.\n * This is a lightweight, string-based sanitizer and not a full HTML sanitizer.\n */\nfunction sanitizeContent(content: string): string {\n return sanitizeMarkdownContent(content);\n}\n\n/**\n * Robust markdown parser with explicit error handling and lightweight sanitization.\n *\n * Features:\n * - Input validation with specific error codes\n * - Result type for explicit error handling\n * - XSS pattern detection and optional lightweight sanitization\n * - Content length limits\n * - Preserves error context for debugging\n *\n * @param content - Markdown string to parse\n * @param options - Parsing options\n * @returns Result containing the AST or a structured error\n *\n * @example\n * ```ts\n * const result = parseMarkdownV3(userInput);\n *\n * if (!result.ok) {\n * switch (result.error.code) {\n * case 'INVALID_INPUT':\n * return <InvalidInputError message={result.error.message} />;\n * case 'CONTENT_TOO_LONG':\n * return <ContentTooLongError />;\n * case 'PARSE_FAILED':\n * console.error('Parse error:', result.error.cause);\n * return <ParseError />;\n * default:\n * return <GenericError />;\n * }\n * }\n *\n * return <MarkdownRenderer ast={result.value} />;\n * ```\n */\nexport function parseMarkdownV3(\n content: string,\n options: ParseOptions = {}\n): Result<MDTree, ParseError> {\n const { maxLength = DEFAULT_MAX_LENGTH, sanitize = true, allowEmpty = false } = options;\n\n // 1. Validate input type\n if (content === null || content === undefined) {\n return err(\n createParseError(\n ParseErrorCode.INVALID_INPUT,\n `Content must be a string, received ${content === null ? 'null' : 'undefined'}`\n )\n );\n }\n\n if (typeof content !== 'string') {\n return err(\n createParseError(\n ParseErrorCode.INVALID_INPUT,\n `Content must be a string, received ${typeof content}`\n )\n );\n }\n\n // 2. Handle empty content\n const trimmed = content.trim();\n if (trimmed.length === 0 && !allowEmpty) {\n return err(\n createParseError(ParseErrorCode.EMPTY_CONTENT, 'Content is empty or contains only whitespace')\n );\n }\n\n // 3. Check content length\n if (content.length > maxLength) {\n return err(\n createParseError(\n ParseErrorCode.CONTENT_TOO_LONG,\n `Content exceeds maximum length of ${maxLength.toLocaleString()} characters ` +\n `(received ${content.length.toLocaleString()})`\n )\n );\n }\n\n // 4. Check for XSS patterns\n const xssPattern = detectXssPattern(content);\n if (xssPattern) {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n `[parseMarkdownV3] XSS pattern detected: ${xssPattern.toString()}`,\n sanitize ? 'Content will be sanitized.' : 'Sanitization is disabled!'\n );\n }\n }\n\n // 5. Optionally sanitize content\n const processedContent = sanitize ? sanitizeContent(content) : content;\n\n // 6. Parse markdown with error handling\n try {\n const ast = mdToJSON(processedContent);\n return ok(ast);\n } catch (error) {\n const cause = error instanceof Error ? error : new Error(String(error));\n return err(\n createParseError(\n ParseErrorCode.PARSE_FAILED,\n `Failed to parse markdown: ${cause.message}`,\n cause\n )\n );\n }\n}\n\n// -----------------------------------------------------------------------------\n// Default Export\n// -----------------------------------------------------------------------------\n\n/**\n * Default markdown parser.\n *\n * This is an alias for `parseMarkdownV3`, the most defensive implementation\n * in this module.\n *\n * @example\n * ```ts\n * import { parseMarkdown } from '@/lib/markdown-utils';\n *\n * const result = parseMarkdown(content);\n * if (!result.ok) {\n * // Handle error with full context\n * console.error(`[${result.error.code}] ${result.error.message}`);\n * return null;\n * }\n * return result.value;\n * ```\n */\nexport const parseMarkdown = parseMarkdownV3;\n\n// -----------------------------------------------------------------------------\n// Utility Functions\n// -----------------------------------------------------------------------------\n\n/**\n * Checks if content is safe markdown (no XSS patterns detected).\n *\n * @param content - Markdown string to check\n * @returns true if no XSS patterns detected\n */\nexport function isSafeMarkdown(content: string): boolean {\n return detectXssPattern(content) === null;\n}\n\n/**\n * Estimates the word count of markdown content.\n * Useful for content length limits and reading time estimates.\n *\n * @param content - Markdown string to count\n * @returns Estimated word count\n */\nconst MAX_ESTIMATE_LENGTH = 500_000;\n\nfunction stripFencedCodeBlocks(text: string): string {\n let result = text;\n let start = result.indexOf('```');\n while (start !== -1) {\n const end = result.indexOf('```', start + 3);\n if (end === -1) break;\n result = result.slice(0, start) + result.slice(end + 3);\n start = result.indexOf('```');\n }\n return result;\n}\n\nfunction stripInlineCodeSpans(text: string): string {\n let result = text;\n let start = result.indexOf('`');\n while (start !== -1) {\n const end = result.indexOf('`', start + 1);\n if (end === -1) break;\n result = result.slice(0, start) + result.slice(end + 1);\n start = result.indexOf('`');\n }\n return result;\n}\n\nfunction stripMarkdownImages(text: string): string {\n let result = text;\n let index = result.indexOf('![');\n while (index !== -1) {\n const closeBracket = result.indexOf(']', index + 2);\n const openParen = closeBracket !== -1 ? result.indexOf('(', closeBracket) : -1;\n const closeParen = openParen !== -1 ? result.indexOf(')', openParen) : -1;\n if (closeBracket === -1 || openParen === -1 || closeParen === -1) break;\n result = result.slice(0, index) + result.slice(closeParen + 1);\n index = result.indexOf('![');\n }\n return result;\n}\n\nfunction convertMarkdownLinksToText(text: string): string {\n let result = text;\n let index = result.indexOf('[');\n while (index !== -1) {\n const closeBracket = result.indexOf(']', index + 1);\n const openParen = closeBracket !== -1 ? result.indexOf('(', closeBracket) : -1;\n const closeParen = openParen !== -1 ? result.indexOf(')', openParen) : -1;\n if (closeBracket === -1 || openParen === -1 || closeParen === -1) break;\n const label = result.slice(index + 1, closeBracket);\n result = result.slice(0, index) + label + result.slice(closeParen + 1);\n index = result.indexOf('[', index + label.length);\n }\n return result;\n}\n\nexport function estimateWordCount(content: string): number {\n const bounded =\n content.length > MAX_ESTIMATE_LENGTH ? content.slice(0, MAX_ESTIMATE_LENGTH) : content;\n\n let plainText = bounded;\n plainText = plainText.replace(/#+\\s/g, '');\n plainText = stripFencedCodeBlocks(plainText);\n plainText = stripInlineCodeSpans(plainText);\n plainText = stripMarkdownImages(plainText);\n plainText = convertMarkdownLinksToText(plainText);\n plainText = plainText.replace(/\\*\\*|__|~~/g, '');\n\n const words = plainText.trim().split(/\\s+/).filter(Boolean);\n return words.length;\n}\n\n/**\n * Estimates reading time for markdown content.\n *\n * @param content - Markdown string\n * @param wordsPerMinute - Reading speed (default 200 WPM)\n * @returns Reading time in minutes\n */\nexport function estimateReadingTime(content: string, wordsPerMinute = 200): number {\n const wordCount = estimateWordCount(content);\n return Math.ceil(wordCount / wordsPerMinute);\n}\n","/**\n * String-based markdown sanitization helpers (no regex backtracking on user input).\n */\n\nconst DANGEROUS_SCHEMES = ['javascript:', 'vbscript:', 'data:'] as const;\n\nconst HTML_URL_ATTRIBUTES = [\n 'href',\n 'src',\n 'action',\n 'formaction',\n 'cite',\n 'background',\n 'poster',\n 'xlink:href',\n] as const;\n\nfunction isHtmlWhitespace(ch: string): boolean {\n return ch === ' ' || ch === '\\t' || ch === '\\n' || ch === '\\r' || ch === '\\f' || ch === '\\v';\n}\n\nfunction neutralizeDangerousSchemesInUrl(url: string): string {\n let result = url;\n let lower = result.toLowerCase();\n\n for (const scheme of DANGEROUS_SCHEMES) {\n const lowerScheme = scheme.toLowerCase();\n let index = lower.indexOf(lowerScheme);\n\n while (index !== -1) {\n const atUrlStart = index === 0;\n const afterSeparator =\n index > 0 &&\n (isHtmlWhitespace(result.charAt(index - 1)) || result.charAt(index - 1) === '\"');\n\n if (atUrlStart || afterSeparator) {\n result = `${result.slice(0, index)}removed:${result.slice(index + scheme.length)}`;\n lower = result.toLowerCase();\n index = lower.indexOf(lowerScheme, index + 'removed:'.length);\n } else {\n index = lower.indexOf(lowerScheme, index + 1);\n }\n }\n }\n\n return result;\n}\n\nexport function stripScriptTags(content: string): string {\n let result = content;\n let lower = result.toLowerCase();\n let searchFrom = 0;\n\n while (searchFrom < lower.length) {\n const start = lower.indexOf('<script', searchFrom);\n if (start === -1) break;\n\n const closeStart = lower.indexOf('</script', start);\n if (closeStart === -1) {\n searchFrom = start + 1;\n continue;\n }\n\n let end = lower.indexOf('>', closeStart);\n if (end === -1) {\n searchFrom = start + 1;\n continue;\n }\n end += 1;\n\n result = result.slice(0, start) + result.slice(end);\n lower = result.toLowerCase();\n searchFrom = start;\n }\n\n return result;\n}\n\nfunction replaceUrlInParenGroup(\n content: string,\n openParen: number,\n closeParen: number\n): { content: string; nextIndex: number } {\n const url = content.slice(openParen + 1, closeParen);\n const sanitized = neutralizeDangerousSchemesInUrl(url);\n if (sanitized === url) {\n return { content, nextIndex: closeParen + 1 };\n }\n return {\n content: content.slice(0, openParen + 1) + sanitized + content.slice(closeParen),\n nextIndex: openParen + sanitized.length + 1,\n };\n}\n\nfunction neutralizeMarkdownLinkAndImageDestinations(content: string): string {\n let result = content;\n let index = 0;\n\n while (index < result.length) {\n const isImage = result.startsWith('![', index);\n const marker = isImage ? '![' : '[';\n const markerIndex = isImage ? index : result.indexOf('[', index);\n\n if (markerIndex === -1) break;\n if (!isImage && result.startsWith('![', markerIndex)) {\n index = markerIndex + 2;\n continue;\n }\n\n const bracketStart = isImage ? markerIndex + 2 : markerIndex + 1;\n const closeBracket = result.indexOf(']', bracketStart);\n if (closeBracket === -1) {\n index = markerIndex + marker.length;\n continue;\n }\n\n const openParen = result.indexOf('(', closeBracket);\n if (openParen !== closeBracket + 1) {\n index = markerIndex + marker.length;\n continue;\n }\n\n const closeParen = result.indexOf(')', openParen);\n if (closeParen === -1) {\n index = markerIndex + marker.length;\n continue;\n }\n\n const replaced = replaceUrlInParenGroup(result, openParen, closeParen);\n result = replaced.content;\n index = replaced.nextIndex;\n }\n\n return result;\n}\n\nfunction readHtmlAttributeValue(content: string, valueStart: number): number {\n let end = valueStart;\n while (end < content.length && isHtmlWhitespace(content.charAt(end))) {\n end += 1;\n }\n\n const quote = content.charAt(end);\n if (quote === '\"' || quote === \"'\") {\n end += 1;\n while (end < content.length && content.charAt(end) !== quote) {\n end += 1;\n }\n if (end < content.length) end += 1;\n return end;\n }\n\n while (end < content.length) {\n const ch = content.charAt(end);\n if (isHtmlWhitespace(ch) || ch === '>') break;\n end += 1;\n }\n return end;\n}\n\nfunction findHtmlAttribute(\n _content: string,\n lower: string,\n attrName: string,\n from: number\n): number {\n const needle = attrName.toLowerCase();\n let i = from;\n\n while (i < lower.length) {\n const idx = lower.indexOf(needle, i);\n if (idx === -1) return -1;\n\n const before = idx > 0 ? lower.charAt(idx - 1) : '';\n if (idx > 0 && !isHtmlWhitespace(before) && before !== '<' && before !== '/') {\n i = idx + 1;\n continue;\n }\n\n let after = idx + needle.length;\n while (after < lower.length && isHtmlWhitespace(lower.charAt(after))) {\n after += 1;\n }\n\n if (lower.charAt(after) === '=') return idx;\n i = idx + 1;\n }\n\n return -1;\n}\n\nfunction neutralizeHtmlUrlAttributes(content: string): string {\n let result = content;\n let lower = result.toLowerCase();\n\n for (const attr of HTML_URL_ATTRIBUTES) {\n let searchFrom = 0;\n\n while (searchFrom < lower.length) {\n const attrIndex = findHtmlAttribute(result, lower, attr, searchFrom);\n if (attrIndex === -1) break;\n\n let valueStart = attrIndex + attr.length;\n while (valueStart < lower.length && isHtmlWhitespace(lower.charAt(valueStart))) {\n valueStart += 1;\n }\n if (lower.charAt(valueStart) !== '=') {\n searchFrom = attrIndex + 1;\n continue;\n }\n valueStart += 1;\n while (valueStart < result.length && isHtmlWhitespace(result.charAt(valueStart))) {\n valueStart += 1;\n }\n\n const valueEnd = readHtmlAttributeValue(result, valueStart);\n const rawValue = result.slice(valueStart, valueEnd);\n const quote =\n rawValue.charAt(0) === '\"' || rawValue.charAt(0) === \"'\" ? rawValue.charAt(0) : null;\n const innerStart = quote ? 1 : 0;\n const innerEnd =\n quote && rawValue.charAt(rawValue.length - 1) === quote\n ? rawValue.length - 1\n : rawValue.length;\n const url = rawValue.slice(innerStart, innerEnd);\n const sanitized = neutralizeDangerousSchemesInUrl(url);\n const wrapped = quote ? `${quote}${sanitized}${quote}` : sanitized;\n\n if (sanitized !== url) {\n result = result.slice(0, valueStart) + wrapped + result.slice(valueEnd);\n lower = result.toLowerCase();\n }\n\n searchFrom = valueStart + (sanitized !== url ? wrapped.length : rawValue.length);\n }\n }\n\n return result;\n}\n\nfunction stripEventHandlersFromTag(tag: string): string {\n let result = tag;\n let lower = result.toLowerCase();\n let searchFrom = 0;\n\n while (searchFrom < lower.length) {\n let eventStart = -1;\n\n for (let j = searchFrom; j < lower.length; j++) {\n if (lower.charAt(j) !== 'o' || !lower.startsWith('on', j)) continue;\n\n if (j > 0 && !isHtmlWhitespace(lower.charAt(j - 1))) continue;\n\n let nameEnd = j + 2;\n while (nameEnd < lower.length) {\n const ch = lower.charAt(nameEnd);\n if (!((ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || ch === '-')) break;\n nameEnd += 1;\n }\n\n let eqIndex = nameEnd;\n while (eqIndex < lower.length && isHtmlWhitespace(lower.charAt(eqIndex))) {\n eqIndex += 1;\n }\n\n if (lower.charAt(eqIndex) !== '=' || nameEnd - j < 3) continue;\n\n eventStart = j;\n break;\n }\n\n if (eventStart === -1) break;\n\n const valueEnd = readHtmlAttributeValue(result, lower.indexOf('=', eventStart) + 1);\n result = result.slice(0, eventStart) + result.slice(valueEnd);\n lower = result.toLowerCase();\n searchFrom = eventStart;\n }\n\n return result;\n}\n\nexport function stripInlineEventHandlers(content: string): string {\n let result = content;\n let i = 0;\n\n while (i < result.length) {\n const tagStart = result.indexOf('<', i);\n if (tagStart === -1) break;\n\n if (result.startsWith('<!--', tagStart)) {\n const commentEnd = result.indexOf('-->', tagStart);\n i = commentEnd === -1 ? result.length : commentEnd + 3;\n continue;\n }\n\n const tagEnd = result.indexOf('>', tagStart);\n if (tagEnd === -1) break;\n\n const tag = result.slice(tagStart, tagEnd + 1);\n const sanitizedTag = stripEventHandlersFromTag(tag);\n result = result.slice(0, tagStart) + sanitizedTag + result.slice(tagEnd + 1);\n i = tagStart + sanitizedTag.length;\n }\n\n return result;\n}\n\nexport function sanitizeMarkdownContent(content: string): string {\n let sanitized = stripScriptTags(content);\n sanitized = neutralizeMarkdownLinkAndImageDestinations(sanitized);\n sanitized = neutralizeHtmlUrlAttributes(sanitized);\n return stripInlineEventHandlers(sanitized);\n}\n\nexport function containsDangerousScheme(content: string, scheme: string): boolean {\n return content.toLowerCase().includes(scheme.toLowerCase());\n}\n","/**\n * Result Type Utilities\n *\n * Go-style error handling with discriminated union types.\n * Provides type-safe success/error handling without exceptions.\n *\n * @example\n * ```ts\n * const [err, data] = await handle(async () => {\n * const response = await fetch(url);\n * if (!response.ok) throw new Error(`HTTP ${response.status}`);\n * return response.json();\n * });\n *\n * if (err) {\n * console.error('Failed:', err.message);\n * return { error: err.message };\n * }\n * return { data };\n * ```\n */\n\n// -----------------------------------------------------------------------------\n// Result Type\n// -----------------------------------------------------------------------------\n\n/**\n * A discriminated union representing either success or failure.\n *\n * @template T - The success value type\n * @template E - The error type (defaults to Error)\n *\n * @example\n * ```ts\n * function divide(a: number, b: number): Result<number, string> {\n * if (b === 0) return err('Division by zero');\n * return ok(a / b);\n * }\n *\n * const result = divide(10, 2);\n * if (isOk(result)) {\n * console.log('Result:', result.value); // 5\n * } else {\n * console.error('Error:', result.error);\n * }\n * ```\n */\nexport type Result<T, E = Error> = { ok: true; value: T } | { ok: false; error: E };\n\n// -----------------------------------------------------------------------------\n// Constructors\n// -----------------------------------------------------------------------------\n\n/**\n * Creates a success Result.\n *\n * @param value - The success value\n * @returns A success Result containing the value\n *\n * @example\n * ```ts\n * const result = ok(42);\n * // { ok: true, value: 42 }\n * ```\n */\nexport function ok<T>(value: T): Result<T, never> {\n return { ok: true, value };\n}\n\n/**\n * Creates a failure Result.\n *\n * @param error - The error value\n * @returns A failure Result containing the error\n *\n * @example\n * ```ts\n * const result = err(new Error('Something went wrong'));\n * // { ok: false, error: Error('Something went wrong') }\n * ```\n */\nexport function err<E>(error: E): Result<never, E> {\n return { ok: false, error };\n}\n\n// -----------------------------------------------------------------------------\n// Type Guards\n// -----------------------------------------------------------------------------\n\n/**\n * Type guard to check if a Result is successful.\n *\n * @param result - The Result to check\n * @returns true if the Result is a success\n *\n * @example\n * ```ts\n * const result = fetchData();\n * if (isOk(result)) {\n * // TypeScript knows result.value exists here\n * console.log(result.value);\n * }\n * ```\n */\nexport function isOk<T, E>(result: Result<T, E>): result is { ok: true; value: T } {\n return result.ok === true;\n}\n\n/**\n * Type guard to check if a Result is a failure.\n *\n * @param result - The Result to check\n * @returns true if the Result is a failure\n *\n * @example\n * ```ts\n * const result = fetchData();\n * if (isErr(result)) {\n * // TypeScript knows result.error exists here\n * console.error(result.error);\n * }\n * ```\n */\nexport function isErr<T, E>(result: Result<T, E>): result is { ok: false; error: E } {\n return result.ok === false;\n}\n\n// -----------------------------------------------------------------------------\n// Extractors\n// -----------------------------------------------------------------------------\n\n/**\n * Extracts the value from a Result, throwing if it's an error.\n *\n * @param result - The Result to unwrap\n * @returns The success value\n * @throws The error if Result is a failure\n *\n * @example\n * ```ts\n * const result = ok(42);\n * const value = unwrap(result); // 42\n *\n * const errorResult = err(new Error('fail'));\n * const value2 = unwrap(errorResult); // throws Error('fail')\n * ```\n */\nexport function unwrap<T, E>(result: Result<T, E>): T {\n if (isOk(result)) {\n return result.value;\n }\n throw result.error;\n}\n\n/**\n * Extracts the value from a Result, returning a default on error.\n *\n * @param result - The Result to unwrap\n * @param defaultValue - The value to return if Result is an error\n * @returns The success value or the default value\n *\n * @example\n * ```ts\n * const result = err(new Error('fail'));\n * const value = unwrapOr(result, 0); // 0\n *\n * const okResult = ok(42);\n * const value2 = unwrapOr(okResult, 0); // 42\n * ```\n */\nexport function unwrapOr<T, E>(result: Result<T, E>, defaultValue: T): T {\n if (isOk(result)) {\n return result.value;\n }\n return defaultValue;\n}\n\n/**\n * Extracts the value from a Result, computing a default on error.\n *\n * @param result - The Result to unwrap\n * @param fn - Function to compute the default value from the error\n * @returns The success value or the computed default\n *\n * @example\n * ```ts\n * const result = err(new Error('not found'));\n * const value = unwrapOrElse(result, (e) => {\n * console.error('Error:', e.message);\n * return [];\n * });\n * ```\n */\nexport function unwrapOrElse<T, E>(result: Result<T, E>, fn: (error: E) => T): T {\n if (isOk(result)) {\n return result.value;\n }\n return fn(result.error);\n}\n\n// -----------------------------------------------------------------------------\n// Transformers\n// -----------------------------------------------------------------------------\n\n/**\n * Maps a successful Result's value.\n *\n * @param result - The Result to map\n * @param fn - Function to transform the value\n * @returns A new Result with the transformed value, or the original error\n *\n * @example\n * ```ts\n * const result = ok(5);\n * const doubled = map(result, (n) => n * 2); // ok(10)\n *\n * const errorResult = err('fail');\n * const still = map(errorResult, (n) => n * 2); // err('fail')\n * ```\n */\nexport function map<T, U, E>(result: Result<T, E>, fn: (value: T) => U): Result<U, E> {\n if (isOk(result)) {\n return ok(fn(result.value));\n }\n return result;\n}\n\n/**\n * Maps a failed Result's error.\n *\n * @param result - The Result to map\n * @param fn - Function to transform the error\n * @returns A new Result with the transformed error, or the original value\n *\n * @example\n * ```ts\n * const result = err('not found');\n * const mapped = mapErr(result, (e) => new Error(e)); // err(Error('not found'))\n * ```\n */\nexport function mapErr<T, E, F>(result: Result<T, E>, fn: (error: E) => F): Result<T, F> {\n if (isErr(result)) {\n return err(fn(result.error));\n }\n return result;\n}\n\n/**\n * Chains Result-returning operations.\n *\n * @param result - The Result to chain from\n * @param fn - Function that returns a new Result\n * @returns The chained Result\n *\n * @example\n * ```ts\n * function parse(input: string): Result<number, string> {\n * const n = parseInt(input, 10);\n * return isNaN(n) ? err('not a number') : ok(n);\n * }\n *\n * function double(n: number): Result<number, string> {\n * return ok(n * 2);\n * }\n *\n * const result = flatMap(parse('5'), double); // ok(10)\n * const fail = flatMap(parse('abc'), double); // err('not a number')\n * ```\n */\nexport function flatMap<T, U, E>(\n result: Result<T, E>,\n fn: (value: T) => Result<U, E>\n): Result<U, E> {\n if (isOk(result)) {\n return fn(result.value);\n }\n return result;\n}\n\n// -----------------------------------------------------------------------------\n// Async Helpers\n// -----------------------------------------------------------------------------\n\n/**\n * Wraps a Promise in a Result type.\n *\n * @param promise - The Promise to wrap\n * @returns A Promise that resolves to a Result\n *\n * @example\n * ```ts\n * const result = await fromPromise(fetch('/api/data'));\n * if (isErr(result)) {\n * console.error('Fetch failed:', result.error);\n * return;\n * }\n * const response = result.value;\n * ```\n */\nexport async function fromPromise<T>(promise: Promise<T>): Promise<Result<T, Error>> {\n try {\n const value = await promise;\n return ok(value);\n } catch (error) {\n return err(error instanceof Error ? error : new Error(String(error)));\n }\n}\n\n/**\n * Wraps a throwing function in a Result type.\n *\n * @param fn - The function to wrap\n * @returns A Result containing the return value or the thrown error\n *\n * @example\n * ```ts\n * const result = tryCatch(() => JSON.parse(input));\n * if (isErr(result)) {\n * console.error('Invalid JSON:', result.error);\n * return null;\n * }\n * return result.value;\n * ```\n */\nexport function tryCatch<T>(fn: () => T): Result<T, Error> {\n try {\n return ok(fn());\n } catch (error) {\n return err(error instanceof Error ? error : new Error(String(error)));\n }\n}\n\n/**\n * Wraps an async function in a Result type.\n *\n * @param fn - The async function to wrap\n * @returns A Promise that resolves to a Result\n *\n * @example\n * ```ts\n * const result = await tryCatchAsync(async () => {\n * const response = await fetch('/api/data');\n * if (!response.ok) throw new Error(`HTTP ${response.status}`);\n * return response.json();\n * });\n * ```\n */\nexport async function tryCatchAsync<T>(fn: () => Promise<T>): Promise<Result<T, Error>> {\n try {\n const value = await fn();\n return ok(value);\n } catch (error) {\n return err(error instanceof Error ? error : new Error(String(error)));\n }\n}\n\n// -----------------------------------------------------------------------------\n// Tuple Helpers (Go-style)\n// -----------------------------------------------------------------------------\n\n/**\n * Go-style tuple for error handling: [error, value]\n *\n * @example\n * ```ts\n * const [err, data] = await handle(fetchData);\n * if (err) {\n * console.error(err);\n * return;\n * }\n * console.log(data);\n * ```\n */\nexport type GoTuple<T, E = Error> = [E, undefined] | [undefined, T];\n\n/**\n * Converts a Result to a Go-style tuple.\n *\n * @param result - The Result to convert\n * @returns A tuple of [error, value]\n *\n * @example\n * ```ts\n * const result = await fetchData();\n * const [err, data] = toTuple(result);\n * ```\n */\nexport function toTuple<T, E>(result: Result<T, E>): GoTuple<T, E> {\n if (isOk(result)) {\n return [undefined, result.value];\n }\n return [result.error, undefined];\n}\n\n/**\n * Wraps an async function and returns a Go-style tuple.\n *\n * @param fn - The async function to wrap\n * @returns A Promise that resolves to [error, value] tuple\n *\n * @example\n * ```ts\n * const [err, data] = await handle(async () => {\n * const res = await fetch('/api/users');\n * if (!res.ok) throw new Error(`HTTP ${res.status}`);\n * return res.json();\n * });\n *\n * if (err) {\n * console.error('Failed to fetch users:', err.message);\n * return [];\n * }\n * return data;\n * ```\n */\nexport async function handle<T>(fn: () => Promise<T>): Promise<GoTuple<T, Error>> {\n try {\n const value = await fn();\n return [undefined, value];\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n return [err, undefined];\n }\n}\n\n/**\n * Wraps a synchronous function and returns a Go-style tuple.\n *\n * @param fn - The function to wrap\n * @returns A tuple of [error, value]\n *\n * @example\n * ```ts\n * const [err, parsed] = handleSync(() => JSON.parse(input));\n * if (err) {\n * console.error('Invalid JSON:', err.message);\n * return null;\n * }\n * return parsed;\n * ```\n */\nexport function handleSync<T>(fn: () => T): GoTuple<T, Error> {\n try {\n const value = fn();\n return [undefined, value];\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n return [err, undefined];\n }\n}\n"],"mappings":";AAaA,SAAS,gBAAgB;;;ACTzB,IAAM,oBAAoB,CAAC,eAAe,aAAa,OAAO;AAE9D,IAAM,sBAAsB;AAAA,EAC1B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,SAAS,iBAAiB,IAAqB;AAC7C,SAAO,OAAO,OAAO,OAAO,OAAQ,OAAO,QAAQ,OAAO,QAAQ,OAAO,QAAQ,OAAO;AAC1F;AAEA,SAAS,gCAAgC,KAAqB;AAC5D,MAAI,SAAS;AACb,MAAI,QAAQ,OAAO,YAAY;AAE/B,aAAW,UAAU,mBAAmB;AACtC,UAAM,cAAc,OAAO,YAAY;AACvC,QAAI,QAAQ,MAAM,QAAQ,WAAW;AAErC,WAAO,UAAU,IAAI;AACnB,YAAM,aAAa,UAAU;AAC7B,YAAM,iBACJ,QAAQ,MACP,iBAAiB,OAAO,OAAO,QAAQ,CAAC,CAAC,KAAK,OAAO,OAAO,QAAQ,CAAC,M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