@blaaiz/docs-core 0.1.0
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/LICENSE +21 -0
- package/README.md +103 -0
- package/dist/chunk-3ZX4WIE3.js +2984 -0
- package/dist/chunk-3ZX4WIE3.js.map +1 -0
- package/dist/chunk-JCYR6RPE.js +31 -0
- package/dist/chunk-JCYR6RPE.js.map +1 -0
- package/dist/chunk-ZKOOKLZ3.js +124 -0
- package/dist/chunk-ZKOOKLZ3.js.map +1 -0
- package/dist/cli.js +534 -0
- package/dist/cli.js.map +1 -0
- package/dist/generator.cjs +508 -0
- package/dist/generator.cjs.map +1 -0
- package/dist/generator.d.cts +122 -0
- package/dist/generator.d.ts +122 -0
- package/dist/generator.js +177 -0
- package/dist/generator.js.map +1 -0
- package/dist/index.cjs +3024 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1182 -0
- package/dist/index.d.ts +1182 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -0
- package/dist/navigation-CGqFIPlP.d.cts +498 -0
- package/dist/navigation-CGqFIPlP.d.ts +498 -0
- package/dist/openapi-types-CJ6p5Cux.d.cts +78 -0
- package/dist/openapi-types-CJ6p5Cux.d.ts +78 -0
- package/dist/ui/api-try-it.cjs +654 -0
- package/dist/ui/api-try-it.cjs.map +1 -0
- package/dist/ui/api-try-it.d.cts +78 -0
- package/dist/ui/api-try-it.d.ts +78 -0
- package/dist/ui/api-try-it.js +509 -0
- package/dist/ui/api-try-it.js.map +1 -0
- package/dist/ui/ask-ai.cjs +810 -0
- package/dist/ui/ask-ai.cjs.map +1 -0
- package/dist/ui/ask-ai.d.cts +57 -0
- package/dist/ui/ask-ai.d.ts +57 -0
- package/dist/ui/ask-ai.js +808 -0
- package/dist/ui/ask-ai.js.map +1 -0
- package/dist/ui/copy-page.cjs +312 -0
- package/dist/ui/copy-page.cjs.map +1 -0
- package/dist/ui/copy-page.d.cts +33 -0
- package/dist/ui/copy-page.d.ts +33 -0
- package/dist/ui/copy-page.js +183 -0
- package/dist/ui/copy-page.js.map +1 -0
- package/dist/ui/mermaid.cjs +363 -0
- package/dist/ui/mermaid.cjs.map +1 -0
- package/dist/ui/mermaid.d.cts +13 -0
- package/dist/ui/mermaid.d.ts +13 -0
- package/dist/ui/mermaid.js +361 -0
- package/dist/ui/mermaid.js.map +1 -0
- package/dist/ui.cjs +661 -0
- package/dist/ui.cjs.map +1 -0
- package/dist/ui.d.cts +428 -0
- package/dist/ui.d.ts +428 -0
- package/dist/ui.js +537 -0
- package/dist/ui.js.map +1 -0
- package/package.json +145 -0
- package/patches/fumadocs-openapi.patch +173 -0
- package/skills/AGENTS-section.md +36 -0
- package/skills/SKILL.md +363 -0
- package/styles/api-reference.css +1417 -0
- package/styles/ask-ai.css +563 -0
- package/styles/auth.css +462 -0
- package/styles/docs.css +247 -0
- package/styles/home.css +376 -0
- package/templates/init/content/docs/index.mdx.tmpl +52 -0
- package/templates/init/content/docs/meta.json.tmpl +3 -0
- package/templates/init/content/docs.json.tmpl +12 -0
- package/templates/init/content/nav.json.tmpl +7 -0
- package/templates/init/docs.config.ts.tmpl +36 -0
- package/templates/init/env.example.tmpl +15 -0
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { O as OpenApiInfo, a as OpenApiServer, b as OpenApiDocument } from './openapi-types-CJ6p5Cux.cjs';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* `@blaaiz/docs-core/generator` — builds the docs content tree from `docs.json`.
|
|
5
|
+
*
|
|
6
|
+
* One call turns the site's navigation file into everything fumadocs needs:
|
|
7
|
+
* generated API pages placed in their configured groups, and `meta.json` files
|
|
8
|
+
* encoding tab and group order. Authors reorganize the docs by editing
|
|
9
|
+
* `docs.json` — never by moving files.
|
|
10
|
+
*
|
|
11
|
+
* Node-only. A site that publishes an API reference injects `createOpenAPI` and
|
|
12
|
+
* `generateFiles` from its own `fumadocs-openapi` install, so this package takes
|
|
13
|
+
* no dependency on it. A site of prose alone injects nothing: with no API pages
|
|
14
|
+
* in `docs.json` the generator writes the `meta.json` files and `nav.json` and
|
|
15
|
+
* never touches `fumadocs-openapi`.
|
|
16
|
+
*
|
|
17
|
+
* @packageDocumentation
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The two fumadocs-openapi functions the generator needs, injected by the site
|
|
22
|
+
* (`createOpenAPI` from `fumadocs-openapi/server`, `generateFiles` from
|
|
23
|
+
* `fumadocs-openapi`). Typed loosely so this package needs no fumadocs types.
|
|
24
|
+
*
|
|
25
|
+
* @public
|
|
26
|
+
*/
|
|
27
|
+
interface FumadocsOpenApi {
|
|
28
|
+
readonly createOpenAPI: (...args: never[]) => unknown;
|
|
29
|
+
readonly generateFiles: (...args: never[]) => unknown;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Options for {@link generateDocsTree}.
|
|
33
|
+
*
|
|
34
|
+
* @public
|
|
35
|
+
*/
|
|
36
|
+
interface GenerateDocsTreeOptions {
|
|
37
|
+
/** The site's content directory (holds `docs.json`, spec files, and `docs/`). */
|
|
38
|
+
readonly contentDir: string;
|
|
39
|
+
/** Path to the navigation file. Default `<contentDir>/docs.json`. */
|
|
40
|
+
readonly docsJson?: string;
|
|
41
|
+
/** Output directory for the page tree. Default `<contentDir>/docs`. */
|
|
42
|
+
readonly outDir?: string;
|
|
43
|
+
/** Folder for generated API pages. Default `api`. */
|
|
44
|
+
readonly apiDir?: string;
|
|
45
|
+
/**
|
|
46
|
+
* `info` block of the merged OpenAPI document. Required when `docs.json`
|
|
47
|
+
* publishes API pages; ignored on a site of prose alone, which merges no
|
|
48
|
+
* documents.
|
|
49
|
+
*/
|
|
50
|
+
readonly info?: OpenApiInfo;
|
|
51
|
+
/** Servers of the merged document. */
|
|
52
|
+
readonly servers?: readonly OpenApiServer[];
|
|
53
|
+
/** Same-origin proxy route for the try-it playground. */
|
|
54
|
+
readonly proxyUrl?: string;
|
|
55
|
+
/** URL base the fumadocs loader serves pages under. Default `/docs`. */
|
|
56
|
+
readonly baseUrl?: string;
|
|
57
|
+
/**
|
|
58
|
+
* The site's fumadocs-openapi functions. Required when `docs.json` publishes
|
|
59
|
+
* API pages; omit it on a site of prose alone.
|
|
60
|
+
*/
|
|
61
|
+
readonly fumadocs?: FumadocsOpenApi;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* A top-navigation link: one tab, pointing at its first page.
|
|
65
|
+
*
|
|
66
|
+
* @public
|
|
67
|
+
*/
|
|
68
|
+
interface NavLink {
|
|
69
|
+
readonly text: string;
|
|
70
|
+
readonly url: string;
|
|
71
|
+
/** The tab's icon name from `docs.json`, for the site to resolve. */
|
|
72
|
+
readonly icon?: string;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* What the generator produced.
|
|
76
|
+
*
|
|
77
|
+
* @public
|
|
78
|
+
*/
|
|
79
|
+
interface GenerateDocsTreeResult {
|
|
80
|
+
readonly pages: number;
|
|
81
|
+
readonly metas: number;
|
|
82
|
+
/**
|
|
83
|
+
* Top-nav links, one per tab, each pointing at the tab's first page — written
|
|
84
|
+
* to `<contentDir>/nav.json` for the site's layout. Keeps the top nav in sync
|
|
85
|
+
* with `docs.json` instead of a hand-maintained list.
|
|
86
|
+
*/
|
|
87
|
+
readonly navLinks: readonly NavLink[];
|
|
88
|
+
/**
|
|
89
|
+
* Page URL to HTTP method, written to `<contentDir>/api-methods.json` for the
|
|
90
|
+
* sidebar method badges (`apiMethodBadges` in `@blaaiz/docs-core/ui`).
|
|
91
|
+
*/
|
|
92
|
+
readonly methodsByUrl: Readonly<Record<string, string>>;
|
|
93
|
+
/** The merged OpenAPI document (reusable for the runtime page renderer). */
|
|
94
|
+
readonly document: OpenApiDocument;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Build the docs content tree from `docs.json`.
|
|
98
|
+
*
|
|
99
|
+
* Reads the navigation, merges every referenced spec, generates one page per
|
|
100
|
+
* declared endpoint into its configured group folder, and writes the
|
|
101
|
+
* `meta.json` files that give the sidebar the navigation's exact structure and
|
|
102
|
+
* order. Operations present in a spec but not declared in `docs.json` get no
|
|
103
|
+
* page — the navigation decides what is published, as on Mintlify.
|
|
104
|
+
*
|
|
105
|
+
* A site of prose alone needs neither option: with no API pages in `docs.json`
|
|
106
|
+
* the run writes the `meta.json` files, `nav.json`, and an empty
|
|
107
|
+
* `api-methods.json`, and never loads `fumadocs-openapi`.
|
|
108
|
+
*
|
|
109
|
+
* @example
|
|
110
|
+
* ```ts
|
|
111
|
+
* // A site of prose alone.
|
|
112
|
+
* await generateDocsTree({ contentDir: 'content' });
|
|
113
|
+
* ```
|
|
114
|
+
*
|
|
115
|
+
* @param options - directories, document info, and the injected fumadocs functions
|
|
116
|
+
* @returns counts and the merged document
|
|
117
|
+
* @throws when `docs.json` publishes API pages and `fumadocs` or `info` is missing
|
|
118
|
+
* @public
|
|
119
|
+
*/
|
|
120
|
+
declare function generateDocsTree(options: GenerateDocsTreeOptions): Promise<GenerateDocsTreeResult>;
|
|
121
|
+
|
|
122
|
+
export { type FumadocsOpenApi, type GenerateDocsTreeOptions, type GenerateDocsTreeResult, type NavLink, generateDocsTree };
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { O as OpenApiInfo, a as OpenApiServer, b as OpenApiDocument } from './openapi-types-CJ6p5Cux.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* `@blaaiz/docs-core/generator` — builds the docs content tree from `docs.json`.
|
|
5
|
+
*
|
|
6
|
+
* One call turns the site's navigation file into everything fumadocs needs:
|
|
7
|
+
* generated API pages placed in their configured groups, and `meta.json` files
|
|
8
|
+
* encoding tab and group order. Authors reorganize the docs by editing
|
|
9
|
+
* `docs.json` — never by moving files.
|
|
10
|
+
*
|
|
11
|
+
* Node-only. A site that publishes an API reference injects `createOpenAPI` and
|
|
12
|
+
* `generateFiles` from its own `fumadocs-openapi` install, so this package takes
|
|
13
|
+
* no dependency on it. A site of prose alone injects nothing: with no API pages
|
|
14
|
+
* in `docs.json` the generator writes the `meta.json` files and `nav.json` and
|
|
15
|
+
* never touches `fumadocs-openapi`.
|
|
16
|
+
*
|
|
17
|
+
* @packageDocumentation
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The two fumadocs-openapi functions the generator needs, injected by the site
|
|
22
|
+
* (`createOpenAPI` from `fumadocs-openapi/server`, `generateFiles` from
|
|
23
|
+
* `fumadocs-openapi`). Typed loosely so this package needs no fumadocs types.
|
|
24
|
+
*
|
|
25
|
+
* @public
|
|
26
|
+
*/
|
|
27
|
+
interface FumadocsOpenApi {
|
|
28
|
+
readonly createOpenAPI: (...args: never[]) => unknown;
|
|
29
|
+
readonly generateFiles: (...args: never[]) => unknown;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Options for {@link generateDocsTree}.
|
|
33
|
+
*
|
|
34
|
+
* @public
|
|
35
|
+
*/
|
|
36
|
+
interface GenerateDocsTreeOptions {
|
|
37
|
+
/** The site's content directory (holds `docs.json`, spec files, and `docs/`). */
|
|
38
|
+
readonly contentDir: string;
|
|
39
|
+
/** Path to the navigation file. Default `<contentDir>/docs.json`. */
|
|
40
|
+
readonly docsJson?: string;
|
|
41
|
+
/** Output directory for the page tree. Default `<contentDir>/docs`. */
|
|
42
|
+
readonly outDir?: string;
|
|
43
|
+
/** Folder for generated API pages. Default `api`. */
|
|
44
|
+
readonly apiDir?: string;
|
|
45
|
+
/**
|
|
46
|
+
* `info` block of the merged OpenAPI document. Required when `docs.json`
|
|
47
|
+
* publishes API pages; ignored on a site of prose alone, which merges no
|
|
48
|
+
* documents.
|
|
49
|
+
*/
|
|
50
|
+
readonly info?: OpenApiInfo;
|
|
51
|
+
/** Servers of the merged document. */
|
|
52
|
+
readonly servers?: readonly OpenApiServer[];
|
|
53
|
+
/** Same-origin proxy route for the try-it playground. */
|
|
54
|
+
readonly proxyUrl?: string;
|
|
55
|
+
/** URL base the fumadocs loader serves pages under. Default `/docs`. */
|
|
56
|
+
readonly baseUrl?: string;
|
|
57
|
+
/**
|
|
58
|
+
* The site's fumadocs-openapi functions. Required when `docs.json` publishes
|
|
59
|
+
* API pages; omit it on a site of prose alone.
|
|
60
|
+
*/
|
|
61
|
+
readonly fumadocs?: FumadocsOpenApi;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* A top-navigation link: one tab, pointing at its first page.
|
|
65
|
+
*
|
|
66
|
+
* @public
|
|
67
|
+
*/
|
|
68
|
+
interface NavLink {
|
|
69
|
+
readonly text: string;
|
|
70
|
+
readonly url: string;
|
|
71
|
+
/** The tab's icon name from `docs.json`, for the site to resolve. */
|
|
72
|
+
readonly icon?: string;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* What the generator produced.
|
|
76
|
+
*
|
|
77
|
+
* @public
|
|
78
|
+
*/
|
|
79
|
+
interface GenerateDocsTreeResult {
|
|
80
|
+
readonly pages: number;
|
|
81
|
+
readonly metas: number;
|
|
82
|
+
/**
|
|
83
|
+
* Top-nav links, one per tab, each pointing at the tab's first page — written
|
|
84
|
+
* to `<contentDir>/nav.json` for the site's layout. Keeps the top nav in sync
|
|
85
|
+
* with `docs.json` instead of a hand-maintained list.
|
|
86
|
+
*/
|
|
87
|
+
readonly navLinks: readonly NavLink[];
|
|
88
|
+
/**
|
|
89
|
+
* Page URL to HTTP method, written to `<contentDir>/api-methods.json` for the
|
|
90
|
+
* sidebar method badges (`apiMethodBadges` in `@blaaiz/docs-core/ui`).
|
|
91
|
+
*/
|
|
92
|
+
readonly methodsByUrl: Readonly<Record<string, string>>;
|
|
93
|
+
/** The merged OpenAPI document (reusable for the runtime page renderer). */
|
|
94
|
+
readonly document: OpenApiDocument;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Build the docs content tree from `docs.json`.
|
|
98
|
+
*
|
|
99
|
+
* Reads the navigation, merges every referenced spec, generates one page per
|
|
100
|
+
* declared endpoint into its configured group folder, and writes the
|
|
101
|
+
* `meta.json` files that give the sidebar the navigation's exact structure and
|
|
102
|
+
* order. Operations present in a spec but not declared in `docs.json` get no
|
|
103
|
+
* page — the navigation decides what is published, as on Mintlify.
|
|
104
|
+
*
|
|
105
|
+
* A site of prose alone needs neither option: with no API pages in `docs.json`
|
|
106
|
+
* the run writes the `meta.json` files, `nav.json`, and an empty
|
|
107
|
+
* `api-methods.json`, and never loads `fumadocs-openapi`.
|
|
108
|
+
*
|
|
109
|
+
* @example
|
|
110
|
+
* ```ts
|
|
111
|
+
* // A site of prose alone.
|
|
112
|
+
* await generateDocsTree({ contentDir: 'content' });
|
|
113
|
+
* ```
|
|
114
|
+
*
|
|
115
|
+
* @param options - directories, document info, and the injected fumadocs functions
|
|
116
|
+
* @returns counts and the merged document
|
|
117
|
+
* @throws when `docs.json` publishes API pages and `fumadocs` or `info` is missing
|
|
118
|
+
* @public
|
|
119
|
+
*/
|
|
120
|
+
declare function generateDocsTree(options: GenerateDocsTreeOptions): Promise<GenerateDocsTreeResult>;
|
|
121
|
+
|
|
122
|
+
export { type FumadocsOpenApi, type GenerateDocsTreeOptions, type GenerateDocsTreeResult, type NavLink, generateDocsTree };
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { parseNavigation, planDocsTree, mergeOpenApiDocuments } from './chunk-3ZX4WIE3.js';
|
|
2
|
+
import { readFile, rm, mkdir, writeFile } from 'fs/promises';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
|
|
5
|
+
function slugify(value) {
|
|
6
|
+
return value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
|
|
7
|
+
}
|
|
8
|
+
function operationKeyOf(content) {
|
|
9
|
+
const match = /operations=\{(\[[\s\S]*?\])\}/.exec(content);
|
|
10
|
+
if (!match?.[1]) {
|
|
11
|
+
return null;
|
|
12
|
+
}
|
|
13
|
+
try {
|
|
14
|
+
const ops = JSON.parse(match[1]);
|
|
15
|
+
const op = ops[0];
|
|
16
|
+
return op ? `${op.method.toUpperCase()} ${op.path}` : null;
|
|
17
|
+
} catch {
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
var PROSE_ONLY_INFO = { title: "No API reference", version: "0.0.0" };
|
|
22
|
+
function requireFumadocs(value, apiPageCount) {
|
|
23
|
+
const because = `docs.json publishes ${String(apiPageCount)} API page(s)`;
|
|
24
|
+
if (typeof value !== "object" || value === null) {
|
|
25
|
+
throw new Error(
|
|
26
|
+
`[docs-core] generateDocsTree: the 'fumadocs' option is required because ${because}. Pass { createOpenAPI, generateFiles } from the site's fumadocs-openapi install.`
|
|
27
|
+
);
|
|
28
|
+
}
|
|
29
|
+
const candidate = value;
|
|
30
|
+
for (const name of ["createOpenAPI", "generateFiles"]) {
|
|
31
|
+
if (typeof candidate[name] !== "function") {
|
|
32
|
+
throw new Error(
|
|
33
|
+
`[docs-core] generateDocsTree: fumadocs.${name} must be a function because ${because}. Import ${name} from ${name === "createOpenAPI" ? "'fumadocs-openapi/server'" : "'fumadocs-openapi'"}.`
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return value;
|
|
38
|
+
}
|
|
39
|
+
async function generateDocsTree(options) {
|
|
40
|
+
const docsJson = options.docsJson ?? path.join(options.contentDir, "docs.json");
|
|
41
|
+
const outDir = options.outDir ?? path.join(options.contentDir, "docs");
|
|
42
|
+
const apiDir = options.apiDir ?? "api";
|
|
43
|
+
const navigation = parseNavigation(JSON.parse(await readFile(docsJson, "utf8")));
|
|
44
|
+
const plan = planDocsTree(navigation, { apiDir });
|
|
45
|
+
const placements = /* @__PURE__ */ new Map();
|
|
46
|
+
const groupPages = /* @__PURE__ */ new Map();
|
|
47
|
+
let pages = 0;
|
|
48
|
+
let document;
|
|
49
|
+
if (plan.apiPages.length === 0) {
|
|
50
|
+
document = mergeOpenApiDocuments([], { info: options.info ?? PROSE_ONLY_INFO });
|
|
51
|
+
} else {
|
|
52
|
+
const fumadocs = requireFumadocs(options.fumadocs, plan.apiPages.length);
|
|
53
|
+
if (options.info === void 0) {
|
|
54
|
+
throw new Error(
|
|
55
|
+
`[docs-core] generateDocsTree: the 'info' option is required because docs.json publishes ${String(plan.apiPages.length)} API page(s). Pass { title, version } for the merged OpenAPI document.`
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
const docs = await Promise.all(
|
|
59
|
+
plan.specs.map(
|
|
60
|
+
async (file) => JSON.parse(await readFile(path.join(options.contentDir, file), "utf8"))
|
|
61
|
+
)
|
|
62
|
+
);
|
|
63
|
+
document = mergeOpenApiDocuments(docs, {
|
|
64
|
+
info: options.info,
|
|
65
|
+
...options.servers ? { servers: options.servers } : {}
|
|
66
|
+
});
|
|
67
|
+
for (const page of plan.apiPages) {
|
|
68
|
+
const operation = document.paths[page.apiPath]?.[page.method.toLowerCase()];
|
|
69
|
+
if (!operation) {
|
|
70
|
+
throw new Error(
|
|
71
|
+
`[docs-core] docs.json references ${page.method} ${page.apiPath}, but ${page.file} defines no such operation.`
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
const slug = operation.operationId ?? slugify(`${page.method} ${page.apiPath}`);
|
|
75
|
+
placements.set(`${page.method.toUpperCase()} ${page.apiPath}`, { ...page, slug });
|
|
76
|
+
const group = groupPages.get(page.dir) ?? [];
|
|
77
|
+
group.push({ order: page.order, slug });
|
|
78
|
+
groupPages.set(page.dir, group);
|
|
79
|
+
}
|
|
80
|
+
await rm(path.join(outDir, apiDir), { recursive: true, force: true });
|
|
81
|
+
const createOpenAPI = fumadocs.createOpenAPI;
|
|
82
|
+
const generateFiles = fumadocs.generateFiles;
|
|
83
|
+
await generateFiles({
|
|
84
|
+
input: createOpenAPI({
|
|
85
|
+
input: { blaaiz: document },
|
|
86
|
+
...options.proxyUrl ? { proxyUrl: options.proxyUrl } : {}
|
|
87
|
+
}),
|
|
88
|
+
output: outDir,
|
|
89
|
+
per: "operation",
|
|
90
|
+
groupBy: "none",
|
|
91
|
+
beforeWrite(files) {
|
|
92
|
+
for (let i = files.length - 1; i >= 0; i -= 1) {
|
|
93
|
+
const file = files[i];
|
|
94
|
+
if (!file) {
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
const key = operationKeyOf(file.content);
|
|
98
|
+
const placement = key ? placements.get(key) : void 0;
|
|
99
|
+
if (!placement) {
|
|
100
|
+
files.splice(i, 1);
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
file.path = path.join(placement.dir, `${placement.slug}.mdx`);
|
|
104
|
+
pages += 1;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
const metas = [
|
|
110
|
+
...plan.metas,
|
|
111
|
+
...plan.apiGroups.map((group) => ({
|
|
112
|
+
path: `${group.dir}/meta.json`,
|
|
113
|
+
content: {
|
|
114
|
+
title: group.title,
|
|
115
|
+
pages: (groupPages.get(group.dir) ?? []).sort((a, b) => a.order - b.order).map((page) => page.slug)
|
|
116
|
+
}
|
|
117
|
+
}))
|
|
118
|
+
];
|
|
119
|
+
for (const meta of metas) {
|
|
120
|
+
const target = path.join(outDir, meta.path);
|
|
121
|
+
await mkdir(path.dirname(target), { recursive: true });
|
|
122
|
+
await writeFile(target, `${JSON.stringify(meta.content, null, 2)}
|
|
123
|
+
`);
|
|
124
|
+
}
|
|
125
|
+
const baseUrl = (options.baseUrl ?? "/docs").replace(/\/$/, "");
|
|
126
|
+
const docUrl = (file) => {
|
|
127
|
+
const clean = file.replace(/\/?index$/, "");
|
|
128
|
+
return clean ? `${baseUrl}/${clean}` : baseUrl;
|
|
129
|
+
};
|
|
130
|
+
const firstUrl = (items) => {
|
|
131
|
+
for (const item of items) {
|
|
132
|
+
if (item.kind === "group") {
|
|
133
|
+
const url = firstUrl(item.items);
|
|
134
|
+
if (url) {
|
|
135
|
+
return url;
|
|
136
|
+
}
|
|
137
|
+
} else if (item.kind === "doc") {
|
|
138
|
+
return docUrl(item.file);
|
|
139
|
+
} else {
|
|
140
|
+
const placement = placements.get(`${item.method.toUpperCase()} ${item.apiPath}`);
|
|
141
|
+
if (placement) {
|
|
142
|
+
return `${baseUrl}/${placement.dir}/${placement.slug}`;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return void 0;
|
|
147
|
+
};
|
|
148
|
+
const navLinks = [];
|
|
149
|
+
for (const tab of navigation) {
|
|
150
|
+
const url = firstUrl(tab.items);
|
|
151
|
+
if (url) {
|
|
152
|
+
navLinks.push({ text: tab.title, url, ...tab.icon ? { icon: tab.icon } : {} });
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
await writeFile(
|
|
156
|
+
path.join(options.contentDir, "nav.json"),
|
|
157
|
+
`${JSON.stringify(navLinks, null, 2)}
|
|
158
|
+
`
|
|
159
|
+
);
|
|
160
|
+
const methodsByUrl = {};
|
|
161
|
+
for (const page of plan.apiPages) {
|
|
162
|
+
const placement = placements.get(`${page.method.toUpperCase()} ${page.apiPath}`);
|
|
163
|
+
if (placement) {
|
|
164
|
+
methodsByUrl[`${baseUrl}/${placement.dir}/${placement.slug}`] = page.method.toUpperCase();
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
await writeFile(
|
|
168
|
+
path.join(options.contentDir, "api-methods.json"),
|
|
169
|
+
`${JSON.stringify(methodsByUrl, null, 2)}
|
|
170
|
+
`
|
|
171
|
+
);
|
|
172
|
+
return { pages, metas: metas.length, navLinks, methodsByUrl, document };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export { generateDocsTree };
|
|
176
|
+
//# sourceMappingURL=generator.js.map
|
|
177
|
+
//# sourceMappingURL=generator.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/generator/index.ts"],"names":[],"mappings":";;;;AA8GA,SAAS,QAAQ,KAAA,EAAuB;AACtC,EAAA,OAAO,KAAA,CACJ,aAAY,CACZ,OAAA,CAAQ,eAAe,GAAG,CAAA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GAAI,GAAA,CAAI,IAAA,GAAO,EAAE,MAAM,GAAA,CAAI,IAAA,EAAK,GAAI,IAAK,CAAA;AAAA,IACjF;AAAA,EACF;AACA,EAAA,MAAM,SAAA;AAAA,IACJ,IAAA,CAAK,IAAA,CAAK,OAAA,CAAQ,UAAA,EAAY,UAAU,CAAA;AAAA,IACxC,GAAG,IAAA,CAAK,SAAA,CAAU,QAAA,EAAU,IAAA,EAAM,CAAC,CAAC;AAAA;AAAA,GACtC;AAGA,EAAA,MAAM,eAAuC,EAAC;AAC9C,EAAA,KAAA,MAAW,IAAA,IAAQ,KAAK,QAAA,EAAU;AAChC,IAAA,MAAM,SAAA,GAAY,UAAA,CAAW,GAAA,CAAI,CAAA,EAAG,IAAA,CAAK,MAAA,CAAO,WAAA,EAAa,CAAA,CAAA,EAAI,IAAA,CAAK,OAAO,CAAA,CAAE,CAAA;AAC/E,IAAA,IAAI,SAAA,EAAW;AACb,MAAA,YAAA,CAAa,CAAA,EAAG,OAAO,CAAA,CAAA,EAAI,SAAA,CAAU,GAAG,CAAA,CAAA,EAAI,SAAA,CAAU,IAAI,CAAA,CAAE,CAAA,GAAI,IAAA,CAAK,MAAA,CAAO,WAAA,EAAY;AAAA,IAC1F;AAAA,EACF;AACA,EAAA,MAAM,SAAA;AAAA,IACJ,IAAA,CAAK,IAAA,CAAK,OAAA,CAAQ,UAAA,EAAY,kBAAkB,CAAA;AAAA,IAChD,GAAG,IAAA,CAAK,SAAA,CAAU,YAAA,EAAc,IAAA,EAAM,CAAC,CAAC;AAAA;AAAA,GAC1C;AAEA,EAAA,OAAO,EAAE,KAAA,EAAO,KAAA,EAAO,MAAM,MAAA,EAAQ,QAAA,EAAU,cAAc,QAAA,EAAS;AACxE","file":"generator.js","sourcesContent":["/**\n * `@blaaiz/docs-core/generator` — builds the docs content tree from `docs.json`.\n *\n * One call turns the site's navigation file into everything fumadocs needs:\n * generated API pages placed in their configured groups, and `meta.json` files\n * encoding tab and group order. Authors reorganize the docs by editing\n * `docs.json` — never by moving files.\n *\n * Node-only. A site that publishes an API reference injects `createOpenAPI` and\n * `generateFiles` from its own `fumadocs-openapi` install, so this package takes\n * no dependency on it. A site of prose alone injects nothing: with no API pages\n * in `docs.json` the generator writes the `meta.json` files and `nav.json` and\n * never touches `fumadocs-openapi`.\n *\n * @packageDocumentation\n */\n\nimport { mkdir, readFile, rm, writeFile } from 'node:fs/promises';\nimport path from 'node:path';\n\nimport { mergeOpenApiDocuments } from '../adapters/index.js';\nimport { parseNavigation } from '../adapters/index.js';\nimport type { NavItem, OpenApiDocument, OpenApiInfo, OpenApiServer } from '../core/index.js';\nimport { planDocsTree } from '../core/index.js';\n\n/**\n * The two fumadocs-openapi functions the generator needs, injected by the site\n * (`createOpenAPI` from `fumadocs-openapi/server`, `generateFiles` from\n * `fumadocs-openapi`). Typed loosely so this package needs no fumadocs types.\n *\n * @public\n */\nexport interface FumadocsOpenApi {\n readonly createOpenAPI: (...args: never[]) => unknown;\n readonly generateFiles: (...args: never[]) => unknown;\n}\n\n/**\n * Options for {@link generateDocsTree}.\n *\n * @public\n */\nexport interface GenerateDocsTreeOptions {\n /** The site's content directory (holds `docs.json`, spec files, and `docs/`). */\n readonly contentDir: string;\n /** Path to the navigation file. Default `<contentDir>/docs.json`. */\n readonly docsJson?: string;\n /** Output directory for the page tree. Default `<contentDir>/docs`. */\n readonly outDir?: string;\n /** Folder for generated API pages. Default `api`. */\n readonly apiDir?: string;\n /**\n * `info` block of the merged OpenAPI document. Required when `docs.json`\n * publishes API pages; ignored on a site of prose alone, which merges no\n * documents.\n */\n readonly info?: OpenApiInfo;\n /** Servers of the merged document. */\n readonly servers?: readonly OpenApiServer[];\n /** Same-origin proxy route for the try-it playground. */\n readonly proxyUrl?: string;\n /** URL base the fumadocs loader serves pages under. Default `/docs`. */\n readonly baseUrl?: string;\n /**\n * The site's fumadocs-openapi functions. Required when `docs.json` publishes\n * API pages; omit it on a site of prose alone.\n */\n readonly fumadocs?: FumadocsOpenApi;\n}\n\n/**\n * A top-navigation link: one tab, pointing at its first page.\n *\n * @public\n */\nexport interface NavLink {\n readonly text: string;\n readonly url: string;\n /** The tab's icon name from `docs.json`, for the site to resolve. */\n readonly icon?: string;\n}\n\n/**\n * What the generator produced.\n *\n * @public\n */\nexport interface GenerateDocsTreeResult {\n readonly pages: number;\n readonly metas: number;\n /**\n * Top-nav links, one per tab, each pointing at the tab's first page — written\n * to `<contentDir>/nav.json` for the site's layout. Keeps the top nav in sync\n * with `docs.json` instead of a hand-maintained list.\n */\n readonly navLinks: readonly NavLink[];\n /**\n * Page URL to HTTP method, written to `<contentDir>/api-methods.json` for the\n * sidebar method badges (`apiMethodBadges` in `@blaaiz/docs-core/ui`).\n */\n readonly methodsByUrl: Readonly<Record<string, string>>;\n /** The merged OpenAPI document (reusable for the runtime page renderer). */\n readonly document: OpenApiDocument;\n}\n\ninterface GeneratedFile {\n path: string;\n content: string;\n}\n\nfunction slugify(value: string): string {\n return value\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '');\n}\n\n/** The `METHOD path` key of the first operation a generated page renders. */\nfunction operationKeyOf(content: string): string | null {\n const match = /operations=\\{(\\[[\\s\\S]*?\\])\\}/.exec(content);\n if (!match?.[1]) {\n return null;\n }\n try {\n const ops = JSON.parse(match[1]) as { path: string; method: string }[];\n const op = ops[0];\n return op ? `${op.method.toUpperCase()} ${op.path}` : null;\n } catch {\n return null;\n }\n}\n\n/**\n * The `info` a docs-only run reports on its (empty) merged document. Nothing\n * renders it: with no API pages there is no reference view to title.\n */\nconst PROSE_ONLY_INFO: OpenApiInfo = { title: 'No API reference', version: '0.0.0' };\n\n/**\n * The fumadocs functions, checked. Called only when the navigation publishes\n * API pages, so the message can name the exact reason they are needed.\n */\nfunction requireFumadocs(value: unknown, apiPageCount: number): FumadocsOpenApi {\n const because = `docs.json publishes ${String(apiPageCount)} API page(s)`;\n if (typeof value !== 'object' || value === null) {\n throw new Error(\n `[docs-core] generateDocsTree: the 'fumadocs' option is required because ${because}. ` +\n \"Pass { createOpenAPI, generateFiles } from the site's fumadocs-openapi install.\",\n );\n }\n const candidate = value as Record<string, unknown>;\n for (const name of ['createOpenAPI', 'generateFiles'] as const) {\n if (typeof candidate[name] !== 'function') {\n throw new Error(\n `[docs-core] generateDocsTree: fumadocs.${name} must be a function because ${because}. ` +\n `Import ${name} from ${name === 'createOpenAPI' ? \"'fumadocs-openapi/server'\" : \"'fumadocs-openapi'\"}.`,\n );\n }\n }\n return value as FumadocsOpenApi;\n}\n\n/**\n * Build the docs content tree from `docs.json`.\n *\n * Reads the navigation, merges every referenced spec, generates one page per\n * declared endpoint into its configured group folder, and writes the\n * `meta.json` files that give the sidebar the navigation's exact structure and\n * order. Operations present in a spec but not declared in `docs.json` get no\n * page — the navigation decides what is published, as on Mintlify.\n *\n * A site of prose alone needs neither option: with no API pages in `docs.json`\n * the run writes the `meta.json` files, `nav.json`, and an empty\n * `api-methods.json`, and never loads `fumadocs-openapi`.\n *\n * @example\n * ```ts\n * // A site of prose alone.\n * await generateDocsTree({ contentDir: 'content' });\n * ```\n *\n * @param options - directories, document info, and the injected fumadocs functions\n * @returns counts and the merged document\n * @throws when `docs.json` publishes API pages and `fumadocs` or `info` is missing\n * @public\n */\nexport async function generateDocsTree(\n options: GenerateDocsTreeOptions,\n): Promise<GenerateDocsTreeResult> {\n const docsJson = options.docsJson ?? path.join(options.contentDir, 'docs.json');\n const outDir = options.outDir ?? path.join(options.contentDir, 'docs');\n const apiDir = options.apiDir ?? 'api';\n\n const navigation = parseNavigation(JSON.parse(await readFile(docsJson, 'utf8')));\n const plan = planDocsTree(navigation, { apiDir });\n\n // Where each planned API page lands. Both stay empty on a prose-only site.\n const placements = new Map<string, { dir: string; order: number; slug: string }>();\n const groupPages = new Map<string, { order: number; slug: string }[]>();\n let pages = 0;\n let document: OpenApiDocument;\n\n if (plan.apiPages.length === 0) {\n // A site of prose alone. Nothing to merge, nothing to generate, and — most\n // importantly — nothing removed: a hand-written folder named `api` is the\n // site's own content, not our output.\n document = mergeOpenApiDocuments([], { info: options.info ?? PROSE_ONLY_INFO });\n } else {\n const fumadocs = requireFumadocs(options.fumadocs, plan.apiPages.length);\n if (options.info === undefined) {\n throw new Error(\n `[docs-core] generateDocsTree: the 'info' option is required because docs.json ` +\n `publishes ${String(plan.apiPages.length)} API page(s). ` +\n 'Pass { title, version } for the merged OpenAPI document.',\n );\n }\n\n // Merge exactly the specs the navigation references.\n const docs = await Promise.all(\n plan.specs.map(\n async (file) =>\n JSON.parse(await readFile(path.join(options.contentDir, file), 'utf8')) as unknown,\n ),\n );\n document = mergeOpenApiDocuments(docs, {\n info: options.info,\n ...(options.servers ? { servers: options.servers } : {}),\n });\n\n // Resolve each planned page's slug from the merged document.\n for (const page of plan.apiPages) {\n const operation = document.paths[page.apiPath]?.[page.method.toLowerCase()] as\n { operationId?: string } | undefined;\n if (!operation) {\n throw new Error(\n `[docs-core] docs.json references ${page.method} ${page.apiPath}, ` +\n `but ${page.file} defines no such operation.`,\n );\n }\n const slug = operation.operationId ?? slugify(`${page.method} ${page.apiPath}`);\n placements.set(`${page.method.toUpperCase()} ${page.apiPath}`, { ...page, slug });\n const group = groupPages.get(page.dir) ?? [];\n group.push({ order: page.order, slug });\n groupPages.set(page.dir, group);\n }\n\n // Fresh API tree, then generate pages and route each into its planned folder.\n await rm(path.join(outDir, apiDir), { recursive: true, force: true });\n const createOpenAPI = fumadocs.createOpenAPI as (input: unknown) => unknown;\n const generateFiles = fumadocs.generateFiles as (input: unknown) => Promise<void>;\n await generateFiles({\n input: createOpenAPI({\n input: { blaaiz: document },\n ...(options.proxyUrl ? { proxyUrl: options.proxyUrl } : {}),\n }),\n output: outDir,\n per: 'operation',\n groupBy: 'none',\n beforeWrite(files: GeneratedFile[]) {\n for (let i = files.length - 1; i >= 0; i -= 1) {\n const file = files[i];\n if (!file) {\n continue;\n }\n const key = operationKeyOf(file.content);\n const placement = key ? placements.get(key) : undefined;\n if (!placement) {\n files.splice(i, 1); // not declared in docs.json -> not published\n continue;\n }\n file.path = path.join(placement.dir, `${placement.slug}.mdx`);\n pages += 1;\n }\n },\n });\n }\n\n // Meta files: the plan's static ones, plus page order for each API group.\n const metas = [\n ...plan.metas,\n ...plan.apiGroups.map((group) => ({\n path: `${group.dir}/meta.json`,\n content: {\n title: group.title,\n pages: (groupPages.get(group.dir) ?? [])\n .sort((a, b) => a.order - b.order)\n .map((page) => page.slug),\n },\n })),\n ];\n for (const meta of metas) {\n const target = path.join(outDir, meta.path);\n await mkdir(path.dirname(target), { recursive: true });\n await writeFile(target, `${JSON.stringify(meta.content, null, 2)}\\n`);\n }\n\n // Top-nav links: each tab points at its first page. The URL of an API page\n // needs its resolved slug, which is why this runs here, not in the planner.\n const baseUrl = (options.baseUrl ?? '/docs').replace(/\\/$/, '');\n const docUrl = (file: string): string => {\n const clean = file.replace(/\\/?index$/, '');\n return clean ? `${baseUrl}/${clean}` : baseUrl;\n };\n const firstUrl = (items: readonly NavItem[]): string | undefined => {\n for (const item of items) {\n if (item.kind === 'group') {\n const url = firstUrl(item.items);\n if (url) {\n return url;\n }\n } else if (item.kind === 'doc') {\n return docUrl(item.file);\n } else {\n const placement = placements.get(`${item.method.toUpperCase()} ${item.apiPath}`);\n if (placement) {\n return `${baseUrl}/${placement.dir}/${placement.slug}`;\n }\n }\n }\n return undefined;\n };\n const navLinks: NavLink[] = [];\n for (const tab of navigation) {\n const url = firstUrl(tab.items);\n if (url) {\n navLinks.push({ text: tab.title, url, ...(tab.icon ? { icon: tab.icon } : {}) });\n }\n }\n await writeFile(\n path.join(options.contentDir, 'nav.json'),\n `${JSON.stringify(navLinks, null, 2)}\\n`,\n );\n\n // Page URL -> HTTP method, for the sidebar method badges.\n const methodsByUrl: Record<string, string> = {};\n for (const page of plan.apiPages) {\n const placement = placements.get(`${page.method.toUpperCase()} ${page.apiPath}`);\n if (placement) {\n methodsByUrl[`${baseUrl}/${placement.dir}/${placement.slug}`] = page.method.toUpperCase();\n }\n }\n await writeFile(\n path.join(options.contentDir, 'api-methods.json'),\n `${JSON.stringify(methodsByUrl, null, 2)}\\n`,\n );\n\n return { pages, metas: metas.length, navLinks, methodsByUrl, document };\n}\n"]}
|