doccupine 0.0.140 → 0.0.142
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -7
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +191 -0
- package/dist/index.d.ts +3 -7
- package/dist/index.js +5 -1894
- package/dist/lib/config-manager.d.ts +1 -0
- package/dist/lib/config-manager.js +63 -3
- package/dist/lib/generated-artifacts.d.ts +26 -0
- package/dist/lib/generated-artifacts.js +147 -0
- package/dist/lib/layout.js +30 -30
- package/dist/lib/metadata.js +58 -30
- package/dist/lib/openapi-types.d.ts +2 -2
- package/dist/lib/openapi.d.ts +6 -3
- package/dist/lib/openapi.js +330 -50
- package/dist/lib/output-safety.d.ts +15 -0
- package/dist/lib/output-safety.js +428 -0
- package/dist/lib/structures.js +11 -0
- package/dist/lib/utils.d.ts +10 -5
- package/dist/lib/utils.js +108 -5
- package/dist/mdx-to-nextjs-generator.d.ts +166 -0
- package/dist/mdx-to-nextjs-generator.js +2229 -0
- package/dist/templates/app/api/gate/route.d.ts +1 -1
- package/dist/templates/app/api/gate/route.js +18 -6
- package/dist/templates/app/api/mcp/route.d.ts +1 -1
- package/dist/templates/app/api/mcp/route.js +181 -111
- package/dist/templates/app/api/playground/route.d.ts +1 -1
- package/dist/templates/app/api/playground/route.js +45 -13
- package/dist/templates/app/api/rag/route.d.ts +1 -1
- package/dist/templates/app/api/rag/route.js +72 -20
- package/dist/templates/app/api/search/route.d.ts +1 -1
- package/dist/templates/app/api/search/route.js +5 -0
- package/dist/templates/app/robots.d.ts +1 -1
- package/dist/templates/app/robots.js +1 -26
- package/dist/templates/app/theme.d.ts +1 -1
- package/dist/templates/app/theme.js +31 -19
- package/dist/templates/components/Chat.d.ts +1 -1
- package/dist/templates/components/Chat.js +342 -34
- package/dist/templates/components/SearchDocs.d.ts +1 -1
- package/dist/templates/components/SearchDocs.js +63 -11
- package/dist/templates/components/SearchModalContent.d.ts +1 -1
- package/dist/templates/components/SearchModalContent.js +191 -49
- package/dist/templates/components/SideBar.d.ts +1 -1
- package/dist/templates/components/SideBar.js +8 -2
- package/dist/templates/components/layout/Accordion.d.ts +1 -1
- package/dist/templates/components/layout/Accordion.js +26 -3
- package/dist/templates/components/layout/Badge.d.ts +1 -1
- package/dist/templates/components/layout/Badge.js +1 -1
- package/dist/templates/components/layout/Button.d.ts +1 -1
- package/dist/templates/components/layout/Button.js +4 -4
- package/dist/templates/components/layout/Callout.d.ts +1 -1
- package/dist/templates/components/layout/Callout.js +6 -6
- package/dist/templates/components/layout/Card.d.ts +1 -1
- package/dist/templates/components/layout/Card.js +9 -4
- package/dist/templates/components/layout/CherryThemeProvider.d.ts +1 -1
- package/dist/templates/components/layout/CherryThemeProvider.js +63 -12
- package/dist/templates/components/layout/Code.d.ts +1 -1
- package/dist/templates/components/layout/Code.js +5 -5
- package/dist/templates/components/layout/CopyButton.d.ts +1 -1
- package/dist/templates/components/layout/CopyButton.js +1 -1
- package/dist/templates/components/layout/DemoTheme.d.ts +1 -1
- package/dist/templates/components/layout/DemoTheme.js +8 -28
- package/dist/templates/components/layout/DocsComponents.d.ts +1 -1
- package/dist/templates/components/layout/DocsComponents.js +57 -6
- package/dist/templates/components/layout/GlobalStyles.d.ts +1 -1
- package/dist/templates/components/layout/GlobalStyles.js +15 -9
- package/dist/templates/components/layout/Prompt.d.ts +1 -1
- package/dist/templates/components/layout/Prompt.js +4 -7
- package/dist/templates/components/layout/Steps.d.ts +1 -1
- package/dist/templates/components/layout/Steps.js +7 -1
- package/dist/templates/components/layout/Tabs.d.ts +1 -1
- package/dist/templates/components/layout/Tabs.js +108 -19
- package/dist/templates/env.example.d.ts +1 -1
- package/dist/templates/env.example.js +11 -0
- package/dist/templates/eslint.config.d.ts +1 -1
- package/dist/templates/eslint.config.js +20 -0
- package/dist/templates/gitignore.d.ts +1 -1
- package/dist/templates/gitignore.js +4 -3
- package/dist/templates/lib/access.d.ts +1 -0
- package/dist/templates/lib/access.js +41 -0
- package/dist/templates/mdx/ai-assistant.mdx.d.ts +1 -1
- package/dist/templates/mdx/ai-assistant.mdx.js +17 -1
- package/dist/templates/mdx/api-playground.mdx.d.ts +1 -1
- package/dist/templates/mdx/api-playground.mdx.js +5 -3
- package/dist/templates/mdx/authentication.mdx.d.ts +1 -1
- package/dist/templates/mdx/authentication.mdx.js +5 -3
- package/dist/templates/mdx/commands.mdx.d.ts +1 -1
- package/dist/templates/mdx/commands.mdx.js +20 -6
- package/dist/templates/mdx/components.mdx.d.ts +1 -1
- package/dist/templates/mdx/components.mdx.js +3 -0
- package/dist/templates/mdx/deployment-and-hosting.mdx.d.ts +1 -1
- package/dist/templates/mdx/deployment-and-hosting.mdx.js +2 -2
- package/dist/templates/mdx/globals.mdx.d.ts +1 -1
- package/dist/templates/mdx/globals.mdx.js +14 -11
- package/dist/templates/mdx/model-context-protocol.mdx.d.ts +1 -1
- package/dist/templates/mdx/model-context-protocol.mdx.js +22 -35
- package/dist/templates/mdx/platform/ai-assistant.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/ai-assistant.mdx.js +23 -0
- package/dist/templates/mdx/platform/api-playground.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/api-playground.mdx.js +7 -0
- package/dist/templates/mdx/platform/authentication.mdx.d.ts +1 -0
- package/dist/templates/mdx/platform/authentication.mdx.js +63 -0
- package/dist/templates/mdx/platform/import-from-github.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/import-from-github.mdx.js +2 -2
- package/dist/templates/mdx/platform/index.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/index.mdx.js +1 -0
- package/dist/templates/mdx/platform/mcp.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/mcp.mdx.js +2 -1
- package/dist/templates/mdx/platform/navigation-settings.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/navigation-settings.mdx.js +12 -1
- package/dist/templates/mdx/platform/publishing.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/publishing.mdx.js +43 -10
- package/dist/templates/mdx/platform/self-updating-docs.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/self-updating-docs.mdx.js +48 -9
- package/dist/templates/mdx/sections.mdx.d.ts +1 -1
- package/dist/templates/mdx/sections.mdx.js +4 -0
- package/dist/templates/mdx/space.mdx.d.ts +1 -0
- package/dist/templates/mdx/space.mdx.js +125 -0
- package/dist/templates/mdx/tabs.mdx.d.ts +1 -1
- package/dist/templates/mdx/tabs.mdx.js +4 -0
- package/dist/templates/next.config.js +20 -8
- package/dist/templates/package.js +3 -3
- package/dist/templates/prettierignore.d.ts +1 -1
- package/dist/templates/prettierignore.js +1 -0
- package/dist/templates/proxy.js +47 -19
- package/dist/templates/scripts/build-docs-index.d.ts +1 -1
- package/dist/templates/scripts/build-docs-index.js +1 -0
- package/dist/templates/services/mcp/docsContentStub.d.ts +1 -0
- package/dist/templates/services/mcp/docsContentStub.js +1 -0
- package/dist/templates/services/mcp/server.d.ts +1 -1
- package/dist/templates/services/mcp/server.js +140 -83
- package/dist/templates/services/mcp/tools.d.ts +1 -1
- package/dist/templates/services/mcp/tools.js +65 -137
- package/dist/templates/utils/playgroundAllowlist.d.ts +1 -1
- package/dist/templates/utils/playgroundAllowlist.js +13 -4
- package/dist/templates/utils/rateLimit.d.ts +1 -1
- package/dist/templates/utils/rateLimit.js +40 -3
- package/dist/templates/utils/requestBody.d.ts +1 -0
- package/dist/templates/utils/requestBody.js +56 -0
- package/dist/templates/utils/ssrfGuard.d.ts +1 -1
- package/dist/templates/utils/ssrfGuard.js +138 -33
- package/package.json +13 -5
- package/dist/lib/mdxToMarkdown.d.ts +0 -1
- package/dist/lib/mdxToMarkdown.js +0 -134
- package/dist/templates/mdx/image-and-embeds.mdx.d.ts +0 -1
- package/dist/templates/mdx/image-and-embeds.mdx.js +0 -118
|
@@ -2,6 +2,7 @@ export const rateLimitTemplate = `const rateLimitMap = new Map<string, { count:
|
|
|
2
2
|
|
|
3
3
|
const WINDOW_MS = 60_000; // 1 minute
|
|
4
4
|
const MAX_REQUESTS = 10;
|
|
5
|
+
const MAX_TRACKED_CLIENTS = 10_000;
|
|
5
6
|
|
|
6
7
|
// Clean up stale entries periodically
|
|
7
8
|
const CLEANUP_INTERVAL_MS = 5 * 60_000;
|
|
@@ -18,17 +19,53 @@ function cleanup() {
|
|
|
18
19
|
});
|
|
19
20
|
}
|
|
20
21
|
|
|
21
|
-
|
|
22
|
+
function validClientAddress(value: string | null): string | null {
|
|
23
|
+
const candidate = value?.split(",")[0]?.trim();
|
|
24
|
+
return candidate && /^[0-9a-f:.]{3,64}$/i.test(candidate) ? candidate : null;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Web Request does not expose the peer address. Trust an IP header only when
|
|
29
|
+
* the runtime identifies a platform that overwrites that specific header.
|
|
30
|
+
* Self-hosted deployments fall back to one shared bucket and should enforce a
|
|
31
|
+
* stronger distributed rate limit at their trusted reverse proxy.
|
|
32
|
+
*/
|
|
33
|
+
function clientIdentity(request: Request): string {
|
|
34
|
+
let platform = "";
|
|
35
|
+
let address: string | null = null;
|
|
36
|
+
|
|
37
|
+
if (process.env.VERCEL === "1") {
|
|
38
|
+
platform = "vercel";
|
|
39
|
+
address = validClientAddress(request.headers.get("x-vercel-forwarded-for"));
|
|
40
|
+
} else if (process.env.CF_PAGES === "1") {
|
|
41
|
+
platform = "cloudflare";
|
|
42
|
+
address = validClientAddress(request.headers.get("cf-connecting-ip"));
|
|
43
|
+
} else if (process.env.FLY_APP_NAME) {
|
|
44
|
+
platform = "fly";
|
|
45
|
+
address = validClientAddress(request.headers.get("fly-client-ip"));
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
return address ? \`\${platform}:\${address}\` : "shared:untrusted-proxy";
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function rateLimit(request: Request): {
|
|
22
52
|
allowed: boolean;
|
|
23
53
|
retryAfter: number;
|
|
24
54
|
} {
|
|
25
55
|
cleanup();
|
|
26
56
|
|
|
27
57
|
const now = Date.now();
|
|
28
|
-
const
|
|
58
|
+
const identity = clientIdentity(request);
|
|
59
|
+
const entry = rateLimitMap.get(identity);
|
|
29
60
|
|
|
30
61
|
if (!entry || now > entry.resetTime) {
|
|
31
|
-
|
|
62
|
+
// Bound memory even when an attacker rotates spoofed forwarding headers.
|
|
63
|
+
// Map iteration is insertion ordered, so remove the oldest tracked client.
|
|
64
|
+
if (rateLimitMap.size >= MAX_TRACKED_CLIENTS) {
|
|
65
|
+
const oldestKey = rateLimitMap.keys().next().value;
|
|
66
|
+
if (oldestKey !== undefined) rateLimitMap.delete(oldestKey);
|
|
67
|
+
}
|
|
68
|
+
rateLimitMap.set(identity, { count: 1, resetTime: now + WINDOW_MS });
|
|
32
69
|
return { allowed: true, retryAfter: 0 };
|
|
33
70
|
}
|
|
34
71
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const requestBodyTemplate = "export class RequestTooLargeError extends Error {}\n\nexport async function readJsonBody(\n req: Request,\n maxBytes: number,\n): Promise<unknown> {\n const contentLength = req.headers.get(\"content-length\");\n if (contentLength !== null && Number(contentLength) > maxBytes) {\n throw new RequestTooLargeError();\n }\n\n req.signal.throwIfAborted();\n if (!req.body) throw new SyntaxError(\"Missing body\");\n\n const reader = req.body.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n const abortRead = () => {\n void reader.cancel(req.signal.reason).catch(() => {});\n };\n req.signal.addEventListener(\"abort\", abortRead, { once: true });\n\n try {\n while (true) {\n req.signal.throwIfAborted();\n const { done, value } = await reader.read();\n req.signal.throwIfAborted();\n if (done) break;\n\n size += value.byteLength;\n if (size > maxBytes) {\n try {\n await reader.cancel();\n } catch {\n // The request may have been aborted while the oversized body arrived.\n }\n throw new RequestTooLargeError();\n }\n chunks.push(value);\n }\n\n const bytes = new Uint8Array(size);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n\n const text = new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n return JSON.parse(text);\n } finally {\n req.signal.removeEventListener(\"abort\", abortRead);\n reader.releaseLock();\n }\n}\n";
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
export const requestBodyTemplate = `export class RequestTooLargeError extends Error {}
|
|
2
|
+
|
|
3
|
+
export async function readJsonBody(
|
|
4
|
+
req: Request,
|
|
5
|
+
maxBytes: number,
|
|
6
|
+
): Promise<unknown> {
|
|
7
|
+
const contentLength = req.headers.get("content-length");
|
|
8
|
+
if (contentLength !== null && Number(contentLength) > maxBytes) {
|
|
9
|
+
throw new RequestTooLargeError();
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
req.signal.throwIfAborted();
|
|
13
|
+
if (!req.body) throw new SyntaxError("Missing body");
|
|
14
|
+
|
|
15
|
+
const reader = req.body.getReader();
|
|
16
|
+
const chunks: Uint8Array[] = [];
|
|
17
|
+
let size = 0;
|
|
18
|
+
const abortRead = () => {
|
|
19
|
+
void reader.cancel(req.signal.reason).catch(() => {});
|
|
20
|
+
};
|
|
21
|
+
req.signal.addEventListener("abort", abortRead, { once: true });
|
|
22
|
+
|
|
23
|
+
try {
|
|
24
|
+
while (true) {
|
|
25
|
+
req.signal.throwIfAborted();
|
|
26
|
+
const { done, value } = await reader.read();
|
|
27
|
+
req.signal.throwIfAborted();
|
|
28
|
+
if (done) break;
|
|
29
|
+
|
|
30
|
+
size += value.byteLength;
|
|
31
|
+
if (size > maxBytes) {
|
|
32
|
+
try {
|
|
33
|
+
await reader.cancel();
|
|
34
|
+
} catch {
|
|
35
|
+
// The request may have been aborted while the oversized body arrived.
|
|
36
|
+
}
|
|
37
|
+
throw new RequestTooLargeError();
|
|
38
|
+
}
|
|
39
|
+
chunks.push(value);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const bytes = new Uint8Array(size);
|
|
43
|
+
let offset = 0;
|
|
44
|
+
for (const chunk of chunks) {
|
|
45
|
+
bytes.set(chunk, offset);
|
|
46
|
+
offset += chunk.byteLength;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
50
|
+
return JSON.parse(text);
|
|
51
|
+
} finally {
|
|
52
|
+
req.signal.removeEventListener("abort", abortRead);
|
|
53
|
+
reader.releaseLock();
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const ssrfGuardTemplate = "// SERVER-ONLY. Imported solely by app/api/playground/route.ts (a route handler,\n// which never ships to the client). Performs SSRF-safe outbound requests for\n// the API playground proxy: it resolves the target host, rejects any address in\n// a private/loopback/link-local/metadata range, and pins the connection to the\n// pre-validated IPs so DNS rebinding between check and connect cannot redirect\n// the socket to an internal address.\n\nimport dns from \"node:dns/promises\";\nimport net from \"node:net\";\nimport http from \"node:http\";\nimport https from \"node:https\";\nimport type { LookupAddress } from \"node:dns\";\nimport type { LookupFunction } from \"node:net\";\nimport type { AllowlistEntry } from \"@/utils/playgroundAllowlist\";\n\nexport class BlockedError extends Error {\n constructor(public reason: string) {\n super(reason);\n this.name = \"BlockedError\";\n }\n}\n\nexport interface GuardedInit {\n method: string;\n headers: Record<string, string>;\n body?: Buffer;\n timeoutMs: number;\n maxBytes: number;\n}\n\nexport interface GuardedResult {\n status: number;\n statusText: string;\n headers: Record<string, string>;\n body: Buffer;\n truncated: boolean;\n durationMs: number;\n}\n\nfunction isBlockedIpv4(ip: string): boolean {\n const parts = ip.split(\".\");\n if (parts.length !== 4) return true;\n const nums = parts.map((p) => Number(p));\n if (nums.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return true;\n const a = nums[0];\n const b = nums[1];\n const c = nums[2];\n if (a === 0 || a === 10 || a === 127) return true;\n if (a === 169 && b === 254) return true; // link-local incl. metadata\n if (a === 172 && b >= 16 && b <= 31) return true;\n if (a === 192 && b === 168) return true;\n if (a === 192 && b === 0 && c === 0) return true;\n if (a === 100 && b >= 64 && b <= 127) return true; // CGNAT\n if (a === 198 && (b === 18 || b === 19)) return true; // benchmarking\n if (a >= 224) return true; // multicast + reserved + broadcast\n return false;\n}\n\nfunction isBlockedIpv6(ip: string): boolean {\n const clean = ip.toLowerCase().split(\"%\")[0];\n if (clean === \"::\" || clean === \"::1\") return true;\n if (clean.startsWith(\"::ffff:\")) {\n const rest = clean.slice(\"::ffff:\".length);\n if (rest.includes(\".\")) return isBlockedIpv4(rest);\n const segs = rest.split(\":\");\n if (segs.length === 2) {\n const hi = parseInt(segs[0], 16);\n const lo = parseInt(segs[1], 16);\n if (Number.isInteger(hi) && Number.isInteger(lo)) {\n const v4 = [(hi >> 8) & 255, hi & 255, (lo >> 8) & 255, lo & 255].join(\n \".\",\n );\n return isBlockedIpv4(v4);\n }\n }\n }\n const head = clean.split(\":\")[0];\n if (\n head.startsWith(\"fe8\") ||\n head.startsWith(\"fe9\") ||\n head.startsWith(\"fea\") ||\n head.startsWith(\"feb\")\n ) {\n return true; // link-local fe80::/10\n }\n if (head.startsWith(\"fc\") || head.startsWith(\"fd\")) return true; // unique-local\n return false;\n}\n\nfunction isBlockedIp(ip: string): boolean {\n const type = net.isIP(ip);\n if (type === 4) return isBlockedIpv4(ip);\n if (type === 6) return isBlockedIpv6(ip);\n return true; // not a parseable IP -> fail closed\n}\n\nfunction flattenHeaders(\n headers: http.IncomingHttpHeaders,\n): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [key, value] of Object.entries(headers)) {\n if (value === undefined) continue;\n out[key.toLowerCase()] = Array.isArray(value) ? value.join(\", \") : value;\n }\n return out;\n}\n\nexport async function guardedFetch(\n targetUrl: string,\n entry: AllowlistEntry,\n init: GuardedInit,\n): Promise<GuardedResult> {\n const url = new URL(targetUrl);\n let host = url.hostname.toLowerCase();\n if (host.endsWith(\".\")) host = host.slice(0, -1);\n\n const literalType = net.isIP(host);\n let validated: LookupAddress[];\n\n if (literalType !== 0) {\n // Raw-IP target: only allowed if the spec itself declared this host, and\n // only into a private range when it opted in via allowPrivate.\n if (isBlockedIp(host) && !entry.allowPrivate) {\n throw new BlockedError(\"blocked: private IP-literal target\");\n }\n validated = [{ address: host, family: literalType }];\n } else {\n let records: LookupAddress[];\n try {\n records = await dns.lookup(host, { all: true, verbatim: true });\n } catch {\n throw new BlockedError(\"blocked: DNS resolution failed\");\n }\n if (records.length === 0) throw new BlockedError(\"blocked: no DNS records\");\n if (!entry.allowPrivate) {\n for (const record of records) {\n if (isBlockedIp(record.address)) {\n throw new BlockedError(\"blocked: private IP\");\n }\n }\n }\n validated = records;\n }\n\n const isHttps = url.protocol === \"https:\";\n const transport = isHttps ? https : http;\n\n // Pin resolution to the addresses we just validated so a re-resolution\n // between check and connect (DNS rebinding) cannot swap in a private IP.\n const lookup: LookupFunction = (_hostname, options, callback) => {\n if (options && options.all) {\n callback(null, validated);\n } else {\n callback(null, validated[0].address, validated[0].family);\n }\n };\n\n const requestOptions: https.RequestOptions = {\n method: init.method,\n headers: init.headers,\n lookup,\n timeout: init.timeoutMs,\n };\n\n return await new Promise<GuardedResult>((resolve, reject) => {\n const start = Date.now();\n let settled = false;\n const done = (fn: () => void) => {\n if (settled) return;\n settled = true;\n fn();\n };\n\n const req = transport.request(url, requestOptions, (res) => {\n const chunks: Buffer[] = [];\n let received = 0;\n let truncated = false;\n\n res.on(\"data\", (chunk: Buffer) => {\n received += chunk.length;\n if (received > init.maxBytes) {\n truncated = true;\n res.destroy();\n return;\n }\n chunks.push(chunk);\n });\n\n const finish = () =>\n done(() =>\n resolve({\n status: res.statusCode ?? 0,\n statusText: res.statusMessage ?? \"\",\n headers: flattenHeaders(res.headers),\n body: Buffer.concat(chunks),\n truncated,\n durationMs: Date.now() - start,\n }),\n );\n\n res.on(\"end\", finish);\n res.on(\"close\", finish);\n res.on(\"error\", () => done(() => reject(new Error(\"stream error\"))));\n });\n\n req.on(\"timeout\", () => {\n req.destroy(new Error(\"timeout\"));\n });\n req.on(\"error\", (err) => done(() => reject(err)));\n\n if (init.body && init.method !== \"GET\" && init.method !== \"HEAD\") {\n req.write(init.body);\n }\n req.end();\n });\n}\n";
|
|
1
|
+
export declare const ssrfGuardTemplate = "// SERVER-ONLY. Imported solely by app/api/playground/route.ts (a route handler,\n// which never ships to the client). Performs SSRF-safe outbound requests for\n// the API playground proxy: it resolves the target host, rejects any address in\n// a private/loopback/link-local/metadata range, and pins the connection to the\n// pre-validated IPs so DNS rebinding between check and connect cannot redirect\n// the socket to an internal address.\n\nimport dns from \"node:dns/promises\";\nimport net from \"node:net\";\nimport http from \"node:http\";\nimport https from \"node:https\";\nimport type { LookupAddress } from \"node:dns\";\nimport type { LookupFunction } from \"node:net\";\nimport type { AllowlistEntry } from \"@/utils/playgroundAllowlist\";\n\nexport class BlockedError extends Error {\n constructor(public reason: string) {\n super(reason);\n this.name = \"BlockedError\";\n }\n}\n\nexport interface GuardedInit {\n method: string;\n headers: Record<string, string>;\n body?: Buffer;\n timeoutMs: number;\n maxBytes: number;\n}\n\nexport interface GuardedResult {\n status: number;\n statusText: string;\n headers: Record<string, string>;\n body: Buffer;\n truncated: boolean;\n durationMs: number;\n}\n\nfunction parseIpv4(ip: string): number[] | null {\n const parts = ip.split(\".\");\n if (parts.length !== 4) return null;\n const nums = parts.map((p) => Number(p));\n if (nums.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return null;\n return nums;\n}\n\nfunction isBlockedIpv4(ip: string): boolean {\n const nums = parseIpv4(ip);\n if (!nums) return true;\n const a = nums[0];\n const b = nums[1];\n const c = nums[2];\n if (a === 0 || a === 10 || a === 127) return true;\n if (a === 169 && b === 254) return true; // link-local incl. metadata\n if (a === 172 && b >= 16 && b <= 31) return true;\n if (a === 192 && b === 168) return true;\n if (a === 192 && b === 0 && c === 0) return true;\n if (a === 100 && b >= 64 && b <= 127) return true; // CGNAT\n if (a === 198 && (b === 18 || b === 19)) return true; // benchmarking\n if (a >= 224) return true; // multicast + reserved + broadcast\n return false;\n}\n\nfunction parseIpv6Words(ip: string): number[] | null {\n let clean = ip.toLowerCase().split(\"%\")[0];\n if (clean.includes(\".\")) {\n const separator = clean.lastIndexOf(\":\");\n const ipv4 = parseIpv4(clean.slice(separator + 1));\n if (separator < 0 || !ipv4) return null;\n clean =\n clean.slice(0, separator) +\n \":\" +\n ((ipv4[0] << 8) | ipv4[1]).toString(16) +\n \":\" +\n ((ipv4[2] << 8) | ipv4[3]).toString(16);\n }\n\n const halves = clean.split(\"::\");\n if (halves.length > 2) return null;\n const parseHalf = (half: string): number[] | null => {\n if (!half) return [];\n const segments = half.split(\":\");\n if (segments.some((segment) => !/^[0-9a-f]{1,4}$/.test(segment))) {\n return null;\n }\n return segments.map((segment) => parseInt(segment, 16));\n };\n const left = parseHalf(halves[0]);\n const right = parseHalf(halves[1] ?? \"\");\n if (!left || !right) return null;\n\n if (halves.length === 1) return left.length === 8 ? left : null;\n const omitted = 8 - left.length - right.length;\n if (omitted < 1) return null;\n return [...left, ...Array(omitted).fill(0), ...right];\n}\n\nfunction ipv4FromWords(words: number[]): string {\n return [words[6] >> 8, words[6] & 255, words[7] >> 8, words[7] & 255].join(\n \".\",\n );\n}\n\nfunction translatedIpv4(words: number[]): string | null {\n const firstFourZero = words.slice(0, 4).every((word) => word === 0);\n const firstFiveZero = firstFourZero && words[4] === 0;\n\n // IPv4-compatible (::/96), mapped (::ffff:0:0/96), and translated\n // (::ffff:0:0:0/96) forms all carry the IPv4 address in the final 32 bits.\n if (\n (firstFiveZero && (words[5] === 0 || words[5] === 0xffff)) ||\n (firstFourZero && words[4] === 0xffff && words[5] === 0)\n ) {\n return ipv4FromWords(words);\n }\n\n // RFC 6052 well-known NAT64 prefix 64:ff9b::/96.\n if (\n words[0] === 0x64 &&\n words[1] === 0xff9b &&\n words.slice(2, 6).every((word) => word === 0)\n ) {\n return ipv4FromWords(words);\n }\n\n return null;\n}\n\nfunction isNat64LocalUse(words: number[]): boolean {\n // RFC 8215 reserves the entire 64:ff9b:1::/48 prefix for local translation.\n return words[0] === 0x64 && words[1] === 0xff9b && words[2] === 1;\n}\n\nfunction isBlockedIpv6(ip: string): boolean {\n const words = parseIpv6Words(ip);\n if (!words) return true;\n if (isNat64LocalUse(words)) return true;\n\n const translated = translatedIpv4(words);\n if (translated) return isBlockedIpv4(translated);\n\n const allZero = words.every((word) => word === 0);\n const loopback =\n words.slice(0, 7).every((word) => word === 0) && words[7] === 1;\n if (allZero || loopback) return true;\n\n const head = words[0];\n if ((head & 0xffc0) === 0xfe80 || (head & 0xffc0) === 0xfec0) {\n return true; // link-local fe80::/10 + deprecated site-local fec0::/10\n }\n if ((head & 0xfe00) === 0xfc00) return true; // unique-local fc00::/7\n if ((head & 0xff00) === 0xff00) return true; // multicast ff00::/8\n return false;\n}\n\nexport function isBlockedIp(ip: string): boolean {\n const type = net.isIP(ip);\n if (type === 4) return isBlockedIpv4(ip);\n if (type === 6) return isBlockedIpv6(ip);\n return true; // not a parseable IP -> fail closed\n}\n\n/**\n * Ranges that remain blocked even for an explicitly loopback-enabled entry.\n * In particular, link-local addresses include cloud instance metadata services\n * and must never become reachable through an imported OpenAPI document.\n */\nfunction isAlwaysBlockedIpv4(ip: string): boolean {\n const nums = parseIpv4(ip);\n if (!nums) return true;\n const [a, b] = nums;\n return a === 0 || (a === 169 && b === 254) || a >= 224;\n}\n\nexport function isAlwaysBlockedIp(ip: string): boolean {\n const type = net.isIP(ip);\n if (type === 4) return isAlwaysBlockedIpv4(ip);\n if (type === 6) {\n const words = parseIpv6Words(ip);\n if (!words || isNat64LocalUse(words)) return true;\n const translated = translatedIpv4(words);\n if (translated) return isAlwaysBlockedIpv4(translated);\n\n const head = words[0];\n return (\n words.every((word) => word === 0) ||\n (head & 0xffc0) === 0xfe80 ||\n (head & 0xffc0) === 0xfec0 ||\n (head & 0xff00) === 0xff00\n );\n }\n return true;\n}\n\nfunction flattenHeaders(\n headers: http.IncomingHttpHeaders,\n): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [key, value] of Object.entries(headers)) {\n if (value === undefined) continue;\n out[key.toLowerCase()] = Array.isArray(value) ? value.join(\", \") : value;\n }\n return out;\n}\n\nexport async function guardedFetch(\n targetUrl: string,\n entry: AllowlistEntry,\n init: GuardedInit,\n): Promise<GuardedResult> {\n const url = new URL(targetUrl);\n let host = url.hostname.toLowerCase();\n if (host.endsWith(\".\")) host = host.slice(0, -1);\n host = host.replace(/^\\[|\\]$/g, \"\");\n\n const literalType = net.isIP(host);\n let validated: LookupAddress[];\n // Loopback opt-in exists only for local development. Production always\n // applies the complete private-address block regardless of generated data.\n const allowPrivate =\n process.env.NODE_ENV !== \"production\" && entry.allowPrivate === true;\n\n if (literalType !== 0) {\n // Raw-IP target: only allowed if the spec itself declared this host, and\n // only into a private range when it opted in via allowPrivate.\n if (isAlwaysBlockedIp(host) || (isBlockedIp(host) && !allowPrivate)) {\n throw new BlockedError(\"blocked: private IP-literal target\");\n }\n validated = [{ address: host, family: literalType }];\n } else {\n let records: LookupAddress[];\n try {\n records = await dns.lookup(host, { all: true, verbatim: true });\n } catch {\n throw new BlockedError(\"blocked: DNS resolution failed\");\n }\n if (records.length === 0) throw new BlockedError(\"blocked: no DNS records\");\n for (const record of records) {\n if (\n isAlwaysBlockedIp(record.address) ||\n (isBlockedIp(record.address) && !allowPrivate)\n ) {\n throw new BlockedError(\"blocked: private IP\");\n }\n }\n validated = records;\n }\n\n const isHttps = url.protocol === \"https:\";\n const transport = isHttps ? https : http;\n\n // Pin resolution to the addresses we just validated so a re-resolution\n // between check and connect (DNS rebinding) cannot swap in a private IP.\n const lookup: LookupFunction = (_hostname, options, callback) => {\n if (options && options.all) {\n callback(null, validated);\n } else {\n callback(null, validated[0].address, validated[0].family);\n }\n };\n\n const requestOptions: https.RequestOptions = {\n method: init.method,\n headers: init.headers,\n lookup,\n timeout: init.timeoutMs,\n };\n\n return await new Promise<GuardedResult>((resolve, reject) => {\n const start = Date.now();\n let settled = false;\n const done = (fn: () => void) => {\n if (settled) return;\n settled = true;\n fn();\n };\n\n const req = transport.request(url, requestOptions, (res) => {\n const chunks: Buffer[] = [];\n let received = 0;\n let truncated = false;\n\n res.on(\"data\", (chunk: Buffer) => {\n received += chunk.length;\n if (received > init.maxBytes) {\n truncated = true;\n res.destroy();\n return;\n }\n chunks.push(chunk);\n });\n\n const finish = () =>\n done(() =>\n resolve({\n status: res.statusCode ?? 0,\n statusText: res.statusMessage ?? \"\",\n headers: flattenHeaders(res.headers),\n body: Buffer.concat(chunks),\n truncated,\n durationMs: Date.now() - start,\n }),\n );\n\n res.on(\"end\", finish);\n res.on(\"close\", finish);\n res.on(\"error\", () => done(() => reject(new Error(\"stream error\"))));\n });\n\n req.on(\"timeout\", () => {\n req.destroy(new Error(\"timeout\"));\n });\n req.on(\"error\", (err) => done(() => reject(err)));\n\n if (init.body && init.method !== \"GET\" && init.method !== \"HEAD\") {\n req.write(init.body);\n }\n req.end();\n });\n}\n";
|
|
@@ -37,11 +37,17 @@ export interface GuardedResult {
|
|
|
37
37
|
durationMs: number;
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
-
function
|
|
40
|
+
function parseIpv4(ip: string): number[] | null {
|
|
41
41
|
const parts = ip.split(".");
|
|
42
|
-
if (parts.length !== 4) return
|
|
42
|
+
if (parts.length !== 4) return null;
|
|
43
43
|
const nums = parts.map((p) => Number(p));
|
|
44
|
-
if (nums.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return
|
|
44
|
+
if (nums.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return null;
|
|
45
|
+
return nums;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function isBlockedIpv4(ip: string): boolean {
|
|
49
|
+
const nums = parseIpv4(ip);
|
|
50
|
+
if (!nums) return true;
|
|
45
51
|
const a = nums[0];
|
|
46
52
|
const b = nums[1];
|
|
47
53
|
const c = nums[2];
|
|
@@ -56,44 +62,137 @@ function isBlockedIpv4(ip: string): boolean {
|
|
|
56
62
|
return false;
|
|
57
63
|
}
|
|
58
64
|
|
|
59
|
-
function
|
|
60
|
-
|
|
61
|
-
if (clean
|
|
62
|
-
|
|
63
|
-
const
|
|
64
|
-
if (
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
65
|
+
function parseIpv6Words(ip: string): number[] | null {
|
|
66
|
+
let clean = ip.toLowerCase().split("%")[0];
|
|
67
|
+
if (clean.includes(".")) {
|
|
68
|
+
const separator = clean.lastIndexOf(":");
|
|
69
|
+
const ipv4 = parseIpv4(clean.slice(separator + 1));
|
|
70
|
+
if (separator < 0 || !ipv4) return null;
|
|
71
|
+
clean =
|
|
72
|
+
clean.slice(0, separator) +
|
|
73
|
+
":" +
|
|
74
|
+
((ipv4[0] << 8) | ipv4[1]).toString(16) +
|
|
75
|
+
":" +
|
|
76
|
+
((ipv4[2] << 8) | ipv4[3]).toString(16);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const halves = clean.split("::");
|
|
80
|
+
if (halves.length > 2) return null;
|
|
81
|
+
const parseHalf = (half: string): number[] | null => {
|
|
82
|
+
if (!half) return [];
|
|
83
|
+
const segments = half.split(":");
|
|
84
|
+
if (segments.some((segment) => !/^[0-9a-f]{1,4}$/.test(segment))) {
|
|
85
|
+
return null;
|
|
75
86
|
}
|
|
87
|
+
return segments.map((segment) => parseInt(segment, 16));
|
|
88
|
+
};
|
|
89
|
+
const left = parseHalf(halves[0]);
|
|
90
|
+
const right = parseHalf(halves[1] ?? "");
|
|
91
|
+
if (!left || !right) return null;
|
|
92
|
+
|
|
93
|
+
if (halves.length === 1) return left.length === 8 ? left : null;
|
|
94
|
+
const omitted = 8 - left.length - right.length;
|
|
95
|
+
if (omitted < 1) return null;
|
|
96
|
+
return [...left, ...Array(omitted).fill(0), ...right];
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function ipv4FromWords(words: number[]): string {
|
|
100
|
+
return [words[6] >> 8, words[6] & 255, words[7] >> 8, words[7] & 255].join(
|
|
101
|
+
".",
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function translatedIpv4(words: number[]): string | null {
|
|
106
|
+
const firstFourZero = words.slice(0, 4).every((word) => word === 0);
|
|
107
|
+
const firstFiveZero = firstFourZero && words[4] === 0;
|
|
108
|
+
|
|
109
|
+
// IPv4-compatible (::/96), mapped (::ffff:0:0/96), and translated
|
|
110
|
+
// (::ffff:0:0:0/96) forms all carry the IPv4 address in the final 32 bits.
|
|
111
|
+
if (
|
|
112
|
+
(firstFiveZero && (words[5] === 0 || words[5] === 0xffff)) ||
|
|
113
|
+
(firstFourZero && words[4] === 0xffff && words[5] === 0)
|
|
114
|
+
) {
|
|
115
|
+
return ipv4FromWords(words);
|
|
76
116
|
}
|
|
77
|
-
|
|
117
|
+
|
|
118
|
+
// RFC 6052 well-known NAT64 prefix 64:ff9b::/96.
|
|
78
119
|
if (
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
head.startsWith("feb")
|
|
120
|
+
words[0] === 0x64 &&
|
|
121
|
+
words[1] === 0xff9b &&
|
|
122
|
+
words.slice(2, 6).every((word) => word === 0)
|
|
83
123
|
) {
|
|
84
|
-
return
|
|
124
|
+
return ipv4FromWords(words);
|
|
85
125
|
}
|
|
86
|
-
|
|
126
|
+
|
|
127
|
+
return null;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function isNat64LocalUse(words: number[]): boolean {
|
|
131
|
+
// RFC 8215 reserves the entire 64:ff9b:1::/48 prefix for local translation.
|
|
132
|
+
return words[0] === 0x64 && words[1] === 0xff9b && words[2] === 1;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function isBlockedIpv6(ip: string): boolean {
|
|
136
|
+
const words = parseIpv6Words(ip);
|
|
137
|
+
if (!words) return true;
|
|
138
|
+
if (isNat64LocalUse(words)) return true;
|
|
139
|
+
|
|
140
|
+
const translated = translatedIpv4(words);
|
|
141
|
+
if (translated) return isBlockedIpv4(translated);
|
|
142
|
+
|
|
143
|
+
const allZero = words.every((word) => word === 0);
|
|
144
|
+
const loopback =
|
|
145
|
+
words.slice(0, 7).every((word) => word === 0) && words[7] === 1;
|
|
146
|
+
if (allZero || loopback) return true;
|
|
147
|
+
|
|
148
|
+
const head = words[0];
|
|
149
|
+
if ((head & 0xffc0) === 0xfe80 || (head & 0xffc0) === 0xfec0) {
|
|
150
|
+
return true; // link-local fe80::/10 + deprecated site-local fec0::/10
|
|
151
|
+
}
|
|
152
|
+
if ((head & 0xfe00) === 0xfc00) return true; // unique-local fc00::/7
|
|
153
|
+
if ((head & 0xff00) === 0xff00) return true; // multicast ff00::/8
|
|
87
154
|
return false;
|
|
88
155
|
}
|
|
89
156
|
|
|
90
|
-
function isBlockedIp(ip: string): boolean {
|
|
157
|
+
export function isBlockedIp(ip: string): boolean {
|
|
91
158
|
const type = net.isIP(ip);
|
|
92
159
|
if (type === 4) return isBlockedIpv4(ip);
|
|
93
160
|
if (type === 6) return isBlockedIpv6(ip);
|
|
94
161
|
return true; // not a parseable IP -> fail closed
|
|
95
162
|
}
|
|
96
163
|
|
|
164
|
+
/**
|
|
165
|
+
* Ranges that remain blocked even for an explicitly loopback-enabled entry.
|
|
166
|
+
* In particular, link-local addresses include cloud instance metadata services
|
|
167
|
+
* and must never become reachable through an imported OpenAPI document.
|
|
168
|
+
*/
|
|
169
|
+
function isAlwaysBlockedIpv4(ip: string): boolean {
|
|
170
|
+
const nums = parseIpv4(ip);
|
|
171
|
+
if (!nums) return true;
|
|
172
|
+
const [a, b] = nums;
|
|
173
|
+
return a === 0 || (a === 169 && b === 254) || a >= 224;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export function isAlwaysBlockedIp(ip: string): boolean {
|
|
177
|
+
const type = net.isIP(ip);
|
|
178
|
+
if (type === 4) return isAlwaysBlockedIpv4(ip);
|
|
179
|
+
if (type === 6) {
|
|
180
|
+
const words = parseIpv6Words(ip);
|
|
181
|
+
if (!words || isNat64LocalUse(words)) return true;
|
|
182
|
+
const translated = translatedIpv4(words);
|
|
183
|
+
if (translated) return isAlwaysBlockedIpv4(translated);
|
|
184
|
+
|
|
185
|
+
const head = words[0];
|
|
186
|
+
return (
|
|
187
|
+
words.every((word) => word === 0) ||
|
|
188
|
+
(head & 0xffc0) === 0xfe80 ||
|
|
189
|
+
(head & 0xffc0) === 0xfec0 ||
|
|
190
|
+
(head & 0xff00) === 0xff00
|
|
191
|
+
);
|
|
192
|
+
}
|
|
193
|
+
return true;
|
|
194
|
+
}
|
|
195
|
+
|
|
97
196
|
function flattenHeaders(
|
|
98
197
|
headers: http.IncomingHttpHeaders,
|
|
99
198
|
): Record<string, string> {
|
|
@@ -113,14 +212,19 @@ export async function guardedFetch(
|
|
|
113
212
|
const url = new URL(targetUrl);
|
|
114
213
|
let host = url.hostname.toLowerCase();
|
|
115
214
|
if (host.endsWith(".")) host = host.slice(0, -1);
|
|
215
|
+
host = host.replace(/^\\[|\\]$/g, "");
|
|
116
216
|
|
|
117
217
|
const literalType = net.isIP(host);
|
|
118
218
|
let validated: LookupAddress[];
|
|
219
|
+
// Loopback opt-in exists only for local development. Production always
|
|
220
|
+
// applies the complete private-address block regardless of generated data.
|
|
221
|
+
const allowPrivate =
|
|
222
|
+
process.env.NODE_ENV !== "production" && entry.allowPrivate === true;
|
|
119
223
|
|
|
120
224
|
if (literalType !== 0) {
|
|
121
225
|
// Raw-IP target: only allowed if the spec itself declared this host, and
|
|
122
226
|
// only into a private range when it opted in via allowPrivate.
|
|
123
|
-
if (isBlockedIp(host) && !
|
|
227
|
+
if (isAlwaysBlockedIp(host) || (isBlockedIp(host) && !allowPrivate)) {
|
|
124
228
|
throw new BlockedError("blocked: private IP-literal target");
|
|
125
229
|
}
|
|
126
230
|
validated = [{ address: host, family: literalType }];
|
|
@@ -132,11 +236,12 @@ export async function guardedFetch(
|
|
|
132
236
|
throw new BlockedError("blocked: DNS resolution failed");
|
|
133
237
|
}
|
|
134
238
|
if (records.length === 0) throw new BlockedError("blocked: no DNS records");
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
239
|
+
for (const record of records) {
|
|
240
|
+
if (
|
|
241
|
+
isAlwaysBlockedIp(record.address) ||
|
|
242
|
+
(isBlockedIp(record.address) && !allowPrivate)
|
|
243
|
+
) {
|
|
244
|
+
throw new BlockedError("blocked: private IP");
|
|
140
245
|
}
|
|
141
246
|
}
|
|
142
247
|
validated = records;
|
package/package.json
CHANGED
|
@@ -1,19 +1,27 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "doccupine",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.142",
|
|
4
4
|
"description": "Free and open-source documentation platform. Write MDX, get a production-ready site with AI chat, built-in components, and an MCP server - in one command.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"bin": {
|
|
7
7
|
"doccupine": "dist/index.js"
|
|
8
8
|
},
|
|
9
9
|
"type": "module",
|
|
10
|
+
"engines": {
|
|
11
|
+
"node": ">=22"
|
|
12
|
+
},
|
|
13
|
+
"packageManager": "pnpm@11.18.0",
|
|
10
14
|
"scripts": {
|
|
11
|
-
"
|
|
15
|
+
"clean": "node scripts/clean.mjs",
|
|
16
|
+
"build": "pnpm clean && tsc",
|
|
12
17
|
"dev": "tsc --watch",
|
|
13
18
|
"start": "node dist/index.js",
|
|
14
|
-
"prepare": "tsc",
|
|
15
|
-
"test": "vitest run",
|
|
16
|
-
"
|
|
19
|
+
"prepare": "node scripts/clean.mjs && tsc",
|
|
20
|
+
"test": "pnpm build && vitest run",
|
|
21
|
+
"test:package": "pnpm build && node scripts/verify-package.mjs",
|
|
22
|
+
"smoke:generated": "node scripts/smoke-generated-site.mjs",
|
|
23
|
+
"format": "prettier --write .",
|
|
24
|
+
"format:check": "prettier --check ."
|
|
17
25
|
},
|
|
18
26
|
"keywords": [
|
|
19
27
|
"doccupine",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export declare function mdxToMarkdown(body: string): string;
|
|
@@ -1,134 +0,0 @@
|
|
|
1
|
-
// Converts an MDX page body into the plain markdown its HTML render shows.
|
|
2
|
-
// The .md mirrors and llms-full.txt are built from this so agents get real
|
|
3
|
-
// text instead of raw JSX: component tags are unwrapped (children are already
|
|
4
|
-
// markdown), and text that only exists in JSX props (Card titles, Field
|
|
5
|
-
// names, Frame captions, ...) is hoisted into the output where the rendered
|
|
6
|
-
// page displays it. Unknown components fall through to "drop the tag, keep
|
|
7
|
-
// the children".
|
|
8
|
-
// Matches an open, close, or self-closing JSX/HTML tag. The (?=[\s/>])
|
|
9
|
-
// lookahead after the name keeps markdown autolinks like <https://...> from
|
|
10
|
-
// matching. Attribute text may contain quoted strings and one level of
|
|
11
|
-
// nested braces (enough for expressions like tabs={[{ ... }, { ... }]}).
|
|
12
|
-
const TAG_RE = /<(\/?)([A-Za-z][\w]*)(?=[\s/>])((?:"[^"]*"|'[^']*'|\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}|[^>"'{])*?)(\/?)>/g;
|
|
13
|
-
const ATTR_RE = /([A-Za-z][\w-]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}))?/g;
|
|
14
|
-
function parseAttrs(raw) {
|
|
15
|
-
const attrs = new Map();
|
|
16
|
-
for (const m of raw.matchAll(ATTR_RE)) {
|
|
17
|
-
attrs.set(m[1], m[2] ?? m[3] ?? true);
|
|
18
|
-
}
|
|
19
|
-
return attrs;
|
|
20
|
-
}
|
|
21
|
-
function str(value) {
|
|
22
|
-
return typeof value === "string" ? value : "";
|
|
23
|
-
}
|
|
24
|
-
export function mdxToMarkdown(body) {
|
|
25
|
-
const stash = [];
|
|
26
|
-
const keep = (match) => `\u0000${stash.push(match) - 1}\u0000`;
|
|
27
|
-
// Code renders verbatim in HTML, so it must survive untouched.
|
|
28
|
-
let text = body.replace(/```[\s\S]*?```/g, keep);
|
|
29
|
-
text = text.replace(/`[^`\n]+`/g, keep);
|
|
30
|
-
text = text.replace(/\{\/\*[\s\S]*?\*\/\}/g, "");
|
|
31
|
-
// Some tags emit text where their children END (a Frame caption renders
|
|
32
|
-
// under the image, a Tooltip definition follows the wrapped term), so the
|
|
33
|
-
// open tag pushes the text and the close tag pops it.
|
|
34
|
-
const pending = {};
|
|
35
|
-
const push = (name, value) => (pending[name] ??= []).push(value);
|
|
36
|
-
const pop = (name) => pending[name]?.pop() ?? "";
|
|
37
|
-
text = text.replace(TAG_RE, (_match, close, name, rawAttrs, _selfClose) => {
|
|
38
|
-
const isClose = close === "/";
|
|
39
|
-
const attrs = isClose
|
|
40
|
-
? new Map()
|
|
41
|
-
: parseAttrs(rawAttrs);
|
|
42
|
-
switch (name) {
|
|
43
|
-
// Title props render as the block's visible heading.
|
|
44
|
-
case "Card":
|
|
45
|
-
case "Accordion":
|
|
46
|
-
case "Step":
|
|
47
|
-
case "TabContent": {
|
|
48
|
-
if (isClose)
|
|
49
|
-
return "";
|
|
50
|
-
const title = str(attrs.get("title"));
|
|
51
|
-
return title ? `**${title}**\n\n` : "";
|
|
52
|
-
}
|
|
53
|
-
case "Update": {
|
|
54
|
-
if (isClose)
|
|
55
|
-
return "";
|
|
56
|
-
const label = str(attrs.get("label"));
|
|
57
|
-
const description = str(attrs.get("description"));
|
|
58
|
-
return ((label ? `## ${label}\n\n` : "") +
|
|
59
|
-
(description ? `${description}\n\n` : ""));
|
|
60
|
-
}
|
|
61
|
-
case "Field": {
|
|
62
|
-
if (isClose)
|
|
63
|
-
return "";
|
|
64
|
-
const value = str(attrs.get("value"));
|
|
65
|
-
if (!value)
|
|
66
|
-
return "";
|
|
67
|
-
const parts = [str(attrs.get("type"))].filter(Boolean);
|
|
68
|
-
if (attrs.get("required") === true)
|
|
69
|
-
parts.push("required");
|
|
70
|
-
return parts.length
|
|
71
|
-
? `**${value}** (${parts.join(", ")})\n\n`
|
|
72
|
-
: `**${value}**\n\n`;
|
|
73
|
-
}
|
|
74
|
-
case "ColorSwatch": {
|
|
75
|
-
if (isClose)
|
|
76
|
-
return "";
|
|
77
|
-
const token = str(attrs.get("token"));
|
|
78
|
-
const value = str(attrs.get("value"));
|
|
79
|
-
return token && value ? `- ${token}: ${value}\n` : "";
|
|
80
|
-
}
|
|
81
|
-
case "Prompt": {
|
|
82
|
-
if (isClose)
|
|
83
|
-
return "";
|
|
84
|
-
const description = str(attrs.get("description"));
|
|
85
|
-
return description ? `${description}\n\n` : "";
|
|
86
|
-
}
|
|
87
|
-
case "Frame": {
|
|
88
|
-
if (isClose) {
|
|
89
|
-
const caption = pop(name);
|
|
90
|
-
return caption ? `\n\n${caption}\n\n` : "";
|
|
91
|
-
}
|
|
92
|
-
const caption = [str(attrs.get("caption")), str(attrs.get("hint"))]
|
|
93
|
-
.filter(Boolean)
|
|
94
|
-
.join(" ");
|
|
95
|
-
push(name, caption);
|
|
96
|
-
return "";
|
|
97
|
-
}
|
|
98
|
-
case "Tooltip": {
|
|
99
|
-
if (isClose) {
|
|
100
|
-
const tip = pop(name);
|
|
101
|
-
return tip ? ` (${tip})` : "";
|
|
102
|
-
}
|
|
103
|
-
push(name, str(attrs.get("tip")));
|
|
104
|
-
return "";
|
|
105
|
-
}
|
|
106
|
-
case "CodeTabs": {
|
|
107
|
-
if (isClose)
|
|
108
|
-
return "";
|
|
109
|
-
const pairs = [
|
|
110
|
-
...rawAttrs.matchAll(/label:\s*"([^"]*)"\s*,\s*code:\s*"([^"]*)"/g),
|
|
111
|
-
];
|
|
112
|
-
return pairs
|
|
113
|
-
.map(([, label, code]) => `**${label}**\n\n\`\`\`\n${code}\n\`\`\`\n\n`)
|
|
114
|
-
.join("");
|
|
115
|
-
}
|
|
116
|
-
case "img": {
|
|
117
|
-
const src = str(attrs.get("src"));
|
|
118
|
-
const alt = str(attrs.get("alt"));
|
|
119
|
-
return src ? `` : "";
|
|
120
|
-
}
|
|
121
|
-
case "br":
|
|
122
|
-
return "\n";
|
|
123
|
-
// Everything else (Callout, Badge, Button, Tabs, Steps, Columns, Tree,
|
|
124
|
-
// SidePanel, iframe, ...) is presentation-only: drop the tag, keep the
|
|
125
|
-
// markdown children.
|
|
126
|
-
default:
|
|
127
|
-
return "";
|
|
128
|
-
}
|
|
129
|
-
});
|
|
130
|
-
// Collapse the gaps the removed tags leave behind, then restore code.
|
|
131
|
-
text = text.replace(/[ \t]+$/gm, "").replace(/\n{3,}/g, "\n\n");
|
|
132
|
-
text = text.replace(/\u0000(\d+)\u0000/g, (_m, i) => stash[Number(i)]);
|
|
133
|
-
return text.trim() + "\n";
|
|
134
|
-
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export declare const imageAndEmbedsMdxTemplate = "---\ntitle: \"Images and embeds\"\ndescription: \"Enrich your documentation with visuals, videos, and interactive embeds.\"\ndate: \"2026-02-19\"\ncategory: \"Components\"\ncategoryOrder: 1\norder: 14\n---\n# Images and embeds\n\nEnrich your documentation with visuals, videos, and interactive embeds.\n\nDisplay images, embed video content, or add interactive frames via iframes to supplement your docs.\n\n\n\n## Images\n\nImages enhance documentation with context, illustration, or decorative visual cues.\n\n### Basic Image Syntax\n\nInclude an image in Markdown using the syntax below:\n\n```md\n\n```\n\n<Callout type=\"note\">\n Use clear, descriptive alt text for accessibility and better SEO. Alt text should describe the image\u2019s appearance or content.\n</Callout>\n\n### HTML image embeds\n\nEmbed images in your Markdown content using HTML syntax.\n\n```md\n<img src=\"https://docs.doccupine.com/demo.png\" alt=\"Alt text\">\n```\n\n### Theme-aware images\n\nShow different images depending on whether the user is in light or dark mode. Add the `light-only` or `dark-only` className to display an image exclusively in that theme.\n\n```md\n<img className=\"light-only\" src=\"/images/diagram-light.png\" alt=\"Diagram\">\n<img className=\"dark-only\" src=\"/images/diagram-dark.png\" alt=\"Diagram\">\n```\n\n<img className=\"light-only\" src=\"https://docs.doccupine.com/demo.png\" alt=\"This image is only visible in light mode\" />\n<img className=\"dark-only\" src=\"https://docs.doccupine.com/demo.png\" alt=\"This image is only visible in dark mode\" style={{ filter: \"invert(1)\" }} />\n\n<Callout type=\"note\">\n The `light-only` and `dark-only` classes work on any element, not just images. You can use them on videos, iframes, or wrapper divs too.\n</Callout>\n\n## Videos\n\nVideos add a dynamic element to your documentation, engaging your audience and providing a more immersive experience.\n\n### YouTube Embed\n\nTo embed a YouTube video, use the following syntax:\n\n```html\n<iframe\n className=\"aspect-video\"\n src=\"https://www.youtube.com/embed/ResP_eVPYQo\"\n title=\"YouTube video player\"\n frameborder=\"0\"\n allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\"\n allowfullscreen\n></iframe>\n```\n\n<iframe\n className=\"aspect-video\"\n src=\"https://www.youtube.com/embed/ResP_eVPYQo\"\n title=\"YouTube video player\"\n frameBorder=\"0\"\n allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\"\n allowFullScreen\n></iframe>\n\n### Self-hosted videos\n\nServe up your own video content using the `<video>` tag:\n\n```html\n<video\n controls\n className=\"aspect-video\"\n src=\"https://samplelib.com/lib/preview/mp4/sample-20s.mp4\"\n></video>\n```\n\n<video\ncontrols\nclassName=\"aspect-video\"\nsrc=\"https://samplelib.com/lib/preview/mp4/sample-20s.mp4\"\n\n> </video>\n\n#### Autoplay and Looping\n\nFor demonstration videos that loop or start automatically, add attributes as shown:\n\n```html\n<video\n controls\n className=\"aspect-video\"\n src=\"https://samplelib.com/lib/preview/mp4/sample-20s.mp4\"\n autoplay\n muted\n loop\n playsinline\n></video>\n```";
|