pi-doc-injector 0.6.0 → 0.7.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.
package/registry.ts CHANGED
@@ -6,9 +6,15 @@
6
6
  * 2. readFile(filePath) → parse frontmatter or generate keywords
7
7
  */
8
8
  import type { Dirent } from "node:fs";
9
- import { readdir, readFile, stat } from "node:fs/promises";
9
+ import { lstat, readdir, readFile, stat } from "node:fs/promises";
10
10
  import { basename, extname, join, relative, resolve } from "node:path";
11
- import { LLM_CACHE_SENTINEL, type CacheEntry, type DocEntry, type DocInjectorConfig, type KeywordCache } from "./types";
11
+ import {
12
+ LLM_CACHE_SENTINEL,
13
+ type CacheEntry,
14
+ type DocEntry,
15
+ type DocInjectorConfig,
16
+ type KeywordCache,
17
+ } from "./types";
12
18
  import type { Notifier } from "./notifier";
13
19
  import { createGlobFilter } from "./globber";
14
20
  import { generateKeywords } from "./keyword-gen";
@@ -17,7 +23,9 @@ import { generateKeywords } from "./keyword-gen";
17
23
  * Shared parser for frontmatter block content (title + keywords).
18
24
  * Extracts title and keywords from YAML-like content between delimiters.
19
25
  */
