doccupine 0.0.140 → 0.0.141

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.
Files changed (145) hide show
  1. package/README.md +14 -7
  2. package/dist/cli.d.ts +1 -0
  3. package/dist/cli.js +191 -0
  4. package/dist/index.d.ts +3 -7
  5. package/dist/index.js +5 -1894
  6. package/dist/lib/config-manager.d.ts +1 -0
  7. package/dist/lib/config-manager.js +63 -3
  8. package/dist/lib/generated-artifacts.d.ts +26 -0
  9. package/dist/lib/generated-artifacts.js +147 -0
  10. package/dist/lib/layout.js +30 -30
  11. package/dist/lib/metadata.js +58 -30
  12. package/dist/lib/openapi-types.d.ts +2 -2
  13. package/dist/lib/openapi.d.ts +6 -3
  14. package/dist/lib/openapi.js +330 -50
  15. package/dist/lib/output-safety.d.ts +15 -0
  16. package/dist/lib/output-safety.js +428 -0
  17. package/dist/lib/structures.js +11 -0
  18. package/dist/lib/utils.d.ts +10 -5
  19. package/dist/lib/utils.js +108 -5
  20. package/dist/mdx-to-nextjs-generator.d.ts +166 -0
  21. package/dist/mdx-to-nextjs-generator.js +2229 -0
  22. package/dist/templates/app/api/gate/route.d.ts +1 -1
  23. package/dist/templates/app/api/gate/route.js +18 -6
  24. package/dist/templates/app/api/mcp/route.d.ts +1 -1
  25. package/dist/templates/app/api/mcp/route.js +181 -111
  26. package/dist/templates/app/api/playground/route.d.ts +1 -1
  27. package/dist/templates/app/api/playground/route.js +45 -13
  28. package/dist/templates/app/api/rag/route.d.ts +1 -1
  29. package/dist/templates/app/api/rag/route.js +72 -20
  30. package/dist/templates/app/api/search/route.d.ts +1 -1
  31. package/dist/templates/app/api/search/route.js +5 -0
  32. package/dist/templates/app/robots.d.ts +1 -1
  33. package/dist/templates/app/robots.js +1 -26
  34. package/dist/templates/app/theme.d.ts +1 -1
  35. package/dist/templates/app/theme.js +31 -19
  36. package/dist/templates/components/Chat.d.ts +1 -1
  37. package/dist/templates/components/Chat.js +342 -34
  38. package/dist/templates/components/SearchDocs.d.ts +1 -1
  39. package/dist/templates/components/SearchDocs.js +63 -11
  40. package/dist/templates/components/SearchModalContent.d.ts +1 -1
  41. package/dist/templates/components/SearchModalContent.js +191 -49
  42. package/dist/templates/components/SideBar.d.ts +1 -1
  43. package/dist/templates/components/SideBar.js +8 -2
  44. package/dist/templates/components/layout/Accordion.d.ts +1 -1
  45. package/dist/templates/components/layout/Accordion.js +26 -3
  46. package/dist/templates/components/layout/Badge.d.ts +1 -1
  47. package/dist/templates/components/layout/Badge.js +1 -1
  48. package/dist/templates/components/layout/Button.d.ts +1 -1
  49. package/dist/templates/components/layout/Button.js +4 -4
  50. package/dist/templates/components/layout/Callout.d.ts +1 -1
  51. package/dist/templates/components/layout/Callout.js +6 -6
  52. package/dist/templates/components/layout/Card.d.ts +1 -1
  53. package/dist/templates/components/layout/Card.js +9 -4
  54. package/dist/templates/components/layout/CherryThemeProvider.d.ts +1 -1
  55. package/dist/templates/components/layout/CherryThemeProvider.js +63 -12
  56. package/dist/templates/components/layout/Code.d.ts +1 -1
  57. package/dist/templates/components/layout/Code.js +5 -5
  58. package/dist/templates/components/layout/CopyButton.d.ts +1 -1
  59. package/dist/templates/components/layout/CopyButton.js +1 -1
  60. package/dist/templates/components/layout/DemoTheme.d.ts +1 -1
  61. package/dist/templates/components/layout/DemoTheme.js +8 -28
  62. package/dist/templates/components/layout/DocsComponents.d.ts +1 -1
  63. package/dist/templates/components/layout/DocsComponents.js +57 -6
  64. package/dist/templates/components/layout/GlobalStyles.d.ts +1 -1
  65. package/dist/templates/components/layout/GlobalStyles.js +15 -9
  66. package/dist/templates/components/layout/Prompt.d.ts +1 -1
  67. package/dist/templates/components/layout/Prompt.js +4 -7
  68. package/dist/templates/components/layout/Steps.d.ts +1 -1
  69. package/dist/templates/components/layout/Steps.js +7 -1
  70. package/dist/templates/components/layout/Tabs.d.ts +1 -1
  71. package/dist/templates/components/layout/Tabs.js +108 -19
  72. package/dist/templates/env.example.d.ts +1 -1
  73. package/dist/templates/env.example.js +11 -0
  74. package/dist/templates/eslint.config.d.ts +1 -1
  75. package/dist/templates/eslint.config.js +20 -0
  76. package/dist/templates/gitignore.d.ts +1 -1
  77. package/dist/templates/gitignore.js +4 -3
  78. package/dist/templates/lib/access.d.ts +1 -0
  79. package/dist/templates/lib/access.js +41 -0
  80. package/dist/templates/mdx/ai-assistant.mdx.d.ts +1 -1
  81. package/dist/templates/mdx/ai-assistant.mdx.js +17 -1
  82. package/dist/templates/mdx/api-playground.mdx.d.ts +1 -1
  83. package/dist/templates/mdx/api-playground.mdx.js +5 -3
  84. package/dist/templates/mdx/authentication.mdx.d.ts +1 -1
  85. package/dist/templates/mdx/authentication.mdx.js +5 -3
  86. package/dist/templates/mdx/commands.mdx.d.ts +1 -1
  87. package/dist/templates/mdx/commands.mdx.js +20 -6
  88. package/dist/templates/mdx/components.mdx.d.ts +1 -1
  89. package/dist/templates/mdx/components.mdx.js +3 -0
  90. package/dist/templates/mdx/deployment-and-hosting.mdx.d.ts +1 -1
  91. package/dist/templates/mdx/deployment-and-hosting.mdx.js +2 -2
  92. package/dist/templates/mdx/globals.mdx.d.ts +1 -1
  93. package/dist/templates/mdx/globals.mdx.js +14 -11
  94. package/dist/templates/mdx/model-context-protocol.mdx.d.ts +1 -1
  95. package/dist/templates/mdx/model-context-protocol.mdx.js +22 -35
  96. package/dist/templates/mdx/platform/ai-assistant.mdx.d.ts +1 -1
  97. package/dist/templates/mdx/platform/ai-assistant.mdx.js +23 -0
  98. package/dist/templates/mdx/platform/api-playground.mdx.d.ts +1 -1
  99. package/dist/templates/mdx/platform/api-playground.mdx.js +7 -0
  100. package/dist/templates/mdx/platform/authentication.mdx.d.ts +1 -0
  101. package/dist/templates/mdx/platform/authentication.mdx.js +63 -0
  102. package/dist/templates/mdx/platform/import-from-github.mdx.d.ts +1 -1
  103. package/dist/templates/mdx/platform/import-from-github.mdx.js +2 -2
  104. package/dist/templates/mdx/platform/index.mdx.d.ts +1 -1
  105. package/dist/templates/mdx/platform/index.mdx.js +1 -0
  106. package/dist/templates/mdx/platform/mcp.mdx.d.ts +1 -1
  107. package/dist/templates/mdx/platform/mcp.mdx.js +2 -1
  108. package/dist/templates/mdx/platform/navigation-settings.mdx.d.ts +1 -1
  109. package/dist/templates/mdx/platform/navigation-settings.mdx.js +12 -1
  110. package/dist/templates/mdx/platform/publishing.mdx.d.ts +1 -1
  111. package/dist/templates/mdx/platform/publishing.mdx.js +43 -10
  112. package/dist/templates/mdx/platform/self-updating-docs.mdx.d.ts +1 -1
  113. package/dist/templates/mdx/platform/self-updating-docs.mdx.js +48 -9
  114. package/dist/templates/mdx/sections.mdx.d.ts +1 -1
  115. package/dist/templates/mdx/sections.mdx.js +4 -0
  116. package/dist/templates/mdx/space.mdx.d.ts +1 -0
  117. package/dist/templates/mdx/space.mdx.js +125 -0
  118. package/dist/templates/mdx/tabs.mdx.d.ts +1 -1
  119. package/dist/templates/mdx/tabs.mdx.js +4 -0
  120. package/dist/templates/next.config.js +20 -8
  121. package/dist/templates/package.js +3 -3
  122. package/dist/templates/prettierignore.d.ts +1 -1
  123. package/dist/templates/prettierignore.js +1 -0
  124. package/dist/templates/proxy.js +47 -19
  125. package/dist/templates/scripts/build-docs-index.d.ts +1 -1
  126. package/dist/templates/scripts/build-docs-index.js +1 -0
  127. package/dist/templates/services/mcp/docsContentStub.d.ts +1 -0
  128. package/dist/templates/services/mcp/docsContentStub.js +1 -0
  129. package/dist/templates/services/mcp/server.d.ts +1 -1
  130. package/dist/templates/services/mcp/server.js +140 -83
  131. package/dist/templates/services/mcp/tools.d.ts +1 -1
  132. package/dist/templates/services/mcp/tools.js +65 -137
  133. package/dist/templates/utils/playgroundAllowlist.d.ts +1 -1
  134. package/dist/templates/utils/playgroundAllowlist.js +13 -4
  135. package/dist/templates/utils/rateLimit.d.ts +1 -1
  136. package/dist/templates/utils/rateLimit.js +40 -3
  137. package/dist/templates/utils/requestBody.d.ts +1 -0
  138. package/dist/templates/utils/requestBody.js +56 -0
  139. package/dist/templates/utils/ssrfGuard.d.ts +1 -1
  140. package/dist/templates/utils/ssrfGuard.js +138 -33
  141. package/package.json +14 -9
  142. package/dist/lib/mdxToMarkdown.d.ts +0 -1
  143. package/dist/lib/mdxToMarkdown.js +0 -134
  144. package/dist/templates/mdx/image-and-embeds.mdx.d.ts +0 -1
  145. package/dist/templates/mdx/image-and-embeds.mdx.js +0 -118
