@mandujs/core 0.24.0 → 0.25.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,400 @@
1
+ /**
2
+ * Content Prebuild Runner (Issue #196).
3
+ *
4
+ * # Purpose
5
+ *
6
+ * `mandu dev` manages routes, the bundler, and HMR — but it does NOT
7
+ * auto-generate files under `content/` that derived scripts produce
8
+ * (e.g. `scripts/prebuild-docs.ts` writes `content/docs-data.ts`,
9
+ * `scripts/prebuild-seo.ts` writes `content/sitemap.xml`, …). Without
10
+ * this module every project has to wire the chain by hand:
11
+ *
12
+ * bun scripts/prebuild-docs.ts && bun scripts/prebuild-seo.ts && mandu dev
13
+ *
14
+ * — which is error-prone and fragile on Windows where `&&` chains misbehave
15
+ * in some shells. Issue #196 asks us to move this into the CLI so `mandu dev`
16
+ * alone is enough.
17
+ *
18
+ * # Contract
19
+ *
20
+ * 1. **Discovery**: walk `<rootDir>/scripts/` for any file matching
21
+ * `prebuild*.{ts,tsx,js,mjs}`. Sort lexicographically so
22
+ * `prebuild-1-xxx` always runs before `prebuild-2-yyy` when the user
23
+ * needs ordering control via filename prefix.
24
+ *
25
+ * 2. **Execution**: run each script in a fresh `bun` subprocess with
26
+ * `stdio: "inherit"` so prebuild logs flow through unchanged. Scripts
27
+ * run **sequentially** (the first one's exit must settle before the
28
+ * next starts) — parallel execution is tempting but most docs-style
29
+ * prebuilds write to the same output dir and race conditions would
30
+ * silently corrupt output files.
31
+ *
32
+ * 3. **Failure mode**: a non-zero exit from any script aborts the chain
33
+ * and surfaces `PrebuildError` to the caller. `mandu dev` decides
34
+ * whether to abort (prod) or log + continue (dev) based on caller
35
+ * flags — this module does not make that policy decision.
36
+ *
37
+ * 4. **Timeout**: per-script 2-minute wall-clock cap, matching the
38
+ * policy established by `packages/mcp/src/util/runCommand.ts` (#136).
39
+ * Override via `options.timeoutMs` for unusual long-running seeds.
40
+ *
41
+ * 5. **No side-effects on empty discovery**: if no scripts are found,
42
+ * `runPrebuildScripts` returns `{ ran: 0 }` silently. This is the
43
+ * default for projects without a `content/` workflow, so importing
44
+ * this module into `dev.ts` must stay invisible to them.
45
+ *
46
+ * # Non-goals
47
+ *
48
+ * - NOT a general task-runner. Scripts are pure one-shot generators —
49
+ * no daemon / watch / IPC semantics.
50
+ * - NOT content-layer integration. This module does not know about
51
+ * `defineContentConfig` or the `ContentLayer` class; it purely
52
+ * orchestrates `scripts/prebuild-*.ts`.
53
+ * - NOT a Bun-only primitive: we use `Bun.spawn` for the subprocess
54
+ * because it is cheaper than `node:child_process` and matches the
55
+ * rest of the codebase (see MEMORY "child_process.spawn → Bun.spawn
56
+ * 교체"), but the module exports do not expose any Bun types on the
57
+ * public surface.
58
+ */
59
+
60
+ import path from "node:path";
61
+ import fs from "node:fs";
62
+
63
+ // ---------------------------------------------------------------------------
64
+ // Discovery
65
+ // ---------------------------------------------------------------------------
66
+
67
+ /**
68
+ * Filename shapes we treat as prebuild scripts. Sorted by lexicographic
69
+ * order after discovery so that `prebuild-01-foo.ts` reliably runs before
70
+ * `prebuild-02-bar.ts` — the user's ordering knob.
71
+ *
72
+ * We include `.mjs` because some projects ship pre-compiled prebuild
73
+ * scripts in ESM format for CI speed.
74
+ */
75
+ const PREBUILD_EXTENSIONS = new Set([".ts", ".tsx", ".js", ".mjs"]);
76
+ const PREBUILD_FILENAME_RE = /^prebuild[-_.a-zA-Z0-9]*\.(ts|tsx|js|mjs)$/;
77
+
78
+ /**
79
+ * Discover prebuild scripts under `<rootDir>/<scriptsDir>`.
80
+ *
81
+ * Returns absolute paths (forward-slash on Windows) sorted lexicographically.
82
+ * Does NOT touch the filesystem beyond a single `readdir` — symlinks are
83
+ * treated like regular files (followed by Node's default policy).
84
+ *
85
+ * Exported as a named function so the dev-autoprebuild test can exercise
86
+ * discovery independently of execution.
87
+ */
88
+ export function discoverPrebuildScripts(
89
+ rootDir: string,
90
+ scriptsDir = "scripts",
91
+ ): string[] {
92
+ const scriptsPath = path.resolve(rootDir, scriptsDir);
93
+ let entries: string[];
94
+ try {
95
+ entries = fs.readdirSync(scriptsPath);
96
+ } catch {
97
+ // No scripts/ directory — not an error, just an empty discovery.
98
+ return [];
99
+ }
100
+
101
+ const matched: string[] = [];
102
+ for (const name of entries) {
103
+ if (!PREBUILD_FILENAME_RE.test(name)) continue;
104
+ const ext = path.extname(name);
105
+ if (!PREBUILD_EXTENSIONS.has(ext)) continue;
106
+ // Full absolute path — forward-slash on Windows so the log output is
107
+ // consistent with the rest of the dev logging (see `maskSlotPath` in
108
+ // `packages/cli/src/commands/dev.ts` for the same normalization
109
+ // pattern).
110
+ const abs = path.join(scriptsPath, name).replace(/\\/g, "/");
111
+ matched.push(abs);
112
+ }
113
+ matched.sort((a, b) => a.localeCompare(b));
114
+ return matched;
115
+ }
116
+
117
+ // ---------------------------------------------------------------------------
118
+ // Execution
119
+ // ---------------------------------------------------------------------------
120
+
121
+ /**
122
+ * Error thrown when a prebuild script exits non-zero or times out. The
123
+ * `scriptPath` + `exitCode` fields are stable so callers can decide
124
+ * recovery policy without string-matching the message.
125
+ */
126
+ export class PrebuildError extends Error {
127
+ readonly scriptPath: string;
128
+ readonly exitCode: number | null;
129
+ readonly durationMs: number;
130
+
131
+ constructor(
132
+ message: string,
133
+ options: {
134
+ scriptPath: string;
135
+ exitCode: number | null;
136
+ durationMs: number;
137
+ cause?: unknown;
138
+ },
139
+ ) {
140
+ super(message);
141
+ this.name = "PrebuildError";
142
+ this.scriptPath = options.scriptPath;
143
+ this.exitCode = options.exitCode;
144
+ this.durationMs = options.durationMs;
145
+ if (options.cause !== undefined) {
146
+ (this as Error & { cause?: unknown }).cause = options.cause;
147
+ }
148
+ }
149
+ }
150
+
151
+ export interface PrebuildRunnerOptions {
152
+ /** Project root. Absolute path — we resolve scripts relative to this. */
153
+ rootDir: string;
154
+ /**
155
+ * Relative scripts dir (default: `"scripts"`). Override for projects
156
+ * that put generators in a non-standard location.
157
+ */
158
+ scriptsDir?: string;
159
+ /**
160
+ * Per-script wall-clock timeout in milliseconds. Default: 2 minutes,
161
+ * matching the MCP `runCommand()` convention (#136).
162
+ */
163
+ timeoutMs?: number;
164
+ /**
165
+ * Called once per discovered script, before the subprocess starts.
166
+ * Useful for CLI progress logs. Not awaited.
167
+ */
168
+ onStart?: (scriptPath: string, index: number, total: number) => void;
169
+ /**
170
+ * Called once per script after the subprocess exits (success OR failure).
171
+ * Always runs before the Promise resolves/rejects.
172
+ */
173
+ onFinish?: (result: {
174
+ scriptPath: string;
175
+ exitCode: number | null;
176
+ durationMs: number;
177
+ }) => void;
178
+ /**
179
+ * Injected spawn hook — overridable in tests so we do not have to
180
+ * actually fork `bun`. Default uses `Bun.spawn` with `stdio: "inherit"`.
181
+ *
182
+ * Contract: returns a `{ exited }` with an `exited` Promise that
183
+ * resolves to the exit code (null on signal / timeout kill). The hook
184
+ * is responsible for the actual kill on timeout.
185
+ */
186
+ spawn?: SpawnHook;
187
+ }
188
+
189
+ export interface PrebuildResult {
190
+ ran: number;
191
+ scripts: Array<{
192
+ scriptPath: string;
193
+ exitCode: number | null;
194
+ durationMs: number;
195
+ }>;
196
+ }
197
+
198
+ /**
199
+ * Spawn shim — kept as an interface so tests can inject a pure-in-memory
200
+ * replacement without monkey-patching `globalThis.Bun`.
201
+ */
202
+ export type SpawnHook = (args: {
203
+ scriptPath: string;
204
+ cwd: string;
205
+ timeoutMs: number;
206
+ }) => Promise<{ exitCode: number | null; durationMs: number }>;
207
+
208
+ /**
209
+ * Default spawn hook: fork `bun <scriptPath>` with `stdio: "inherit"` so
210
+ * the user sees prebuild logs on the terminal in real time.
211
+ *
212
+ * The `timeoutMs` guard kills the subprocess via SIGTERM (Unix) /
213
+ * `proc.kill()` (which sends SIGKILL on Windows — Bun's cross-platform
214
+ * `kill` API). We intentionally do not chain SIGTERM → SIGKILL because
215
+ * prebuild scripts are short-lived generators: a hung one is a bug the
216
+ * user should see as a timeout error, not a half-killed zombie.
217
+ *
218
+ * `env` is inherited but we strip the inherited `MANDU_PERF` flag so the
219
+ * prebuild's own perf log output doesn't muddle the dev boot perf trace
220
+ * — otherwise the user's "dev boot in Nms" numbers include every
221
+ * prebuild step, which is misleading.
222
+ */
223
+ export const defaultSpawn: SpawnHook = async ({
224
+ scriptPath,
225
+ cwd,
226
+ timeoutMs,
227
+ }) => {
228
+ const start = performance.now();
229
+
230
+ // Scrub MANDU_PERF so prebuild logs don't leak into `mandu dev` perf
231
+ // traces. Everything else is inherited.
232
+ const env: Record<string, string> = {};
233
+ for (const [k, v] of Object.entries(process.env)) {
234
+ if (k === "MANDU_PERF") continue;
235
+ if (typeof v === "string") env[k] = v;
236
+ }
237
+
238
+ // Feature-detect Bun.spawn so this module can be imported in Node test
239
+ // contexts without crashing on module load. Tests that need Bun-less
240
+ // execution use the `spawn` injection hook anyway.
241
+ type BunLike = {
242
+ spawn: (opts: {
243
+ cmd: string[];
244
+ cwd?: string;
245
+ stdio?: readonly [unknown, unknown, unknown];
246
+ env?: Record<string, string>;
247
+ }) => {
248
+ exited: Promise<number>;
249
+ kill: (signal?: number | string) => void;
250
+ };
251
+ };
252
+ const bun = (globalThis as { Bun?: BunLike }).Bun;
253
+ if (!bun) {
254
+ throw new Error(
255
+ "[Mandu prebuild] Bun.spawn is not available in this environment. " +
256
+ "Inject a custom `spawn` hook via PrebuildRunnerOptions to run outside Bun.",
257
+ );
258
+ }
259
+
260
+ const proc = bun.spawn({
261
+ cmd: ["bun", scriptPath],
262
+ cwd,
263
+ stdio: ["inherit", "inherit", "inherit"],
264
+ env,
265
+ });
266
+
267
+ // Timeout guard. Bun.spawn's `exited` Promise never rejects; it resolves
268
+ // with the exit code (or null on signal). So we race against a setTimeout
269
+ // and kill the subprocess if the timer wins.
270
+ let timedOut = false;
271
+ const timer = setTimeout(() => {
272
+ timedOut = true;
273
+ try {
274
+ proc.kill();
275
+ } catch {
276
+ // Ignore — child may already be gone.
277
+ }
278
+ }, timeoutMs);
279
+
280
+ try {
281
+ const exitCode = await proc.exited;
282
+ const durationMs = performance.now() - start;
283
+ if (timedOut) {
284
+ throw new PrebuildError(
285
+ `Prebuild script '${scriptPath}' exceeded timeout (${timeoutMs}ms) and was killed.`,
286
+ { scriptPath, exitCode: null, durationMs },
287
+ );
288
+ }
289
+ return { exitCode, durationMs };
290
+ } finally {
291
+ clearTimeout(timer);
292
+ }
293
+ };
294
+
295
+ /**
296
+ * Run every `scripts/prebuild-*.ts` in sequence. Resolves with a summary
297
+ * of which scripts ran and how long each took. Rejects with
298
+ * `PrebuildError` on the first failure (subsequent scripts are NOT run,
299
+ * matching the `&&` chain semantics the user relied on before).
300
+ *
301
+ * @example
302
+ * ```ts
303
+ * await runPrebuildScripts({ rootDir: process.cwd() });
304
+ * ```
305
+ */
306
+ export async function runPrebuildScripts(
307
+ options: PrebuildRunnerOptions,
308
+ ): Promise<PrebuildResult> {
309
+ const {
310
+ rootDir,
311
+ scriptsDir = "scripts",
312
+ timeoutMs = 2 * 60 * 1000,
313
+ onStart,
314
+ onFinish,
315
+ spawn = defaultSpawn,
316
+ } = options;
317
+
318
+ const scripts = discoverPrebuildScripts(rootDir, scriptsDir);
319
+ if (scripts.length === 0) {
320
+ return { ran: 0, scripts: [] };
321
+ }
322
+
323
+ const results: PrebuildResult["scripts"] = [];
324
+ for (let i = 0; i < scripts.length; i++) {
325
+ const scriptPath = scripts[i];
326
+ onStart?.(scriptPath, i, scripts.length);
327
+
328
+ let exitCode: number | null;
329
+ let durationMs: number;
330
+ try {
331
+ const res = await spawn({ scriptPath, cwd: rootDir, timeoutMs });
332
+ exitCode = res.exitCode;
333
+ durationMs = res.durationMs;
334
+ } catch (err) {
335
+ if (err instanceof PrebuildError) {
336
+ onFinish?.({
337
+ scriptPath: err.scriptPath,
338
+ exitCode: err.exitCode,
339
+ durationMs: err.durationMs,
340
+ });
341
+ results.push({
342
+ scriptPath: err.scriptPath,
343
+ exitCode: err.exitCode,
344
+ durationMs: err.durationMs,
345
+ });
346
+ // Re-throw to abort the chain on failure.
347
+ throw err;
348
+ }
349
+ // Non-PrebuildError rejection — wrap so callers only see one error shape.
350
+ throw new PrebuildError(
351
+ `Prebuild script '${scriptPath}' failed: ${err instanceof Error ? err.message : String(err)}`,
352
+ {
353
+ scriptPath,
354
+ exitCode: null,
355
+ durationMs: 0,
356
+ cause: err,
357
+ },
358
+ );
359
+ }
360
+
361
+ onFinish?.({ scriptPath, exitCode, durationMs });
362
+ results.push({ scriptPath, exitCode, durationMs });
363
+
364
+ if (exitCode !== 0) {
365
+ throw new PrebuildError(
366
+ `Prebuild script '${scriptPath}' exited with code ${exitCode}. ` +
367
+ `Subsequent prebuild scripts were not run.`,
368
+ { scriptPath, exitCode, durationMs },
369
+ );
370
+ }
371
+ }
372
+
373
+ return { ran: results.length, scripts: results };
374
+ }
375
+
376
+ /**
377
+ * Determine whether a project appears to use the content/prebuild workflow.
378
+ * Used by `mandu dev` to decide whether to enable auto-prebuild by default:
379
+ * projects without `content/` AND without `scripts/prebuild-*.ts` pay no
380
+ * cost and see no behaviour change.
381
+ *
382
+ * Policy: auto-prebuild activates when EITHER
383
+ * (a) `<rootDir>/content/` exists (the convention for Astro-style
384
+ * content collections), OR
385
+ * (b) at least one `scripts/prebuild-*.ts` is discovered.
386
+ *
387
+ * Returns `false` in every other case so `mandu dev` stays a pure
388
+ * pass-through for simple apps.
389
+ */
390
+ export function shouldAutoPrebuild(rootDir: string, scriptsDir = "scripts"): boolean {
391
+ const contentDir = path.resolve(rootDir, "content");
392
+ try {
393
+ const stat = fs.statSync(contentDir);
394
+ if (stat.isDirectory()) return true;
395
+ } catch {
396
+ // No content/ — fall through to scripts check.
397
+ }
398
+ const scripts = discoverPrebuildScripts(rootDir, scriptsDir);
399
+ return scripts.length > 0;
400
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Schema Re-exports (Issue #199)
3
+ *
4
+ * Thin re-export shim so content authors can `import { z } from
5
+ * '@mandujs/core/content'` without pulling `zod` directly into their
6
+ * `content.config.ts`. This keeps the import path consistent with
7
+ * how users import `defineCollection`, and it gives us one chokepoint
8
+ * if we ever need to swap the validation backend or wrap Zod with
9
+ * Mandu-specific helpers.
10
+ *
11
+ * NOTE: we intentionally do NOT add a "fat" z here (no custom helpers,
12
+ * no `.mandu()` extensions) — keeping it identical to upstream Zod
13
+ * means `content.config.ts` files stay portable if a project moves
14
+ * between frameworks.
15
+ */
16
+
17
+ import { z } from "zod";
18
+
19
+ export { z };
20
+ export type { ZodSchema, ZodError, ZodType, ZodTypeAny, infer as Infer } from "zod";
@@ -0,0 +1,212 @@
1
+ /**
2
+ * Sidebar Generator (Issue #199)
3
+ *
4
+ * Takes a loaded `Collection` and produces a nested `{ title, href,
5
+ * children }` tree suitable for rendering a docs sidebar. The goal is
6
+ * to make the common case (slash-delimited slugs → hierarchical nav)
7
+ * work with zero config, while leaving escape hatches for projects
8
+ * with bespoke ordering.
9
+ *
10
+ * # Ordering rules
11
+ *
12
+ * 1. `order` field from frontmatter (ascending, missing = +Infinity)
13
+ * 2. Fallback: slug alphabetical
14
+ * 3. Category-level ordering: a `_category` meta file with an
15
+ * `order` field controls sibling order at the parent level —
16
+ * deliberately NOT implemented at the MVP; callers that need it
17
+ * today can pass a custom `sortNodes` comparator.
18
+ *
19
+ * # Draft entries
20
+ *
21
+ * When `collection.all()` yields entries with `data.draft === true`,
22
+ * they are **filtered out by default**. Callers can disable this by
23
+ * passing `includeDrafts: true` (useful during preview builds).
24
+ */
25
+
26
+ import type { Collection, CollectionEntry } from "./collection";
27
+ export type { Collection };
28
+
29
+ /** A node in the sidebar tree. */
30
+ export interface SidebarNode {
31
+ title: string;
32
+ href: string;
33
+ /** Present only on branch nodes (grouped categories). */
34
+ children?: SidebarNode[];
35
+ /** Draft/external flags — populated by the generator, caller-facing. */
36
+ draft?: boolean;
37
+ }
38
+
39
+ /** Options controlling sidebar shape and filtering. */
40
+ export interface GenerateSidebarOptions<T> {
41
+ /**
42
+ * Href prefix prepended to every node. Defaults to `/` so a slug
43
+ * of `intro` becomes `/intro`. Projects mounting docs under
44
+ * `/docs/` should pass `basePath: '/docs'`.
45
+ */
46
+ basePath?: string;
47
+ /**
48
+ * Extract the title shown in the sidebar. Defaults to
49
+ * `entry.data.title ?? entry.slug`. Implementations that store
50
+ * the sidebar label in a different field (e.g. `nav_title`) can
51
+ * override here.
52
+ */
53
+ getTitle?: (entry: CollectionEntry<T>) => string;
54
+ /**
55
+ * When true, include entries with `data.draft === true`. Defaults
56
+ * to false so production builds never leak unpublished pages into
57
+ * the nav.
58
+ */
59
+ includeDrafts?: boolean;
60
+ /**
61
+ * Custom comparator applied to siblings at every level. When
62
+ * omitted, the default (order-then-slug) comparator is used —
63
+ * consistent with `Collection.all()`'s default sort so the
64
+ * sidebar order matches the `.all()` order.
65
+ */
66
+ sortNodes?: (a: SidebarNode, b: SidebarNode, depth: number) => number;
67
+ /**
68
+ * When a directory has no own "index" entry, synthesize a branch
69
+ * node from the directory name. Default: true. Disable when a
70
+ * project prefers flat nav with all leaves at root.
71
+ */
72
+ synthesizeGroups?: boolean;
73
+ }
74
+
75
+ interface InternalNode {
76
+ title: string;
77
+ href: string;
78
+ order: number;
79
+ draft: boolean;
80
+ slugSegments: string[];
81
+ children: Map<string, InternalNode>;
82
+ /** Source entry if this node corresponds to a real file. */
83
+ entry?: CollectionEntry<unknown>;
84
+ }
85
+
86
+ /**
87
+ * Build a sidebar tree from a collection. Awaits `collection.all()`
88
+ * internally so callers don't need to load beforehand.
89
+ */
90
+ export async function generateSidebar<T>(
91
+ collection: Collection<T>,
92
+ options: GenerateSidebarOptions<T> = {}
93
+ ): Promise<SidebarNode[]> {
94
+ const {
95
+ basePath = "/",
96
+ getTitle,
97
+ includeDrafts = false,
98
+ sortNodes,
99
+ synthesizeGroups = true,
100
+ } = options;
101
+ const entries = await collection.all();
102
+ const visible = includeDrafts
103
+ ? entries
104
+ : entries.filter((e) => !(e.data as { draft?: unknown })?.draft);
105
+
106
+ const root = new Map<string, InternalNode>();
107
+ for (const entry of visible) {
108
+ insertEntry(root, entry, getTitle, basePath, synthesizeGroups);
109
+ }
110
+
111
+ const tree = toSidebarNodes(root, basePath, synthesizeGroups);
112
+ sortTree(tree, 0, sortNodes);
113
+ return tree;
114
+ }
115
+
116
+ function insertEntry<T>(
117
+ root: Map<string, InternalNode>,
118
+ entry: CollectionEntry<T>,
119
+ getTitle: ((entry: CollectionEntry<T>) => string) | undefined,
120
+ basePath: string,
121
+ synthesizeGroups: boolean
122
+ ): void {
123
+ const segments = entry.slug === "" ? [""] : entry.slug.split("/");
124
+ let cursor = root;
125
+ for (let i = 0; i < segments.length; i++) {
126
+ const seg = segments[i];
127
+ const isLeaf = i === segments.length - 1;
128
+ let node = cursor.get(seg);
129
+ if (!node) {
130
+ node = {
131
+ title: seg || "index",
132
+ href: joinHref(basePath, segments.slice(0, i + 1).join("/")),
133
+ order: Number.POSITIVE_INFINITY,
134
+ draft: false,
135
+ slugSegments: segments.slice(0, i + 1),
136
+ children: new Map(),
137
+ };
138
+ cursor.set(seg, node);
139
+ }
140
+ if (isLeaf) {
141
+ // Attach entry data to this node — overrides synthesized title.
142
+ node.entry = entry as CollectionEntry<unknown>;
143
+ node.title = getTitle
144
+ ? getTitle(entry)
145
+ : typeof (entry.data as { title?: unknown })?.title === "string"
146
+ ? String((entry.data as { title: string }).title)
147
+ : entry.slug || "index";
148
+ const rawOrder = (entry.data as { order?: unknown })?.order;
149
+ if (typeof rawOrder === "number") node.order = rawOrder;
150
+ node.draft = Boolean((entry.data as { draft?: unknown })?.draft);
151
+ node.href = joinHref(basePath, entry.slug);
152
+ } else if (!synthesizeGroups) {
153
+ // When groups are disabled, promote deeply-nested leaves to
154
+ // flat root entries. We still traverse for consistent sorting.
155
+ cursor = node.children;
156
+ continue;
157
+ }
158
+ cursor = node.children;
159
+ }
160
+ }
161
+
162
+ function toSidebarNodes(
163
+ map: Map<string, InternalNode>,
164
+ _basePath: string,
165
+ _synthesizeGroups: boolean
166
+ ): SidebarNode[] {
167
+ const out: SidebarNode[] = [];
168
+ for (const node of map.values()) {
169
+ const children =
170
+ node.children.size > 0
171
+ ? toSidebarNodes(node.children, _basePath, _synthesizeGroups)
172
+ : undefined;
173
+ const sidebarNode: SidebarNode = {
174
+ title: node.title,
175
+ href: node.href,
176
+ };
177
+ if (node.draft) sidebarNode.draft = true;
178
+ if (children) sidebarNode.children = children;
179
+ out.push(sidebarNode);
180
+ }
181
+ return out;
182
+ }
183
+
184
+ function sortTree(
185
+ nodes: SidebarNode[],
186
+ depth: number,
187
+ custom: ((a: SidebarNode, b: SidebarNode, depth: number) => number) | undefined
188
+ ): void {
189
+ // Fallback comparator: order field via per-node metadata is lost in
190
+ // the conversion to SidebarNode (intentionally — the public surface
191
+ // is title/href), so sort by title with a numeric-aware collator so
192
+ // "10-foo" sorts after "2-foo" for authors prefixing filenames.
193
+ const fallback = (a: SidebarNode, b: SidebarNode): number =>
194
+ a.title.localeCompare(b.title, undefined, { numeric: true });
195
+ nodes.sort((a, b) => {
196
+ if (custom) {
197
+ const c = custom(a, b, depth);
198
+ if (c !== 0) return c;
199
+ }
200
+ return fallback(a, b);
201
+ });
202
+ for (const node of nodes) {
203
+ if (node.children) sortTree(node.children, depth + 1, custom);
204
+ }
205
+ }
206
+
207
+ function joinHref(base: string, slug: string): string {
208
+ const normalizedBase = base.endsWith("/") ? base.slice(0, -1) : base;
209
+ if (!slug) return normalizedBase || "/";
210
+ const normalizedSlug = slug.startsWith("/") ? slug.slice(1) : slug;
211
+ return `${normalizedBase}/${normalizedSlug}`.replace(/\/+/g, "/");
212
+ }