@mandujs/core 0.25.2 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -72,8 +72,19 @@ export interface GenerateLLMSTxtOptions {
72
72
  * an absolute origin (e.g. `https://example.com`) to produce an
73
73
  * outward-facing llms.txt that third-party crawlers can consume
74
74
  * without resolving against the host.
75
+ *
76
+ * Alias for `baseUrl` — accepts either name so the API reads
77
+ * naturally whether the caller thinks in "site base path" or
78
+ * "absolute URL".
75
79
  */
76
80
  basePath?: string;
81
+ /**
82
+ * Alias for `basePath`. When both are provided, `baseUrl` wins
83
+ * (callers explicitly typing an absolute URL typically mean
84
+ * "use this verbatim"). Useful in docs-site configs that already
85
+ * expose `baseUrl` for their router / canonical URL helpers.
86
+ */
87
+ baseUrl?: string;
77
88
  /**
78
89
  * When true, include each entry's body verbatim under its heading.
79
90
  * This produces the `llms-full.txt` variant — significantly larger
@@ -92,6 +103,18 @@ export interface GenerateLLMSTxtOptions {
92
103
  * omits the trailing `: {summary}` tail.
93
104
  */
94
105
  getSummary?: (entry: CollectionEntry<unknown>) => string;
106
+ /**
107
+ * When true, emit a nested heading structure that groups entries
108
+ * by their first slug segment (the "category"). With `full: true`
109
+ * this produces an `llms-full.txt` that mirrors the docs sidebar
110
+ * layout — useful for LLM crawlers that consume the
111
+ * category-section convention.
112
+ *
113
+ * The category headings use `###` so they nest cleanly under the
114
+ * `##` collection heading. Entries without a slash in their slug
115
+ * are placed under an implicit "root" section.
116
+ */
117
+ groupByCategory?: boolean;
95
118
  }
96
119
 