@@ -20,6 +20,41 @@ import type { DocsChunk } from "@/services/mcp/types";
20
20
  /** A doc chunk with its stored int8-quantized embedding. */
21
21
  type IndexedChunk = DocsChunk & { embedding: Int8Array };
22
22
 
23
+ export const MCP_MAX_REQUEST_BYTES = 64 * 1024;
24
+ export const MCP_MAX_TOOL_ARGUMENT_BYTES = 8 * 1024;
25
+ export const MCP_MAX_RESULT_BYTES = 256 * 1024;
26
+
27
+ export const searchDocsArgsSchema = z
28
+ .object({
29
+ query: z.string().min(1).max(2000),
30
+ limit: z.number().int().min(1).max(20).optional(),
31
+ })
32
+ .strict();
33
+
34
+ export const getDocArgsSchema = z
35
+ .object({ path: z.string().min(1).max(500) })
36
+ .strict();
37
+
38
+ export const listDocsArgsSchema = z
39
+ .object({ directory: z.string().max(500).optional() })
40
+ .strict();
41
+
42
+ export function serializeMCPResult(value: unknown): {
43
+ text: string;
44
+ tooLarge: boolean;
45
+ } {
46
+ const text = JSON.stringify(value, null, 2) ?? "null";
47
+ if (new TextEncoder().encode(text).byteLength <= MCP_MAX_RESULT_BYTES) {
48
+ return { text, tooLarge: false };
49
+ }
50
+ return {
51
+ text: JSON.stringify({
52
+ error: "Tool result exceeds the maximum response size",
53
+ }),
54
+ tooLarge: true,
55
+ };
56
+ }
57
+
23
58
  /**
24
59
  * Thrown when a query arrives but no usable prebuilt embeddings index exists AND
25
60
  * the doc set is too large to embed within a single serverless request. Surfaced
@@ -237,7 +272,11 @@ async function buildDocsIndex(force = false): Promise<void> {
237
272
  * Ensure the docs index is ready.
238
273
  * On first call, triggers the build; subsequent calls wait for the same promise.
239
274
  */
