doccupine 0.0.139 → 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 (151) 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 -1895
  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 +18 -0
  19. package/dist/lib/utils.js +125 -0
  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 +102 -25
  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 +411 -104
  38. package/dist/templates/components/Docs.d.ts +1 -1
  39. package/dist/templates/components/Docs.js +56 -13
  40. package/dist/templates/components/SearchDocs.d.ts +1 -1
  41. package/dist/templates/components/SearchDocs.js +63 -11
  42. package/dist/templates/components/SearchModalContent.d.ts +1 -1
  43. package/dist/templates/components/SearchModalContent.js +191 -49
  44. package/dist/templates/components/SideBar.d.ts +1 -1
  45. package/dist/templates/components/SideBar.js +8 -2
  46. package/dist/templates/components/layout/Accordion.d.ts +1 -1
  47. package/dist/templates/components/layout/Accordion.js +26 -3
  48. package/dist/templates/components/layout/ApiPlayground.d.ts +1 -1
  49. package/dist/templates/components/layout/ApiPlayground.js +4 -7
  50. package/dist/templates/components/layout/Badge.d.ts +1 -1
  51. package/dist/templates/components/layout/Badge.js +1 -1
  52. package/dist/templates/components/layout/Button.d.ts +1 -1
  53. package/dist/templates/components/layout/Button.js +4 -4
  54. package/dist/templates/components/layout/Callout.d.ts +1 -1
  55. package/dist/templates/components/layout/Callout.js +6 -6
  56. package/dist/templates/components/layout/Card.d.ts +1 -1
  57. package/dist/templates/components/layout/Card.js +9 -4
  58. package/dist/templates/components/layout/CherryThemeProvider.d.ts +1 -1
  59. package/dist/templates/components/layout/CherryThemeProvider.js +63 -12
  60. package/dist/templates/components/layout/Code.d.ts +1 -1
  61. package/dist/templates/components/layout/Code.js +5 -5
  62. package/dist/templates/components/layout/CopyButton.d.ts +1 -1
  63. package/dist/templates/components/layout/CopyButton.js +1 -1
  64. package/dist/templates/components/layout/DemoTheme.d.ts +1 -1
  65. package/dist/templates/components/layout/DemoTheme.js +8 -28
  66. package/dist/templates/components/layout/DocsComponents.d.ts +1 -1
  67. package/dist/templates/components/layout/DocsComponents.js +57 -18
  68. package/dist/templates/components/layout/GlobalStyles.d.ts +1 -1
  69. package/dist/templates/components/layout/GlobalStyles.js +15 -9
  70. package/dist/templates/components/layout/Prompt.d.ts +1 -1
  71. package/dist/templates/components/layout/Prompt.js +4 -7
  72. package/dist/templates/components/layout/Steps.d.ts +1 -1
  73. package/dist/templates/components/layout/Steps.js +7 -1
  74. package/dist/templates/components/layout/Tabs.d.ts +1 -1
  75. package/dist/templates/components/layout/Tabs.js +108 -19
  76. package/dist/templates/env.example.d.ts +1 -1
  77. package/dist/templates/env.example.js +11 -0
  78. package/dist/templates/eslint.config.d.ts +1 -1
  79. package/dist/templates/eslint.config.js +20 -0
  80. package/dist/templates/gitignore.d.ts +1 -1
  81. package/dist/templates/gitignore.js +4 -3
  82. package/dist/templates/lib/access.d.ts +1 -0
  83. package/dist/templates/lib/access.js +41 -0
  84. package/dist/templates/mdx/ai-assistant.mdx.d.ts +1 -1
  85. package/dist/templates/mdx/ai-assistant.mdx.js +17 -1
  86. package/dist/templates/mdx/api-playground.mdx.d.ts +1 -1
  87. package/dist/templates/mdx/api-playground.mdx.js +5 -3
  88. package/dist/templates/mdx/authentication.mdx.d.ts +1 -1
  89. package/dist/templates/mdx/authentication.mdx.js +5 -3
  90. package/dist/templates/mdx/commands.mdx.d.ts +1 -1
  91. package/dist/templates/mdx/commands.mdx.js +20 -6
  92. package/dist/templates/mdx/components.mdx.d.ts +1 -1
  93. package/dist/templates/mdx/components.mdx.js +3 -0
  94. package/dist/templates/mdx/deployment-and-hosting.mdx.d.ts +1 -1
  95. package/dist/templates/mdx/deployment-and-hosting.mdx.js +2 -2
  96. package/dist/templates/mdx/globals.mdx.d.ts +1 -1
  97. package/dist/templates/mdx/globals.mdx.js +14 -11
  98. package/dist/templates/mdx/model-context-protocol.mdx.d.ts +1 -1
  99. package/dist/templates/mdx/model-context-protocol.mdx.js +22 -35
  100. package/dist/templates/mdx/platform/ai-assistant.mdx.d.ts +1 -1
  101. package/dist/templates/mdx/platform/ai-assistant.mdx.js +23 -0
  102. package/dist/templates/mdx/platform/api-playground.mdx.d.ts +1 -1
  103. package/dist/templates/mdx/platform/api-playground.mdx.js +7 -0
  104. package/dist/templates/mdx/platform/authentication.mdx.d.ts +1 -0
  105. package/dist/templates/mdx/platform/authentication.mdx.js +63 -0
  106. package/dist/templates/mdx/platform/build-and-deploy.mdx.d.ts +1 -1
  107. package/dist/templates/mdx/platform/build-and-deploy.mdx.js +1 -1
  108. package/dist/templates/mdx/platform/import-from-github.mdx.d.ts +1 -1
  109. package/dist/templates/mdx/platform/import-from-github.mdx.js +2 -2
  110. package/dist/templates/mdx/platform/index.mdx.d.ts +1 -1
  111. package/dist/templates/mdx/platform/index.mdx.js +1 -0
  112. package/dist/templates/mdx/platform/mcp.mdx.d.ts +1 -1
  113. package/dist/templates/mdx/platform/mcp.mdx.js +2 -1
  114. package/dist/templates/mdx/platform/navigation-settings.mdx.d.ts +1 -1
  115. package/dist/templates/mdx/platform/navigation-settings.mdx.js +12 -1
  116. package/dist/templates/mdx/platform/publishing.mdx.d.ts +1 -1
  117. package/dist/templates/mdx/platform/publishing.mdx.js +43 -10
  118. package/dist/templates/mdx/platform/self-updating-docs.mdx.d.ts +1 -1
  119. package/dist/templates/mdx/platform/self-updating-docs.mdx.js +48 -9
  120. package/dist/templates/mdx/sections.mdx.d.ts +1 -1
  121. package/dist/templates/mdx/sections.mdx.js +4 -0
  122. package/dist/templates/mdx/space.mdx.d.ts +1 -0
  123. package/dist/templates/mdx/space.mdx.js +125 -0
  124. package/dist/templates/mdx/tabs.mdx.d.ts +1 -1
  125. package/dist/templates/mdx/tabs.mdx.js +4 -0
  126. package/dist/templates/next.config.js +20 -8
  127. package/dist/templates/package.js +3 -3
  128. package/dist/templates/prettierignore.d.ts +1 -1
  129. package/dist/templates/prettierignore.js +1 -0
  130. package/dist/templates/proxy.js +47 -19
  131. package/dist/templates/scripts/build-docs-index.d.ts +1 -1
  132. package/dist/templates/scripts/build-docs-index.js +1 -0
  133. package/dist/templates/services/mcp/docsContentStub.d.ts +1 -0
  134. package/dist/templates/services/mcp/docsContentStub.js +1 -0
  135. package/dist/templates/services/mcp/server.d.ts +1 -1
  136. package/dist/templates/services/mcp/server.js +140 -83
  137. package/dist/templates/services/mcp/tools.d.ts +1 -1
  138. package/dist/templates/services/mcp/tools.js +65 -137
  139. package/dist/templates/utils/playgroundAllowlist.d.ts +1 -1
  140. package/dist/templates/utils/playgroundAllowlist.js +13 -4
  141. package/dist/templates/utils/rateLimit.d.ts +1 -1
  142. package/dist/templates/utils/rateLimit.js +40 -3
  143. package/dist/templates/utils/requestBody.d.ts +1 -0
  144. package/dist/templates/utils/requestBody.js +56 -0
  145. package/dist/templates/utils/ssrfGuard.d.ts +1 -1
  146. package/dist/templates/utils/ssrfGuard.js +138 -33
  147. package/package.json +14 -9
  148. package/dist/lib/mdxToMarkdown.d.ts +0 -1
  149. package/dist/lib/mdxToMarkdown.js +0 -134
  150. package/dist/templates/mdx/image-and-embeds.mdx.d.ts +0 -1
  151. package/dist/templates/mdx/image-and-embeds.mdx.js +0 -118