97
120
  /**
@@ -108,11 +131,13 @@ export async function generateLLMSTxt(
108
131
  const {
109
132
  siteName,
110
133
  description,
111
- basePath = "/",
112
134
  full = false,
113
135
  includeDrafts = false,
114
136
  getSummary,
137
+ groupByCategory = false,
115
138
  } = options;
139
+ // `baseUrl` wins when both are provided — see the option JSDoc.
140
+ const basePath = options.baseUrl ?? options.basePath ?? "/";
116
141
 
117
142
  const lines: string[] = [];
118
143
  if (siteName) {
@@ -140,23 +165,54 @@ export async function generateLLMSTxt(
140
165
 
141
166
  lines.push(`## ${input.name}`);
142
167
  lines.push("");
143
- for (const entry of sorted) {
144
- const title =
145
- typeof (entry.data as { title?: unknown })?.title === "string"
146
- ? String((entry.data as { title: string }).title)
147
- : entry.slug || "index";
148
- const href = joinHref(basePath, input.name, entry.slug);
149
- const summary = getSummary
150
- ? getSummary(entry)
151
- : typeof (entry.data as { description?: unknown })?.description === "string"
152
- ? String((entry.data as { description: string }).description)
153
- : "";
154
- const tail = summary ? `: ${summary}` : "";
155
- lines.push(`- [${title}](${href})${tail}`);
156
- if (full) {
157
- lines.push("");
158
- lines.push(entry.content);
168
+
169
+ if (groupByCategory) {
170
+ // Bucket entries by their first slug segment. Entries without
171
+ // a slash go under the "__root__" sentinel so we can render
172
+ // them above the categorized groups.
173
+ const groups = new Map<string, typeof sorted>();
174
+ for (const entry of sorted) {
175
+ const [head, ...rest] = entry.slug.split("/");
176
+ const key = rest.length > 0 ? head : "__root__";
177
+ const bucket = groups.get(key);
178
+ if (bucket) bucket.push(entry);
179
+ else groups.set(key, [entry]);
180
+ }
181
+ // Emit root-level entries first (if any), then categorized
182
+ // groups in alphabetical category order for determinism.
183
+ const rootEntries = groups.get("__root__") ?? [];
184
+ for (const entry of rootEntries) {
185
+ lines.push(renderEntryLine(entry, input.name, basePath, getSummary));
186
+ if (full) {
187
+ lines.push("");
188
+ lines.push(entry.content);
189
+ lines.push("");
190
+ }
191
+ }
192
+ const categoryKeys = Array.from(groups.keys())
193
+ .filter((k) => k !== "__root__")
194
+ .sort();
195
+ for (const catKey of categoryKeys) {
196
+ if (rootEntries.length > 0) lines.push("");
197
+ lines.push(`### ${catKey}`);
159
198
  lines.push("");
199
+ for (const entry of groups.get(catKey) ?? []) {
200
+ lines.push(renderEntryLine(entry, input.name, basePath, getSummary));
201
+ if (full) {
202
+ lines.push("");
203
+ lines.push(entry.content);
204
+ lines.push("");
205
+ }
206
+ }
207
+ }
208
+ } else {
209
+ for (const entry of sorted) {
210
+ lines.push(renderEntryLine(entry, input.name, basePath, getSummary));
211
+ if (full) {
212
+ lines.push("");
213
+ lines.push(entry.content);
214
+ lines.push("");
215
+ }
160
216
  }
161
217
  }
162
218
  lines.push("");
@@ -177,6 +233,31 @@ async function loadInput(input: LLMSTxtInput): Promise<CollectionEntry<unknown>[
177
233
  return entries as CollectionEntry<unknown>[];
178
234
  }
179
235
 
236
+ /**
237
+ * Format a single entry as a `- [Title](href): summary` line. Split
238
+ * out from the main loop so both the flat and the categorized
239
+ * rendering paths share the same output shape.
240
+ */
241
+ function renderEntryLine(
242
+ entry: CollectionEntry<unknown>,
243
+ collectionName: string,
244
+ basePath: string,
245
+ getSummary: ((entry: CollectionEntry<unknown>) => string) | undefined
246
+ ): string {
247
+ const title =
248
+ typeof (entry.data as { title?: unknown })?.title === "string"
249
+ ? String((entry.data as { title: string }).title)
250
+ : entry.slug || "index";
251
+ const href = joinHref(basePath, collectionName, entry.slug);
252
+ const summary = getSummary
253
+ ? getSummary(entry)
254
+ : typeof (entry.data as { description?: unknown })?.description === "string"
255
+ ? String((entry.data as { description: string }).description)
256
+ : "";
257
+ const tail = summary ? `: ${summary}` : "";
258
+ return `- [${title}](${href})${tail}`;
259
+ }
260
+
180
261
  function joinHref(base: string, collectionName: string, slug: string): string {
181
262
  const parts = [collectionName, slug].filter((x) => x !== "" && x !== "/");
182
263
  const tail = parts.join("/").replace(/\/+/g, "/");
@@ -24,6 +24,11 @@ import {
24
24
  shouldAutoPrebuild,
25
25
  runPrebuildScripts,
26
26
  PrebuildError,
27
+ PrebuildTimeoutError,
28
+ resolvePrebuildTimeout,
29
+ DEFAULT_PREBUILD_TIMEOUT_MS,
30
+ PREBUILD_TIMEOUT_ENV,
31
+ defaultSpawn,
27
32
  type SpawnHook,
28
33
  } from "./prebuild";
29
34
 
@@ -247,3 +252,320 @@ describe("runPrebuildScripts", () => {
247
252
  expect(spawn.calls[0].timeoutMs).toBe(2 * 60 * 1000);
248
253
  });
249
254
  });
