Skip to content

Commit 8d5c67f

Browse files
committed
docs(docs): generate an API reference from the package entry points
initPangularHub, the Vite plugin, the overlay, popup and HTTP entry points and the config types were only described in prose, so their exact names and signatures could drift from the code. Generate one page per public entry point of packages/devtools/package.json under api/, with every exported symbol, its kind, JSDoc summary, declaration and source link, and an index page. @internal symbols stay out, as in the published types. pnpm docs:api writes the pages and pnpm docs:test fails while one is stale. The pages join the sidebar and the installation page links to them. Both generator scripts now run prettier from the repository root, since apps/docs ignores its content folder.
1 parent f518b84 commit 8d5c67f

26 files changed

Lines changed: 2534 additions & 1 deletion

‎apps/docs/api-reference.spec.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import {readFileSync, readdirSync} from 'node:fs';
2+
import {join, resolve} from 'node:path';
3+
import * as prettier from 'prettier';
4+
import {API_DIR, readApiEntries, renderApiReference} from './api-reference';
5+
6+
const docsRoot = import.meta.dirname;
7+
const repoRoot = resolve(docsRoot, '../..');
8+
const dir = join(docsRoot, API_DIR);
9+
10+
describe('API reference', () => {
11+
it('matches the pages in the repository; run pnpm docs:api when it fails', async () => {
12+
const pages = renderApiReference(repoRoot, 'https://github.com/pangular-inspector/devtools');
13+
const onDisk = readdirSync(dir).filter((file) => file.endsWith('.md'));
14+
expect(onDisk.sort()).toEqual([...pages.keys()].sort());
15+
for (const [file, markdown] of pages) {
16+
const path = join(dir, file);
17+
const options = (await prettier.resolveConfig(path)) ?? {};
18+
const expected = await prettier.format(markdown, {...options, filepath: path});
19+
expect(readFileSync(path, 'utf8'), file).toBe(expected);
20+
}
21+
}, 60_000);
22+
23+
it('documents the entry points apps use, without internal symbols', () => {
24+
const entries = readApiEntries(repoRoot);
25+
const hub = entries.find((entry) => entry.slug === 'hub');
26+
expect(hub?.symbols.map((s) => s.name)).toContain('initPangularHub');
27+
expect(entries.some((entry) => entry.slug === 'internal-config')).toBe(false);
28+
}, 60_000);
29+
});

‎apps/docs/api-reference.ts‎