@@ -0,0 +1,428 @@
1
+ import fs from "fs-extra";
2
+ import { open } from "node:fs/promises";
3
+ import path from "node:path";
4
+ const MARKER_FILE = ".doccupine-generated.json";
5
+ const SAFE_UNOWNED_FILES = new Set([".DS_Store", ".gitkeep", ".env"]);
6
+ const GENERATED_SUBTREES = new Set([
7
+ "app",
8
+ "components",
9
+ "lib",
10
+ "public",
11
+ "scripts",
12
+ "services",
13
+ "types",
14
+ "utils",
15
+ ]);
16
+ const GENERATED_TOP_LEVEL_FILES = new Set([
17
+ ".env.example",
18
+ ".gitignore",
19
+ ".npmrc",
20
+ ".prettierignore",
21
+ ".prettierrc",
22
+ "analytics.json",
23
+ "config.json",
24
+ "eslint.config.mjs",
25
+ "fonts.json",
26
+ "links.json",
27
+ "navigation.json",
28
+ "next.config.ts",
29
+ "package.json",
30
+ "pnpm-workspace.yaml",
31
+ "proxy.ts",
32
+ "sections.json",
33
+ "theme.json",
34
+ "tsconfig.json",
35
+ ]);
36
+ const claimedOutputRoots = new Map();
37
+ const LEGACY_FILE_FINGERPRINTS = [
38
+ {
39
+ path: "components/Docs.tsx",
40
+ fragments: [
41
+ "@/components/layout/DocsComponents",
42
+ "StyledMarkdownContainer",
43
+ "remarkGfm",
44
+ ],
45
+ },
46
+ {
47
+ path: "components/SideBar.tsx",
48
+ fragments: [
49
+ "@/components/layout/DocsComponents",
50
+ "StyledSidebar",
51
+ "function SideBar(",
52
+ ],
53
+ },
54
+ {
55
+ path: "components/layout/DocsComponents.tsx",
56
+ fragments: [
57
+ "StyledMarkdownContainer",
58
+ "function DocsContainer(",
59
+ "DocsSidebar",
60
+ ],
61
+ },
62
+ ];
63
+ function isSafeUnownedEntry(name) {
64
+ return SAFE_UNOWNED_FILES.has(name) || name.startsWith(".env.");
65
+ }
66
+ export function isPathInside(parent, candidate) {
67
+ const relative = path.relative(path.resolve(parent), path.resolve(candidate));
68
+ return (relative === "" ||
69
+ (relative !== ".." &&
70
+ !relative.startsWith(`..${path.sep}`) &&
71
+ !path.isAbsolute(relative)));
72
+ }
73
+ export function resolveWithin(root, ...segments) {
74
+ const resolvedRoot = path.resolve(root);
75
+ const candidate = path.resolve(resolvedRoot, ...segments);
76
+ if (!isPathInside(resolvedRoot, candidate)) {
77
+ throw new Error(`Refusing to write outside generated output: ${candidate} is not within ${resolvedRoot}`);
78
+ }
79
+ return candidate;
80
+ }
81
+ function identityFrom(lexicalRoot, realRoot, stat) {
82
+ return {
83
+ lexicalRoot,
84
+ realRoot,
85
+ dev: stat.dev,
86
+ ino: stat.ino,
87
+ };
88
+ }
89
+ function assertClaimedIdentity(identity) {
90
+ let lexicalStat;
91
+ let realRoot;
92
+ let realStat;
93
+ try {
94
+ lexicalStat = fs.lstatSync(identity.lexicalRoot);
95
+ realRoot = fs.realpathSync(identity.lexicalRoot);
96
+ realStat = fs.lstatSync(realRoot);
97
+ }
98
+ catch {
99
+ throw new Error(`Refusing generated operation in ${identity.lexicalRoot}: the claimed outputDir no longer exists or cannot be resolved.`);
100
+ }
101
+ if (lexicalStat.isSymbolicLink() ||
102
+ !lexicalStat.isDirectory() ||
103
+ realRoot !== identity.realRoot ||
104
+ lexicalStat.dev !== identity.dev ||
105
+ lexicalStat.ino !== identity.ino ||
106
+ !sameFile(lexicalStat, realStat)) {
107
+ throw new Error(`Refusing generated operation in ${identity.lexicalRoot}: the claimed outputDir was replaced or its physical identity changed.`);
108
+ }
109
+ }
110
+ function enclosingClaims(filePath) {
111
+ const resolvedPath = path.resolve(filePath);
112
+ return [...claimedOutputRoots.values()].filter((identity) => isPathInside(identity.lexicalRoot, resolvedPath) ||
113
+ isPathInside(identity.realRoot, resolvedPath));
114
+ }
115
+ function assertNoClaimedChildSymlinks(identity, filePath) {
116
+ const resolvedPath = path.resolve(filePath);
117
+ const root = isPathInside(identity.realRoot, resolvedPath)
118
+ ? identity.realRoot
119
+ : identity.lexicalRoot;
120
+ const relativeParent = path.relative(root, path.dirname(resolvedPath));
121
+ if (relativeParent === "" ||
122
+ relativeParent === ".." ||
123
+ relativeParent.startsWith(`..${path.sep}`) ||
124
+ path.isAbsolute(relativeParent)) {
125
+ return;
126
+ }
127
+ let current = root;
128
+ for (const component of relativeParent.split(path.sep).filter(Boolean)) {
129
+ current = path.join(current, component);
130
+ try {
131
+ if (fs.lstatSync(current).isSymbolicLink()) {
132
+ throw new Error(`Refusing generated operation at ${resolvedPath}: ${current} is a symbolic link. Replace it with a real path inside outputDir.`);
133
+ }
134
+ }
135
+ catch (error) {
136
+ if (errorCode(error) === "ENOENT")
137
+ return;
138
+ throw error;
139
+ }
140
+ }
141
+ }
142
+ /** Revalidates the claimed output root containing a previously resolved path. */
143
+ export function assertClaimedOutputPath(filePath) {
144
+ for (const identity of enclosingClaims(filePath)) {
145
+ assertClaimedIdentity(identity);
146
+ assertNoClaimedChildSymlinks(identity, filePath);
147
+ }
148
+ }
149
+ /**
150
+ * Resolves a generated destination and rejects any existing symlink component.
151
+ * This is synchronous so callers can validate immediately before an fs call.
152
+ */
153
+ export function resolveOutputPath(root, ...segments) {
154
+ const resolvedRoot = path.resolve(root);
155
+ assertClaimedOutputPath(resolvedRoot);
156
+ const lexicalCandidate = resolveWithin(resolvedRoot, ...segments);
157
+ const rootStat = fs.lstatSync(resolvedRoot);
158
+ if (rootStat.isSymbolicLink() || !rootStat.isDirectory()) {
159
+ throw new Error(`Refusing generated operation in ${resolvedRoot}: outputDir is not a real directory.`);
160
+ }
161
+ const realRoot = fs.realpathSync(resolvedRoot);
162
+ const currentRootStat = fs.lstatSync(resolvedRoot);
163
+ const realRootStat = fs.lstatSync(realRoot);
164
+ if (currentRootStat.isSymbolicLink() ||
165
+ !currentRootStat.isDirectory() ||
166
+ !sameFile(rootStat, currentRootStat) ||
167
+ !sameFile(currentRootStat, realRootStat)) {
168
+ throw new Error(`Refusing generated operation in ${resolvedRoot}: outputDir changed while its physical path was being resolved.`);
169
+ }
170
+ const relative = path.relative(resolvedRoot, lexicalCandidate);
171
+ const candidate = path.resolve(realRoot, relative);
172
+ let current = realRoot;
173
+ for (const component of relative.split(path.sep).filter(Boolean)) {
174
+ current = path.join(current, component);
175
+ try {
176
+ if (fs.lstatSync(current).isSymbolicLink()) {
177
+ throw new Error(`Refusing generated operation at ${candidate}: ${current} is a symbolic link. Replace it with a real path inside outputDir.`);
178
+ }
179
+ }
180
+ catch (error) {
181
+ if (errorCode(error) === "ENOENT")
182
+ break;
183
+ throw error;
184
+ }
185
+ }
186
+ return candidate;
187
+ }
188
+ function errorCode(error) {
189
+ return error && typeof error === "object" && "code" in error
190
+ ? String(error.code)
191
+ : undefined;
192
+ }
193
+ async function lstatIfPresent(filePath) {
194
+ try {
195
+ return await fs.lstat(filePath);
196
+ }
197
+ catch (error) {
198
+ if (errorCode(error) === "ENOENT")
199
+ return null;
200
+ throw error;
201
+ }
202
+ }
203
+ function sameFile(left, right) {
204
+ return left.dev === right.dev && left.ino === right.ino;
205
+ }
206
+ async function readStableRegularFile(outputDir, filePath, expectedStat) {
207
+ const handle = await open(filePath, "r");
208
+ try {
209
+ const beforeRead = await handle.stat();
210
+ if (!beforeRead.isFile() || !sameFile(expectedStat, beforeRead)) {
211
+ throw new Error(`Refusing to use ${outputDir}: ${filePath} changed while it was being opened. Run the command again after checking the directory.`);
212
+ }
213
+ const content = await handle.readFile("utf8");
214
+ const afterRead = await handle.stat();
215
+ if (!sameFile(beforeRead, afterRead) ||
216
+ beforeRead.size !== afterRead.size ||
217
+ beforeRead.mtimeMs !== afterRead.mtimeMs ||
218
+ beforeRead.ctimeMs !== afterRead.ctimeMs) {
219
+ throw new Error(`Refusing to use ${outputDir}: ${filePath} changed while it was being read. Run the command again after checking the directory.`);
220
+ }
221
+ return content;
222
+ }
223
+ finally {
224
+ await handle.close();
225
+ }
226
+ }
227
+ export async function readOutputFileIfPresent(root, ...segments) {
228
+ const filePath = resolveOutputPath(root, ...segments);
229
+ const stat = await lstatIfPresent(filePath);
230
+ if (!stat)
231
+ return null;
232
+ if (stat.isSymbolicLink() || !stat.isFile()) {
233
+ throw new Error(`Refusing generated read at ${filePath}: expected a regular file, not a symbolic link or directory.`);
234
+ }
235
+ return readStableRegularFile(root, filePath, stat);
236
+ }
237
+ function symlinkError(outputDir, linkPath, detail) {
238
+ return new Error(`Refusing to use ${outputDir}: symbolic link ${linkPath} ${detail}. Replace it with a real file or directory inside outputDir.`);
239
+ }
240
+ async function rejectGeneratedSymlink(outputDir, realOutputDir, linkPath) {
241
+ let target;
242
+ try {
243
+ target = await fs.realpath(linkPath);
244
+ }
245
+ catch {
246
+ throw symlinkError(outputDir, linkPath, "is dangling or cannot be resolved");
247
+ }
248
+ if (!isPathInside(realOutputDir, target)) {
249
+ throw symlinkError(outputDir, linkPath, `resolves outside outputDir to ${target}`);
250
+ }
251
+ throw symlinkError(outputDir, linkPath, `is inside a generated path and resolves to ${target}`);
252
+ }
253
+ async function inspectGeneratedSubtree(outputDir, realOutputDir, directory) {
254
+ const entries = await fs.readdir(directory);
255
+ for (const name of entries) {
256
+ const entryPath = path.join(directory, name);
257
+ const stat = await fs.lstat(entryPath);
258
+ if (stat.isSymbolicLink()) {
259
+ await rejectGeneratedSymlink(outputDir, realOutputDir, entryPath);
260
+ }
261
+ else if (stat.isDirectory()) {
262
+ await inspectGeneratedSubtree(outputDir, realOutputDir, entryPath);
263
+ }
264
+ }
265
+ }
266
+ function isGeneratedName(name) {
267
+ return (GENERATED_SUBTREES.has(name) ||
268
+ GENERATED_TOP_LEVEL_FILES.has(name) ||
269
+ name.startsWith(".doccupine-"));
270
+ }
271
+ async function isGeneratedPathName(outputDir, name, stat) {
272
+ if (isGeneratedName(name))
273
+ return true;
274
+ const lowercaseName = name.toLowerCase();
275
+ if (lowercaseName === name || !isGeneratedName(lowercaseName))
276
+ return false;
277
+ const lowercaseStat = await lstatIfPresent(path.join(outputDir, lowercaseName));
278
+ return lowercaseStat !== null && sameFile(stat, lowercaseStat);
279
+ }
280
+ async function assertSafeOutputLinks(outputDir, realOutputDir) {
281
+ const entries = await fs.readdir(realOutputDir);
282
+ for (const name of entries) {
283
+ const entryPath = path.join(realOutputDir, name);
284
+ const stat = await fs.lstat(entryPath);
285
+ const isGeneratedPath = await isGeneratedPathName(realOutputDir, name, stat);
286
+ if (stat.isSymbolicLink() && isGeneratedPath) {
287
+ await rejectGeneratedSymlink(outputDir, realOutputDir, entryPath);
288
+ }
289
+ else if (stat.isDirectory() &&
290
+ isGeneratedPath &&
291
+ GENERATED_SUBTREES.has(name.toLowerCase())) {
292
+ await inspectGeneratedSubtree(outputDir, realOutputDir, entryPath);
293
+ }
294
+ }
295
+ }
296
+ function isRecord(value) {
297
+ return value !== null && typeof value === "object" && !Array.isArray(value);
298
+ }
299
+ function hasStringProperty(value, property) {
300
+ return isRecord(value) && typeof value[property] === "string";
301
+ }
302
+ async function isRealDirectory(directory) {
303
+ try {
304
+ return (await fs.lstat(directory)).isDirectory();
305
+ }
306
+ catch {
307
+ return false;
308
+ }
309
+ }
310
+ async function matchesLegacyFileFingerprints(outputDir) {
311
+ for (const fingerprint of LEGACY_FILE_FINGERPRINTS) {
312
+ const filePath = resolveOutputPath(outputDir, fingerprint.path);
313
+ let content;
314
+ try {
315
+ content = await fs.readFile(filePath, "utf8");
316
+ }
317
+ catch {
318
+ return false;
319
+ }
320
+ if (!fingerprint.fragments.every((fragment) => content.includes(fragment))) {
321
+ return false;
322
+ }
323
+ }
324
+ return true;
325
+ }
326
+ async function looksLikeLegacyGeneratedApp(outputDir) {
327
+ try {
328
+ const packagePath = resolveOutputPath(outputDir, "package.json");
329
+ if (!(await fs.pathExists(packagePath)))
330
+ return false;
331
+ const packageJson = await fs.readJson(packagePath);
332
+ if (!isRecord(packageJson))
333
+ return false;
334
+ const scripts = packageJson.scripts;
335
+ const dependencies = packageJson.dependencies;
336
+ const devDependencies = packageJson.devDependencies;
337
+ return (packageJson.name === "doccupine" &&
338
+ packageJson.version === "0.1.0" &&
339
+ packageJson.private === true &&
340
+ isRecord(scripts) &&
341
+ scripts.dev === "next dev" &&
342
+ scripts.start === "next start" &&
343
+ hasStringProperty(dependencies, "next") &&
344
+ hasStringProperty(dependencies, "react") &&
345
+ hasStringProperty(dependencies, "react-dom") &&
346
+ (hasStringProperty(dependencies, "next-mdx-remote") ||
347
+ hasStringProperty(devDependencies, "next-mdx-remote") ||
348
+ hasStringProperty(dependencies, "react-markdown") ||
349
+ hasStringProperty(devDependencies, "react-markdown")) &&
350
+ (await isRealDirectory(resolveOutputPath(outputDir, "app"))) &&
351
+ (await matchesLegacyFileFingerprints(outputDir)));
352
+ }
353
+ catch {
354
+ return false;
355
+ }
356
+ }
357
+ /**
358
+ * Claims an empty output directory, recognizes directories generated by older
359
+ * Doccupine versions, and refuses to overwrite arbitrary existing projects.
360
+ */
361
+ export async function claimOutputDirectory(outputDir) {
362
+ const lexicalOutputDir = path.resolve(outputDir);
363
+ assertClaimedOutputPath(lexicalOutputDir);
364
+ const existingRoot = await lstatIfPresent(outputDir);
365
+ if (existingRoot?.isSymbolicLink()) {
366
+ throw symlinkError(outputDir, outputDir, "is the outputDir itself and may redirect generated operations");
367
+ }
368
+ if (existingRoot && !existingRoot.isDirectory()) {
369
+ throw new Error(`Refusing to use ${outputDir}: outputDir exists and is not a directory.`);
370
+ }
371
+ await fs.ensureDir(outputDir);
372
+ const createdRoot = await fs.lstat(outputDir);
373
+ if (createdRoot.isSymbolicLink() || !createdRoot.isDirectory()) {
374
+ throw new Error(`Refusing to use ${outputDir}: outputDir changed while it was being claimed.`);
375
+ }
376
+ const realOutputDir = await fs.realpath(outputDir);
377
+ const verifiedRoot = await fs.lstat(outputDir);
378
+ const realRoot = await fs.lstat(realOutputDir);
379
+ if (verifiedRoot.isSymbolicLink() ||
380
+ !verifiedRoot.isDirectory() ||
381
+ !sameFile(createdRoot, verifiedRoot) ||
382
+ !sameFile(verifiedRoot, realRoot)) {
383
+ throw new Error(`Refusing to use ${outputDir}: outputDir changed while its physical path was being resolved.`);
384
+ }
385
+ const claimedIdentity = identityFrom(lexicalOutputDir, realOutputDir, verifiedRoot);
386
+ // Validate links before reading ownership or allowing callers to remove app/.
387
+ // Installed dependencies are outside the generated subtrees and are not
388
+ // traversed; generated direct output entries are still checked before use.
389
+ await assertSafeOutputLinks(outputDir, realOutputDir);
390
+ const markerPath = path.join(realOutputDir, MARKER_FILE);
391
+ const markerStat = await lstatIfPresent(markerPath);
392
+ if (markerStat) {
393
+ if (markerStat.isSymbolicLink() || !markerStat.isFile()) {
394
+ throw new Error(`Refusing to use ${outputDir}: ${MARKER_FILE} must be a regular file, not a symbolic link or directory. Replace it with a valid Doccupine marker or remove the directory manually.`);
395
+ }
396
+ const markerContent = await readStableRegularFile(outputDir, markerPath, markerStat);
397
+ let marker;
398
+ try {
399
+ marker = JSON.parse(markerContent);
400
+ }
401
+ catch {
402
+ throw new Error(`Refusing to use ${outputDir}: ${MARKER_FILE} is invalid. Restore or remove the directory manually.`);
403
+ }
404
+ if (marker.generator !== "doccupine") {
405
+ throw new Error(`Refusing to use ${outputDir}: ${MARKER_FILE} is invalid. Restore or remove the directory manually.`);
406
+ }
407
+ assertClaimedIdentity(claimedIdentity);
408
+ claimedOutputRoots.set(lexicalOutputDir, claimedIdentity);
409
+ return;
410
+ }
411
+ const entries = await fs.readdir(realOutputDir);
412
+ const canClaim = entries.every(isSafeUnownedEntry) ||
413
+ (await looksLikeLegacyGeneratedApp(realOutputDir));
414
+ if (!canClaim) {
415
+ throw new Error(`Refusing to overwrite non-empty directory ${outputDir}. Choose an empty outputDir or a Doccupine-generated directory.`);
416
+ }
417
+ try {
418
+ await fs.writeFile(markerPath, `${JSON.stringify({ generator: "doccupine", schemaVersion: 1 }, null, 2)}\n`, { flag: "wx" });
419
+ }
420
+ catch (error) {
421
+ if (errorCode(error) === "EEXIST") {
422
+ throw new Error(`Refusing to use ${outputDir}: ${MARKER_FILE} changed while the directory was being claimed. Run the command again after checking the directory.`);
423
+ }
424
+ throw error;
425
+ }
426
+ assertClaimedIdentity(claimedIdentity);
427
+ claimedOutputRoots.set(lexicalOutputDir, claimedIdentity);
428
+ }
@@ -73,6 +73,7 @@ import { mcpToolsTemplate } from "../templates/services/mcp/tools.js";
73
73
  import { mcpTypesTemplate } from "../templates/services/mcp/types.js";
