@mosetta/build 0.0.27 → 0.0.30

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/CHANGELOG.md CHANGED
@@ -1,5 +1,38 @@
1
1
  # @mosetta/build
2
2
 
3
+ ## 0.0.30
4
+
5
+ ### Patch Changes
6
+
7
+ - @mosetta/server@0.0.30
8
+ - @mosetta/router@0.0.30
9
+ - @mosetta/runtime@0.0.30
10
+ - @mosetta/server-action@0.0.30
11
+ - @mosetta/tar@0.0.30
12
+
13
+ ## 0.0.29
14
+
15
+ ### Patch Changes
16
+
17
+ - @mosetta/router@0.0.29
18
+ - @mosetta/runtime@0.0.29
19
+ - @mosetta/server@0.0.29
20
+ - @mosetta/server-action@0.0.29
21
+ - @mosetta/tar@0.0.29
22
+
23
+ ## 0.0.28
24
+
25
+ ### Patch Changes
26
+
27
+ - Updated dependencies [81174bd]
28
+ - Updated dependencies [d63601e]
29
+ - Updated dependencies [b88a5d8]
30
+ - @mosetta/server-action@0.0.28
31
+ - @mosetta/server@0.0.28
32
+ - @mosetta/router@0.0.28
33
+ - @mosetta/runtime@0.0.28
34
+ - @mosetta/tar@0.0.28
35
+
3
36
  ## 0.0.27
4
37
 
5
38
  ### Patch Changes
package/docs.md ADDED
@@ -0,0 +1,56 @@
1
+ # @mosetta/build
2
+
3
+ The core of the tile forge: builds a tile palette — its tile side artifacts, their dependency closure, the tile host descriptor. Environment-agnostic — the file system and the bundling engine are supplied from outside.
4
+
5
+ > Generated from the doc comments in this package's sources (`pnpm docs`) — to change it, change the comments.
6
+
7
+ ## Contents
8
+
9
+ - [Documentation from the code](#docs) — A source file documents itself in block comments that open with `/**` and one of five tags on the first line; every other comment in the file is for whoever edits the code and is never published.
10
+
11
+ <a id="docs" name="docs"></a>
12
+ ## Documentation from the code
13
+
14
+ A source file documents itself in block comments that open with `/**` and one of five tags on
15
+ the first line; every other comment in the file is for whoever edits the code and is never
16
+ published. The build renders a
17
+ tile's comments into a Markdown page shipped beside the tile (`<id>.doc.md`, named by its
18
+ descriptor's `doc`, with its settings schema as a table at the end); a palette gets a page of its
19
+ blocks (`doc.md`); a repository's docs tool renders a package's comments into its `docs.md` and
20
+ every package's into one document. Pure string work over the file port — no node, no TypeScript —
21
+ so the same scanner runs in the CLI, in a build container and in a browser build.
22
+
23
+ | tag | what it opens |
24
+ |---|---|
25
+ | `@doc Title` | the module's page — what it is; one per module (a file of a package, a tile) |
26
+ | `@topic Title` | a titled section: how a part of it works |
27
+ | `@howto Title` | a recipe: the steps to get something done with it |
28
+ | `@example Title` | a worked example — code in a fence |
29
+ | `@pitfall Title` | what goes wrong, how to tell, what to do instead |
30
+
31
+ `parseDocComments(text)` reads one file; `docModuleOf(files, identity)` makes a module out of
32
+ several; `scanDocModules(fileSystem, dir, { owner })` walks a package's sources and
33
+ `tileDocModule(fileSystem, dir, { brand, name })` reads a tile's folder; `DocIndex` resolves
34
+ links across modules and lists what is wrong; `renderModule`, `renderPackageDocs`,
35
+ `renderPaletteDocs` and `renderTileDocs` write Markdown.
36
+
37
+ <a id="docs--addresses-and-links" name="docs--addresses-and-links"></a>
38
+ ### Addresses and links
39
+
40
+ The body is Markdown. A link is `{@link` + an address, `|words` at will, + `}`; it refers to
41
+ another module or one of its sections — the address is
42
+ `#anchor` (this module), `routing#specificity` (a module of the same package or palette),
43
+ `@mosetta/core/routing#specificity` (a module of a package: its name, then the file's path under
44
+ `src` without the extension), `mosetta-ui/heading#restyling` (a tile: its palette's brand, then
45
+ its name). An anchor is the section's title as a slug — letters and digits kept, the rest a
46
+ dash. A bare name (`useTile`) finds the one module of that name anywhere in the index; two of
47
+ them make the link ambiguous, and the index says so.
48
+
49
+ <a id="docs--what-the-index-refuses" name="docs--what-the-index-refuses"></a>
50
+ ### Pitfall: What the index refuses
51
+
52
+ `DocIndex.problems()` names, with file and line: a link to a module or section that is not
53
+ documented, an ambiguous bare name, a second `@doc` in one module, two sections with one
54
+ anchor, a section without a title, and words that belong to a repository's internal notes
55
+ (decision numbers, `docs/…` paths) in text that is published. A build never fails on them — it ships
56
+ the pages it can; the repository's check does.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mosetta/build",
3
- "version": "0.0.27",
3
+ "version": "0.0.30",
4
4
  "license": "MIT",
5
5
  "description": "The core of the tile forge: builds a tile palette — its tile side artifacts, their dependency closure, the tile host descriptor. Environment-agnostic — the file system and the bundling engine are supplied from outside.",
6
6
  "type": "module",
@@ -12,7 +12,8 @@
12
12
  "./scanner": "./src/scanner.mjs",
13
13
  "./archive": "./src/archive.mjs",
14
14
  "./release": "./src/release.mjs",
15
- "./node": "./src/node.mjs"
15
+ "./node": "./src/node.mjs",
16
+ "./docs": "./src/docs.mjs"
16
17
  },