20
- function parseFrontmatterBlock(block: string): { title: string; keywords: string[] } | null {
26
+ function parseFrontmatterBlock(
27
+ block: string,
28
+ ): { title: string; keywords: string[] } | null {
21
29
  // Extract title
22
30
  const titleMatch = block.match(/^title:\s*["']?([^"'\n]+)["']?$/m);
23
31
  const title = titleMatch ? titleMatch[1].trim() : "";
@@ -26,7 +34,7 @@ function parseFrontmatterBlock(block: string): { title: string; keywords: string
26
34
  const keywords: string[] = [];
27
35
 
28
36
  // Try flow array: keywords: [a, b, c]
29
- const flowMatch = block.match(/keywords:\s*\[([^\]]*)\]/);
37
+ const flowMatch = block.match(/^keywords:[ \t]*\[([^\]]*)\]/m);
30
38
  if (flowMatch) {
31
39
  keywords.push(
32
40
  ...flowMatch[1]
@@ -36,7 +44,9 @@ function parseFrontmatterBlock(block: string): { title: string; keywords: string
36
44
  );
37
45
  } else {
38
46
  // Try block array: keywords:\n - a\n - b
39
- const blockMatches = block.matchAll(/keywords:\s*\n((?:\s*-\s*.+\n?)+)/g);
47
+ const blockMatches = block.matchAll(
48
+ /^keywords:[ \t]*\n((?:[ \t]*-[ \t]*.+\n?)+)/gm,
49
+ );
40
50
  for (const bm of blockMatches) {
41
51
  const items = bm[1].matchAll(/^\s*-\s*["']?([^"'\n]+)["']?$/gm);
42
52
  for (const im of items) {
@@ -172,10 +182,10 @@ export function parseFrontmatter(
172
182
  content: string,
173
183
  ): { title: string; keywords: string[]; body: string } | null {
174
184
  return (
175
- parseYamlFrontmatter(content)
176
- ?? parseCStyleFrontmatter(content)
177
- ?? parseHTMLFrontmatter(content)
178
- ?? parseSlashSlashFrontmatter(content)
185
+ parseYamlFrontmatter(content) ??
186
+ parseCStyleFrontmatter(content) ??
187
+ parseHTMLFrontmatter(content) ??
188
+ parseSlashSlashFrontmatter(content)
179
189
  );
180
190
  }
181
191
 
@@ -226,42 +236,42 @@ class PromisePool {
226
236
  * Document Registry class. Scans a docs folder and maintains an index of DocEntry.
227
237
  */
228
238
  export class DocRegistry {
229
- private entries: DocEntry[] = [];
230
- private docsPath: string;
231
- private config: DocInjectorConfig;
232
- private cache: KeywordCache | null = null;
233
- private dirtyCache: KeywordCache = { version: 1, files: {} };
234
- private notifier: Notifier;
235
- // Per-registry flag: warn about a missing docs folder at most once.
236
- // rebuild() is called twice at startup (once from session_start, once
237
- // from resources_discover); without this flag the user sees the
238
- // same warning twice. Not reset across rebuilds — a missing folder
239
- // is a persistent condition, not a transient one.
240
- private warnedMissingDocs = false;
241
-
242
- private constructor(
243
- docsPath: string,
244
- config: DocInjectorConfig,
245
- cache: KeywordCache | undefined,
246
- notifier: Notifier,
247
- ) {
248
- this.docsPath = docsPath;
249
- this.config = config;
250
- this.cache = cache ?? null;
251
- this.notifier = notifier;
252
- }
239
+ private entries: DocEntry[] = [];
240
+ private docsPath: string;
241
+ private config: DocInjectorConfig;
242
+ private cache: KeywordCache | null = null;
243
+ private dirtyCache: KeywordCache = { version: 1, files: {} };
244
+ private notifier: Notifier;
245
+ // Per-registry flag: warn about a missing docs folder at most once.
246
+ // rebuild() is called twice at startup (once from session_start, once
247
+ // from resources_discover); without this flag the user sees the
248
+ // same warning twice. Not reset across rebuilds — a missing folder
249
+ // is a persistent condition, not a transient one.
250
+ private warnedMissingDocs = false;
251
+
252
+ private constructor(
253
+ docsPath: string,
254
+ config: DocInjectorConfig,
255
+ cache: KeywordCache | undefined,
256
+ notifier: Notifier,
257
+ ) {
258
+ this.docsPath = docsPath;
259
+ this.config = config;
260
+ this.cache = cache ?? null;
261
+ this.notifier = notifier;
262
+ }
253
263
 
254
- /** Create a registry by scanning the docs folder. */
255
- static async create(
256
- docsPath: string,
257
- config: DocInjectorConfig,
258
- cache: KeywordCache | undefined,
259
- notifier: Notifier,
260
- ): Promise<DocRegistry> {
261
- const registry = new DocRegistry(docsPath, config, cache, notifier);
262
- await registry.rebuild();
263
- return registry;
264
- }
264
+ /** Create a registry by scanning the docs folder. */
265
+ static async create(
266
+ docsPath: string,
267
+ config: DocInjectorConfig,
268
+ cache: KeywordCache | undefined,
269
+ notifier: Notifier,
270
+ ): Promise<DocRegistry> {
271
+ const registry = new DocRegistry(docsPath, config, cache, notifier);
272
+ await registry.rebuild();
273
+ return registry;
274
+ }
265
275
 
266
276
  /** Re-scan the docs folder and rebuild the index. */
267
277
  async rebuild(): Promise<void> {
@@ -297,9 +307,11 @@ export class DocRegistry {
297
307
  // Process files concurrently with PromisePool
298
308
  const pool = new PromisePool(this.config.maxConcurrent);
299
309
 
300
- const tasks = scanResults.map((sr) => async (): Promise<DocEntry | null> => {
301
- return this.processFile(sr, preserved);
302
- });
310
+ const tasks = scanResults.map(
311
+ (sr) => async (): Promise<DocEntry | null> => {
312
+ return this.processFile(sr, preserved);
313
+ },
314
+ );
303
315
 
304
316
  const results = await pool.all(tasks);
305
317
  this.entries = results.filter((e): e is DocEntry => e !== null);
@@ -335,6 +347,8 @@ export class DocRegistry {
335
347
  ): Promise<DocEntry | null> {
336
348
  try {
337
349
  // ─── METADATA ─────────────────────────────────────────────
350
+ const linkStat = await lstat(filePath);
351
+ if (!linkStat.isFile()) return null;
338
352
  const fileStat = await stat(filePath);
339
353
 
340
354
  if (fileStat.size > this.config.maxFileSize) {
@@ -347,6 +361,25 @@ export class DocRegistry {
347
361
  // Read once — needed for frontmatter parse, content, and title.
348
362
  const raw = await readFile(filePath, "utf-8");
349
363
 
364
+ if (this.config.mode === "simple") {
365
+ // Simple mode indexes only docs/{name}.md, not subfolders or metadata.
366
+ if (relativePath !== fileName || extname(fileName) !== ".md") {
367
+ return null;
368
+ }
369
+ const name = fileName.slice(0, -3);
370
+ if (!name) return null;
371
+ return {
372
+ filePath,
373
+ fileName,
374
+ relativePath,
375
+ title: extractTitle(raw, fileName),
376
+ keywords: [name],
377
+ content: raw,
378
+ injected: preserved.get(filePath) ?? false,
379
+ keywordSource: "filename",
380
+ };
381
+ }
382
+
350
383
  // ─── PRIORITY 1: Frontmatter (authoritative) ─────────────
351
384
  const parsed = parseFrontmatter(raw);
352
385
  if (parsed) {
@@ -427,7 +460,9 @@ export class DocRegistry {
427
460
  } catch (err) {
428
461
  // Only warn for unexpected errors, not ENOENT (file deleted/moved after scan)
429
462
  if ((err as NodeJS.ErrnoException).code !== "ENOENT") {
430
- this.notifier.warn(`[doc-injector] Error reading ${relativePath}: ${err instanceof Error ? err.message : String(err)}`);
463
+ this.notifier.warn(
464
+ `[doc-injector] Error reading ${relativePath}: ${err instanceof Error ? err.message : String(err)}`,
465
+ );
431
466
  }
432
467
  return null;
433
468
  }
@@ -450,7 +485,10 @@ export class DocRegistry {
450
485
  private async scanRecursive(dir: string): Promise<ScanResult[]> {
451
486
  const filter = createGlobFilter(this.config.include, this.config.exclude);
452
487
  const results: ScanResult[] = [];
453
- const dirents = await readdir(dir, { recursive: true, withFileTypes: true }) as Dirent[];
488
+ const dirents = (await readdir(dir, {
489
+ recursive: true,
490
+ withFileTypes: true,
491
+ })) as Dirent[];
454
492
 
455
493
  for (const dirent of dirents) {
456
494
  if (!dirent.isFile()) continue;
@@ -460,9 +498,11 @@ export class DocRegistry {
460
498
  // Resolve relative path cross-runtime
461
499
  let relPath: string;
462
500
  if (dirent.name === fileName) {
463
- const parentPath = (dirent as Dirent & { parentPath?: string; path?: string }).parentPath
464
- ?? (dirent as Dirent & { path?: string }).path
465
- ?? "";
501
+ const parentPath =
502
+ (dirent as Dirent & { parentPath?: string; path?: string })
503
+ .parentPath ??
504
+ (dirent as Dirent & { path?: string }).path ??
505
+ "";
466
506
  relPath = parentPath
467
507
  ? relative(dir, join(parentPath, dirent.name))
468
508
  : dirent.name;
@@ -500,7 +540,6 @@ export class DocRegistry {
500
540
  this.cache = cache;
501
541
  }
502
542
 
503
-
504
543
  /**
505
544
  * Get all registered entries.
506
545
  *
package/types.ts CHANGED
@@ -3,7 +3,12 @@
3
3
  */
4
4
 
5
5
  /** Source of keywords for a doc entry. */
6
- export type KeywordSource = "frontmatter" | "heuristic" | "llm" | "cache";
6
+ export type KeywordSource =
7
+ | "filename"
8
+ | "frontmatter"
9
+ | "heuristic"
10
+ | "llm"
11
+ | "cache";
7
12
 
8
13
  /** A parsed document from the docs folder. */
9
14
  export interface DocEntry {
@@ -70,6 +75,8 @@ export interface GlobFilter {
70
75
 
71
76
  /** Extension configuration. */
72
77
  export interface DocInjectorConfig {
78
+ /** Simple filename matching (default) or legacy keyword matching. */
79
+ mode: "simple" | "keywords";
73
80
  /** Path to docs folder (relative to cwd) */
74
81
  docsPath: string;
75
82
  /** Minimum keyword matches to trigger injection */
@@ -103,6 +110,7 @@ export interface DocInjectorConfig {
103
110
 
104
111
  /** Default configuration values. */
105
112
  export const DEFAULT_CONFIG: DocInjectorConfig = {
113
+ mode: "simple",
106
114
  docsPath: "./docs",
107
115
  matchThreshold: 2,
108
116
  streamWindowSize: 500,