74
74
  import { vectorHelpersTemplate } from "../templates/services/mcp/vector.js";
75
75
  import { docsIndexStubTemplate } from "../templates/services/mcp/docsIndexStub.js";
76
+ import { docsContentStubTemplate } from "../templates/services/mcp/docsContentStub.js";
76
77
  import { llmConfigTemplate } from "../templates/services/llm/config.js";
77
78
  import { llmFactoryTemplate } from "../templates/services/llm/factory.js";
78
79
  import { llmIndexTemplate } from "../templates/services/llm/index.js";
@@ -81,6 +82,7 @@ import { buildDocsIndexScriptTemplate } from "../templates/scripts/build-docs-in
81
82
  import { posthogServerTemplate } from "../templates/lib/posthog.js";
82
83
  import { rssLibTemplate } from "../templates/lib/rss.js";
83
84
  import { siteGateTemplate } from "../templates/lib/siteGate.js";
85
+ import { accessControlTemplate } from "../templates/lib/access.js";
84
86
  import { styledDTemplate } from "../templates/types/styled.js";
85
87
  import { openapiTypesTemplate } from "../templates/types/openapi.js";
86
88
  import { orderNavItemsTemplate } from "../templates/utils/orderNavItems.js";
@@ -90,6 +92,7 @@ import { configTemplate } from "../templates/utils/config.js";
90
92
  import { playgroundAllowlistTemplate } from "../templates/utils/playgroundAllowlist.js";