255
+
256
+ // ---------------------------------------------------------------------------
257
+ // resolvePrebuildTimeout (Issue #203)
258
+ // ---------------------------------------------------------------------------
259
+
260
+ describe("resolvePrebuildTimeout", () => {
261
+ const originalEnv = process.env[PREBUILD_TIMEOUT_ENV];
262
+ afterEach(() => {
263
+ if (originalEnv === undefined) delete process.env[PREBUILD_TIMEOUT_ENV];
264
+ else process.env[PREBUILD_TIMEOUT_ENV] = originalEnv;
265
+ });
266
+
267
+ it("returns DEFAULT_PREBUILD_TIMEOUT_MS (120s) when no override", () => {
268
+ delete process.env[PREBUILD_TIMEOUT_ENV];
269
+ expect(resolvePrebuildTimeout()).toBe(DEFAULT_PREBUILD_TIMEOUT_MS);
270
+ expect(DEFAULT_PREBUILD_TIMEOUT_MS).toBe(120_000);
271
+ });
272
+
273
+ it("explicit arg wins over env var", () => {
274
+ process.env[PREBUILD_TIMEOUT_ENV] = "5000";
275
+ expect(resolvePrebuildTimeout(1234)).toBe(1234);
276
+ });
277
+
278
+ it("env var is used when no explicit arg", () => {
279
+ process.env[PREBUILD_TIMEOUT_ENV] = "7500";
280
+ expect(resolvePrebuildTimeout()).toBe(7500);
281
+ });
282
+
283
+ it("ignores invalid env var (non-numeric) and falls back to default", () => {
284
+ process.env[PREBUILD_TIMEOUT_ENV] = "not-a-number";
285
+ expect(resolvePrebuildTimeout()).toBe(DEFAULT_PREBUILD_TIMEOUT_MS);
286
+ });
287
+
288
+ it("ignores invalid env var (zero / negative) and falls back to default", () => {
289
+ process.env[PREBUILD_TIMEOUT_ENV] = "0";
290
+ expect(resolvePrebuildTimeout()).toBe(DEFAULT_PREBUILD_TIMEOUT_MS);
291
+ process.env[PREBUILD_TIMEOUT_ENV] = "-5";
292
+ expect(resolvePrebuildTimeout()).toBe(DEFAULT_PREBUILD_TIMEOUT_MS);
293
+ });
294
+
295
+ it("ignores non-positive explicit arg", () => {
296
+ delete process.env[PREBUILD_TIMEOUT_ENV];
297
+ expect(resolvePrebuildTimeout(0)).toBe(DEFAULT_PREBUILD_TIMEOUT_MS);
298
+ expect(resolvePrebuildTimeout(-1)).toBe(DEFAULT_PREBUILD_TIMEOUT_MS);
299
+ });
300
+ });
301
+
302
+ // ---------------------------------------------------------------------------
303
+ // Issue #203 — Timeout + error surface regressions
304
+ // ---------------------------------------------------------------------------
305
+
306
+ describe("runPrebuildScripts — timeout surface (Issue #203)", () => {
307
+ let dir = "";
308
+ beforeEach(() => { dir = mktmp("timeout-"); });
309
+ afterEach(() => { fs.rmSync(dir, { recursive: true, force: true }); });
310
+
311
+ it("honours MANDU_PREBUILD_TIMEOUT_MS env override when timeoutMs omitted", async () => {
312
+ const originalEnv = process.env[PREBUILD_TIMEOUT_ENV];
313
+ process.env[PREBUILD_TIMEOUT_ENV] = "9999";
314
+ try {
315
+ writeFile(dir, "scripts/prebuild-1.ts");
316
+ const spawn = makeMockSpawn(() => ({ exitCode: 0, durationMs: 1 }));
317
+ await runPrebuildScripts({ rootDir: dir, spawn });
318
+ expect(spawn.calls[0].timeoutMs).toBe(9999);
319
+ } finally {
320
+ if (originalEnv === undefined) delete process.env[PREBUILD_TIMEOUT_ENV];
321
+ else process.env[PREBUILD_TIMEOUT_ENV] = originalEnv;
322
+ }
323
+ });
324
+
325
+ it("explicit timeoutMs wins over env var", async () => {
326
+ const originalEnv = process.env[PREBUILD_TIMEOUT_ENV];
327
+ process.env[PREBUILD_TIMEOUT_ENV] = "9999";
328
+ try {
329
+ writeFile(dir, "scripts/prebuild-1.ts");
330
+ const spawn = makeMockSpawn(() => ({ exitCode: 0, durationMs: 1 }));
331
+ await runPrebuildScripts({ rootDir: dir, spawn, timeoutMs: 2222 });
332
+ expect(spawn.calls[0].timeoutMs).toBe(2222);
333
+ } finally {
334
+ if (originalEnv === undefined) delete process.env[PREBUILD_TIMEOUT_ENV];
335
+ else process.env[PREBUILD_TIMEOUT_ENV] = originalEnv;
336
+ }
337
+ });
338
+
339
+ it("defaultSpawn throws PrebuildTimeoutError with script name + limit when the script runs longer than timeout", async () => {
340
+ // Script sleeps 300ms — we set timeout 80ms, so the timer must win.
341
+ // We use `Bun.sleep` + `process.exit(0)` so the script exits cleanly
342
+ // if somehow the kill is skipped (no zombie in test harness).
343
+ const scriptAbs = writeFile(
344
+ dir,
345
+ "scripts/prebuild-slow.ts",
346
+ "await Bun.sleep(300);\nprocess.exit(0);\n",
347
+ );
348
+
349
+ let caught: unknown;
350
+ try {
351
+ await defaultSpawn({ scriptPath: scriptAbs, cwd: dir, timeoutMs: 80 });
352
+ } catch (e) {
353
+ caught = e;
354
+ }
355
+ expect(caught).toBeInstanceOf(PrebuildTimeoutError);
356
+ expect(caught).toBeInstanceOf(PrebuildError); // subclass relationship
357
+ const err = caught as PrebuildTimeoutError;
358
+ expect(err.timeoutMs).toBe(80);
359
+ expect(err.scriptPath).toContain("prebuild-slow.ts");
360
+ // Message contract: includes script name + timeout limit + override hint.
361
+ expect(err.message).toContain("prebuild-slow.ts");
362
+ expect(err.message).toContain("80ms");
363
+ expect(err.message).toContain("dev.prebuildTimeoutMs");
364
+ expect(err.message).toContain(PREBUILD_TIMEOUT_ENV);
365
+ // Regression beacon: message MUST NOT contain the opaque
366
+ // "non-Error thrown" string Issue #203 was reported against.
367
+ expect(err.message).not.toContain("non-Error thrown");
368
+ });
369
+
370
+ it("runPrebuildScripts surfaces PrebuildTimeoutError via injected spawn", async () => {
371
+ writeFile(dir, "scripts/prebuild-slow.ts");
372
+ const spawn: SpawnHook = async (args) => {
373
+ throw new PrebuildTimeoutError({
374
+ scriptPath: args.scriptPath,
375
+ timeoutMs: args.timeoutMs,
376
+ durationMs: args.timeoutMs,
377
+ });
378
+ };
379
+ let caught: unknown;
380
+ try {
381
+ await runPrebuildScripts({ rootDir: dir, spawn, timeoutMs: 100 });
382
+ } catch (e) {
383
+ caught = e;
384
+ }
385
+ expect(caught).toBeInstanceOf(PrebuildTimeoutError);
386
+ const err = caught as PrebuildTimeoutError;
387
+ expect(err.timeoutMs).toBe(100);
388
+ expect(err.scriptPath).toContain("prebuild-slow.ts");
389
+ });
390
+ });
391
+
392
+ describe("runPrebuildScripts — error preservation (Issue #203)", () => {
393
+ let dir = "";
394
+ beforeEach(() => { dir = mktmp("err-surface-"); });
395
+ afterEach(() => { fs.rmSync(dir, { recursive: true, force: true }); });
396
+
397
+ it("preserves the inner Error message ('boom') when a spawn rejection occurs", async () => {
398
+ writeFile(dir, "scripts/prebuild.ts");
399
+ const inner = new Error("boom");
400
+ const spawn: SpawnHook = async () => {
401
+ throw inner;
402
+ };
403
+ let caught: unknown;
404
+ try {
405
+ await runPrebuildScripts({ rootDir: dir, spawn });
406
+ } catch (e) {
407
+ caught = e;
408
+ }
409
+ expect(caught).toBeInstanceOf(PrebuildError);
410
+ const err = caught as PrebuildError & { cause?: unknown };
411
+ // The inner message MUST appear verbatim — the whole point of #203.
412
+ expect(err.message).toContain("boom");
413
+ // Regression beacon.
414
+ expect(err.message).not.toContain("non-Error thrown");
415
+ // The inner error is attached as `.cause` so debug tooling can
416
+ // recover its stack.
417
+ expect(err.cause).toBe(inner);
418
+ });
419
+
420
+ it("preserves stack via .cause when inner Error has a stack", async () => {
421
+ writeFile(dir, "scripts/prebuild.ts");
422
+ const inner = new Error("kaboom");
423
+ const originalStack = inner.stack;
424
+ expect(originalStack).toBeTruthy();
425
+ const spawn: SpawnHook = async () => {
426
+ throw inner;
427
+ };
428
+ let caught: unknown;
429
+ try {
430
+ await runPrebuildScripts({ rootDir: dir, spawn });
431
+ } catch (e) {
432
+ caught = e;
433
+ }
434
+ const err = caught as PrebuildError & { cause?: Error };
435
+ expect(err.cause).toBe(inner);
436
+ expect(err.cause?.stack).toBe(originalStack);
437
+ });
438
+
439
+ it("handles non-Error rejections (string) without producing 'non-Error thrown'", async () => {
440
+ writeFile(dir, "scripts/prebuild.ts");
441
+ const spawn: SpawnHook = async () => {
442
+ // Raw string throw — the pathological case Issue #203 was about.
443
+ throw "spawn blew up";
444
+ };
445
+ let caught: unknown;
446
+ try {
447
+ await runPrebuildScripts({ rootDir: dir, spawn });
448
+ } catch (e) {
449
+ caught = e;
450
+ }
451
+ expect(caught).toBeInstanceOf(PrebuildError);
452
+ const err = caught as PrebuildError & { cause?: unknown };
453
+ // The raw string survives into `.message`.
454
+ expect(err.message).toContain("spawn blew up");
455
+ expect(err.message).not.toContain("non-Error thrown");
456
+ expect(err.cause).toBe("spawn blew up");
457
+ });
458
+
459
+ it("handles non-Error rejections (object) without producing 'non-Error thrown'", async () => {
460
+ writeFile(dir, "scripts/prebuild.ts");
461
+ const raw = { code: "EBADF", info: "fd closed" };
462
+ const spawn: SpawnHook = async () => {
463
+ throw raw;
464
+ };
465
+ let caught: unknown;
466
+ try {
467
+ await runPrebuildScripts({ rootDir: dir, spawn });
468
+ } catch (e) {
469
+ caught = e;
470
+ }
471
+ const err = caught as PrebuildError & { cause?: unknown };
472
+ expect(err.message).toContain("EBADF");
473
+ expect(err.message).not.toContain("non-Error thrown");
474
+ expect(err.cause).toBe(raw);
475
+ });
476
+
477
+ it("includes stdout/stderr tails in PrebuildError.message for non-zero exit", async () => {
478
+ writeFile(dir, "scripts/prebuild.ts");
479
+ const stderrSample = Array.from({ length: 15 }, (_, i) => `err-line-${i + 1}`).join("\n");
480
+ const stdoutSample = Array.from({ length: 12 }, (_, i) => `out-line-${i + 1}`).join("\n");
481
+ const spawn: SpawnHook = async () => ({
482
+ exitCode: 1,
483
+ durationMs: 5,
484
+ stdoutTail: stdoutSample,
485
+ stderrTail: stderrSample,
486
+ });
487
+ let caught: unknown;
488
+ try {
489
+ await runPrebuildScripts({ rootDir: dir, spawn });
490
+ } catch (e) {
491
+ caught = e;
492
+ }
493
+ expect(caught).toBeInstanceOf(PrebuildError);
494
+ const err = caught as PrebuildError;
495
+ // Exactly last 10 stderr lines are kept.
496
+ expect(err.message).toContain("err-line-15");
497
+ expect(err.message).toContain("err-line-6"); // the 10-from-last
498
+ expect(err.message).not.toContain("err-line-5"); // trimmed
499
+ // Stdout tail is also present (10 lines out of 12).
500
+ expect(err.message).toContain("out-line-12");
501
+ expect(err.message).toContain("out-line-3");
502
+ expect(err.message).not.toContain("out-line-2");
503
+ // Structured fields carry the full captured tails.
504
+ expect(err.stderrTail).toBe(stderrSample);
505
+ expect(err.stdoutTail).toBe(stdoutSample);
506
+ });
507
+
508
+ it("omits empty tail sections when the spawn hook didn't capture", async () => {
509
+ writeFile(dir, "scripts/prebuild.ts");
510
+ const spawn: SpawnHook = async () => ({ exitCode: 2, durationMs: 3 });
511
+ let caught: unknown;
512
+ try {
513
+ await runPrebuildScripts({ rootDir: dir, spawn });
514
+ } catch (e) {
515
+ caught = e;
516
+ }
517
+ const err = caught as PrebuildError;
518
+ // The "exited with code 2" prefix is present but no "--- stderr ---" sections.
519
+ expect(err.message).toContain("exited with code 2");
520
+ expect(err.message).not.toContain("--- stderr");
521
+ expect(err.message).not.toContain("--- stdout");
522
+ });
523
+
524
+ it("normalizes Windows-style CRLF line endings in stderr tail", async () => {
525
+ writeFile(dir, "scripts/prebuild.ts");
526
+ const crlf = ["a", "b", "c", "d"].join("\r\n");
527
+ const spawn: SpawnHook = async () => ({
528
+ exitCode: 1,
529
+ durationMs: 1,
530
+ stderrTail: crlf,
531
+ });
532
+ let caught: unknown;
533
+ try {
534
+ await runPrebuildScripts({ rootDir: dir, spawn });
535
+ } catch (e) {
536
+ caught = e;
537
+ }
538
+ const err = caught as PrebuildError;
539
+ // All 4 lines survive (under the 10-line cap).
540
+ expect(err.message).toContain("a\nb\nc\nd");
541
+ // No raw \r\n survived.
542
+ expect(err.message).not.toContain("\r\n");
543
+ });
544
+ });
545
+
546
+ describe("PrebuildTimeoutError shape (Issue #203)", () => {
547
+ it("is a subclass of PrebuildError so existing `instanceof PrebuildError` callers still match", () => {
548
+ const err = new PrebuildTimeoutError({
549
+ scriptPath: "/tmp/foo/scripts/prebuild.ts",
550
+ timeoutMs: 500,
551
+ durationMs: 500,
552
+ });
553
+ expect(err).toBeInstanceOf(PrebuildTimeoutError);
554
+ expect(err).toBeInstanceOf(PrebuildError);
555
+ expect(err).toBeInstanceOf(Error);
556
+ expect(err.name).toBe("PrebuildTimeoutError");
557
+ expect(err.exitCode).toBeNull();
558
+ });
559
+
560
+ it("message names the script + limit + override paths", () => {
561
+ const err = new PrebuildTimeoutError({
562
+ scriptPath: "/repo/scripts/prebuild-seed.ts",
563
+ timeoutMs: 250,
564
+ durationMs: 250,
565
+ });
566
+ expect(err.message).toContain("prebuild-seed.ts");
567
+ expect(err.message).toContain("250ms");
568
+ expect(err.message).toContain("dev.prebuildTimeoutMs");
569
+ expect(err.message).toContain(PREBUILD_TIMEOUT_ENV);
570
+ });
571
+ });