240
- export async function ensureDocsIndex(force = false): Promise<void> {
275
+ export async function ensureDocsIndex(
276
+ force = false,
277
+ signal?: AbortSignal,
278
+ ): Promise<void> {
279
+ signal?.throwIfAborted();
241
280
  if (force) {
242
281
  // Wait for any in-flight build before starting a forced rebuild
243
282
  if (docsIndex.building && indexReady) {
@@ -246,12 +285,68 @@ export async function ensureDocsIndex(force = false): Promise<void> {
246
285
  docsIndex.ready = false;
247
286
  docsIndex.chunks = [];
248
287
  indexReady = buildDocsIndex(true);
249
- return indexReady;
250
- }
251
- if (!indexReady) {
288
+ } else if (!indexReady) {
252
289
  indexReady = buildDocsIndex();
253
290
  }
254
- return indexReady;
291
+
292
+ const build = indexReady;
293
+ if (!signal) return build;
294
+
295
+ // Embedding clients do not expose AbortSignal parameters. Keep the shared
296
+ // index build alive for other requests, but stop this caller waiting as soon
297
+ // as its request is cancelled.
298
+ await new Promise<void>((resolve, reject) => {
299
+ const abort = () => reject(signal.reason);
300
+ signal.addEventListener("abort", abort, { once: true });
301
+ void build.then(resolve, reject).finally(() => {
302
+ signal.removeEventListener("abort", abort);
303
+ });
304
+ });
305
+ signal.throwIfAborted();
306
+ }
307
+
308
+ function throwIfCancelled(signal?: AbortSignal): void {
309
+ signal?.throwIfAborted();
310
+ }
311
+
312
+ async function embedQuery(
313
+ query: string,
314
+ signal?: AbortSignal,
315
+ ): Promise<number[]> {
316
+ throwIfCancelled(signal);
317
+ // LangChain's provider-neutral Embeddings interface has no signal option.
318
+ const vector = await getEmbeddings().embedQuery(query);
319
+ throwIfCancelled(signal);
320
+ return vector;
321
+ }
322
+
323
+ function normalizeSearchLimit(limit: number): number {
324
+ if (!Number.isFinite(limit)) return 6;
325
+ return Math.max(1, Math.min(20, Math.floor(limit)));
326
+ }
327
+
328
+ function toolResult(value: unknown) {
329
+ const serialized = serializeMCPResult(value);
330
+ return {
331
+ content: [{ type: "text" as const, text: serialized.text }],
332
+ ...(serialized.tooLarge ? { isError: true as const } : {}),
333
+ };
334
+ }
335
+
336
+ function toolError(message: string) {
337
+ return {
338
+ content: [
339
+ {
340
+ type: "text" as const,
341
+ text: JSON.stringify({ error: message }),
342
+ },
343
+ ],
344
+ isError: true as const,
345
+ };
346
+ }
347
+
348
+ function resourceText(value: unknown): string {
349
+ return serializeMCPResult(value).text;
255
350
  }
256
351
 
257
352
  // Eagerly start building the index on server startup if LLM is configured
@@ -280,13 +375,15 @@ function getEmbeddings() {
280
375
  export async function searchDocs(
281
376
  query: string,
282
377
  limit = 6,
378
+ signal?: AbortSignal,
283
379
  ): Promise<{ chunk: DocsChunk; score: number }[]> {
284
- await ensureDocsIndex();
380
+ await ensureDocsIndex(false, signal);
381
+ throwIfCancelled(signal);
285
382
 
286
383
  // Reduce the query vector with the exact same transform used at index time so
287
384
  // dimensions line up. Scoring runs directly against the int8 vectors - cosine
288
385
  // is scale-invariant, so no dequantization is needed.
289
- const rawQueryVector = await getEmbeddings().embedQuery(query);
386
+ const rawQueryVector = await embedQuery(query, signal);
290
387
  const queryVector = reduceDims(rawQueryVector, getLLMConfig().embeddingDims);
291
388
 
292
389
  const scored = docsIndex.chunks
@@ -295,7 +392,7 @@ export async function searchDocs(
295
392
  score: cosineFloatInt8(queryVector, c.embedding),
296
393
  }))
297
394
  .sort((a, b) => b.score - a.score)
298
- .slice(0, limit);
395
+ .slice(0, normalizeSearchLimit(limit));
299
396
 
300
397
  return scored;
301
398
  }
@@ -325,99 +422,61 @@ export function createMCPServer(): McpServer {
325
422
  });
326
423
 
327
424
  // Register the search_docs tool
328
- server.tool(
425
+ server.registerTool(
329
426
  "search_docs",
330
- DOCS_TOOLS[0].description,
331
427
  {
332
- query: z
333
- .string()
334
- .describe("The search query to find relevant documentation"),
335
- limit: z
336
- .number()
337
- .optional()
338
- .describe("Maximum number of results to return (default: 6)"),
428
+ description: DOCS_TOOLS[0].description,
429
+ inputSchema: searchDocsArgsSchema,
339
430
  },
340
- async ({ query, limit }) => {
341
- const results = await searchDocs(query, limit ?? 6);
342
- return {
343
- content: [
344
- {
345
- type: "text" as const,
346
- text: JSON.stringify(
347
- results.map(({ chunk, score }) => ({
348
- path: chunk.path,
349
- uri: chunk.uri,
350
- score: score.toFixed(3),
351
- text: chunk.text,
352
- })),
353
- null,
354
- 2,
355
- ),
356
- },
357
- ],
358
- };
431
+ async ({ query, limit }, { signal }) => {
432
+ const results = await searchDocs(query, limit ?? 6, signal);
433
+ return toolResult(
434
+ results.map(({ chunk, score }) => ({
435
+ path: chunk.path,
436
+ uri: chunk.uri,
437
+ score: score.toFixed(3),
438
+ text: chunk.text,
439
+ })),
440
+ );
359
441
  },
360
442
  );
361
443
 
362
444
  // Register the get_doc tool
363
- server.tool(
445
+ server.registerTool(
364
446
  "get_doc",
365
- DOCS_TOOLS[1].description,
366
447
  {
367
- path: z.string().describe("The file path to the documentation page"),
448
+ description: DOCS_TOOLS[1].description,
449
+ inputSchema: getDocArgsSchema,
368
450
  },
369
- async ({ path }) => {
451
+ async ({ path }, { signal }) => {
452
+ signal.throwIfAborted();
370
453
  const doc = await getDoc({ path });
454
+ signal.throwIfAborted();
371
455
  if (!doc) {
372
- return {
373
- content: [
374
- {
375
- type: "text" as const,
376
- text: JSON.stringify({ error: "Document not found" }),
377
- },
378
- ],
379
- isError: true,
380
- };
456
+ return toolError("Document not found");
381
457
  }
382
- return {
383
- content: [
384
- {
385
- type: "text" as const,
386
- text: JSON.stringify(doc, null, 2),
387
- },
388
- ],
389
- };
458
+ return toolResult(doc);
390
459
  },
391
460
  );
392
461
 
393
462
  // Register the list_docs tool
394
- server.tool(
463
+ server.registerTool(
395
464
  "list_docs",
396
- DOCS_TOOLS[2].description,
397
465
  {
398
- directory: z
399
- .string()
400
- .optional()
401
- .describe("Optional directory to filter results"),
466
+ description: DOCS_TOOLS[2].description,
467
+ inputSchema: listDocsArgsSchema,
402
468
  },
403
- async ({ directory }) => {
469
+ async ({ directory }, { signal }) => {
470
+ signal.throwIfAborted();
404
471
  const docs = await listDocs({ directory });
405
- return {
406
- content: [
407
- {
408
- type: "text" as const,
409
- text: JSON.stringify(
410
- docs.map((d) => ({
411
- name: d.name,
412
- path: d.path,
413
- uri: d.uri,
414
- })),
415
- null,
416
- 2,
417
- ),
418
- },
419
- ],
420
- };
472
+ signal.throwIfAborted();
473
+ return toolResult(
474
+ docs.map((d) => ({
475
+ name: d.name,
476
+ path: d.path,
477
+ uri: d.uri,
478
+ })),
479
+ );
421
480
  },
422
481
  );
423
482
 
@@ -428,10 +487,8 @@ export function createMCPServer(): McpServer {
428
487
  contents: [
429
488
  {
430
489
  uri: "docs://list",
431
- text: JSON.stringify(
490
+ text: resourceText(
432
491
  docs.map((d) => ({ name: d.name, path: d.path, uri: d.uri })),
433
- null,
434
- 2,
435
492
  ),
436
493
  },
437
494
  ],
@@ -1 +1 @@
1
- export declare const mcpToolsTemplate = "import path from \"node:path\";\nimport fs from \"node:fs/promises\";\nimport type {\n MCPToolDefinition,\n DocsResource,\n DocsChunk,\n GetDocParams,\n ListDocsParams,\n} from \"@/services/mcp/types\";\n\nconst APP_DIR = path.join(process.cwd(), \"app\");\nconst VALID_EXT = new Set([\".ts\", \".tsx\", \".js\", \".jsx\"]);\n\n/**\n * Tool definitions for MCP - these describe the available tools\n */\nexport const DOCS_TOOLS: MCPToolDefinition[] = [\n {\n name: \"search_docs\",\n description:\n \"Search through the documentation content using semantic search. Returns relevant chunks of documentation based on the query.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: {\n type: \"string\",\n description: \"The search query to find relevant documentation\",\n },\n limit: {\n type: \"number\",\n description: \"Maximum number of results to return (default: 6)\",\n },\n },\n required: [\"query\"],\n },\n },\n {\n name: \"get_doc\",\n description:\n \"Get the full content of a specific documentation page by its path.\",\n inputSchema: {\n type: \"object\",\n properties: {\n path: {\n type: \"string\",\n description:\n \"The file path to the documentation page (e.g., 'app/getting-started/page.tsx')\",\n },\n },\n required: [\"path\"],\n },\n },\n {\n name: \"list_docs\",\n description:\n \"List all available documentation pages, optionally filtered by directory.\",\n inputSchema: {\n type: \"object\",\n properties: {\n directory: {\n type: \"string\",\n description:\n \"Optional directory to filter results (e.g., 'components')\",\n },\n },\n },\n },\n];\n\n/**\n * Recursively walk directory to find documentation files\n */\nasync function* walkDocs(dir: string): AsyncGenerator<string> {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n if ([\"node_modules\", \".next\", \".git\", \"api\"].includes(entry.name)) {\n continue;\n }\n yield* walkDocs(fullPath);\n } else {\n const ext = path.extname(entry.name).toLowerCase();\n if (VALID_EXT.has(ext) && entry.name.startsWith(\"page.\")) {\n yield fullPath;\n }\n }\n }\n}\n\n/**\n * Extract content blocks from a file\n */\nfunction extractContentBlocks(fileText: string): string[] {\n const results: string[] = [];\n\n const tplRegex = /(?:export\\s+)?const\\s+content\\s*=\\s*`((?:\\\\`|[^`])*)`\\s*;/g;\n let m: RegExpExecArray | null;\n while ((m = tplRegex.exec(fileText)) !== null) {\n results.push(m[1]);\n }\n\n const sglRegex = /(?:export\\s+)?const\\s+content\\s*=\\s*'([^']*)'\\s*;/g;\n while ((m = sglRegex.exec(fileText)) !== null) {\n results.push(m[1]);\n }\n\n const dblRegex = /(?:export\\s+)?const\\s+content\\s*=\\s*\"([^\"]*)\"\\s*;/g;\n while ((m = dblRegex.exec(fileText)) !== null) {\n results.push(m[1]);\n }\n\n return results;\n}\n\n/**\n * Convert a page file path to its URL path, stripping the leading \"app/\"\n * and Next.js route group segments like \"(site)\" which never appear in URLs.\n */\nfunction toDocPath(pagePath: string): string {\n return (\n path\n .dirname(pagePath)\n .replace(/^app\\/?/, \"\")\n .split(\"/\")\n .filter((seg) => !(seg.startsWith(\"(\") && seg.endsWith(\")\")))\n .join(\"/\") || \"/\"\n );\n}\n\n/**\n * Get the title from markdown content\n */\nfunction extractTitle(content: string): string {\n const match = content.match(/^#\\s+(.+)$/m);\n return match ? match[1].trim() : \"Untitled\";\n}\n\n/**\n * List all documentation resources\n */\nexport async function listDocs(\n params?: ListDocsParams,\n): Promise<DocsResource[]> {\n const resources: DocsResource[] = [];\n const filterDir = params?.directory;\n\n for await (const filePath of walkDocs(APP_DIR)) {\n const relativePath = path.join(\"app\", path.relative(APP_DIR, filePath));\n\n if (filterDir && !relativePath.includes(filterDir)) {\n continue;\n }\n\n try {\n const fileContent = await fs.readFile(filePath, \"utf8\");\n const blocks = extractContentBlocks(fileContent);\n const content = blocks.join(\"\\n\\n\");\n const title = extractTitle(content);\n const docPath = toDocPath(relativePath);\n\n resources.push({\n uri: `docs://${docPath}`,\n name: title,\n path: relativePath,\n content,\n });\n } catch (error) {\n console.warn(`Failed to read doc file: ${filePath}`, error);\n }\n }\n\n return resources;\n}\n\n/**\n * Get a specific documentation page\n */\nexport async function getDoc(\n params: GetDocParams,\n): Promise<DocsResource | null> {\n let targetPath = params.path;\n\n // Normalize path - strip leading \"app/\" if present to get the relative part\n const relativePart = targetPath.replace(/^app\\//, \"\");\n if (!relativePart.includes(\"page.\")) {\n targetPath = path.join(\"app\", relativePart, \"page.tsx\");\n } else if (!targetPath.startsWith(\"app/\")) {\n targetPath = path.join(\"app\", relativePart);\n }\n\n const fullPath = path.join(APP_DIR, targetPath.replace(/^app\\//, \"\"));\n\n // Prevent path traversal\n const resolvedPath = path.resolve(fullPath);\n if (!resolvedPath.startsWith(path.resolve(APP_DIR))) {\n return null;\n }\n\n try {\n const fileContent = await fs.readFile(fullPath, \"utf8\");\n const blocks = extractContentBlocks(fileContent);\n const content = blocks.join(\"\\n\\n\");\n const title = extractTitle(content);\n const docPath = toDocPath(targetPath);\n\n return {\n uri: `docs://${docPath}`,\n name: title,\n path: targetPath,\n content,\n };\n } catch (error) {\n console.warn(`Failed to read doc: ${targetPath}`, error);\n return null;\n }\n}\n\n/**\n * Chunk text for embeddings.\n * - chunkSize=800 chars balances granularity with embedding context window limits\n * - overlap=100 chars ensures continuity so searches don't miss content at chunk boundaries\n */\nfunction chunkText(text: string, chunkSize = 800, overlap = 100): string[] {\n const chunks: string[] = [];\n let i = 0;\n while (i < text.length) {\n const end = Math.min(i + chunkSize, text.length);\n chunks.push(text.slice(i, end));\n if (end === text.length) break;\n i = end - overlap;\n if (i < 0) i = 0;\n }\n return chunks;\n}\n\n/**\n * Get all documentation chunks for indexing\n */\nexport async function getAllDocsChunks(): Promise<DocsChunk[]> {\n const allChunks: DocsChunk[] = [];\n const docs = await listDocs();\n\n for (const doc of docs) {\n const cleanContent = doc.content\n .replace(/\\r\\n/g, \"\\n\")\n .replace(/\\n{3,}/g, \"\\n\\n\")\n .slice(0, 200_000);\n\n const textChunks = chunkText(cleanContent);\n for (let i = 0; i < textChunks.length; i++) {\n allChunks.push({\n id: `${doc.path}:${i}`,\n text: textChunks[i],\n path: doc.path,\n uri: doc.uri,\n });\n }\n }\n\n return allChunks;\n}\n";
1
+ export declare const mcpToolsTemplate = "import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type {\n MCPToolDefinition,\n DocsResource,\n DocsChunk,\n GetDocParams,\n ListDocsParams,\n} from \"@/services/mcp/types\";\n\n// Keep the corpus out of the function's JavaScript bundle. next.config.ts\n// traces this fixed file into the RAG/MCP functions, just like docs-index.json.\nconst DOCS_CONTENT_FILE = path.join(\n process.cwd(),\n \"services\",\n \"mcp\",\n \"docs-content.json\",\n);\n\nlet docsContentCache:\n { mtimeMs: number; size: number; docs: DocsResource[] } | undefined;\n\nfunction loadDocsContent(): DocsResource[] {\n try {\n // Generated content changes while `next dev` stays alive. Key the cache by\n // file metadata so watch-mode updates become visible without parsing the\n // whole corpus on every tool call.\n const stat = fs.statSync(DOCS_CONTENT_FILE);\n if (\n docsContentCache?.mtimeMs === stat.mtimeMs &&\n docsContentCache.size === stat.size\n ) {\n return docsContentCache.docs;\n }\n const parsed: unknown = JSON.parse(\n fs.readFileSync(DOCS_CONTENT_FILE, \"utf8\"),\n );\n const docs = Array.isArray(parsed) ? (parsed as DocsResource[]) : [];\n docsContentCache = { mtimeMs: stat.mtimeMs, size: stat.size, docs };\n return docs;\n } catch {\n docsContentCache = undefined;\n return [];\n }\n}\n\n/**\n * Tool definitions for MCP - these describe the available tools\n */\nexport const DOCS_TOOLS: MCPToolDefinition[] = [\n {\n name: \"search_docs\",\n description:\n \"Search through the documentation content using semantic search. Returns relevant chunks of documentation based on the query.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: {\n type: \"string\",\n description: \"The search query to find relevant documentation\",\n },\n limit: {\n type: \"number\",\n description: \"Maximum number of results to return (default: 6)\",\n },\n },\n required: [\"query\"],\n },\n },\n {\n name: \"get_doc\",\n description:\n \"Get the full content of a specific documentation page by its path.\",\n inputSchema: {\n type: \"object\",\n properties: {\n path: {\n type: \"string\",\n description:\n \"The file path to the documentation page (e.g., 'app/getting-started/page.tsx')\",\n },\n },\n required: [\"path\"],\n },\n },\n {\n name: \"list_docs\",\n description:\n \"List all available documentation pages, optionally filtered by directory.\",\n inputSchema: {\n type: \"object\",\n properties: {\n directory: {\n type: \"string\",\n description:\n \"Optional directory to filter results (e.g., 'components')\",\n },\n },\n },\n },\n];\n\n/**\n * List all documentation resources\n */\nexport async function listDocs(\n params?: ListDocsParams,\n): Promise<DocsResource[]> {\n const docsContent = loadDocsContent();\n const filterDir = params?.directory?.replace(/\\\\/g, \"/\");\n const resources = filterDir\n ? docsContent.filter((doc) => doc.path.includes(filterDir))\n : docsContent;\n return resources.map((doc) => ({ ...doc }));\n}\n\n/**\n * Get a specific documentation page\n */\nexport async function getDoc(\n params: GetDocParams,\n): Promise<DocsResource | null> {\n const docsContent = loadDocsContent();\n const requested = params.path.trim().replace(/\\\\/g, \"/\");\n if (!requested || requested.includes(\"\\0\")) return null;\n\n const withoutScheme = requested.replace(/^docs:\\/\\//, \"\");\n const route = withoutScheme\n .replace(/^app\\/(?:\\([^/]+\\)\\/)?/, \"\")\n .replace(/(?:^|\\/)page\\.(?:tsx?|jsx?)$/, \"\")\n .replace(/^\\/+|\\/+$/g, \"\");\n\n const doc = docsContent.find((candidate) => {\n const candidateRoute = candidate.uri\n .replace(/^docs:\\/\\//, \"\")\n .replace(/^\\/+|\\/+$/g, \"\");\n return (\n candidate.path === requested ||\n candidate.uri === requested ||\n candidateRoute === route\n );\n });\n\n return doc ? { ...doc } : null;\n}\n\n/**\n * Chunk text for embeddings.\n * - chunkSize=800 chars balances granularity with embedding context window limits\n * - overlap=100 chars ensures continuity so searches don't miss content at chunk boundaries\n */\nfunction chunkText(text: string, chunkSize = 800, overlap = 100): string[] {\n const chunks: string[] = [];\n let i = 0;\n while (i < text.length) {\n const end = Math.min(i + chunkSize, text.length);\n chunks.push(text.slice(i, end));\n if (end === text.length) break;\n i = end - overlap;\n if (i < 0) i = 0;\n }\n return chunks;\n}\n\n/**\n * Get all documentation chunks for indexing\n */\nexport async function getAllDocsChunks(): Promise<DocsChunk[]> {\n const allChunks: DocsChunk[] = [];\n const docs = await listDocs();\n\n for (const doc of docs) {\n const cleanContent = doc.content\n .replace(/\\r\\n/g, \"\\n\")\n .replace(/\\n{3,}/g, \"\\n\\n\")\n .slice(0, 200_000);\n\n const textChunks = chunkText(cleanContent);\n for (let i = 0; i < textChunks.length; i++) {\n allChunks.push({\n id: `${doc.path}:${i}`,\n text: textChunks[i],\n path: doc.path,\n uri: doc.uri,\n });\n }\n }\n\n return allChunks;\n}\n";
@@ -1,5 +1,5 @@
1
- export const mcpToolsTemplate = `import path from "node:path";
2
- import fs from "node:fs/promises";
1
+ export const mcpToolsTemplate = `import fs from "node:fs";
2
+ import path from "node:path";
3
3
  import type {
4
4
  MCPToolDefinition,
5
5
  DocsResource,
@@ -8,8 +8,41 @@ import type {
8
8
  ListDocsParams,
9
9
  } from "@/services/mcp/types";
10
10
 
11
- const APP_DIR = path.join(process.cwd(), "app");
12
- const VALID_EXT = new Set([".ts", ".tsx", ".js", ".jsx"]);
11
+ // Keep the corpus out of the function's JavaScript bundle. next.config.ts
12
+ // traces this fixed file into the RAG/MCP functions, just like docs-index.json.
13
+ const DOCS_CONTENT_FILE = path.join(
14
+ process.cwd(),
15
+ "services",
16
+ "mcp",
17
+ "docs-content.json",
18
+ );
19
+
20
+ let docsContentCache:
21
+ { mtimeMs: number; size: number; docs: DocsResource[] } | undefined;
22
+
23
+ function loadDocsContent(): DocsResource[] {
24
+ try {
25
+ // Generated content changes while \`next dev\` stays alive. Key the cache by
26
+ // file metadata so watch-mode updates become visible without parsing the
27
+ // whole corpus on every tool call.
28
+ const stat = fs.statSync(DOCS_CONTENT_FILE);
29
+ if (
30
+ docsContentCache?.mtimeMs === stat.mtimeMs &&
31
+ docsContentCache.size === stat.size
32
+ ) {
33
+ return docsContentCache.docs;
34
+ }
35
+ const parsed: unknown = JSON.parse(
36
+ fs.readFileSync(DOCS_CONTENT_FILE, "utf8"),
37
+ );
38
+ const docs = Array.isArray(parsed) ? (parsed as DocsResource[]) : [];
39
+ docsContentCache = { mtimeMs: stat.mtimeMs, size: stat.size, docs };
40
+ return docs;
41
+ } catch {
42
+ docsContentCache = undefined;
43
+ return [];
44
+ }
45
+ }
13
46
 
14
47
  /**
15
48
  * Tool definitions for MCP - these describe the available tools
@@ -67,110 +100,18 @@ export const DOCS_TOOLS: MCPToolDefinition[] = [
67
100
  },
68
101
  ];
69
102
 
70
- /**
71
- * Recursively walk directory to find documentation files
72
- */
73
- async function* walkDocs(dir: string): AsyncGenerator<string> {
74
- const entries = await fs.readdir(dir, { withFileTypes: true });
75
- for (const entry of entries) {
76
- const fullPath = path.join(dir, entry.name);
77
- if (entry.isDirectory()) {
78
- if (["node_modules", ".next", ".git", "api"].includes(entry.name)) {
79
- continue;
80
- }
81
- yield* walkDocs(fullPath);
82
- } else {
83
- const ext = path.extname(entry.name).toLowerCase();
84
- if (VALID_EXT.has(ext) && entry.name.startsWith("page.")) {
85
- yield fullPath;
86
- }
87
- }
88
- }
89
- }
90
-
91
- /**
92
- * Extract content blocks from a file
93
- */
94
- function extractContentBlocks(fileText: string): string[] {
95
- const results: string[] = [];
96
-
97
- const tplRegex = /(?:export\\s+)?const\\s+content\\s*=\\s*\`((?:\\\\\`|[^\`])*)\`\\s*;/g;
98
- let m: RegExpExecArray | null;
99
- while ((m = tplRegex.exec(fileText)) !== null) {
100
- results.push(m[1]);
101
- }
102
-
103
- const sglRegex = /(?:export\\s+)?const\\s+content\\s*=\\s*'([^']*)'\\s*;/g;
104
- while ((m = sglRegex.exec(fileText)) !== null) {
105
- results.push(m[1]);
106
- }
107
-
108
- const dblRegex = /(?:export\\s+)?const\\s+content\\s*=\\s*"([^"]*)"\\s*;/g;
109
- while ((m = dblRegex.exec(fileText)) !== null) {
110
- results.push(m[1]);
111
- }
112
-
113
- return results;
114
- }
115
-
116
- /**
117
- * Convert a page file path to its URL path, stripping the leading "app/"
118
- * and Next.js route group segments like "(site)" which never appear in URLs.
119
- */
120
- function toDocPath(pagePath: string): string {
121
- return (
122
- path
123
- .dirname(pagePath)
124
- .replace(/^app\\/?/, "")
125
- .split("/")
126
- .filter((seg) => !(seg.startsWith("(") && seg.endsWith(")")))
127
- .join("/") || "/"
128
- );
129
- }
130
-
131
- /**
132
- * Get the title from markdown content
133
- */
134
- function extractTitle(content: string): string {
135
- const match = content.match(/^#\\s+(.+)$/m);
136
- return match ? match[1].trim() : "Untitled";
137
- }
138
-
139
103
  /**
140
104
  * List all documentation resources
141
105
  */
142
106
  export async function listDocs(
143
107
  params?: ListDocsParams,
144
108
  ): Promise<DocsResource[]> {
145
- const resources: DocsResource[] = [];
146
- const filterDir = params?.directory;
147
-
148
- for await (const filePath of walkDocs(APP_DIR)) {
149
- const relativePath = path.join("app", path.relative(APP_DIR, filePath));
150
-
151
- if (filterDir && !relativePath.includes(filterDir)) {
152
- continue;
153
- }
154
-
155
- try {
156
- const fileContent = await fs.readFile(filePath, "utf8");
157
- const blocks = extractContentBlocks(fileContent);
158
- const content = blocks.join("\\n\\n");
159
- const title = extractTitle(content);
160
- const docPath = toDocPath(relativePath);
161
-
162
- resources.push({
163
- uri: \`docs://\${docPath}\`,
164
- name: title,
165
- path: relativePath,
166
- content,
167
- });
168
- } catch (error) {
169
- console.warn(\`Failed to read doc file: \${filePath}\`, error);
170
- }
171
- }
172
-
173
- return resources;
109
+ const docsContent = loadDocsContent();
110
+ const filterDir = params?.directory?.replace(/\\\\/g, "/");
111
+ const resources = filterDir
112
+ ? docsContent.filter((doc) => doc.path.includes(filterDir))
113
+ : docsContent;
114
+ return resources.map((doc) => ({ ...doc }));
174
115
  }
175
116
 
176
117
  /**
@@ -179,41 +120,28 @@ export async function listDocs(
179
120
  export async function getDoc(
180
121
  params: GetDocParams,
181
122
  ): Promise<DocsResource | null> {
182
- let targetPath = params.path;
183
-
184
- // Normalize path - strip leading "app/" if present to get the relative part
185
- const relativePart = targetPath.replace(/^app\\//, "");
186
- if (!relativePart.includes("page.")) {
187
- targetPath = path.join("app", relativePart, "page.tsx");
188
- } else if (!targetPath.startsWith("app/")) {
189
- targetPath = path.join("app", relativePart);
190
- }
191
-
192
- const fullPath = path.join(APP_DIR, targetPath.replace(/^app\\//, ""));
193
-
194
- // Prevent path traversal
195
- const resolvedPath = path.resolve(fullPath);
196
- if (!resolvedPath.startsWith(path.resolve(APP_DIR))) {
197
- return null;
198
- }
199
-
200
- try {
201
- const fileContent = await fs.readFile(fullPath, "utf8");
202
- const blocks = extractContentBlocks(fileContent);
203
- const content = blocks.join("\\n\\n");
204
- const title = extractTitle(content);
205
- const docPath = toDocPath(targetPath);
206
-
207
- return {
208
- uri: \`docs://\${docPath}\`,
209
- name: title,
210
- path: targetPath,
211
- content,
212
- };
213
- } catch (error) {
214
- console.warn(\`Failed to read doc: \${targetPath}\`, error);
215
- return null;
216
- }
123
+ const docsContent = loadDocsContent();
124
+ const requested = params.path.trim().replace(/\\\\/g, "/");
125
+ if (!requested || requested.includes("\\0")) return null;
126
+
127
+ const withoutScheme = requested.replace(/^docs:\\/\\//, "");
128
+ const route = withoutScheme
129
+ .replace(/^app\\/(?:\\([^/]+\\)\\/)?/, "")
130
+ .replace(/(?:^|\\/)page\\.(?:tsx?|jsx?)$/, "")
131
+ .replace(/^\\/+|\\/+$/g, "");
132
+
133
+ const doc = docsContent.find((candidate) => {
134
+ const candidateRoute = candidate.uri
135
+ .replace(/^docs:\\/\\//, "")
136
+ .replace(/^\\/+|\\/+$/g, "");
137
+ return (
138
+ candidate.path === requested ||
139
+ candidate.uri === requested ||
140
+ candidateRoute === route
141
+ );
142
+ });
143
+
144
+ return doc ? { ...doc } : null;
217
145
  }
218
146
 
219
147
  /**
@@ -1 +1 @@
1
- export declare const playgroundAllowlistTemplate = "import allowlistData from \"@/services/openapi/playground-allowlist.json\";\n\n// A single request-execution target the API playground is permitted to call.\n// Derived at build time from the union of every OpenAPI spec's `servers`.\n// `allowPrivate` is set ONLY when the spec's own declared server host is itself\n// a loopback/private/metadata literal (the local-dev case).\nexport interface AllowlistEntry {\n scheme: \"http\" | \"https\";\n host: string;\n port: number | null;\n basePath?: string;\n allowPrivate?: boolean;\n}\n\nconst allowlist: AllowlistEntry[] = Array.isArray(allowlistData)\n ? (allowlistData as AllowlistEntry[])\n : [];\n\nexport function getAllowlist(): AllowlistEntry[] {\n return allowlist;\n}\n\nfunction defaultPort(scheme: string): number {\n return scheme === \"https\" ? 443 : 80;\n}\n\n/**\n * Returns the matching allowlist entry for a target URL, or null. Matches on\n * exact scheme + hostname + effective port, plus an optional base-path prefix.\n * This is isomorphic: the server proxy uses it as a hard gate; the client uses\n * it for a consistent pre-flight check (NOT a security boundary on its own).\n */\nexport function matchAllowlistIn(\n entries: AllowlistEntry[],\n targetUrl: string,\n): AllowlistEntry | null {\n let url: URL;\n try {\n url = new URL(targetUrl);\n } catch {\n return null;\n }\n const scheme =\n url.protocol === \"https:\"\n ? \"https\"\n : url.protocol === \"http:\"\n ? \"http\"\n : null;\n if (!scheme) return null;\n // Reject embedded credentials (userinfo) outright.\n if (url.username || url.password) return null;\n\n const host = url.hostname.toLowerCase().replace(/\\.$/, \"\");\n const port = url.port ? Number(url.port) : defaultPort(scheme);\n\n for (const entry of entries) {\n if (entry.scheme !== scheme) continue;\n if (entry.host !== host) continue;\n const entryPort = entry.port ?? defaultPort(entry.scheme);\n if (entryPort !== port) continue;\n if (entry.basePath && !url.pathname.startsWith(entry.basePath)) continue;\n return entry;\n }\n return null;\n}\n\nexport function matchAllowlist(targetUrl: string): AllowlistEntry | null {\n return matchAllowlistIn(allowlist, targetUrl);\n}\n";
1
+ export declare const playgroundAllowlistTemplate = "import allowlistData from \"@/services/openapi/playground-allowlist.json\";\n\n// A single request-execution target the API playground is permitted to call.\n// Derived at build time from the union of every OpenAPI spec's `servers`.\n// `allowPrivate` is set ONLY for a loopback server declared by the spec (the\n// local-development case). Private-network and metadata ranges stay blocked.\nexport interface AllowlistEntry {\n scheme: \"http\" | \"https\";\n host: string;\n port: number | null;\n basePath?: string;\n allowPrivate?: boolean;\n}\n\nconst allowlist: AllowlistEntry[] = Array.isArray(allowlistData)\n ? (allowlistData as AllowlistEntry[])\n : [];\n\nexport function getAllowlist(): AllowlistEntry[] {\n return allowlist;\n}\n\nfunction defaultPort(scheme: string): number {\n return scheme === \"https\" ? 443 : 80;\n}\n\n/**\n * Returns the matching allowlist entry for a target URL, or null. Matches on\n * exact scheme + hostname + effective port, plus an optional base-path prefix.\n * This is isomorphic: the server proxy uses it as a hard gate; the client uses\n * it for a consistent pre-flight check (NOT a security boundary on its own).\n */\nexport function matchAllowlistIn(\n entries: AllowlistEntry[],\n targetUrl: string,\n): AllowlistEntry | null {\n let url: URL;\n try {\n url = new URL(targetUrl);\n } catch {\n return null;\n }\n const scheme =\n url.protocol === \"https:\"\n ? \"https\"\n : url.protocol === \"http:\"\n ? \"http\"\n : null;\n if (!scheme) return null;\n // Reject embedded credentials (userinfo) outright.\n if (url.username || url.password) return null;\n\n const host = url.hostname\n .toLowerCase()\n .replace(/\\.$/, \"\")\n .replace(/^\\[|\\]$/g, \"\");\n const port = url.port ? Number(url.port) : defaultPort(scheme);\n\n for (const entry of entries) {\n if (entry.scheme !== scheme) continue;\n if (entry.host !== host) continue;\n const entryPort = entry.port ?? defaultPort(entry.scheme);\n if (entryPort !== port) continue;\n if (\n entry.basePath &&\n url.pathname !== entry.basePath &&\n !url.pathname.startsWith(entry.basePath + \"/\")\n ) {\n continue;\n }\n return entry;\n }\n return null;\n}\n\nexport function matchAllowlist(targetUrl: string): AllowlistEntry | null {\n return matchAllowlistIn(allowlist, targetUrl);\n}\n";
@@ -2,8 +2,8 @@ export const playgroundAllowlistTemplate = `import allowlistData from "@/service
2
2
 
3
3
  // A single request-execution target the API playground is permitted to call.
4
4
  // Derived at build time from the union of every OpenAPI spec's \`servers\`.
5
- // \`allowPrivate\` is set ONLY when the spec's own declared server host is itself
6
- // a loopback/private/metadata literal (the local-dev case).
5
+ // \`allowPrivate\` is set ONLY for a loopback server declared by the spec (the
6
+ // local-development case). Private-network and metadata ranges stay blocked.
7
7
  export interface AllowlistEntry {
8
8
  scheme: "http" | "https";
9
9
  host: string;
@@ -50,7 +50,10 @@ export function matchAllowlistIn(
50
50
  // Reject embedded credentials (userinfo) outright.
51
51
  if (url.username || url.password) return null;
52
52
 
53
- const host = url.hostname.toLowerCase().replace(/\\.$/, "");
53
+ const host = url.hostname
54
+ .toLowerCase()
55
+ .replace(/\\.$/, "")
56
+ .replace(/^\\[|\\]$/g, "");
54
57
  const port = url.port ? Number(url.port) : defaultPort(scheme);
55
58
 
56
59
  for (const entry of entries) {
@@ -58,7 +61,13 @@ export function matchAllowlistIn(
58
61
  if (entry.host !== host) continue;
59
62
  const entryPort = entry.port ?? defaultPort(entry.scheme);
60
63
  if (entryPort !== port) continue;
61
- if (entry.basePath && !url.pathname.startsWith(entry.basePath)) continue;
64
+ if (
65
+ entry.basePath &&
66
+ url.pathname !== entry.basePath &&
67
+ !url.pathname.startsWith(entry.basePath + "/")
68
+ ) {
69
+ continue;
70
+ }
62
71
  return entry;
63
72
  }
64
73
  return null;
@@ -1 +1 @@
1
- export declare const rateLimitTemplate = "const rateLimitMap = new Map<string, { count: number; resetTime: number }>();\n\nconst WINDOW_MS = 60_000; // 1 minute\nconst MAX_REQUESTS = 10;\n\n// Clean up stale entries periodically\nconst CLEANUP_INTERVAL_MS = 5 * 60_000;\nlet lastCleanup = Date.now();\n\nfunction cleanup() {\n const now = Date.now();\n if (now - lastCleanup < CLEANUP_INTERVAL_MS) return;\n lastCleanup = now;\n rateLimitMap.forEach((entry, key) => {\n if (now > entry.resetTime) {\n rateLimitMap.delete(key);\n }\n });\n}\n\nexport function rateLimit(ip: string): {\n allowed: boolean;\n retryAfter: number;\n} {\n cleanup();\n\n const now = Date.now();\n const entry = rateLimitMap.get(ip);\n\n if (!entry || now > entry.resetTime) {\n rateLimitMap.set(ip, { count: 1, resetTime: now + WINDOW_MS });\n return { allowed: true, retryAfter: 0 };\n }\n\n entry.count++;\n\n if (entry.count > MAX_REQUESTS) {\n const retryAfter = Math.ceil((entry.resetTime - now) / 1000);\n return { allowed: false, retryAfter };\n }\n\n return { allowed: true, retryAfter: 0 };\n}\n";
1
+ export declare const rateLimitTemplate = "const rateLimitMap = new Map<string, { count: number; resetTime: number }>();\n\nconst WINDOW_MS = 60_000; // 1 minute\nconst MAX_REQUESTS = 10;\nconst MAX_TRACKED_CLIENTS = 10_000;\n\n// Clean up stale entries periodically\nconst CLEANUP_INTERVAL_MS = 5 * 60_000;\nlet lastCleanup = Date.now();\n\nfunction cleanup() {\n const now = Date.now();\n if (now - lastCleanup < CLEANUP_INTERVAL_MS) return;\n lastCleanup = now;\n rateLimitMap.forEach((entry, key) => {\n if (now > entry.resetTime) {\n rateLimitMap.delete(key);\n }\n });\n}\n\nfunction validClientAddress(value: string | null): string | null {\n const candidate = value?.split(\",\")[0]?.trim();\n return candidate && /^[0-9a-f:.]{3,64}$/i.test(candidate) ? candidate : null;\n}\n\n/**\n * Web Request does not expose the peer address. Trust an IP header only when\n * the runtime identifies a platform that overwrites that specific header.\n * Self-hosted deployments fall back to one shared bucket and should enforce a\n * stronger distributed rate limit at their trusted reverse proxy.\n */\nfunction clientIdentity(request: Request): string {\n let platform = \"\";\n let address: string | null = null;\n\n if (process.env.VERCEL === \"1\") {\n platform = \"vercel\";\n address = validClientAddress(request.headers.get(\"x-vercel-forwarded-for\"));\n } else if (process.env.CF_PAGES === \"1\") {\n platform = \"cloudflare\";\n address = validClientAddress(request.headers.get(\"cf-connecting-ip\"));\n } else if (process.env.FLY_APP_NAME) {\n platform = \"fly\";\n address = validClientAddress(request.headers.get(\"fly-client-ip\"));\n }\n\n return address ? `${platform}:${address}` : \"shared:untrusted-proxy\";\n}\n\nexport function rateLimit(request: Request): {\n allowed: boolean;\n retryAfter: number;\n} {\n cleanup();\n\n const now = Date.now();\n const identity = clientIdentity(request);\n const entry = rateLimitMap.get(identity);\n\n if (!entry || now > entry.resetTime) {\n // Bound memory even when an attacker rotates spoofed forwarding headers.\n // Map iteration is insertion ordered, so remove the oldest tracked client.\n if (rateLimitMap.size >= MAX_TRACKED_CLIENTS) {\n const oldestKey = rateLimitMap.keys().next().value;\n if (oldestKey !== undefined) rateLimitMap.delete(oldestKey);\n }\n rateLimitMap.set(identity, { count: 1, resetTime: now + WINDOW_MS });\n return { allowed: true, retryAfter: 0 };\n }\n\n entry.count++;\n\n if (entry.count > MAX_REQUESTS) {\n const retryAfter = Math.ceil((entry.resetTime - now) / 1000);\n return { allowed: false, retryAfter };\n }\n\n return { allowed: true, retryAfter: 0 };\n}\n";