@xh/hoist-docs-builder 0.0.0-stage → 0.0.1

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.
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ /*
3
+ * This file belongs to Hoist, an application development toolkit
4
+ * developed by Extremely Heavy Industries (www.xh.io | info@xh.io)
5
+ *
6
+ * Copyright © 2026 Extremely Heavy Industries Inc.
7
+ */
8
+ import process from 'node:process';
9
+
10
+ import {run} from '../dist/cli/build-index.js';
11
+
12
+ await run(process.argv.slice(2));
@@ -0,0 +1,15 @@
1
+ export declare const SCHEMA_VERSION = 1;
2
+ /** The library a checkout's `package.json` describes: its id, import prefix and excluded dirs. */
3
+ export declare function libraryOptions(pkg: any, libraryId?: string): {
4
+ id: string;
5
+ importPrefix: string;
6
+ excludeDirs: string[];
7
+ };
8
+ /**
9
+ * Build the index object in memory. Pass the release version when building a tag: tagged commits
10
+ * carry the next snapshot version in `package.json`, the release version being set at publish.
11
+ */
12
+ export declare function buildIndex(version?: string, libraryId?: string): Promise<object>;
13
+ export declare function main(args: string[]): Promise<void>;
14
+ /** Entry point for `bin/hoist-docs-build.mjs`: report failures on stderr and exit non-zero. */
15
+ export declare function run(args: string[]): Promise<void>;
@@ -0,0 +1,199 @@
1
+ /*
2
+ * This file belongs to Hoist, an application development toolkit
3
+ * developed by Extremely Heavy Industries (www.xh.io | info@xh.io)
4
+ *
5
+ * Copyright © 2026 Extremely Heavy Industries Inc.
6
+ */
7
+ /**
8
+ * Build the Hoist Docs index file for a TypeScript library: hoist-react, hoist-chat-kit, or any
9
+ * library that declares itself in its `package.json`:
10
+ *
11
+ * "hoistDocs": {"id": "acme", "index": "hoist-docs/index.json.gz", "exclude": ["test"]}
12
+ *
13
+ * Writes one JSON file (schema v1, see `docs/index-schema.md`) holding the doc registry and
14
+ * markdown, every indexed symbol with its detail and members precomputed, and the member search
15
+ * index. The Hoist Docs tool reads this file; it never parses library source.
16
+ *
17
+ * A library runs it from its `prepack` script, so the index ships inside its npm package:
18
+ *
19
+ * hoist-docs-build --root . --file hoist-docs/index.json.gz
20
+ *
21
+ * Options: `--root <checkout>` (default: current directory), `--library <id>`, `--version <v>`
22
+ * (default: the checkout's `package.json` version, as set by the publish job), and the output -
23
+ * `--file <path>` (gzipped when it ends `.gz`), else `--out <dir>` (default `indexes`) with
24
+ * `--gzip`, writing `<id>-<version>.json[.gz]`. The checkout needs its dependencies installed, for
25
+ * type resolution.
26
+ */
27
+ import { execFileSync } from 'node:child_process';
28
+ import { mkdirSync, writeFileSync } from 'node:fs';
29
+ import { dirname, resolve } from 'node:path';
30
+ import { gzipSync } from 'node:zlib';
31
+ import { loadDocContent, loadRegistry, parseInstructions } from '../data/doc-registry.js';
32
+ import { log } from '../util/logger.js';
33
+ import { getIndexes, getMembers, getSymbolDetail, isPromiseExtension } from '../data/ts-registry.js';
34
+ import { readPackageJson, resolveRepoRoot, resolveRepoRootPosix, setLibraryOptions, setRepoRoot } from '../util/paths.js';
35
+ export const SCHEMA_VERSION = 1;
36
+ /**
37
+ * XH libraries built before they declared `hoistDocs` in their `package.json`, by package name.
38
+ * A declaration in the checkout wins.
39
+ */
40
+ const KNOWN_LIBRARIES = {
41
+ '@xh/hoist': { id: 'react' },
42
+ '@xh/hoist-chat-kit': { id: 'chat-kit', exclude: ['test'] }
43
+ };
44
+ /** The library a checkout's `package.json` describes: its id, import prefix and excluded dirs. */
45
+ export function libraryOptions(pkg, libraryId) {
46
+ const name = pkg?.name, declared = pkg?.hoistDocs, known = name ? KNOWN_LIBRARIES[name] : undefined, id = libraryId ?? declared?.id ?? known?.id;
47
+ if (!name || !id) {
48
+ throw new Error('Not a library this builder recognizes: its package.json needs a name and a "hoistDocs": {"id": ...} entry.');
49
+ }
50
+ return { id, importPrefix: name, excludeDirs: declared?.exclude ?? known?.exclude ?? [] };
51
+ }
52
+ /**
53
+ * Build the index object in memory. Pass the release version when building a tag: tagged commits
54
+ * carry the next snapshot version in `package.json`, the release version being set at publish.
55
+ */
56
+ export async function buildIndex(version, libraryId) {
57
+ const repoRoot = resolveRepoRoot(), posixRoot = resolveRepoRootPosix(), rel = (p) => (p.startsWith(posixRoot + '/') ? p.slice(posixRoot.length + 1) : p), pkg = readPackageJson(repoRoot), lib = libraryOptions(pkg, libraryId);
58
+ setLibraryOptions({ importPrefix: lib.importPrefix, excludeDirs: lib.excludeDirs });
59
+ // Docs - the checkout's own registry only. Each library builds its own index.
60
+ const registry = loadRegistry(), rawRegistry = JSON.parse(loadDocContent({ filePath: resolve(repoRoot, 'docs/doc-registry.json') })), viewerCategoryById = new Map(rawRegistry.entries.map((e) => [e.id, e.viewerCategory]));
61
+ const docEntries = registry.entries
62
+ .filter(e => e.library == null)
63
+ .map(e => ({
64
+ id: e.id,
65
+ title: e.title,
66
+ mcpCategory: e.mcpCategory,
67
+ viewerCategory: viewerCategoryById.get(e.id) ?? null,
68
+ description: e.description,
69
+ keywords: e.keywords,
70
+ aliases: e.aliases,
71
+ markdown: loadDocContent(e)
72
+ }));
73
+ // Symbols - every entry, with detail and (for classes and interfaces) all members.
74
+ const { symbols, members } = await getIndexes(), allEntries = [...symbols.values()].flat(), outSymbols = [];
75
+ for (const entry of allEntries) {
76
+ const detail = await getSymbolDetail(entry.name, {
77
+ filePath: entry.filePath,
78
+ kind: entry.kind
79
+ });
80
+ const sym = {
81
+ name: entry.name,
82
+ kind: entry.kind,
83
+ filePath: rel(entry.filePath),
84
+ sourcePackage: entry.sourcePackage,
85
+ isExported: entry.isExported,
86
+ importPath: entry.importPath,
87
+ isPromiseExtension: isPromiseExtension(entry) || undefined,
88
+ doc: entry.jsDoc,
89
+ hint: entry.mcpHint,
90
+ memberNames: entry.memberNames || undefined,
91
+ signature: detail?.signature ?? '',
92
+ extends: detail?.extends,
93
+ implements: detail?.implements?.length ? detail.implements : undefined,
94
+ decorators: detail?.decorators?.length ? detail.decorators : undefined,
95
+ constructorType: detail?.constructorType,
96
+ instanceOf: detail?.instanceOf
97
+ };
98
+ if (entry.kind === 'class' || entry.kind === 'interface') {
99
+ const result = await getMembers(entry.name, { filePath: entry.filePath });
100
+ if (result.ok && result.symbol.filePath === entry.filePath) {
101
+ sym.members = result.members.map(m => ({
102
+ name: m.name,
103
+ kind: m.kind,
104
+ type: m.type,
105
+ isStatic: m.isStatic,
106
+ isOptional: m.isOptional,
107
+ decorators: m.decorators,
108
+ doc: m.jsDoc,
109
+ default: m.default,
110
+ parameters: m.parameters,
111
+ returnType: m.returnType,
112
+ returns: m.returns,
113
+ inheritedFrom: m.inheritedFrom,
114
+ docInheritedFrom: m.jsDocInheritedFrom
115
+ }));
116
+ if (result.externalMembers.length)
117
+ sym.externalMembers = result.externalMembers;
118
+ }
119
+ }
120
+ outSymbols.push(sym);
121
+ }
122
+ const memberIndex = [...members.values()].flat().map((m) => ({
123
+ name: m.name,
124
+ memberKind: m.memberKind,
125
+ ownerName: m.ownerName,
126
+ ownerHint: m.ownerHint,
127
+ filePath: rel(m.filePath),
128
+ sourcePackage: m.sourcePackage,
129
+ isStatic: m.isStatic,
130
+ type: m.type,
131
+ doc: m.jsDoc,
132
+ docInheritedFrom: m.jsDocInheritedFrom,
133
+ default: m.default,
134
+ decorators: m.decorators
135
+ }));
136
+ // hoist-react's guidance is the server instructions themselves; another library's comes from
137
+ // its registry's `mcpInstructions`.
138
+ const instructions = lib.id === 'react'
139
+ ? null
140
+ : parseInstructions(rawRegistry.mcpInstructions, msg => log.warn(msg));
141
+ return {
142
+ schemaVersion: SCHEMA_VERSION,
143
+ library: {
144
+ id: lib.id,
145
+ name: lib.importPrefix,
146
+ version: version ?? pkg?.version ?? 'unknown',
147
+ language: 'typescript',
148
+ gitSha: gitSha(repoRoot),
149
+ builtAt: new Date().toISOString(),
150
+ description: pkg?.description ?? null,
151
+ ...(instructions ? { instructions } : {})
152
+ },
153
+ docs: {
154
+ mcpCategories: registry.mcpCategories,
155
+ viewerCategories: rawRegistry.viewerCategories ?? [],
156
+ entries: docEntries
157
+ },
158
+ symbols: outSymbols,
159
+ memberIndex
160
+ };
161
+ }
162
+ function gitSha(dir) {
163
+ try {
164
+ return execFileSync('git', ['rev-parse', 'HEAD'], { cwd: dir, encoding: 'utf8' }).trim();
165
+ }
166
+ catch {
167
+ return null;
168
+ }
169
+ }
170
+ //------------------------------------------------------------------
171
+ // CLI entry point
172
+ //------------------------------------------------------------------
173
+ export async function main(args) {
174
+ const arg = (name) => {
175
+ const i = args.indexOf(name);
176
+ return i >= 0 ? args[i + 1] : undefined;
177
+ };
178
+ setRepoRoot(arg('--root') ?? '.');
179
+ const start = Date.now(), index = await buildIndex(arg('--version'), arg('--library')), json = JSON.stringify(index), file = arg('--file'), gzip = file ? file.endsWith('.gz') : args.includes('--gzip'), outPath = file
180
+ ? resolve(file)
181
+ : resolve(arg('--out') ?? 'indexes', `${index.library.id}-${index.library.version}.json${gzip ? '.gz' : ''}`);
182
+ mkdirSync(dirname(outPath), { recursive: true });
183
+ writeFileSync(outPath, gzip ? gzipSync(json) : json);
184
+ console.log(`Wrote ${outPath}: ${index.docs.entries.length} docs, ${index.symbols.length} symbols, ` +
185
+ `${index.memberIndex.length} member index entries, ` +
186
+ `${(json.length / 1e6).toFixed(1)} MB JSON in ${((Date.now() - start) / 1000).toFixed(1)}s`);
187
+ }
188
+ /** Entry point for `bin/hoist-docs-build.mjs`: report failures on stderr and exit non-zero. */
189
+ export async function run(args) {
190
+ try {
191
+ await main(args);
192
+ }
193
+ catch (e) {
194
+ process.stderr.write(`hoist-docs-build: ${e?.message ?? e}\n`);
195
+ process.exitCode = 1;
196
+ }
197
+ }
198
+ if (import.meta.main)
199
+ await run(process.argv.slice(2));
@@ -0,0 +1,148 @@
1
+ /** MCP category metadata from the JSON registry. */
2
+ export interface McpCategory {
3
+ id: string;
4
+ title: string;
5
+ }
6
+ /** A single document in the registry. */
7
+ export interface DocEntry {
8
+ /**
9
+ * Unique identifier. For hoist-react docs, the file path relative to the repo root (e.g.
10
+ * 'core/README.md'). For companion library docs, that path prefixed with the package name
11
+ * (e.g. `@xh/hoist-chat-kit/core/README.md`).
12
+ */
13
+ id: string;
14
+ /** File path relative to the owning package root, as declared in its registry. */
15
+ path: string;
16
+ /** Package name of the companion library that owns this doc, or null for hoist-react. */
17
+ library: string | null;
18
+ /** Display title, e.g. 'Core Framework', 'Grid Component'. */
19
+ title: string;
20
+ /** Absolute file path on disk. */
21
+ filePath: string;
22
+ /** MCP category for filtering. */
23
+ mcpCategory: string;
24
+ /** Short description from the docs index. */
25
+ description: string;
26
+ /** Key topics/keywords for search matching. */
27
+ keywords: string[];
28
+ /**
29
+ * Optional curated shortcut IDs accepted by the doc-id resolver. Use only
30
+ * when the doc has an obvious short name that would otherwise be ambiguous
31
+ * across multiple entries -- the resolver auto-generates safe shortenings
32
+ * for unambiguous cases. Declared unprefixed - the resolver scopes a
33
+ * companion library's aliases under its package name.
34
+ */
35
+ aliases: string[];
36
+ /** What a companion doc's relative links resolve against. See {@link rewriteRelativeLinks}. */
37
+ links?: DocLinkContext;
38
+ }
39
+ /** The docs and source location that a companion doc's relative links resolve against. */
40
+ export interface DocLinkContext {
41
+ /** Package name, the prefix of each doc id. */
42
+ library: string;
43
+ /** Registry paths of the library's served docs. */
44
+ docPaths: ReadonlySet<string>;
45
+ /** Where agents find the package files. See {@link DocLibrary.sourcePath}. */
46
+ sourcePath: string;
47
+ }
48
+ /** A package whose docs are loaded: hoist-react itself, or an opted-in companion library. */
49
+ export interface DocLibrary {
50
+ /** Package name, e.g. `@xh/hoist` or `@xh/hoist-chat-kit`. */
51
+ name: string;
52
+ version: string;
53
+ /** The package.json description, for the server instructions. */
54
+ description: string;
55
+ /** Absolute package root on disk, with symlinks resolved. */
56
+ root: string;
57
+ /**
58
+ * Where agents find the package files: relative to the working directory when inside it,
59
+ * else absolute. Under pnpm, the `node_modules` link rather than the store path.
60
+ */
61
+ sourcePath: string;
62
+ /** True for hoist-react, whose doc ids carry no prefix. */
63
+ primary: boolean;
64
+ /** Id of the library's `docs/README.md` index, if it registers one. */
65
+ indexId: string | null;
66
+ docCount: number;
67
+ /**
68
+ * Guidance for agents from the library's `mcpInstructions`, for example which Hoist
69
+ * components it replaces. The server instructions and ping surfaces show it. Always null for
70
+ * hoist-react, whose guidance is the server instructions themselves.
71
+ */
72
+ instructions: string | null;
73
+ }
74
+ /** Loaded registry data: entries, MCP category metadata, and the libraries they came from. */
75
+ export interface RegistryData {
76
+ entries: DocEntry[];
77
+ /** Union of categories across all libraries, hoist-react's first. */
78
+ mcpCategories: McpCategory[];
79
+ /** hoist-react first, then companion libraries in discovery order. */
80
+ libraries: DocLibrary[];
81
+ /** Companion library load problems - also logged, and reported by the ping surfaces. */
82
+ warnings: string[];
83
+ }
84
+ /**
85
+ * Raw JSON structure of a doc registry file. Only `entries[].id` is required, so a companion
86
+ * library can start with a minimal file. hoist-react's own registry fills in every field.
87
+ */
88
+ interface RegistryJson {
89
+ mcpCategories?: McpCategory[];
90
+ /** Guidance for agents from a companion library. A string, or an array of lines. */
91
+ mcpInstructions?: string | string[];
92
+ viewerCategories?: Array<{
93
+ id: string;
94
+ title: string;
95
+ }>;
96
+ entries?: Array<{
97
+ id: string;
98
+ title?: string;
99
+ mcpCategory?: string;
100
+ viewerCategory?: string;
101
+ description?: string;
102
+ keywords?: string[];
103
+ aliases?: string[];
104
+ /** `maintainers` to serve the doc only to agents working in the library's own repo. */
105
+ mcpAudience?: string;
106
+ }>;
107
+ }
108
+ /** Package name of hoist-react, which owns the primary docs. */
109
+ export declare const HOIST_PACKAGE = "@xh/hoist";
110
+ /**
111
+ * Build the complete document registry: hoist-react's docs, plus those of any companion
112
+ * libraries discovered from `appRoot`. Omit `appRoot` to load hoist-react's docs alone.
113
+ *
114
+ * Each entry's file path is validated at build time; missing files are
115
+ * logged and skipped.
116
+ */
117
+ export declare function buildRegistry(repoRoot: string, { appRoot }?: {
118
+ appRoot?: string | null;
119
+ }): RegistryData;
120
+ /** Longest library guidance accepted, in characters. Longer guidance is cut, with a warning. */
121
+ export declare const MAX_LIBRARY_INSTRUCTIONS_CHARS = 1500;
122
+ /** Normalize `mcpInstructions` to trimmed, non-empty lines, or null if absent or invalid. */
123
+ export declare function parseInstructions(raw: RegistryJson['mcpInstructions'], warn: (msg: string) => void): string | null;
124
+ /**
125
+ * Load hoist-react's own doc registry for the checkout being indexed. Companion libraries build
126
+ * their own indexes, so none are discovered here.
127
+ */
128
+ export declare function loadRegistry(): RegistryData;
129
+ /**
130
+ * Read and return the full content of a document. A companion library doc has its relative links
131
+ * rewritten to full ids - see {@link rewriteRelativeLinks}.
132
+ *
133
+ * @throws Error if the file does not exist.
134
+ */
135
+ export declare function loadDocContent(entry: DocEntry): string;
136
+ /**
137
+ * Rewrite relative links in a companion library doc so an agent can follow them. Read as
138
+ * written, `../core/README.md` in `@xh/hoist-chat-kit/docs/architecture.md` sends an agent to
139
+ * hoist-react's `core/README.md`, with no error to tell it the doc is the wrong one.
140
+ *
141
+ * A link to a served doc becomes its full id, prefixed with the package name. A link to any other
142
+ * file in the package, such as source or a doc not served here, becomes a file path under
143
+ * {@link DocLinkContext.sourcePath}. Leaves anchors, absolute paths, URLs, links that leave the
144
+ * package root, and code as they are. Keeps line numbers unchanged, so section line ranges still
145
+ * match the file.
146
+ */
147
+ export declare function rewriteRelativeLinks(content: string, docPath: string, { library, docPaths, sourcePath }: DocLinkContext): string;
148
+ export {};