Lines changed: 229 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,229 @@
1+
import {readFileSync} from 'node:fs';
2+
import {join, posix} from 'node:path';
3+
import {Node, Project, ts, type JSDoc} from 'ts-morph';
4+
5+
/**
6+
* Builds the API reference pages in `src/content/api/` from the public entry
7+
* points of `@pangular-inspector/devtools`: the `exports` of
8+
* `packages/devtools/package.json`, read from their TypeScript sources.
9+
*
10+
* Each entry point gets one page with every symbol it exports: its kind, the
11+
* JSDoc summary, the declaration and a link to the source. Symbols marked
12+
* `@internal` are left out, as the published types leave them out.
13+
* `scripts/docs-api.mjs` writes the pages, and `api-reference.spec.ts`
14+
* fails when a page in the repository is stale.
15+
*/
16+
17+
export const API_DIR = 'src/content/api';
18+
19+
/** Entry points that are not part of the public API. */
20+
const SKIPPED_EXPORTS = new Set(['./package.json', './internal/config', '.']);
21+
22+
type Kind = 'class' | 'interface' | 'function' | 'const' | 'type' | 'enum';
23+
24+
interface ApiSymbol {
25+
name: string;
26+
kind: Kind;
27+
summary: string;
28+
tags: Array<{name: string; text: string}>;
29+
declaration: string;
30+
file: string;
31+
}
32+
33+
export interface ApiEntry {
34+
/** The import path, such as `@pangular-inspector/devtools/hub`. */
35+
specifier: string;
36+
/** The page slug, such as `hub`. */
37+
slug: string;
38+
source: string;
39+
symbols: ApiSymbol[];
40+
}
41+
42+
function kindOf(node: Node): Kind | null {
43+
if (Node.isClassDeclaration(node)) return 'class';
44+
if (Node.isInterfaceDeclaration(node)) return 'interface';
45+
if (Node.isFunctionDeclaration(node)) return 'function';
46+
if (Node.isVariableDeclaration(node)) return 'const';
47+
if (Node.isTypeAliasDeclaration(node)) return 'type';
48+
if (Node.isEnumDeclaration(node)) return 'enum';
49+
return null;
50+
}
51+
52+
function jsDocsOf(node: Node): JSDoc[] {
53+
const host = Node.isVariableDeclaration(node)
54+
? (node.getFirstAncestorByKind(ts.SyntaxKind.VariableStatement) ?? node)
55+
: node;
56+
return Node.isJSDocable(host) ? host.getJsDocs() : [];
57+
}
58+
59+
function declarationOf(nodes: Node[]): string {
60+
const [first] = nodes;
61+
if (Node.isFunctionDeclaration(first)) {
62+
const overloads = nodes.filter(Node.isFunctionDeclaration).filter((n) => n.isOverload());
63+
return (overloads.length ? overloads : [first])
64+
.map((n) => {
65+
const text = n.getText();
66+
const body = n.getBody();
67+
return clean(body ? text.slice(0, body.getStart() - n.getStart()) : text);
68+
})
69+
.join('\n');
70+
}
71+
if (Node.isClassDeclaration(first)) {
72+
const brace = first.getFirstChildByKind(ts.SyntaxKind.OpenBraceToken);
73+
const text = first.getText();
74+
return clean(brace ? text.slice(0, brace.getStart() - first.getStart()) : text);
75+
}
76+
if (Node.isVariableDeclaration(first)) {
77+
const type = first.getTypeNode()?.getText() ?? first.getType().getText(first);
78+
return `const ${first.getName()}: ${type}`;
79+
}
80+
return clean(first.getText());
81+
}
82+
83+
function clean(text: string): string {
84+
return text
85+
.trim()
86+
.replace(/^export\s+(default\s+)?(declare\s+)?/, '')
87+
.replace(/;$/, '');
88+
}
89+
90+
/** The entry points of the package, with the symbols each one exports. */
91+
export function readApiEntries(repoRoot: string): ApiEntry[] {
92+
const pkgDir = join(repoRoot, 'packages/devtools');
93+
const pkg = JSON.parse(readFileSync(join(pkgDir, 'package.json'), 'utf8')) as {
94+
name: string;
95+
exports: Record<string, string | {default?: string; import?: string}>;
96+
};
97+
const project = new Project({
98+
tsConfigFilePath: join(pkgDir, 'tsconfig.json'),
99+
skipAddingFilesFromTsConfig: true,
100+
});
101+
const entries: ApiEntry[] = [];
102+
for (const [key, target] of Object.entries(pkg.exports)) {
103+
if (SKIPPED_EXPORTS.has(key)) continue;
104+
const rel = typeof target === 'string' ? target : (target.import ?? target.default);
105+
if (!rel?.endsWith('.ts')) continue;
106+
const sourceFile = project.addSourceFileAtPath(join(pkgDir, rel));
107+
const symbols: ApiSymbol[] = [];
108+
for (const [name, decls] of sourceFile.getExportedDeclarations()) {
109+
const nodes = decls.filter((d) => kindOf(d));
110+
const first = nodes[0];
111+
if (!first || first.getSourceFile().isInNodeModules()) continue;
112+
const docs = nodes.flatMap(jsDocsOf);
113+
const tags = docs.flatMap((d) =>
114+
d.getTags().map((t) => ({name: t.getTagName(), text: (t.getCommentText() ?? '').trim()})),
115+
);
116+
if (tags.some((t) => t.name === 'internal')) continue;
117+
symbols.push({
118+
name,
119+
kind: kindOf(first)!,
120+
summary: docs.at(-1)?.getDescription().trim() ?? '',
121+
tags,
122+
declaration: declarationOf(nodes),
123+
file: posix.relative(repoRoot.replace(/\\/g, '/'), first.getSourceFile().getFilePath()),
124+
});
125+
}
126+
symbols.sort((a, b) => a.name.localeCompare(b.name));
127+
const slug = key === '.' ? 'index' : key.slice(2).replace(/\//g, '-');
128+
entries.push({
129+
specifier: key === '.' ? pkg.name : `${pkg.name}/${key.slice(2)}`,
130+
slug,
131+
source: posix.join('packages/devtools', rel.replace(/^\.\//, '')),
132+
symbols,
133+
});
134+
}
135+
return entries;
136+
}
137+
138+
const KIND_LABEL: Record<Kind, string> = {
139+
class: 'Class',
140+
interface: 'Interface',
141+
function: 'Function',
142+
const: 'Constant',
143+
type: 'Type',
144+
enum: 'Enum',
145+
};
146+
147+
/** JSDoc text as one markdown paragraph: `{@link X}` becomes `X` in code. */
148+
function prose(text: string): string {
149+
return text
150+
.replace(/\{@link\s+([^}\s|]+)(?:[\s|][^}]*)?\}/g, '`$1`')
151+
.replace(/\r/g, '')
152+
.trim();
153+
}
154+
155+
export function renderApiPage(entry: ApiEntry, githubUrl: string): string {
156+
const out = [
157+
'---',
158+
`title: '${entry.specifier}'`,
159+
`description: 'Every symbol the ${entry.specifier} entry point exports, with its declaration and JSDoc, generated from the package source.'`,
160+
'---',
161+
'',
162+
`<ngmd-hero title="${entry.slug}" gradient>`,
163+
` The symbols <code>${entry.specifier.replace('@', '&#64;')}</code> exports, generated from the package source.`,
164+
'</ngmd-hero>',
165+
'',
166+
`# ${entry.specifier}`,
167+
'',
168+
`Import from \`${entry.specifier}\`. This page is generated from [\`${entry.source}\`](${githubUrl}/blob/main/${entry.source}) and the files it re-exports. Run \`pnpm docs:api\` after you change the public API.`,
169+
'',
170+
];
171+
if (!entry.symbols.length) {
172+
out.push('This entry point exports no symbols. Importing it runs its side effect.', '');
173+
}
174+
for (const symbol of entry.symbols) {
175+
out.push(`## ${symbol.name}`, '');
176+
out.push(
177+
`${KIND_LABEL[symbol.kind]}. Source: [\`${symbol.file}\`](${githubUrl}/blob/main/${symbol.file}).`,
178+
'',
179+
);
180+
if (symbol.summary) out.push(prose(symbol.summary), '');
181+
const deprecated = symbol.tags.find((t) => t.name === 'deprecated');
182+
if (deprecated) out.push(`Deprecated. ${prose(deprecated.text)}`.trim(), '');
183+
out.push('```ts', symbol.declaration, '```', '');
184+
}
185+
return escapeEnv(out.join('\n'));
186+
}
187+
188+
/**
189+
* Vite replaces `process.env.NODE_ENV` and `import.meta.env.X` even inside the
190+
* compiled page, which breaks the build. The bracket form means the same and
191+
* is left alone, as the hand-written pages write it.
192+
*/
193+
function escapeEnv(text: string): string {
194+
return text.replace(/\b(process\.env|import\.meta\.env)\.([A-Za-z_]\w*)/g, "$1['$2']");
195+
}
196+
197+
export function renderApiIndex(entries: ApiEntry[]): string {
198+
const rows = entries.map(
199+
(entry) =>
200+
`| [\`${entry.specifier}\`](./${entry.slug}.md) | ${entry.symbols.length ? entry.symbols.map((s) => `\`${s.name}\``).join(', ') : 'None, it runs on import'} |`,
201+
);
202+
return [
203+
'---',
204+
'title: API reference',
205+
"description: 'The public entry points of @pangular-inspector/devtools and the symbols each one exports, generated from the package source.'",
206+
'---',
207+
'',
208+
'<ngmd-hero title="API reference" gradient>',
209+
' Every public entry point of the package and the symbols it exports, generated from the source.',
210+
'</ngmd-hero>',
211+
'',
212+
'# API reference',
213+
'',
214+
'Each entry point of `@pangular-inspector/devtools` has a page with every symbol it exports, its declaration and its JSDoc. The pages are generated from the package source, so names and types match the published code. [Installation](../getting-started/installation.md#entry-points) says what each entry point is for, and [Configuration](../getting-started/configuration.md) explains the options.',
215+
'',
216+
'| Entry point | Exports |',
217+
'| ----------- | ------- |',
218+
...rows,
219+
'',
220+
].join('\n');
221+
}
222+
223+
/** Every page, keyed by its path under `src/content/api/`. */
224+
export function renderApiReference(repoRoot: string, githubUrl: string): Map<string, string> {
225+
const entries = readApiEntries(repoRoot);
226+
const pages = new Map<string, string>([['index.md', renderApiIndex(entries)]]);
227+
for (const entry of entries) pages.set(`${entry.slug}.md`, renderApiPage(entry, githubUrl));
228+
return pages;
229+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
---
2+
title: '@pangular-inspector/devtools/capacitor-hook'
3+
description: 'Every symbol the @pangular-inspector/devtools/capacitor-hook entry point exports, with its declaration and JSDoc, generated from the package source.'
4+
---
5+
6+
<ngmd-hero title="capacitor-hook" gradient>
7+
The symbols <code>&#64;pangular-inspector/devtools/capacitor-hook</code> exports, generated from the package source.
8+
</ngmd-hero>
9+
10+
# @pangular-inspector/devtools/capacitor-hook
11+
12+
Import from `@pangular-inspector/devtools/capacitor-hook`. This page is generated from [`packages/devtools/src/capacitor-hook.ts`](https://github.com/pangular-inspector/devtools/blob/main/packages/devtools/src/capacitor-hook.ts) and the files it re-exports. Run `pnpm docs:api` after you change the public API.
13+
14+
## installCapacitorHook
15+
16+
Function. Source: [`packages/devtools/src/capacitor-hook.ts`](https://github.com/pangular-inspector/devtools/blob/main/packages/devtools/src/capacitor-hook.ts).
17+
18+
Starts logging plugin calls now. Safe to call more than once.
19+
20+
```ts
21+
function installCapacitorHook(options: Pick<CapacitorHookOptions, 'maxCalls'> = {}): void;
22+
```

0 commit comments

Comments
 (0)