17
18
  "dependencies": {
18
19
  "@pnpm/dependency-path": "^1000.0.9",
@@ -27,11 +28,11 @@
27
28
  "scheduler": "*",
28
29
  "systemjs": "^6.15.1",
29
30
  "yaml": "^2.9.0",
30
- "@mosetta/router": "0.0.27",
31
- "@mosetta/server": "0.0.27",
32
- "@mosetta/tar": "0.0.27",
33
- "@mosetta/runtime": "0.0.27",
34
- "@mosetta/server-action": "0.0.27"
31
+ "@mosetta/router": "0.0.30",
32
+ "@mosetta/runtime": "0.0.30",
33
+ "@mosetta/server": "0.0.30",
34
+ "@mosetta/tar": "0.0.30",
35
+ "@mosetta/server-action": "0.0.30"
35
36
  },
36
37
  "publishConfig": {
37
38
  "access": "public"
package/src/build.mjs CHANGED
@@ -12,6 +12,7 @@ import { INERT_BUILD_CONFIG } from './buildConfig.mjs';
12
12
  import { formatBytes } from './format.mjs';
13
13
  import { mtimeStamp } from './artifactCache.mjs';
14
14
  import { describeSettings, SETTINGS_SUFFIX } from './settings.mjs';
15
+ import { DocIndex, renderPaletteDocs, renderTileDocs, tileDocHref, tileDocModule } from './docs.mjs';
15
16
 
16
17
  // entry barrel `.`: exposes the build itself and the size formatter for the host's report
17
18
  export { formatBytes };
@@ -186,6 +187,23 @@ export async function build(root, { mode = 'development', log, fileSystem, resol
186
187
  const sharedCssArtifacts = new Map(); // cssFull -> {file, specifier, version}
187
188
  const entityDescriptors = []; // descriptors of PACKAGE entities (deps + css) for the aggregate
188
189
 
190
+ // a BLOCK'S PAGE: the doc comments of its sides (docs.mjs) — read for every component side
191
+ // before the loop, so one block's page may link to another's knowing it is there; every side
192
+ // file is watched, documented or not
193
+ const tileDocs = new Map(); // full -> the tile's doc module
194
+ const fullOfDoc = new Map(); // a doc module's address -> full
195
+ const docIndex = new DocIndex();
196
+ for (const m of mods.filter((x) => x.type === 'component')) {
197
+ const { module: docModule, files } = tileDocModule(fileSystem, path.dirname(m.file), { brand: m.namespace, name: m.name });
198
+ for (const f of files) watchFiles.add(f);
199
+ if (!docModule) continue;
200
+ tileDocs.set(fullTileName(m), docModule);
201
+ fullOfDoc.set(docModule.address, fullTileName(m));
202
+ docIndex.add(docModule);
203
+ }
204
+ const docFileOf = (full) => `${full}.doc.md`;
205
+ const docHref = tileDocHref(docIndex, (module) => `${fullOfDoc.get(module.address)}/${docFileOf(fullOfDoc.get(module.address))}`);
206
+
189
207
  const moduleResults = [];
190
208
  let skippedSettings = 0;
191
209
  for (const m of mods) {
@@ -229,6 +247,13 @@ export async function build(root, { mode = 'development', log, fileSystem, resol
229
247
  skippedSettings++;
230
248
  }
231
249
  }
250
+ // its PAGE: what its sides say of it in doc comments, as Markdown beside it — `<id>.doc.md`,
251
+ // named by the descriptor's `doc`; the settings schema, when read, closes it as a table
252
+ const docModule = tileDocs.get(r.full);
253
+ if (docModule) {
254
+ r.descriptor.doc = docFileOf(r.full);
255
+ out.set(`${PUB}/modules/${r.full}/${r.descriptor.doc}`, renderTileDocs(docModule, { schema: r.descriptor.settings ?? null, href: docHref(docModule) }));
256
+ }
232
257
  }
233
258
  out.set(`${PUB}/modules/${r.full}/${r.full}.json`, JSON.stringify(r.descriptor, null, 2));
234
259
  if (r.css) out.set(`${PUB}/modules/${r.full}/${r.full}.css`, r.css);
@@ -364,6 +389,17 @@ export async function build(root, { mode = 'development', log, fileSystem, resol
364
389
  out.set(`${PUB}/modules/${fullTileName({ namespace: r.namespace, type: 'distribution', name: r.namespace, version: r.version })}/${name}`, bytes);
365
390
  return name;
366
391
  });
392
+ // the palette's own page (`doc.md`, named by `doc`): its title and description, its blocks with
393
+ // a line on each — the block's page's first sentence, else its schema's — and a link to every
394
+ // block's page
395
+ const blocks = moduleResults
396
+ .filter((x) => x.descriptor.reference.namespace === r.namespace && x.descriptor.reference.type === 'component' && !x.descriptor.internal)
397
+ .map((x) => ({ full: x.full, name: x.descriptor.reference.name, title: tileDocs.get(x.full)?.title ?? x.descriptor.reference.name, summary: tileDocs.get(x.full)?.summary || x.descriptor.settings?.description || '' }))
398
+ .sort((a, b) => a.name.localeCompare(b.name));
399
+ if (blocks.length) {
400
+ descriptor.doc = 'doc.md';
401
+ out.set(`${PUB}/modules/${descriptor.id}/${descriptor.doc}`, renderPaletteDocs({ title: descriptor.title, description: descriptor.description ?? '', version: r.version }, blocks, (b) => (tileDocs.has(b.full) ? `../${b.full}/${docFileOf(b.full)}` : null)));
402
+ }
367
403
  out.set(`${PUB}/modules/${descriptor.id}/${descriptor.id}.json`, JSON.stringify(descriptor, null, 2));
368
404
  entityDescriptors.push(descriptor);
369
405
  }
package/src/docs.mjs ADDED
@@ -0,0 +1,530 @@
1
+ import { path } from './nodeApi.mjs';
2
+
3
+ /**
4
+ * @typedef {{ kind: string, title: string, anchor: string, body: string, file?: string, line: number }} TDocSection
5
+ * @typedef {{ file?: string, line: number | null, message: string }} TDocProblem
6
+ * @typedef {{ kind: 'module' | 'tile', owner: string, slug: string, name: string, address: string, title: string,
7
+ * summary: string, body: string, line: number | null, sections: TDocSection[], files: string[], problems: TDocProblem[] }} TDocModule
8
+ */
9
+
10
+ /**
11
+ * @doc Documentation from the code
12
+ *
13
+ * A source file documents itself in block comments that open with `/**` and one of five tags on
14
+ * the first line; every other comment in the file is for whoever edits the code and is never
15
+ * published. The build renders a
16
+ * tile's comments into a Markdown page shipped beside the tile (`<id>.doc.md`, named by its
17
+ * descriptor's `doc`, with its settings schema as a table at the end); a palette gets a page of its
18
+ * blocks (`doc.md`); a repository's docs tool renders a package's comments into its `docs.md` and
19
+ * every package's into one document. Pure string work over the file port — no node, no TypeScript —
20
+ * so the same scanner runs in the CLI, in a build container and in a browser build.
21
+ *
22
+ * | tag | what it opens |
23
+ * |---|---|
24
+ * | `@doc Title` | the module's page — what it is; one per module (a file of a package, a tile) |
25
+ * | `@topic Title` | a titled section: how a part of it works |
26
+ * | `@howto Title` | a recipe: the steps to get something done with it |
27
+ * | `@example Title` | a worked example — code in a fence |
28
+ * | `@pitfall Title` | what goes wrong, how to tell, what to do instead |
29
+ *
30
+ * `parseDocComments(text)` reads one file; `docModuleOf(files, identity)` makes a module out of
31
+ * several; `scanDocModules(fileSystem, dir, { owner })` walks a package's sources and
32
+ * `tileDocModule(fileSystem, dir, { brand, name })` reads a tile's folder; `DocIndex` resolves
33
+ * links across modules and lists what is wrong; `renderModule`, `renderPackageDocs`,
34
+ * `renderPaletteDocs` and `renderTileDocs` write Markdown.
35
+ */
36
+
37
+ /**
38
+ * @topic Addresses and links
39
+ *
40
+ * The body is Markdown. A link is `{@link` + an address, `|words` at will, + `}`; it refers to
41
+ * another module or one of its sections — the address is
42
+ * `#anchor` (this module), `routing#specificity` (a module of the same package or palette),
43
+ * `@mosetta/core/routing#specificity` (a module of a package: its name, then the file's path under
44
+ * `src` without the extension), `mosetta-ui/heading#restyling` (a tile: its palette's brand, then
45
+ * its name). An anchor is the section's title as a slug — letters and digits kept, the rest a
46
+ * dash. A bare name (`useTile`) finds the one module of that name anywhere in the index; two of
47
+ * them make the link ambiguous, and the index says so.
48
+ */
49
+
50
+ /**
51
+ * @pitfall What the index refuses
52
+ *
53
+ * `DocIndex.problems()` names, with file and line: a link to a module or section that is not
54
+ * documented, an ambiguous bare name, a second `@doc` in one module, two sections with one
55
+ * anchor, a section without a title, and words that belong to a repository's internal notes
56
+ * (decision numbers, `docs/…` paths) in text that is published. A build never fails on them — it ships
57
+ * the pages it can; the repository's check does.
58
+ */
59
+
60
+ /** the tags that open a documentation comment, by what they open */
61
+ export const DOC_TAGS = Object.freeze(['doc', 'topic', 'howto', 'example', 'pitfall']);
62
+
63
+ /** what a section's heading is prefixed with, by kind — a topic is plain */
64
+ const KIND_LABEL = Object.freeze({ topic: '', howto: 'How to: ', example: 'Example: ', pitfall: 'Pitfall: ' });
65
+
66
+ /** the files a module may be documented in */
67
+ const SOURCE_EXTENSIONS = new Set(['.ts', '.tsx', '.mts', '.cts', '.js', '.mjs', '.cjs', '.jsx', '.css']);
68
+
69
+ const TAG_LINE_RE = new RegExp(`^@(${DOC_TAGS.join('|')})(?=\\s|$)\\s*(.*)$`);
70
+ const LINK_RE = /\{@link\s+([^\s|}]+)\s*(?:\|\s*([^}]*?))?\s*\}/g;
71
+ const FENCE_RE = /^\s*(```|~~~)/;
72
+
73
+ /** a title as an anchor: letters and digits kept, the rest a dash */
74
+ export function slugOf(title) {
75
+ return String(title).toLowerCase().normalize('NFKD').replace(/[̀-ͯ]/g, '')
76
+ .replace(/[^\p{L}\p{N}]+/gu, '-').replace(/^-+|-+$/g, '');
77
+ }
78
+
79
+ /** the first sentence of a Markdown body (its first paragraph, up to the first full stop) */
80
+ export function summaryOf(body) {
81
+ const paragraph = String(body).split(/\n\s*\n/).map((p) => p.trim()).find((p) => p && !FENCE_RE.test(p) && !/^[#|>-]/.test(p));
82
+ if (!paragraph) return '';
83
+ const oneLine = paragraph.replace(/\s+/g, ' ');
84
+ const stop = oneLine.search(/[.!?](\s|$)/);
85
+ const sentence = stop >= 0 ? oneLine.slice(0, stop + 1) : oneLine;
86
+ return sentence.length > 200 ? `${sentence.slice(0, 197).trimEnd()}…` : sentence;
87
+ }
88
+
89
+ /** the `{@link}` references in a Markdown text: target, words (null — none given) */
90
+ export function linksIn(markdown) {
91
+ const links = [];
92
+ for (const m of String(markdown).matchAll(LINK_RE)) links.push({ target: m[1], text: m[2]?.trim() || null, raw: m[0] });
93
+ return links;
94
+ }
95
+
96
+ /** a comment's lines without the ` * ` gutter; the first line is what followed `/**` */
97
+ function ungutter(inner) {
98
+ return inner.split(/\r?\n/).map((line) => line.replace(/^\s*\*? ?/, '').replace(/\s+$/, ''));
99
+ }
100
+
101
+ /**
102
+ * The documentation comments of one source text: the module's `@doc` (null — none) and its
103
+ * sections, in order, each with the line it starts at; what is wrong with them as problems.
104
+ */
105
+ export function parseDocComments(text) {
106
+ const source = String(text);
107
+ let doc = null;
108
+ const sections = [];
109
+ const problems = [];
110
+ const anchors = new Map();
111
+ let at = 0;
112
+ for (;;) {
113
+ const open = source.indexOf('/**', at);
114
+ if (open < 0) break;
115
+ const close = source.indexOf('*/', open + 3);
116
+ if (close < 0) break;
117
+ at = close + 2;
118
+ const line = source.slice(0, open).split('\n').length;
119
+ const lines = ungutter(source.slice(open + 3, close));
120
+ const first = lines.findIndex((l) => l.trim());
121
+ if (first < 0) continue;
122
+ const tag = TAG_LINE_RE.exec(lines[first].trim());
123
+ if (!tag) continue; // an ordinary comment: for the code's editor, not the documentation
124
+ const [, kind, titleText] = tag;
125
+ const title = titleText.trim();
126
+ const body = lines.slice(first + 1).join('\n').replace(/^\n+|\n+$/g, '');
127
+ if (kind === 'doc') {
128
+ if (doc) problems.push({ line, message: 'a second @doc — a module has one page; make the rest @topic sections' });
129
+ else doc = { title, body, line };
130
+ continue;
131
+ }
132
+ if (!title) {
133
+ problems.push({ line, message: `@${kind} needs a title on its line` });
134
+ continue;
135
+ }
136
+ const anchor = slugOf(title);
137
+ if (anchors.has(anchor)) problems.push({ line, message: `two sections share the anchor #${anchor} ("${title}" and "${anchors.get(anchor)}")` });
138
+ anchors.set(anchor, title);
139
+ sections.push({ kind, title, anchor, body, line });
140
+ }
141
+ return { doc, sections, problems };
142
+ }
143
+
144
+ /**
145
+ * One documented module out of its files ([{ file, text }], the first file's @doc wins): its
146
+ * title (falls back to `name`), body, sections and problems — or null when none of the files
147
+ * documents anything. `owner` is the package name or the palette brand the address starts with.
148
+ * @param {{ file: string, text: string }[]} files
149
+ * @param {{ owner: string, slug: string, name?: string, kind?: 'module' | 'tile' }} identity
150
+ * @returns {TDocModule | null}
151
+ */
152
+ export function docModuleOf(files, { owner, slug, name = slug, kind = 'module' }) {
153
+ let doc = null;
154
+ const sections = [];
155
+ const problems = [];
156
+ const anchors = new Map();
157
+ const documented = [];
158
+ for (const { file, text } of files) {
159
+ const parsed = parseDocComments(text);
160
+ if (!parsed.doc && !parsed.sections.length && !parsed.problems.length) continue;
161
+ documented.push(file);
162
+ for (const p of parsed.problems) problems.push({ file, ...p });
163
+ if (parsed.doc) {
164
+ if (doc) problems.push({ file, line: parsed.doc.line, message: `a second @doc — ${doc.file} already opens this module's page` });
165
+ else doc = { ...parsed.doc, file };
166
+ }
167
+ for (const s of parsed.sections) {
168
+ if (anchors.has(s.anchor) && anchors.get(s.anchor) !== file) problems.push({ file, line: s.line, message: `#${s.anchor} is already a section of ${anchors.get(s.anchor)}` });
169
+ anchors.set(s.anchor, file);
170
+ sections.push({ ...s, file });
171
+ }
172
+ }
173
+ if (!documented.length) return null;
174
+ const body = doc?.body ?? '';
175
+ return {
176
+ kind,
177
+ owner,
178
+ slug,
179
+ name,
180
+ address: `${owner}/${slug}`,
181
+ title: doc?.title || name,
182
+ summary: summaryOf(body),
183
+ body,
184
+ line: doc?.line ?? null,
185
+ sections,
186
+ files: documented,
187
+ problems,
188
+ };
189
+ }
190
+
191
+ /** the files a tile is made of, its component side first (its @doc is the tile's page by rule) */
192
+ function tileFilesOf(fileSystem, dir, name) {
193
+ const order = (file) => {
194
+ const base = path.basename(file);
195
+ if (base.startsWith(`${name}.component.`)) return 0;
196
+ if (base.startsWith(`${name}.settings.`)) return 1;
197
+ if (base.startsWith(`${name}.editor.`)) return 2;
198
+ if (base.startsWith(`${name}.server.`)) return 3;
199
+ return 4;
200
+ };
201
+ return fileSystem.readDir(dir)
202
+ .filter((e) => !e.isDirectory && SOURCE_EXTENSIONS.has(path.extname(e.name)))
203
+ .map((e) => path.join(dir, e.name))
204
+ .sort((a, b) => order(a) - order(b) || a.localeCompare(b));
205
+ }
206
+
207
+ /**
208
+ * A tile's documentation: the doc comments of every side in its folder as one module addressed
209
+ * `<brand>/<name>`. Null when no side documents anything. `files` lists what was read (watched).
210
+ * @returns {{ module: TDocModule | null, files: string[] }}
211
+ */
212
+ export function tileDocModule(fileSystem, dir, { brand, name }) {
213
+ const files = tileFilesOf(fileSystem, dir, name);
214
+ const module = docModuleOf(files.map((file) => ({ file: path.basename(file), text: fileSystem.readFile(file, 'utf8') })), { owner: brand, slug: name, kind: 'tile' });
215
+ return { module, files };
216
+ }
217
+
218
+ /** what a source walk leaves out: installed packages, builds, tests, type declarations, fixtures */
219
+ const SKIPPED_DIRS = new Set(['node_modules', 'dist', 'build', 'fixtures', '__tests__']);
220
+ const isTestFile = (name) => /\.(test|spec)\.[cm]?[jt]sx?$/.test(name) || name.endsWith('.d.ts') || name.endsWith('.d.mts');
221
+
222
+ /**
223
+ * The documented modules under `dir` (a package's `src`): one per source file with doc comments,
224
+ * addressed `<owner>/<path under dir without the extension>`. Folders are walked in name order.
225
+ * @returns {TDocModule[]}
226
+ */
227
+ export function scanDocModules(fileSystem, dir, { owner }) {
228
+ /** @type {TDocModule[]} */
229
+ const modules = [];
230
+ const walk = (folder, rel) => {
231
+ const entries = [...fileSystem.readDir(folder)].sort((a, b) => a.name.localeCompare(b.name));
232
+ for (const entry of entries) {
233
+ const file = path.join(folder, entry.name);
234
+ const relative = rel ? `${rel}/${entry.name}` : entry.name;
235
+ if (entry.isDirectory) {
236
+ if (!SKIPPED_DIRS.has(entry.name)) walk(file, relative);
237
+ continue;
238
+ }
239
+ const ext = path.extname(entry.name);
240
+ if (!SOURCE_EXTENSIONS.has(ext) || isTestFile(entry.name)) continue;
241
+ const slug = relative.slice(0, -ext.length);
242
+ const module = docModuleOf([{ file: relative, text: fileSystem.readFile(file, 'utf8') }], { owner, slug, name: path.basename(slug) });
243
+ if (module) modules.push(module);
244
+ }
245
+ };
246
+ if (fileSystem.exists(dir)) walk(dir, '');
247
+ return modules;
248
+ }
249
+
250
+ /**
251
+ * Every documented module of a set of packages and palettes, by address, and the resolution of
252
+ * `{@link}` targets against them. `add` takes what `scanDocModules` and `tileDocModule` give.
253
+ */
254
+ export class DocIndex {
255
+ constructor() {
256
+ /** @type {Map<string, TDocModule>} */
257
+ this.modules = new Map();
258
+ /** @type {Map<string, string[]>} */
259
+ this.byName = new Map();
260
+ }
261
+
262
+ /** @param {TDocModule | null} module */
263
+ add(module) {
264
+ if (!module) return this;
265
+ this.modules.set(module.address, module);
266
+ const names = this.byName.get(module.name) ?? [];
267
+ names.push(module.address);
268
+ this.byName.set(module.name, names);
269
+ return this;
270
+ }
271
+
272
+ /** the modules of one owner (a package or a palette), in the order they were added */
273
+ of(owner) {
274
+ return [...this.modules.values()].filter((m) => m.owner === owner);
275
+ }
276
+
277
+ /**
278
+ * What a link target names, seen from `from`: `{ module, section }` (section null — the module
279
+ * itself), or `{ error }` saying why not.
280
+ * @param {string} target
281
+ * @param {TDocModule | null} [from]
282
+ * @returns {{ module: TDocModule, section: TDocSection | null, error?: undefined } | { error: string, module?: undefined, section?: undefined }}
283
+ */
284
+ resolve(target, from = null) {
285
+ const hash = target.indexOf('#');
286
+ const addressPart = hash >= 0 ? target.slice(0, hash) : target;
287
+ const anchor = hash >= 0 ? target.slice(hash + 1) : null;
288
+ let module = null;
289
+ if (!addressPart) {
290
+ if (!from) return { error: `${target}: an anchor alone names a section of the module it is in` };
291
+ module = from;
292
+ } else if (this.modules.has(addressPart)) {
293
+ module = this.modules.get(addressPart);
294
+ } else if (from && this.modules.has(`${from.owner}/${addressPart}`)) {
295
+ module = this.modules.get(`${from.owner}/${addressPart}`);
296
+ } else {
297
+ const named = this.byName.get(addressPart) ?? [];
298
+ if (named.length > 1) return { error: `${target}: ${named.length} modules are called ${addressPart} — name one: ${named.join(', ')}` };
299
+ if (named.length === 1) module = this.modules.get(named[0]);
300
+ }
301
+ if (!module) return { error: `${target}: no module ${addressPart} is documented` };
302
+ if (anchor === null || anchor === '') return { module, section: null };
303
+ const section = module.sections.find((s) => s.anchor === anchor);
304
+ if (!section) return { error: `${target}: ${module.address} has no section #${anchor}${module.sections.length ? ` — it has ${module.sections.map((s) => `#${s.anchor}`).join(', ')}` : ''}` };
305
+ return { module, section };
306
+ }
307
+
308
+ /**
309
+ * What is wrong across the index: every module's own problems, links that lead nowhere, and
310
+ * words that belong to the repository's internal notes (decision numbers, `docs/` paths) in
311
+ * text that is published.
312
+ * @returns {{ address: string, file?: string, line: number | null, message: string }[]}
313
+ */
314
+ problems() {
315
+ /** @type {{ address: string, file?: string, line: number | null, message: string }[]} */
316
+ const out = [];
317
+ for (const module of this.modules.values()) {
318
+ for (const p of module.problems) out.push({ address: module.address, file: p.file, line: p.line, message: p.message });
319
+ const texts = [{ body: module.body, file: module.files[0], line: module.line }, ...module.sections.map((s) => ({ body: s.body, file: s.file, line: s.line }))];
320
+ for (const { body, file, line } of texts) {
321
+ for (const link of linksIn(body)) {
322
+ const found = this.resolve(link.target, module);
323
+ if (found.error) out.push({ address: module.address, file, line, message: `{@link ${link.target}}: ${found.error.slice(link.target.length + 2)}` });
324
+ }
325
+ const internal = /\bADR-\d{4}\b|(?:^|[\s(`])docs\/[\w./-]+/.exec(body);
326
+ if (internal) out.push({ address: module.address, file, line, message: `"${internal[0].trim()}" names the repository's internal notes — published text stands on its own` });
327
+ }
328
+ }
329
+ return out;
330
+ }
331
+ }
332
+
333
+ /** a Markdown table cell: pipes and line breaks tamed */
334
+ const cell = (text) => String(text ?? '').replace(/\|/g, '\\|').replace(/\s*\n\s*/g, ' ').trim();
335
+
336
+ /** how a JSON Schema of one setting reads in a table: its type, the values it allows */
337
+ function typeWords(schema) {
338
+ if (!schema || typeof schema !== 'object') return '';
339
+ if (Array.isArray(schema.enum)) return `one of ${schema.enum.map((v) => `\`${JSON.stringify(v)}\``).join(', ')}`;
340
+ if (Array.isArray(schema.anyOf)) return schema.anyOf.map(typeWords).filter(Boolean).join(' or ');
341
+ if (Array.isArray(schema.oneOf)) return schema.oneOf.map(typeWords).filter(Boolean).join(' or ');
342
+ const type = Array.isArray(schema.type) ? schema.type.join(' or ') : schema.type;
343
+ if (type === 'array') return `array of ${typeWords(schema.items) || 'anything'}`;
344
+ if (type === 'object' && schema.additionalProperties && typeof schema.additionalProperties === 'object') return `map of ${typeWords(schema.additionalProperties) || 'anything'}`;
345
+ if (schema.const !== undefined) return `\`${JSON.stringify(schema.const)}\``;
346
+ return type || '';
347
+ }
348
+
349
+ /**
350
+ * A block's settings as a Markdown table from their JSON Schema (the tile descriptor's
351
+ * `settings`): one row per setting — its name, type, whether it is optional or may hold a
352
+ * translation reference, and what it is for. Empty when the schema lists no properties.
353
+ */
354
+ export function settingsTable(schema) {
355
+ const properties = schema && typeof schema === 'object' && schema.properties && typeof schema.properties === 'object' ? schema.properties : null;
356
+ if (!properties) return '';
357
+ const required = new Set(Array.isArray(schema.required) ? schema.required : []);
358
+ const rows = Object.entries(properties).map(([name, p]) => {
359
+ const marks = [];
360
+ if (!required.has(name)) marks.push('optional');
361
+ if (p && typeof p === 'object' && p.bindable) marks.push('may be a translation reference');
362
+ if (p && typeof p === 'object' && p.readOnly) marks.push('read-only');
363
+ const type = [typeWords(p), ...marks].filter(Boolean).join(', ');
364
+ return `| \`${name}\` | ${cell(type)} | ${cell(p && typeof p === 'object' ? p.description : '')} |`;
365
+ });
366
+ return ['| setting | type | what it is |', '|---|---|---|', ...rows].join('\n');
367
+ }
368
+
369
+ /** Markdown headings in a body moved down `by` levels — a body's `#` lives under its section */
370
+ function shiftHeadings(markdown, by) {
371
+ if (!by) return markdown;
372
+ let fenced = false;
373
+ return markdown.split('\n').map((line) => {
374
+ if (FENCE_RE.test(line)) fenced = !fenced;
375
+ if (fenced) return line;
376
+ const m = /^(#{1,6})(\s)/.exec(line);
377
+ return m ? `${'#'.repeat(Math.min(6, m[1].length + by))}${m[2]}${line.slice(m[0].length)}` : line;
378
+ }).join('\n');
379
+ }
380
+
381
+ /**
382
+ * A body's `{@link}`s as Markdown: `href(target)` gives the address to link to (null — none
383
+ * known here: the words stay, the target follows them in code so a reader knows where to look).
384
+ * @param {string} markdown
385
+ * @param {(target: string) => string | null | undefined} href
386
+ */
387
+ export function renderLinks(markdown, href) {
388
+ return String(markdown).replace(LINK_RE, (raw, target, text) => {
389
+ const words = text?.trim() || null;
390
+ const to = href(target);
391
+ const tail = target.replace(/^.*\//, '');
392
+ const fallbackWords = words ?? (tail.startsWith('#') ? tail.slice(1) : tail.replace(/#/, ' › '));
393
+ if (to) return `[${fallbackWords}](${to})`;
394
+ return words ? `${words} (\`${target}\`)` : `\`${target}\``;
395
+ });
396
+ }
397
+
398
+ /** a `#`-heading of `level` */
399
+ const heading = (level, text) => `${'#'.repeat(Math.max(1, Math.min(6, level)))} ${text}`;
400
+
401
+ /** an explicit anchor a Markdown renderer keeps (`<a id>`): where a link into the document lands */
402
+ export const anchorTag = (id) => `<a id="${id}" name="${id}"></a>`;
403
+
404
+ /**
405
+ * A module as Markdown: its title as a heading of `level`, its body, each section under a heading
406
+ * one level deeper (prefixed by kind: "How to:", "Example:", "Pitfall:"; a topic plain), with an
407
+ * explicit anchor before each from `id(module, section)` (undefined — none). `href(target)` says
408
+ * where a `{@link}` leads. `extra` — Markdown appended after the body (a settings table).
409
+ * @param {TDocModule} module
410
+ * @param {{ level?: number, id?: (module: TDocModule, section: TDocSection | null) => string | undefined,
411
+ * href?: (target: string) => string | null | undefined, extra?: string }} [options]
412
+ */
413
+ export function renderModule(module, { level = 1, id = () => undefined, href = () => null, extra = '' } = {}) {
414
+ const out = [];
415
+ const moduleId = id(module, null);
416
+ if (moduleId) out.push(anchorTag(moduleId));
417
+ out.push(heading(level, module.title));
418
+ if (module.body) out.push('', renderLinks(shiftHeadings(module.body, level), href));
419
+ if (extra) out.push('', extra);
420
+ for (const section of module.sections) {
421
+ out.push('');
422
+ const sectionId = id(module, section);
423
+ if (sectionId) out.push(anchorTag(sectionId));
424
+ out.push(heading(level + 1, `${KIND_LABEL[section.kind] ?? ''}${section.title}`));
425
+ if (section.body) out.push('', renderLinks(shiftHeadings(section.body, level + 1), href));
426
+ }
427
+ return `${out.join('\n')}\n`;
428
+ }
429
+
430
+ /** a link's target as `{ module, section }` of `index` seen from `from`, else null */
431
+ function resolved(index, target, from) {
432
+ const found = index.resolve(target, from);
433
+ return found.error ? null : found;
434
+ }
435
+
436
+ /**
437
+ * a module's anchor id inside a document of its owner
438
+ * @param {TDocModule} module
439
+ */
440
+ export const moduleIdOf = (module) => slugOf(module.slug);
441
+ /**
442
+ * a section's anchor id inside a document of its owner
443
+ * @param {TDocModule} module
444
+ * @param {TDocSection | null} section
445
+ */
446
+ export const sectionIdOf = (module, section) => (section ? `${moduleIdOf(module)}--${section.anchor}` : moduleIdOf(module));
447
+
448
+ /**
449
+ * A package's `docs.md`: its name and description, a contents list, then every module of it from
450
+ * `index` — links inside the package land on anchors in this file, links elsewhere keep their
451
+ * address in code (where to read next). `owners` — whose modules are the package's: its name, and
452
+ * its palette's brand when it brings tiles.
453
+ * @param {{ name: string, description?: string, note?: string, owners?: string[] }} pkg
454
+ * @param {DocIndex} index
455
+ */
456
+ export function renderPackageDocs({ name, description = '', note = '', owners = [name] }, index) {
457
+ const modules = owners.flatMap((owner) => index.of(owner));
458
+ /** @param {TDocModule} from */
459
+ const href = (from) => (/** @type {string} */ target) => {
460
+ const found = resolved(index, target, from);
461
+ if (!found || !owners.includes(found.module.owner)) return null;
462
+ return `#${sectionIdOf(found.module, found.section)}`;
463
+ };
464
+ const out = [heading(1, name)];
465
+ if (description) out.push('', description);
466
+ if (note) out.push('', `> ${note}`);
467
+ if (modules.length) {
468
+ out.push('', heading(2, 'Contents'), '');
469
+ for (const m of modules) out.push(`- [${m.title}](#${moduleIdOf(m)})${m.summary ? ` — ${renderLinks(m.summary, href(m))}` : ''}`);
470
+ for (const m of modules) out.push('', renderModule(m, { level: 2, id: sectionIdOf, href: href(m) }).trimEnd());
471
+ }
472
+ return `${out.join('\n')}\n`;
473
+ }
474
+
475
+ /**
476
+ * A palette's page: its title and description, then its blocks with a line on each and a link to
477
+ * each block's own document (`docOf(block)`: the file's address relative to this page, null when
478
+ * the block has none). `blocks` — [{ name, title, summary }] in the order to list them.
479
+ * @param {{ title: string, description?: string, version?: string }} palette
480
+ * @param {{ name: string, title: string, summary?: string }[]} blocks
481
+ * @param {(block: { name: string, title: string, summary?: string }) => string | null | undefined} docOf
482
+ */
483
+ export function renderPaletteDocs({ title, description = '', version = '' }, blocks, docOf) {
484
+ const out = [heading(1, title)];
485
+ if (version) out.push('', `Version ${version}.`);
486
+ if (description) out.push('', description);
487
+ if (blocks.length) {
488
+ out.push('', heading(2, 'Blocks'), '', '| block | about |', '|---|---|');
489
+ for (const b of blocks) {
490
+ const link = docOf(b);
491
+ out.push(`| ${link ? `[${b.name}](${link})` : `\`${b.name}\``} | ${cell(b.summary ?? '')} |`);
492
+ }
493
+ }
494
+ return `${out.join('\n')}\n`;
495
+ }
496
+
497
+ /**
498
+ * A block's own page, shipped beside it: its doc and sections (anchors by section), then its
499
+ * settings as a table when the schema is known (`schema` — the descriptor's `settings`).
500
+ * `href(target)` says where a `{@link}` leads — another block's page, as a relative address.
501
+ * @param {TDocModule} module
502
+ * @param {{ schema?: object | null, href?: (target: string) => string | null | undefined }} [options]
503
+ */
504
+ export function renderTileDocs(module, { schema = null, href = () => null } = {}) {
505
+ let md = renderModule(module, { level: 1, id: (m, s) => (s ? s.anchor : undefined), href });
506
+ const table = settingsTable(schema);
507
+ if (table) {
508
+ const about = schema && typeof schema.description === 'string' && schema.description.trim() ? `${schema.description.trim()}\n\n` : '';
509
+ md += `\n${anchorTag('settings')}\n${heading(2, 'Settings')}\n\n${about}${table}\n`;
510
+ }
511
+ return md;
512
+ }
513
+
514
+ /**
515
+ * Where a `{@link}` of one block's page leads among the pages of a build: `#anchor` stays on the
516
+ * page; a block of the build (`brand/name`, or `name` within the same palette) — its page by the
517
+ * relative address `../<its id>/<its doc>#anchor`; anything else (a package) — nowhere here.
518
+ * @param {DocIndex} index the build's documented tiles
519
+ * @param {(module: TDocModule) => string} docPathOf a tile module's page, relative to the modules folder
520
+ */
521
+ export function tileDocHref(index, docPathOf) {
522
+ return (/** @type {TDocModule} */ from) => (/** @type {string} */ target) => {
523
+ const found = index.resolve(target, from);
524
+ if (found.error) return null;
525
+ const anchor = found.section ? `#${found.section.anchor}` : '';
526
+ if (found.module === from) return anchor || null;
527
+ return `../${docPathOf(found.module)}${anchor}`;
528
+ };
529
+ }
530
+