91
93
  import { ssrfGuardTemplate } from "../templates/utils/ssrfGuard.js";
92
94
  import { apiSnippetsTemplate } from "../templates/utils/apiSnippets.js";
95
+ import { requestBodyTemplate } from "../templates/utils/requestBody.js";
93
96
  import { playgroundRoutesTemplate } from "../templates/app/api/playground/route.js";
94
97
  import { playgroundAllowlistStubTemplate } from "../templates/services/openapi/playgroundAllowlistStub.js";
95
98
  import { copyButtonTemplate } from "../templates/components/layout/CopyButton.js";
@@ -127,6 +130,7 @@ import { navigationMdxTemplate } from "../templates/mdx/navigation.mdx.js";
127
130
  import { promptMdxTemplate } from "../templates/mdx/prompt.mdx.js";
128
131
  import { sectionsMdxTemplate } from "../templates/mdx/sections.mdx.js";
129
132
  import { sidePanelMdxTemplate } from "../templates/mdx/side-panel.mdx.js";
133
+ import { spaceMdxTemplate } from "../templates/mdx/space.mdx.js";
130
134
  import { stepsMdxTemplate } from "../templates/mdx/steps.mdx.js";
131
135
  import { tabsMdxTemplate } from "../templates/mdx/tabs.mdx.js";
132
136
  import { themeMdxTemplate } from "../templates/mdx/theme.mdx.js";
@@ -145,6 +149,7 @@ import { platformThemeSettingsMdxTemplate } from "../templates/mdx/platform/them
145
149
  import { platformNavigationSettingsMdxTemplate } from "../templates/mdx/platform/navigation-settings.mdx.js";
146
150
  import { platformFontsSettingsMdxTemplate } from "../templates/mdx/platform/fonts-settings.mdx.js";
147
151
  import { platformFooterLinksMdxTemplate } from "../templates/mdx/platform/footer-links.mdx.js";
152
+ import { platformAuthenticationMdxTemplate } from "../templates/mdx/platform/authentication.mdx.js";
148
153
  import { platformAnalyticsMdxTemplate } from "../templates/mdx/platform/analytics.mdx.js";
149
154
  import { platformApiPlaygroundMdxTemplate } from "../templates/mdx/platform/api-playground.mdx.js";
150
155
  import { platformAiAssistantMdxTemplate } from "../templates/mdx/platform/ai-assistant.mdx.js";
@@ -178,6 +183,7 @@ export const appStructure = {
178
183
  "services/mcp/types.ts": mcpTypesTemplate,
179
184
  "services/mcp/vector.ts": vectorHelpersTemplate,
180
185
  "services/mcp/docs-index.json": docsIndexStubTemplate,
186
+ "services/mcp/docs-content.json": docsContentStubTemplate,
181
187
  "services/llm/config.ts": llmConfigTemplate,
182
188
  "services/llm/factory.ts": llmFactoryTemplate,
183
189
  "services/llm/index.ts": llmIndexTemplate,
@@ -189,6 +195,7 @@ export const appStructure = {
189
195
  "lib/posthog.ts": posthogServerTemplate,
190
196
  "lib/rss.ts": rssLibTemplate,
191
197
  "lib/siteGate.ts": siteGateTemplate,
198
+ "lib/access.ts": accessControlTemplate,
192
199
  "utils/branding.ts": brandingTemplate,
193
200
  "utils/mermaid.ts": mermaidTemplate,
194
201
  "utils/orderNavItems.ts": orderNavItemsTemplate,
@@ -199,6 +206,7 @@ export const appStructure = {
199
206
  "utils/playgroundAllowlist.ts": playgroundAllowlistTemplate,
200
207
  "utils/ssrfGuard.ts": ssrfGuardTemplate,
201
208
  "utils/apiSnippets.ts": apiSnippetsTemplate,
209
+ "utils/requestBody.ts": requestBodyTemplate,
202
210
  "components/Chat.tsx": chatTemplate,
203
211
  "components/LockBodyScroll.ts": lockBodyScrollTemplate,
204
212
  "components/Docs.tsx": docsTemplate,
@@ -259,6 +267,7 @@ export const appStructure = {
259
267
  // copies around — failing lint or importing modules that are gone.
260
268
  export const obsoleteFiles = [
261
269
  "components/ClickOutside.ts",
270
+ "utils/polishedCompat.ts",
262
271
  "components/layout/ClientThemeProvider.tsx",
263
272
  "components/layout/ThemeToggle.tsx",
264
273
  ];
@@ -295,6 +304,7 @@ export const startingDocsStructure = {
295
304
  "prompt.mdx": promptMdxTemplate,
296
305
  "sections.mdx": sectionsMdxTemplate,
297
306
  "side-panel.mdx": sidePanelMdxTemplate,
307
+ "space.mdx": spaceMdxTemplate,
298
308
  "steps.mdx": stepsMdxTemplate,
299
309
  "tabs.mdx": tabsMdxTemplate,
300
310
  "theme.mdx": themeMdxTemplate,
@@ -313,6 +323,7 @@ export const startingDocsStructure = {
313
323
  "platform/navigation-settings.mdx": platformNavigationSettingsMdxTemplate,
314
324
  "platform/fonts-settings.mdx": platformFontsSettingsMdxTemplate,
315
325
  "platform/footer-links.mdx": platformFooterLinksMdxTemplate,
326
+ "platform/authentication.mdx": platformAuthenticationMdxTemplate,
316
327
  "platform/analytics.mdx": platformAnalyticsMdxTemplate,
317
328
  "platform/ai-assistant.mdx": platformAiAssistantMdxTemplate,
318
329
  "platform/mcp.mdx": platformMcpMdxTemplate,
@@ -6,6 +6,11 @@ export interface ResolvedPackageManager {
6
6
  * even when its install dir is missing from the process PATH. */
7
7
  bin: string;
8
8
  }
9
+ /**
10
+ * Writes a generated file without exposing a partially-written version to the
11
+ * Next.js dev server or another watcher pass.
12
+ */
13
+ export declare function writeFileAtomic(filePath: string, content: string | Uint8Array): Promise<void>;
9
14
  /**
10
15
  * Chooses the package manager for the generated app. The app ships a pnpm
11
16
  * workspace, so pnpm is preferred whenever it can be found; npm is the fallback.
@@ -18,6 +23,19 @@ export declare function findAvailablePort(startPort: number): Promise<number>;
18
23
  export declare function generateSlug(filePath: string): string;
19
24
  export declare function getFullSlug(pageSlug: string, sectionSlug: string): string;
20
25
  export declare function escapeTemplateContent(content: string): string;
26
+ /**
27
+ * YAML-only gray-matter that never throws: unsupported tagged engines and
28
+ * malformed YAML frontmatter are reported as warnings and treated as having no
29
+ * frontmatter. The broken block is stripped from the body best-effort; an
30
+ * unterminated block passes through as-is and the generated app's MDX error
31
+ * panel absorbs it.
32
+ */
33
+ export declare function safeMatter(raw: string, label?: string): {
34
+ data: {
35
+ [key: string]: any;
36
+ };
37
+ content: string;
38
+ };
21
39
  /**
22
40
  * Renders `value` as a JS string literal using the same quote Prettier would
23
41
  * choose: double by default, switching to single when that needs fewer escapes
package/dist/lib/utils.js CHANGED
@@ -1,7 +1,102 @@
1
1
  import fs from "fs-extra";
2
+ import { randomBytes } from "node:crypto";
3
+ import { constants } from "node:fs";
4
+ import { open, unlink } from "node:fs/promises";
2
5
  import path from "path";
3
6
  import { execSync } from "child_process";
4
7
  import chalk from "chalk";
8
+ import matter from "gray-matter";
9
+ import { assertClaimedOutputPath } from "./output-safety.js";
10
+ async function createAtomicTempFile(filePath) {
11
+ const noFollow = typeof constants.O_NOFOLLOW === "number" ? constants.O_NOFOLLOW : 0;
12
+ const flags = constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | noFollow;
13
+ for (let attempt = 0; attempt < 10; attempt += 1) {
14
+ const tempPath = path.join(path.dirname(filePath), `.doccupine-${process.pid}-${randomBytes(16).toString("hex")}.tmp`);
15
+ try {
16
+ return { handle: await open(tempPath, flags, 0o666), tempPath };
17
+ }
18
+ catch (error) {
19
+ const code = error && typeof error === "object" && "code" in error
20
+ ? String(error.code)
21
+ : "";
22
+ if (code !== "EEXIST")
23
+ throw error;
24
+ }
25
+ }
26
+ throw new Error(`Unable to create a unique temporary file for ${filePath}`);
27
+ }
28
+ async function removeAtomicTempFile(tempPath) {
29
+ try {
30
+ await unlink(tempPath);
31
+ }
32
+ catch (error) {
33
+ const code = error && typeof error === "object" && "code" in error
34
+ ? String(error.code)
35
+ : "";
36
+ if (code !== "ENOENT")
37
+ throw error;
38
+ }
39
+ }
40
+ /**
41
+ * Writes a generated file without exposing a partially-written version to the
42
+ * Next.js dev server or another watcher pass.
43
+ */
44
+ export async function writeFileAtomic(filePath, content) {
45
+ assertClaimedOutputPath(filePath);
46
+ await fs.ensureDir(path.dirname(filePath));
47
+ assertClaimedOutputPath(filePath);
48
+ let handle;
49
+ let tempPath;
50
+ try {
51
+ ({ handle, tempPath } = await createAtomicTempFile(filePath));
52
+ if (typeof content === "string") {
53
+ await handle.writeFile(content, "utf8");
54
+ }
55
+ else {
56
+ await handle.writeFile(content);
57
+ }
58
+ await handle.close();
59
+ handle = undefined;
60
+ assertClaimedOutputPath(filePath);
61
+ try {
62
+ // Atomic replacement on POSIX: the destination is never absent or
63
+ // partially written, so dev-server watchers see one coherent change.
64
+ await fs.rename(tempPath, filePath);
65
+ return;
66
+ }
67
+ catch (error) {
68
+ const code = error && typeof error === "object" && "code" in error
69
+ ? String(error.code)
70
+ : "";
71
+ const windowsReplaceFailure = process.platform === "win32" && (code === "EPERM" || code === "EEXIST");
72
+ if (!windowsReplaceFailure)
73
+ throw error;
74
+ // Windows cannot always rename over an existing destination. fs-extra's
75
+ // overwrite move is the compatibility fallback for that platform only.
76
+ await fs.move(tempPath, filePath, { overwrite: true });
77
+ return;
78
+ }
79
+ }
80
+ catch (error) {
81
+ if (handle) {
82
+ try {
83
+ await handle.close();
84
+ }
85
+ catch {
86
+ // Preserve the original write/open error.
87
+ }
88
+ }
89
+ if (tempPath) {
90
+ try {
91
+ await removeAtomicTempFile(tempPath);
92
+ }
93
+ catch {
94
+ // Preserve the original error; cleanup is best effort.
95
+ }
96
+ }
97
+ throw error;
98
+ }
99
+ }
5
100
  /**
6
101
  * Locates a usable pnpm binary without relying solely on the caller's PATH.
7
102
  * Standalone pnpm installs (e.g. ~/Library/pnpm) expose PNPM_HOME but only add
@@ -94,6 +189,36 @@ export function escapeTemplateContent(content) {
94
189
  .replace(/`/g, "\\`")
95
190
  .replace(/\$\{/g, "\\${");
96
191
  }
192
+ /**
193
+ * YAML-only gray-matter that never throws: unsupported tagged engines and
194
+ * malformed YAML frontmatter are reported as warnings and treated as having no
195
+ * frontmatter. The broken block is stripped from the body best-effort; an
196
+ * unterminated block passes through as-is and the generated app's MDX error
197
+ * panel absorbs it.
198
+ */
199
+ export function safeMatter(raw, label) {
200
+ const taggedDelimiter = raw.match(/^\uFEFF?---[^\r\n]+(?:\r?\n|$)/);
201
+ if (taggedDelimiter) {
202
+ const where = label ? ` in ${label}` : "";
203
+ console.warn(chalk.yellow(`⚠️ Unsupported tagged frontmatter${where}; only YAML frontmatter is allowed.`));
204
+ return {
205
+ data: {},
206
+ content: raw.replace(/^\uFEFF?---[^\r\n]+\r?\n[\s\S]*?\r?\n---\r?\n?/, ""),
207
+ };
208
+ }
209
+ try {
210
+ const { data, content } = matter(raw);
211
+ return { data, content };
212
+ }
213
+ catch (error) {
214
+ const where = label ? ` in ${label}` : "";
215
+ console.warn(chalk.yellow(`⚠️ Invalid frontmatter${where}; ignoring it.`), error instanceof Error ? error.message : error);
216
+ return {
217
+ data: {},
218
+ content: raw.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, ""),
219
+ };
220
+ }
221
+ }
97
222
  /**
98
223
  * Renders `value` as a JS string literal using the same quote Prettier would
99
224
  * choose: double by default, switching to single when that needs fewer escapes