@doccov/sdk 0.15.1 → 0.19.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.
Files changed (4) hide show
  1. package/LICENSE +1 -1
  2. package/dist/index.d.ts +785 -551
  3. package/dist/index.js +1630 -983
  4. package/package.json +8 -3
package/dist/index.d.ts CHANGED
@@ -1,3 +1,273 @@
1
+ /**
2
+ * Configuration types for DocCov.
3
+ * These types are shared between CLI and API.
4
+ */
5
+ /**
6
+ * Documentation configuration options.
7
+ */
8
+ interface DocsConfig {
9
+ /** Glob patterns for markdown docs to include */
10
+ include?: string[];
11
+ /** Glob patterns for markdown docs to exclude */
12
+ exclude?: string[];
13
+ }
14
+ /**
15
+ * Example validation modes.
16
+ */
17
+ type ExampleValidationMode = "presence" | "typecheck" | "run";
18
+ /**
19
+ * Schema extraction modes for validation libraries (Zod, Valibot, TypeBox, ArkType).
20
+ *
21
+ * - 'static': TypeScript Compiler API only (no runtime, always safe)
22
+ * - 'runtime': Standard Schema runtime extraction (requires built package)
23
+ * - 'hybrid': Try runtime first, fall back to static
24
+ */
25
+ type SchemaExtractionMode = "static" | "runtime" | "hybrid";
26
+ /**
27
+ * Check command configuration options.
28
+ */
29
+ interface CheckConfig {
30
+ /**
31
+ * Example validation modes to run.
32
+ * Can be a single mode, array of modes, or comma-separated string.
33
+ * - 'presence': Check that @example blocks exist on exports
34
+ * - 'typecheck': Compile examples with TypeScript
35
+ * - 'run': Execute examples and validate assertions
36
+ */
37
+ examples?: ExampleValidationMode | ExampleValidationMode[] | string;
38
+ /** Minimum coverage percentage required (0-100) */
39
+ minCoverage?: number;
40
+ /** Maximum drift percentage allowed (0-100) */
41
+ maxDrift?: number;
42
+ }
43
+ /**
44
+ * Normalized DocCov configuration.
45
+ * This is the parsed/normalized form used by commands.
46
+ */
47
+ interface DocCovConfig {
48
+ /** Export include patterns */
49
+ include?: string[];
50
+ /** Export exclude patterns */
51
+ exclude?: string[];
52
+ /** Plugins (future) */
53
+ plugins?: unknown[];
54
+ /** Documentation configuration */
55
+ docs?: DocsConfig;
56
+ /** Check command configuration */
57
+ check?: CheckConfig;
58
+ /**
59
+ * Schema extraction mode for validation libraries.
60
+ *
61
+ * - 'static' (default): Safe, uses TypeScript Compiler API
62
+ * - 'runtime': Uses Standard Schema (requires built package)
63
+ * - 'hybrid': Tries runtime first, falls back to static
64
+ *
65
+ * Runtime extraction provides richer JSON Schema output (formats, patterns)
66
+ * but requires the package to be built first.
67
+ */
68
+ schemaExtraction?: SchemaExtractionMode;
69
+ }
70
+ /**
71
+ * Define a DocCov configuration.
72
+ * Helper function for type-safe configuration in doccov.config.ts.
73
+ *
74
+ * @param config - Configuration object
75
+ * @returns The configuration object (for type inference)
76
+ *
77
+ * @example
78
+ * ```typescript
79
+ * // doccov.config.ts
80
+ * import { defineConfig } from '@doccov/sdk';
81
+ *
82
+ * defineConfig({
83
+ * include: ['MyClass', 'myFunction'],
84
+ * exclude: ['internal*'],
85
+ * check: {
86
+ * minCoverage: 80,
87
+ * },
88
+ * });
89
+ * ```
90
+ */
91
+ declare function defineConfig(config: DocCovConfig): DocCovConfig;
92
+ interface DocCovOptions {
93
+ includePrivate?: boolean;
94
+ followImports?: boolean;
95
+ maxDepth?: number;
96
+ resolveExternalTypes?: boolean;
97
+ /** Enable spec caching (default: true) */
98
+ useCache?: boolean;
99
+ /** Working directory for cache operations (default: process.cwd()) */
100
+ cwd?: string;
101
+ /**
102
+ * Schema extraction mode for validation libraries (Zod, Valibot, etc.)
103
+ *
104
+ * - 'static' (default): TypeScript Compiler API only (no runtime)
105
+ * - 'runtime': Standard Schema runtime extraction (requires built package)
106
+ * - 'hybrid': Try runtime first, fall back to static
107
+ */
108
+ schemaExtraction?: SchemaExtractionMode;
109
+ }
110
+ /**
111
+ * Pre-detected Standard Schema for a variable export.
112
+ */
113
+ interface DetectedSchemaEntry {
114
+ schema: Record<string, unknown>;
115
+ vendor: string;
116
+ }
117
+ /**
118
+ * Runtime Schema Detection (Stubbed)
119
+ *
120
+ * Standard Schema extraction has been removed. This module provides
121
+ * empty stubs to maintain API compatibility.
122
+ */
123
+ interface SchemaDetectionContext {
124
+ baseDir: string;
125
+ entryFile: string;
126
+ }
127
+ interface SchemaDetectionResult {
128
+ schemas: Map<string, never>;
129
+ errors: string[];
130
+ }
131
+ declare function detectRuntimeSchemas(_context: SchemaDetectionContext): Promise<SchemaDetectionResult>;
132
+ declare function clearSchemaCache(): void;
133
+ import * as TS from "typescript";
134
+ /**
135
+ * A schema adapter can detect and extract output types from a specific
136
+ * schema validation library.
137
+ */
138
+ interface SchemaAdapter {
139
+ /** Unique identifier for this adapter */
140
+ readonly id: string;
141
+ /** npm package name(s) this adapter handles */
142
+ readonly packages: readonly string[];
143
+ /**
144
+ * Check if a type matches this adapter's schema library.
145
+ * Should be fast - called for every export.
146
+ */
147
+ matches(type: TS.Type, checker: TS.TypeChecker): boolean;
148
+ /**
149
+ * Extract the output type from a schema type.
150
+ * Returns null if extraction fails.
151
+ */
152
+ extractOutputType(type: TS.Type, checker: TS.TypeChecker): TS.Type | null;
153
+ /**
154
+ * Extract the input type from a schema type (optional).
155
+ * Useful for transforms where input differs from output.
156
+ */
157
+ extractInputType?(type: TS.Type, checker: TS.TypeChecker): TS.Type | null;
158
+ }
159
+ /**
160
+ * Result of schema type extraction
161
+ */
162
+ interface SchemaExtractionResult {
163
+ /** The adapter that matched */
164
+ adapter: SchemaAdapter;
165
+ /** The extracted output type */
166
+ outputType: TS.Type;
167
+ /** The extracted input type (if different from output) */
168
+ inputType?: TS.Type;
169
+ }
170
+ import * as TS2 from "typescript";
171
+ /**
172
+ * Find an adapter that matches the given type.
173
+ * Returns null if no adapter matches.
174
+ */
175
+ declare function findAdapter(type: TS2.Type, checker: TS2.TypeChecker): SchemaAdapter | null;
176
+ /**
177
+ * Check if a type is from a recognized schema library.
178
+ */
179
+ declare function isSchemaType(type: TS2.Type, checker: TS2.TypeChecker): boolean;
180
+ /**
181
+ * Extract the output type from a schema type.
182
+ * Returns null if:
183
+ * - The type is not from a recognized schema library
184
+ * - The adapter fails to extract the output type
185
+ */
186
+ declare function extractSchemaOutputType(type: TS2.Type, checker: TS2.TypeChecker): TS2.Type | null;
187
+ /**
188
+ * Full extraction with adapter info.
189
+ * Useful when you need to know which library was detected.
190
+ */
191
+ declare function extractSchemaType(type: TS2.Type, checker: TS2.TypeChecker): SchemaExtractionResult | null;
192
+ /**
193
+ * Get all registered adapters.
194
+ * Useful for logging/debugging.
195
+ */
196
+ declare function getRegisteredAdapters(): readonly SchemaAdapter[];
197
+ /**
198
+ * Get supported library names.
199
+ * Useful for documentation/help output.
200
+ */
201
+ declare function getSupportedLibraries(): readonly string[];
202
+ /**
203
+ * Standard JSON Schema v1 interface (minimal for detection).
204
+ */
205
+ interface StandardJSONSchemaV1 {
206
+ "~standard": {
207
+ version: number;
208
+ vendor: string;
209
+ jsonSchema?: {
210
+ output: (target?: string) => Record<string, unknown>;
211
+ input?: (target?: string) => Record<string, unknown>;
212
+ };
213
+ };
214
+ }
215
+ /**
216
+ * Result of extracting Standard Schema from an export.
217
+ */
218
+ interface StandardSchemaExtractionResult {
219
+ exportName: string;
220
+ vendor: string;
221
+ outputSchema: Record<string, unknown>;
222
+ inputSchema?: Record<string, unknown>;
223
+ }
224
+ /**
225
+ * Options for runtime Standard Schema extraction.
226
+ */
227
+ interface ExtractStandardSchemasOptions {
228
+ /** Timeout in milliseconds (default: 10000) */
229
+ timeout?: number;
230
+ /** JSON Schema target version (default: 'draft-2020-12') */
231
+ target?: "draft-2020-12" | "draft-07" | "openapi-3.0";
232
+ }
233
+ /**
234
+ * Result of Standard Schema extraction.
235
+ */
236
+ interface StandardSchemaExtractionOutput {
237
+ schemas: Map<string, StandardSchemaExtractionResult>;
238
+ errors: string[];
239
+ }
240
+ /**
241
+ * Check if an object implements StandardJSONSchemaV1.
242
+ * This is a static type guard - doesn't require runtime.
243
+ */
244
+ declare function isStandardJSONSchema(obj: unknown): obj is StandardJSONSchemaV1;
245
+ /**
246
+ * Resolve compiled JS path from TypeScript source.
247
+ * Tries common output locations: dist/, build/, lib/, same dir.
248
+ */
249
+ declare function resolveCompiledPath(tsPath: string, baseDir: string): string | null;
250
+ /**
251
+ * Extract Standard Schema JSON Schemas from a compiled JS module.
252
+ *
253
+ * **Security Note**: This executes the module in a subprocess.
254
+ * Only use with trusted code (user's own packages).
255
+ *
256
+ * @param compiledJsPath - Path to compiled .js file
257
+ * @param options - Extraction options
258
+ * @returns Extraction results with schemas and any errors
259
+ */
260
+ declare function extractStandardSchemas(compiledJsPath: string, options?: ExtractStandardSchemasOptions): Promise<StandardSchemaExtractionOutput>;
261
+ /**
262
+ * Extract Standard Schema from a TypeScript project.
263
+ *
264
+ * Convenience function that resolves compiled JS and extracts schemas.
265
+ *
266
+ * @param entryFile - TypeScript entry file path
267
+ * @param baseDir - Project base directory
268
+ * @param options - Extraction options
269
+ */
270
+ declare function extractStandardSchemasFromProject(entryFile: string, baseDir: string, options?: ExtractStandardSchemasOptions): Promise<StandardSchemaExtractionOutput>;
1
271
  import { DriftCategory, SpecDocDrift, SpecExport } from "@openpkg-ts/spec";
2
272
  interface ExampleRunResult {
3
273
  success: boolean;
@@ -225,222 +495,18 @@ declare function ensureSpecCoverage(spec: OpenPkgSpec): OpenPkgSpec & {
225
495
  coverageScore: number;
226
496
  };
227
497
  };
228
- import { OpenPkg as OpenPkg3, SpecDocDrift as SpecDocDrift2, SpecDocsMetadata, SpecExport as SpecExport3 } from "@openpkg-ts/spec";
229
- import { SpecExport as SpecExport2, SpecExportKind } from "@openpkg-ts/spec";
230
- import * as TS from "typescript";
231
- /**
232
- * Represents a single parameter in a JSDoc patch
233
- */
234
- interface JSDocParam {
235
- name: string;
236
- type?: string;
237
- description?: string;
238
- optional?: boolean;
239
- }
240
- /**
241
- * Represents a return type in a JSDoc patch
242
- */
243
- interface JSDocReturn {
244
- type?: string;
245
- description?: string;
246
- }
247
- /**
248
- * Represents a generic tag in a JSDoc patch
249
- */
250
- interface JSDocTag {
251
- name: string;
252
- text: string;
253
- }
254
- /**
255
- * A patchable representation of a JSDoc comment
256
- */
257
- interface JSDocPatch {
258
- description?: string;
259
- params?: JSDocParam[];
260
- returns?: JSDocReturn;
261
- examples?: string[];
262
- deprecated?: string | false;
263
- async?: boolean;
264
- type?: string;
265
- typeParams?: Array<{
266
- name: string;
267
- constraint?: string;
268
- description?: string;
269
- }>;
270
- otherTags?: JSDocTag[];
271
- }
272
- /**
273
- * Represents an edit to be applied to a source file
274
- */
275
- interface JSDocEdit {
276
- filePath: string;
277
- symbolName: string;
278
- startLine: number;
279
- endLine: number;
280
- hasExisting: boolean;
281
- existingJSDoc?: string;
282
- newJSDoc: string;
283
- indent: string;
284
- }
285
- /**
286
- * Result of applying edits to source files
287
- */
288
- interface ApplyEditsResult {
289
- filesModified: number;
290
- editsApplied: number;
291
- errors: Array<{
292
- file: string;
293
- error: string;
294
- }>;
295
- }
296
- /**
297
- * Parse a JSDoc comment string into a patchable structure
298
- */
299
- declare function parseJSDocToPatch(jsDocText: string): JSDocPatch;
300
- /**
301
- * Apply a partial patch to an existing JSDoc patch, preserving unmodified content
302
- */
303
- declare function applyPatchToJSDoc(existing: JSDocPatch, updates: Partial<JSDocPatch>): JSDocPatch;
304
- /**
305
- * Serialize a JSDocPatch back to a formatted comment string
306
- */
307
- declare function serializeJSDoc(patch: JSDocPatch, indent?: string): string;
308
- /**
309
- * Find the JSDoc location for a declaration in a source file
310
- */
311
- declare function findJSDocLocation(sourceFile: TS.SourceFile, symbolName: string, approximateLine?: number): {
312
- startLine: number;
313
- endLine: number;
314
- declarationLine: number;
315
- hasExisting: boolean;
316
- existingJSDoc?: string;
317
- indent: string;
318
- } | null;
319
- /**
320
- * Apply a batch of edits to source files
321
- */
322
- declare function applyEdits(edits: JSDocEdit[]): Promise<ApplyEditsResult>;
323
- /**
324
- * Create a TypeScript source file from a file path
325
- */
326
- declare function createSourceFile(filePath: string): TS.SourceFile;
327
- /**
328
- * Quality rule severity levels.
329
- */
330
- type QualitySeverity = "error" | "warn" | "off";
331
- /**
332
- * Context passed to quality rule checks.
333
- */
334
- interface RuleContext {
335
- export: SpecExport2;
336
- rawJSDoc?: string;
337
- }
338
- /**
339
- * A violation reported by a quality rule.
340
- */
341
- interface QualityViolation {
342
- ruleId: string;
343
- severity: "error" | "warn";
344
- message: string;
345
- line?: number;
346
- fixable: boolean;
347
- }
348
- /**
349
- * A quality rule checks one aspect of documentation quality.
350
- * Rules can contribute to coverage score, lint violations, or both.
351
- */
352
- interface QualityRule {
353
- /** Unique rule identifier */
354
- id: string;
355
- /** Human-readable name */
356
- name: string;
357
- /** What this rule checks */
358
- description: string;
359
- /**
360
- * Which kinds this rule applies to.
361
- * If undefined, applies to all kinds.
362
- */
363
- appliesTo?: SpecExportKind[];
364
- /**
365
- * Does this rule contribute to coverage score?
366
- * If true, the rule is counted as a "signal" for coverage calculation.
367
- */
368
- affectsCoverage: boolean;
369
- /**
370
- * Default lint severity. Set to 'off' if rule is coverage-only.
371
- */
372
- defaultSeverity: QualitySeverity;
373
- /**
374
- * Check if the satisfies this rule.
375
- * Returns true if satisfied, false if not.
376
- */
377
- check(ctx: RuleContext): boolean;
378
- /**
379
- * Get detailed violation info when check returns false.
380
- * Only called if check() returns false and severity !== 'off'.
381
- */
382
- getViolation?(ctx: RuleContext): QualityViolation;
383
- /**
384
- * Generate a fix for the violation.
385
- * Only called if check() returns false and fix is requested.
386
- */
387
- fix?(ctx: RuleContext): JSDocPatch | null;
388
- }
389
- /**
390
- * User configuration for quality rules.
391
- */
392
- interface QualityConfig {
393
- rules: Record<string, QualitySeverity>;
394
- }
395
- /**
396
- * Result of evaluating quality for a single export.
397
- */
398
- interface QualityResult {
399
- /** Coverage score (0-100) */
400
- coverageScore: number;
401
- /** Coverage details */
402
- coverage: {
403
- /** Rule IDs that passed */
404
- satisfied: string[];
405
- /** Rule IDs that failed */
406
- missing: string[];
407
- /** All applicable rule IDs */
408
- applicable: string[];
409
- };
410
- /** Lint violations (only for rules with severity !== 'off') */
411
- violations: QualityViolation[];
412
- /** Summary counts */
413
- summary: {
414
- errorCount: number;
415
- warningCount: number;
416
- fixableCount: number;
417
- };
418
- }
419
- /**
420
- * Aggregate result for multiple exports.
421
- */
422
- interface AggregateQualityResult {
423
- byExport: Map<string, QualityResult>;
424
- overall: {
425
- coverageScore: number;
426
- totalViolations: number;
427
- errorCount: number;
428
- warningCount: number;
429
- };
430
- }
498
+ import { OpenPkg as OpenPkg3, SpecDocDrift as SpecDocDrift2, SpecDocsMetadata, SpecExport as SpecExport2 } from "@openpkg-ts/spec";
431
499
  /**
432
500
  * An enriched with computed documentation metadata.
433
501
  * Extends SpecExport with the `docs` field for coverage analysis.
434
502
  */
435
- type EnrichedExport = SpecExport3 & {
503
+ type EnrichedExport = SpecExport2 & {
436
504
  docs?: EnrichedDocsMetadata;
437
505
  };
438
506
  /**
439
- * Extended docs metadata with quality violations.
507
+ * Extended docs metadata.
440
508
  */
441
- type EnrichedDocsMetadata = SpecDocsMetadata & {
442
- violations?: QualityViolation[];
443
- };
509
+ type EnrichedDocsMetadata = SpecDocsMetadata;
444
510
  /**
445
511
  * An enriched OpenPkg spec with computed documentation metadata.
446
512
  * Extends OpenPkg with per-and aggregate coverage data.
@@ -457,21 +523,11 @@ interface EnrichOptions {
457
523
  * Map from ID to drift issues.
458
524
  */
459
525
  driftByExport?: Map<string, SpecDocDrift2[]>;
460
- /**
461
- * Quality configuration with rule severities.
462
- */
463
- qualityConfig?: QualityConfig;
464
- /**
465
- * Per-raw JSDoc text for style rule checks.
466
- * Map from ID to raw JSDoc string.
467
- */
468
- rawJSDocByExport?: Map<string, string>;
469
526
  }
470
527
  /**
471
528
  * Enrich an OpenPkg spec with documentation coverage metadata.
472
529
  *
473
- * This function computes coverage scores using quality rules,
474
- * detects drift issues, and produces an EnrichedOpenPkg.
530
+ * Computes coverage scores and detects drift issues.
475
531
  *
476
532
  * @param spec - The pure OpenPkg spec to enrich
477
533
  * @param options - Optional enrichment configuration
@@ -484,10 +540,8 @@ interface EnrichOptions {
484
540
  * const doccov = new DocCov();
485
541
  * const { spec } = await doccov.analyzeFileWithDiagnostics('src/index.ts');
486
542
  *
487
- * // Enrich with coverage data
488
543
  * const enriched = enrichSpec(spec);
489
544
  * console.log(enriched.docs?.coverageScore); // e.g., 85
490
- * console.log(enriched.docs?.missing); // e.g., ['has-examples']
491
545
  * ```
492
546
  */
493
547
  declare function enrichSpec(spec: OpenPkg3, options?: EnrichOptions): EnrichedOpenPkg;
@@ -670,60 +724,264 @@ interface DocCovReport {
670
724
  exports: Record<string, ExportCoverageData>;
671
725
  }
672
726
  /**
673
- * Generate a DocCov report from an OpenPkg spec.
674
- *
675
- * @param spec - The pure OpenPkg spec to analyze
676
- * @returns A DocCov report with coverage analysis
727
+ * Generate a DocCov report from an OpenPkg spec.
728
+ *
729
+ * @param spec - The pure OpenPkg spec to analyze
730
+ * @returns A DocCov report with coverage analysis
731
+ *
732
+ * @example
733
+ * ```ts
734
+ * import { DocCov, generateReport } from '@doccov/sdk';
735
+ *
736
+ * const doccov = new DocCov();
737
+ * const { spec } = await doccov.analyzeFileWithDiagnostics('src/index.ts');
738
+ * const report = generateReport(spec);
739
+ *
740
+ * console.log(`Coverage: ${report.coverage.score}%`);
741
+ * ```
742
+ */
743
+ declare function generateReport(spec: OpenPkg4): DocCovReport;
744
+ /**
745
+ * Generate a DocCov report from an already-enriched spec.
746
+ *
747
+ * Use this when you've already called enrichSpec() and want to avoid
748
+ * recomputing coverage data.
749
+ *
750
+ * @param enriched - The enriched OpenPkg spec
751
+ * @returns A DocCov report with coverage analysis
752
+ */
753
+ declare function generateReportFromEnriched(enriched: EnrichedOpenPkg): DocCovReport;
754
+ /**
755
+ * Load a cached DocCov report from disk.
756
+ *
757
+ * @param reportPath - Path to the report file (defaults to .doccov/report.json)
758
+ * @returns The cached report, or null if not found
759
+ */
760
+ declare function loadCachedReport(reportPath?: string): DocCovReport | null;
761
+ /**
762
+ * Save a DocCov report to disk.
763
+ *
764
+ * @param report - The report to save
765
+ * @param reportPath - Path to save the report (defaults to .doccov/report.json)
766
+ */
767
+ declare function saveReport(report: DocCovReport, reportPath?: string): void;
768
+ /**
769
+ * Check if a cached report is still valid.
770
+ *
771
+ * A report is considered stale if:
772
+ * - It doesn't exist
773
+ * - The spec version has changed
774
+ * - Source files have been modified since generation
775
+ *
776
+ * @param reportPath - Path to the report file
777
+ * @param sourceFiles - Source files to check modification times against
778
+ * @returns True if the cached report is still valid
779
+ */
780
+ declare function isCachedReportValid(reportPath?: string, sourceFiles?: string[]): boolean;
781
+ /**
782
+ * Generate a git-trackable API surface markdown file from an OpenPkg spec.
783
+ *
784
+ * This produces a deterministic, sorted output suitable for version control.
785
+ * Changes to the API will show up as diffs in this file.
786
+ *
787
+ * @param spec - The OpenPkg spec to render
788
+ * @returns Markdown string representing the API surface
789
+ *
790
+ * @example
791
+ * ```ts
792
+ * import { DocCov, renderApiSurface } from '@doccov/sdk';
793
+ *
794
+ * const doccov = new DocCov();
795
+ * const { spec } = await doccov.analyzeFileWithDiagnostics('src/index.ts');
796
+ * const apiSurface = renderApiSurface(spec);
797
+ *
798
+ * fs.writeFileSync('api-surface.md', apiSurface);
799
+ * ```
800
+ */
801
+ declare function renderApiSurface(spec: OpenPkg4): string;
802
+ import { OpenPkg as OpenPkg5 } from "@openpkg-ts/spec";
803
+ /** Directory for storing history snapshots */
804
+ declare const HISTORY_DIR = ".doccov/history";
805
+ /**
806
+ * A historical coverage snapshot.
807
+ */
808
+ interface CoverageSnapshot {
809
+ /** ISO 8601 timestamp */
810
+ timestamp: string;
811
+ /** Package name */
812
+ package: string;
813
+ /** Package version (if available) */
814
+ version?: string;
815
+ /** Coverage score (0-100) */
816
+ coverageScore: number;
817
+ /** Total number of exports */
818
+ totalExports: number;
819
+ /** Number of documented exports */
820
+ documentedExports: number;
821
+ /** Number of drift issues */
822
+ driftCount: number;
823
+ /** Git commit hash (if available) */
824
+ commit?: string;
825
+ /** Git branch (if available) */
826
+ branch?: string;
827
+ }
828
+ /**
829
+ * Coverage trend data.
830
+ */
831
+ interface CoverageTrend {
832
+ /** Current snapshot */
833
+ current: CoverageSnapshot;
834
+ /** Previous snapshots (most recent first) */
835
+ history: CoverageSnapshot[];
836
+ /** Score delta from previous */
837
+ delta?: number;
838
+ /** Sparkline data (last N scores) */
839
+ sparkline: number[];
840
+ }
841
+ /**
842
+ * Tier-based retention settings.
843
+ */
844
+ type RetentionTier = "free" | "team" | "pro";
845
+ /**
846
+ * Retention days per tier.
847
+ */
848
+ declare const RETENTION_DAYS: Record<RetentionTier, number>;
849
+ /**
850
+ * Weekly summary of coverage data.
851
+ */
852
+ interface WeeklySummary {
853
+ /** Week start date (ISO string) */
854
+ weekStart: string;
855
+ /** Week end date (ISO string) */
856
+ weekEnd: string;
857
+ /** Average coverage for the week */
858
+ avgCoverage: number;
859
+ /** Coverage at start of week */
860
+ startCoverage: number;
861
+ /** Coverage at end of week */
862
+ endCoverage: number;
863
+ /** Change during the week */
864
+ delta: number;
865
+ /** Number of snapshots in the week */
866
+ snapshotCount: number;
867
+ }
868
+ /**
869
+ * Extended trend analysis result.
870
+ */
871
+ interface ExtendedTrendAnalysis {
872
+ /** Current trend data */
873
+ trend: CoverageTrend;
874
+ /** Weekly summaries (most recent first) */
875
+ weeklySummaries: WeeklySummary[];
876
+ /** 7-day velocity (average daily change) */
877
+ velocity7d: number;
878
+ /** 30-day velocity */
879
+ velocity30d: number;
880
+ /** 90-day velocity (Pro only) */
881
+ velocity90d?: number;
882
+ /** Projected coverage in 30 days (based on velocity) */
883
+ projected30d: number;
884
+ /** Best coverage ever recorded */
885
+ allTimeHigh: number;
886
+ /** Worst coverage ever recorded */
887
+ allTimeLow: number;
888
+ /** Date range of available data */
889
+ dataRange: {
890
+ start: string;
891
+ end: string;
892
+ } | null;
893
+ }
894
+ /**
895
+ * Compute a coverage snapshot from an OpenPkg spec.
896
+ */
897
+ declare function computeSnapshot(spec: OpenPkg5, options?: {
898
+ commit?: string;
899
+ branch?: string;
900
+ }): CoverageSnapshot;
901
+ /**
902
+ * Save a coverage snapshot to history.
903
+ *
904
+ * @param snapshot - The snapshot to save
905
+ * @param cwd - Working directory
906
+ */
907
+ declare function saveSnapshot(snapshot: CoverageSnapshot, cwd: string): void;
908
+ /**
909
+ * Load all historical snapshots.
677
910
  *
678
- * @example
679
- * ```ts
680
- * import { DocCov, generateReport } from '@doccov/sdk';
911
+ * @param cwd - Working directory
912
+ * @returns Array of snapshots sorted by timestamp (most recent first)
913
+ */
914
+ declare function loadSnapshots(cwd: string): CoverageSnapshot[];
915
+ /**
916
+ * Get coverage trend data.
681
917
  *
682
- * const doccov = new DocCov();
683
- * const { spec } = await doccov.analyzeFileWithDiagnostics('src/index.ts');
684
- * const report = generateReport(spec);
918
+ * @param spec - Current OpenPkg spec
919
+ * @param cwd - Working directory
920
+ * @param options - Optional git metadata
921
+ * @returns Trend data with history and delta
922
+ */
923
+ declare function getTrend(spec: OpenPkg5, cwd: string, options?: {
924
+ commit?: string;
925
+ branch?: string;
926
+ }): CoverageTrend;
927
+ /**
928
+ * Generate a sparkline character representation.
685
929
  *
686
- * console.log(`Coverage: ${report.coverage.score}%`);
687
- * ```
930
+ * @param values - Array of values (0-100 for coverage)
931
+ * @returns Sparkline string using unicode characters
688
932
  */
689
- declare function generateReport(spec: OpenPkg4): DocCovReport;
933
+ declare function renderSparkline(values: number[]): string;
690
934
  /**
691
- * Generate a DocCov report from an already-enriched spec.
935
+ * Format a delta value with arrow and color indicator.
692
936
  *
693
- * Use this when you've already called enrichSpec() and want to avoid
694
- * recomputing coverage data.
937
+ * @param delta - Coverage delta (positive = improvement)
938
+ * @returns Formatted delta string
939
+ */
940
+ declare function formatDelta(delta: number): string;
941
+ /**
942
+ * Prune old snapshots to keep history manageable.
695
943
  *
696
- * @param enriched - The enriched OpenPkg spec
697
- * @returns A DocCov report with coverage analysis
944
+ * @param cwd - Working directory
945
+ * @param keepCount - Number of snapshots to keep (default: 100)
946
+ * @returns Number of snapshots deleted
698
947
  */
699
- declare function generateReportFromEnriched(enriched: EnrichedOpenPkg): DocCovReport;
948
+ declare function pruneHistory(cwd: string, keepCount?: number): number;
700
949
  /**
701
- * Load a cached DocCov report from disk.
950
+ * Prune snapshots based on tier retention policy.
702
951
  *
703
- * @param reportPath - Path to the report file (defaults to .doccov/report.json)
704
- * @returns The cached report, or null if not found
952
+ * @param cwd - Working directory
953
+ * @param tier - Retention tier (free: 7d, team: 30d, pro: 90d)
954
+ * @returns Number of snapshots deleted
705
955
  */
706
- declare function loadCachedReport(reportPath?: string): DocCovReport | null;
956
+ declare function pruneByTier(cwd: string, tier: RetentionTier): number;
707
957
  /**
708
- * Save a DocCov report to disk.
958
+ * Load snapshots within a date range.
709
959
  *
710
- * @param report - The report to save
711
- * @param reportPath - Path to save the report (defaults to .doccov/report.json)
960
+ * @param cwd - Working directory
961
+ * @param days - Number of days to include
962
+ * @returns Filtered snapshots
712
963
  */
713
- declare function saveReport(report: DocCovReport, reportPath?: string): void;
964
+ declare function loadSnapshotsForDays(cwd: string, days: number): CoverageSnapshot[];
714
965
  /**
715
- * Check if a cached report is still valid.
966
+ * Generate weekly summaries from snapshots.
716
967
  *
717
- * A report is considered stale if:
718
- * - It doesn't exist
719
- * - The spec version has changed
720
- * - Source files have been modified since generation
968
+ * @param snapshots - Snapshots to summarize (most recent first)
969
+ * @returns Weekly summaries (most recent first)
970
+ */
971
+ declare function generateWeeklySummaries(snapshots: CoverageSnapshot[]): WeeklySummary[];
972
+ /**
973
+ * Get extended trend analysis with velocity and projections.
721
974
  *
722
- * @param reportPath - Path to the report file
723
- * @param sourceFiles - Source files to check modification times against
724
- * @returns True if the cached report is still valid
975
+ * @param spec - Current OpenPkg spec
976
+ * @param cwd - Working directory
977
+ * @param options - Analysis options
978
+ * @returns Extended trend analysis
725
979
  */
726
- declare function isCachedReportValid(reportPath?: string, sourceFiles?: string[]): boolean;
980
+ declare function getExtendedTrend(spec: OpenPkg5, cwd: string, options?: {
981
+ commit?: string;
982
+ branch?: string;
983
+ tier?: RetentionTier;
984
+ }): ExtendedTrendAnalysis;
727
985
  /**
728
986
  * Compute a hash of file contents.
729
987
  * Uses truncated SHA-256 for balance of speed and collision resistance.
@@ -755,7 +1013,7 @@ declare function hashFiles(filePaths: string[], cwd: string): Record<string, str
755
1013
  * @returns Array of file paths that changed, were added, or were removed
756
1014
  */
757
1015
  declare function diffHashes(cached: Record<string, string>, current: Record<string, string>): string[];
758
- import { OpenPkg as OpenPkg5 } from "@openpkg-ts/spec";
1016
+ import { OpenPkg as OpenPkg6 } from "@openpkg-ts/spec";
759
1017
  /** Current cache format version */
760
1018
  declare const CACHE_VERSION = "1.0.0";
761
1019
  /** Default cache file path */
@@ -790,7 +1048,7 @@ interface SpecCache {
790
1048
  /** Analysis configuration that affects output */
791
1049
  config: SpecCacheConfig;
792
1050
  /** The cached OpenPkg spec */
793
- spec: OpenPkg5;
1051
+ spec: OpenPkg6;
794
1052
  }
795
1053
  /**
796
1054
  * Result of cache validation.
@@ -833,7 +1091,7 @@ declare function loadSpecCache(cwd: string): SpecCache | null;
833
1091
  * @param spec - OpenPkg spec to cache
834
1092
  * @param context - Cache context with file paths and config
835
1093
  */
836
- declare function saveSpecCache(spec: OpenPkg5, context: CacheContext): void;
1094
+ declare function saveSpecCache(spec: OpenPkg6, context: CacheContext): void;
837
1095
  /**
838
1096
  * Validate if cached spec is still valid.
839
1097
  *
@@ -865,97 +1123,6 @@ declare function clearSpecCache(cwd: string): boolean;
865
1123
  */
866
1124
  declare function getSpecCachePath(cwd: string): string;
867
1125
  /**
868
- * Configuration types for DocCov.
869
- * These types are shared between CLI and API.
870
- */
871
- /**
872
- * Documentation configuration options.
873
- */
874
- interface DocsConfig {
875
- /** Glob patterns for markdown docs to include */
876
- include?: string[];
877
- /** Glob patterns for markdown docs to exclude */
878
- exclude?: string[];
879
- }
880
- /**
881
- * Example validation modes.
882
- */
883
- type ExampleValidationMode = "presence" | "typecheck" | "run";
884
- /**
885
- * Check command configuration options.
886
- */
887
- interface CheckConfig {
888
- /**
889
- * Example validation modes to run.
890
- * Can be a single mode, array of modes, or comma-separated string.
891
- * - 'presence': Check that @example blocks exist on exports
892
- * - 'typecheck': Compile examples with TypeScript
893
- * - 'run': Execute examples and validate assertions
894
- */
895
- examples?: ExampleValidationMode | ExampleValidationMode[] | string;
896
- /** Minimum coverage percentage required (0-100) */
897
- minCoverage?: number;
898
- /** Maximum drift percentage allowed (0-100) */
899
- maxDrift?: number;
900
- }
901
- /**
902
- * Quality rule severity level.
903
- */
904
- type QualitySeverity2 = "error" | "warn" | "off";
905
- /**
906
- * Quality rules configuration.
907
- */
908
- interface QualityRulesConfig {
909
- /** Rule severity overrides */
910
- rules?: Record<string, QualitySeverity2>;
911
- }
912
- /**
913
- * Normalized DocCov configuration.
914
- * This is the parsed/normalized form used by commands.
915
- */
916
- interface DocCovConfig {
917
- /** Export include patterns */
918
- include?: string[];
919
- /** Export exclude patterns */
920
- exclude?: string[];
921
- /** Plugins (future) */
922
- plugins?: unknown[];
923
- /** Documentation configuration */
924
- docs?: DocsConfig;
925
- /** Check command configuration */
926
- check?: CheckConfig;
927
- /** Quality rules configuration */
928
- quality?: QualityRulesConfig;
929
- }
930
- /**
931
- * Define a DocCov configuration.
932
- * Helper function for type-safe configuration in doccov.config.ts.
933
- *
934
- * @param config - Configuration object
935
- * @returns The configuration object (for type inference)
936
- *
937
- * @example
938
- * ```typescript
939
- * // doccov.config.ts
940
- * import { defineConfig } from '@doccov/sdk';
941
- *
942
- * defineConfig({
943
- * include: ['MyClass', 'myFunction'],
944
- * exclude: ['internal*'],
945
- * docs: {
946
- * include: ['docs/**\/*.md'],
947
- * },
948
- * quality: {
949
- * rules: {
950
- * 'has-description': 'error',
951
- * 'has-examples': 'warn',
952
- * },
953
- * },
954
- * });
955
- * ```
956
- */
957
- declare function defineConfig(config: DocCovConfig): DocCovConfig;
958
- /**
959
1126
  * Project detection types for I/O-agnostic project analysis.
960
1127
  * Used by both CLI (NodeFileSystem) and API (SandboxFileSystem).
961
1128
  */
@@ -1244,7 +1411,7 @@ declare function parseExamplesFlag(value: boolean | string | undefined): Example
1244
1411
  * Check if a specific validation is enabled.
1245
1412
  */
1246
1413
  declare function shouldValidate(validations: ExampleValidation[], check: ExampleValidation): boolean;
1247
- import { SpecExport as SpecExport4 } from "@openpkg-ts/spec";
1414
+ import { SpecExport as SpecExport3 } from "@openpkg-ts/spec";
1248
1415
  interface ExampleTypeError {
1249
1416
  /** Index of the example in the examples array */
1250
1417
  exampleIndex: number;
@@ -1367,77 +1534,173 @@ interface ExampleValidationResult {
1367
1534
  * - `typecheck`: type-checks examples (doesn't require presence or run)
1368
1535
  * - `run`: executes examples (doesn't require presence or typecheck)
1369
1536
  */
1370
- declare function validateExamples(exports: SpecExport4[], options: ExampleValidationOptions): Promise<ExampleValidationResult>;
1371
- interface DocCovOptions {
1372
- includePrivate?: boolean;
1373
- followImports?: boolean;
1374
- maxDepth?: number;
1375
- resolveExternalTypes?: boolean;
1376
- /** Enable spec caching (default: true) */
1377
- useCache?: boolean;
1378
- /** Working directory for cache operations (default: process.cwd()) */
1379
- cwd?: string;
1380
- }
1537
+ declare function validateExamples(exports: SpecExport3[], options: ExampleValidationOptions): Promise<ExampleValidationResult>;
1381
1538
  declare function extractPackageSpec(entryFile: string, packageDir?: string, content?: string, options?: DocCovOptions): Promise<OpenPkgSpec>;
1539
+ /**
1540
+ * Release stage/visibility tags that can be used for filtering.
1541
+ * Based on TSDoc release tags.
1542
+ */
1543
+ type ReleaseTag = "public" | "beta" | "alpha" | "internal";
1382
1544
  interface FilterOptions {
1545
+ /** Include exports matching these patterns */
1546
+ include?: string[];
1547
+ /** Exclude exports matching these patterns */
1548
+ exclude?: string[];
1549
+ /** Filter by visibility/release stage (e.g., ['public', 'beta']) */
1550
+ visibility?: ReleaseTag[];
1551
+ }
1552
+ /**
1553
+ * Source of filter options.
1554
+ */
1555
+ type FilterSource = "config" | "override" | "combined";
1556
+ /**
1557
+ * Resolved filter options after merging config and overrides.
1558
+ */
1559
+ interface ResolvedFilters {
1560
+ /** Include patterns */
1383
1561
  include?: string[];
1562
+ /** Exclude patterns */
1384
1563
  exclude?: string[];
1564
+ /** Source of the filters */
1565
+ source?: FilterSource;
1566
+ /** Whether filters were applied from config */
1567
+ fromConfig: boolean;
1568
+ /** Whether filters were applied from overrides */
1569
+ fromOverride: boolean;
1570
+ }
1571
+ /**
1572
+ * Parse a comma-separated list flag into an array.
1573
+ *
1574
+ * @param value - String or string array from CLI flag
1575
+ * @returns Parsed array, or undefined if empty
1576
+ *
1577
+ * @example
1578
+ * ```typescript
1579
+ * parseListFlag('a,b,c'); // ['a', 'b', 'c']
1580
+ * parseListFlag(['a,b', 'c']); // ['a', 'b', 'c']
1581
+ * parseListFlag(undefined); // undefined
1582
+ * ```
1583
+ */
1584
+ declare function parseListFlag(value?: string | string[]): string[] | undefined;
1585
+ /**
1586
+ * Merge filter options from config and CLI/API overrides.
1587
+ *
1588
+ * Merge behavior:
1589
+ * - Include: CLI values intersect with config values (narrowing)
1590
+ * - Exclude: CLI values are added to config values (expanding)
1591
+ *
1592
+ * @param config - Configuration (from doccov.config.ts)
1593
+ * @param overrides - Override filters (from CLI flags or API params)
1594
+ * @returns Merged filter options
1595
+ *
1596
+ * @example
1597
+ * ```typescript
1598
+ * const config = { include: ['A', 'B', 'C'] };
1599
+ * const overrides = { include: ['B', 'C', 'D'] };
1600
+ *
1601
+ * const resolved = mergeFilters(config, overrides);
1602
+ * // resolved.include = ['B', 'C'] (intersection)
1603
+ * ```
1604
+ */
1605
+ declare function mergeFilters(config: DocCovConfig | null, overrides: FilterOptions): ResolvedFilters;
1606
+ import { SpecDocDrift as SpecDocDrift4, SpecExport as SpecExport4 } from "@openpkg-ts/spec";
1607
+ import * as TS3 from "typescript";
1608
+ /**
1609
+ * Represents a single parameter in a JSDoc patch
1610
+ */
1611
+ interface JSDocParam {
1612
+ name: string;
1613
+ type?: string;
1614
+ description?: string;
1615
+ optional?: boolean;
1616
+ }
1617
+ /**
1618
+ * Represents a return type in a JSDoc patch
1619
+ */
1620
+ interface JSDocReturn {
1621
+ type?: string;
1622
+ description?: string;
1623
+ }
1624
+ /**
1625
+ * Represents a generic tag in a JSDoc patch
1626
+ */
1627
+ interface JSDocTag {
1628
+ name: string;
1629
+ text: string;
1630
+ }
1631
+ /**
1632
+ * A patchable representation of a JSDoc comment
1633
+ */
1634
+ interface JSDocPatch {
1635
+ description?: string;
1636
+ params?: JSDocParam[];
1637
+ returns?: JSDocReturn;
1638
+ examples?: string[];
1639
+ deprecated?: string | false;
1640
+ async?: boolean;
1641
+ type?: string;
1642
+ typeParams?: Array<{
1643
+ name: string;
1644
+ constraint?: string;
1645
+ description?: string;
1646
+ }>;
1647
+ otherTags?: JSDocTag[];
1648
+ }
1649
+ /**
1650
+ * Represents an edit to be applied to a source file
1651
+ */
1652
+ interface JSDocEdit {
1653
+ filePath: string;
1654
+ symbolName: string;
1655
+ startLine: number;
1656
+ endLine: number;
1657
+ hasExisting: boolean;
1658
+ existingJSDoc?: string;
1659
+ newJSDoc: string;
1660
+ indent: string;
1661
+ }
1662
+ /**
1663
+ * Result of applying edits to source files
1664
+ */
1665
+ interface ApplyEditsResult {
1666
+ filesModified: number;
1667
+ editsApplied: number;
1668
+ errors: Array<{
1669
+ file: string;
1670
+ error: string;
1671
+ }>;
1385
1672
  }
1386
1673
  /**
1387
- * Source of filter options.
1674
+ * Parse a JSDoc comment string into a patchable structure
1388
1675
  */
1389
- type FilterSource = "config" | "override" | "combined";
1676
+ declare function parseJSDocToPatch(jsDocText: string): JSDocPatch;
1390
1677
  /**
1391
- * Resolved filter options after merging config and overrides.
1678
+ * Apply a partial patch to an existing JSDoc patch, preserving unmodified content
1392
1679
  */
1393
- interface ResolvedFilters {
1394
- /** Include patterns */
1395
- include?: string[];
1396
- /** Exclude patterns */
1397
- exclude?: string[];
1398
- /** Source of the filters */
1399
- source?: FilterSource;
1400
- /** Whether filters were applied from config */
1401
- fromConfig: boolean;
1402
- /** Whether filters were applied from overrides */
1403
- fromOverride: boolean;
1404
- }
1680
+ declare function applyPatchToJSDoc(existing: JSDocPatch, updates: Partial<JSDocPatch>): JSDocPatch;
1405
1681
  /**
1406
- * Parse a comma-separated list flag into an array.
1407
- *
1408
- * @param value - String or string array from CLI flag
1409
- * @returns Parsed array, or undefined if empty
1410
- *
1411
- * @example
1412
- * ```typescript
1413
- * parseListFlag('a,b,c'); // ['a', 'b', 'c']
1414
- * parseListFlag(['a,b', 'c']); // ['a', 'b', 'c']
1415
- * parseListFlag(undefined); // undefined
1416
- * ```
1682
+ * Serialize a JSDocPatch back to a formatted comment string
1417
1683
  */
1418
- declare function parseListFlag(value?: string | string[]): string[] | undefined;
1684
+ declare function serializeJSDoc(patch: JSDocPatch, indent?: string): string;
1419
1685
  /**
1420
- * Merge filter options from config and CLI/API overrides.
1421
- *
1422
- * Merge behavior:
1423
- * - Include: CLI values intersect with config values (narrowing)
1424
- * - Exclude: CLI values are added to config values (expanding)
1425
- *
1426
- * @param config - Configuration (from doccov.config.ts)
1427
- * @param overrides - Override filters (from CLI flags or API params)
1428
- * @returns Merged filter options
1429
- *
1430
- * @example
1431
- * ```typescript
1432
- * const config = { include: ['A', 'B', 'C'] };
1433
- * const overrides = { include: ['B', 'C', 'D'] };
1434
- *
1435
- * const resolved = mergeFilters(config, overrides);
1436
- * // resolved.include = ['B', 'C'] (intersection)
1437
- * ```
1686
+ * Find the JSDoc location for a declaration in a source file
1438
1687
  */
1439
- declare function mergeFilters(config: DocCovConfig | null, overrides: FilterOptions): ResolvedFilters;
1440
- import { SpecDocDrift as SpecDocDrift4, SpecExport as SpecExport5 } from "@openpkg-ts/spec";
1688
+ declare function findJSDocLocation(sourceFile: TS3.SourceFile, symbolName: string, approximateLine?: number): {
1689
+ startLine: number;
1690
+ endLine: number;
1691
+ declarationLine: number;
1692
+ hasExisting: boolean;
1693
+ existingJSDoc?: string;
1694
+ indent: string;
1695
+ } | null;
1696
+ /**
1697
+ * Apply a batch of edits to source files
1698
+ */
1699
+ declare function applyEdits(edits: JSDocEdit[]): Promise<ApplyEditsResult>;
1700
+ /**
1701
+ * Create a TypeScript source file from a file path
1702
+ */
1703
+ declare function createSourceFile(filePath: string): TS3.SourceFile;
1441
1704
  /**
1442
1705
  * Types of fixes that can be generated
1443
1706
  */
@@ -1459,11 +1722,11 @@ declare function isFixableDrift(drift: SpecDocDrift4): boolean;
1459
1722
  /**
1460
1723
  * Generate a fix for a single drift issue
1461
1724
  */
1462
- declare function generateFix(drift: SpecDocDrift4, exportEntry: SpecExport5, existingPatch?: JSDocPatch): FixSuggestion | null;
1725
+ declare function generateFix(drift: SpecDocDrift4, exportEntry: SpecExport4, existingPatch?: JSDocPatch): FixSuggestion | null;
1463
1726
  /**
1464
1727
  * Generate all fixes for an export's drift issues
1465
1728
  */
1466
- declare function generateFixesForExport(exportEntry: SpecExport5, existingPatch?: JSDocPatch): FixSuggestion[];
1729
+ declare function generateFixesForExport(exportEntry: SpecExport4, existingPatch?: JSDocPatch): FixSuggestion[];
1467
1730
  /**
1468
1731
  * Merge multiple fix patches into a single patch
1469
1732
  */
@@ -1475,7 +1738,7 @@ declare function categorizeDrifts(drifts: SpecDocDrift4[]): {
1475
1738
  fixable: SpecDocDrift4[];
1476
1739
  nonFixable: SpecDocDrift4[];
1477
1740
  };
1478
- import { OpenPkg as OpenPkg6 } from "@openpkg-ts/spec";
1741
+ import { OpenPkg as OpenPkg7 } from "@openpkg-ts/spec";
1479
1742
  /**
1480
1743
  * Parsed components of a GitHub URL.
1481
1744
  */
@@ -1568,7 +1831,16 @@ declare function buildRawUrl(parsed: ParsedGitHubUrl, filePath: string): string;
1568
1831
  * }
1569
1832
  * ```
1570
1833
  */
1571
- declare function fetchSpecFromGitHub(parsed: ParsedGitHubUrl): Promise<OpenPkg6 | null>;
1834
+ declare function fetchSpecFromGitHub(parsed: ParsedGitHubUrl): Promise<OpenPkg7 | null>;
1835
+ /**
1836
+ * Options for fetching a spec from GitHub.
1837
+ */
1838
+ interface FetchSpecOptions {
1839
+ /** Git ref (branch or tag). Default: 'main' */
1840
+ ref?: string;
1841
+ /** Path to openpkg.json (for monorepos). Default: 'openpkg.json' */
1842
+ path?: string;
1843
+ }
1572
1844
  /**
1573
1845
  * Fetch an OpenPkg spec from a GitHub repository by owner/repo/branch.
1574
1846
  *
@@ -1576,10 +1848,10 @@ declare function fetchSpecFromGitHub(parsed: ParsedGitHubUrl): Promise<OpenPkg6
1576
1848
  *
1577
1849
  * @param owner - Repository owner
1578
1850
  * @param repo - Repository name
1579
- * @param branch - Branch name (default: 'main')
1851
+ * @param branchOrOptions - Branch name (default: 'main') or options object
1580
1852
  * @returns The OpenPkg spec, or null if not found
1581
1853
  */
1582
- declare function fetchSpec(owner: string, repo: string, branch?: string): Promise<OpenPkg6 | null>;
1854
+ declare function fetchSpec(owner: string, repo: string, branchOrOptions?: string | FetchSpecOptions): Promise<OpenPkg7 | null>;
1583
1855
  /**
1584
1856
  * Progress event for installation status updates.
1585
1857
  */
@@ -1838,7 +2110,7 @@ declare function getDocumentedExports(markdownFiles: MarkdownDocFile[], exportNa
1838
2110
  * Get all exports that lack documentation
1839
2111
  */
1840
2112
  declare function getUndocumentedExports(markdownFiles: MarkdownDocFile[], exportNames: string[]): string[];
1841
- import { CategorizedBreaking, OpenPkg as OpenPkg8, SpecDiff as SpecDiff2 } from "@openpkg-ts/spec";
2113
+ import { CategorizedBreaking, OpenPkg as OpenPkg9, SpecDiff as SpecDiff2 } from "@openpkg-ts/spec";
1842
2114
  /**
1843
2115
  * Extended spec diff result with docs impact
1844
2116
  */
@@ -1884,7 +2156,7 @@ interface DiffWithDocsOptions {
1884
2156
  * }
1885
2157
  * ```
1886
2158
  */
1887
- declare function diffSpecWithDocs(oldSpec: OpenPkg8, newSpec: OpenPkg8, options?: DiffWithDocsOptions): SpecDiffWithDocs;
2159
+ declare function diffSpecWithDocs(oldSpec: OpenPkg9, newSpec: OpenPkg9, options?: DiffWithDocsOptions): SpecDiffWithDocs;
1888
2160
  /**
1889
2161
  * Check if a diff has any docs impact
1890
2162
  */
@@ -2009,6 +2281,11 @@ declare class DocCov {
2009
2281
  */
2010
2282
  private tryLoadFromCache;
2011
2283
  /**
2284
+ * Get current source files from a fresh TypeScript program.
2285
+ * Used for cache validation to detect new files.
2286
+ */
2287
+ private getCurrentSourceFiles;
2288
+ /**
2012
2289
  * Save analysis result to cache.
2013
2290
  */
2014
2291
  private saveToCache;
@@ -2020,6 +2297,11 @@ declare class DocCov {
2020
2297
  * Find package.json starting from a directory.
2021
2298
  */
2022
2299
  private findPackageJson;
2300
+ /**
2301
+ * Opportunistically detect Standard Schema exports from compiled modules.
2302
+ * Returns undefined if detection fails or no schemas found (fallback to AST).
2303
+ */
2304
+ private detectSchemas;
2023
2305
  private normalizeDiagnostic;
2024
2306
  private mapSeverity;
2025
2307
  private normalizeMetadata;
@@ -2027,63 +2309,6 @@ declare class DocCov {
2027
2309
  }
2028
2310
  declare function analyze(code: string, options?: AnalyzeOptions): Promise<OpenPkgSpec>;
2029
2311
  declare function analyzeFile(filePath: string, options?: AnalyzeOptions): Promise<OpenPkgSpec>;
2030
- import { SpecExport as SpecExport6 } from "@openpkg-ts/spec";
2031
- import { SpecExportKind as SpecExportKind2 } from "@openpkg-ts/spec";
2032
- /**
2033
- * Core quality rules - these affect coverage score.
2034
- */
2035
- declare const CORE_RULES: QualityRule[];
2036
- /**
2037
- * Style rules - these don't affect coverage, only lint.
2038
- */
2039
- declare const STYLE_RULES: QualityRule[];
2040
- /**
2041
- * All built-in quality rules.
2042
- */
2043
- declare const BUILTIN_RULES: QualityRule[];
2044
- /**
2045
- * Get rules that affect coverage calculation.
2046
- */
2047
- declare function getCoverageRules(): QualityRule[];
2048
- /**
2049
- * Get rules applicable to a specific kind.
2050
- */
2051
- declare function getRulesForKind(kind: SpecExportKind2): QualityRule[];
2052
- /**
2053
- * Get a rule by ID.
2054
- */
2055
- declare function getRule(id: string): QualityRule | undefined;
2056
- /**
2057
- * Get default configuration with all rule defaults.
2058
- */
2059
- declare function getDefaultConfig(): Record<string, QualitySeverity>;
2060
- /**
2061
- * Evaluate quality for a single export.
2062
- *
2063
- * @param exp - The to evaluate
2064
- * @param rawJSDoc - Optional raw JSDoc text for regex-based checks
2065
- * @param config - Quality configuration with rule severities
2066
- * @returns Quality result with coverage score and violations
2067
- */
2068
- declare function evaluateExportQuality(exp: SpecExport6, rawJSDoc?: string, config?: QualityConfig): QualityResult;
2069
- /**
2070
- * Evaluate quality for multiple exports.
2071
- *
2072
- * @param exports - Array of exports with optional raw JSDoc
2073
- * @param config - Quality configuration with rule severities
2074
- * @returns Aggregate result with per-and overall scores
2075
- */
2076
- declare function evaluateQuality(exports: Array<{
2077
- export: SpecExport6;
2078
- rawJSDoc?: string;
2079
- }>, config?: QualityConfig): AggregateQualityResult;
2080
- /**
2081
- * Merge user configuration with defaults.
2082
- *
2083
- * @param userConfig - Partial user configuration
2084
- * @returns Complete configuration with defaults filled in
2085
- */
2086
- declare function mergeConfig(userConfig: Partial<QualityConfig>): QualityConfig;
2087
2312
  /**
2088
2313
  * Options for resolving a target package/entry point.
2089
2314
  */
@@ -2138,6 +2363,90 @@ interface ResolvedTarget {
2138
2363
  */
2139
2364
  declare function resolveTarget(fs: FileSystem, options: ResolveTargetOptions): Promise<ResolvedTarget>;
2140
2365
  /**
2366
+ * Repository metadata from GitHub API.
2367
+ */
2368
+ interface GitHubRepoMetadata {
2369
+ owner: string;
2370
+ repo: string;
2371
+ defaultBranch: string;
2372
+ description: string | null;
2373
+ language: string | null;
2374
+ topics: string[];
2375
+ isPrivate: boolean;
2376
+ }
2377
+ /**
2378
+ * Detected package manager from lockfile.
2379
+ */
2380
+ type DetectedPackageManager = "npm" | "yarn" | "pnpm" | "bun" | "unknown";
2381
+ /**
2382
+ * Workspace/monorepo configuration.
2383
+ */
2384
+ interface WorkspaceConfig {
2385
+ isMonorepo: boolean;
2386
+ tool?: "npm" | "yarn" | "pnpm" | "lerna" | "turborepo" | "nx";
2387
+ packages?: string[];
2388
+ }
2389
+ /**
2390
+ * Build hints detected from project files.
2391
+ */
2392
+ interface BuildHints {
2393
+ hasTypeScript: boolean;
2394
+ hasWasm: boolean;
2395
+ hasNativeModules: boolean;
2396
+ hasBuildScript: boolean;
2397
+ buildScript?: string;
2398
+ frameworks: string[];
2399
+ }
2400
+ /**
2401
+ * Complete project context for build plan generation.
2402
+ */
2403
+ interface GitHubProjectContext {
2404
+ /** Repository metadata */
2405
+ metadata: GitHubRepoMetadata;
2406
+ /** Git ref being analyzed */
2407
+ ref: string;
2408
+ /** Detected package manager */
2409
+ packageManager: DetectedPackageManager;
2410
+ /** Workspace/monorepo configuration */
2411
+ workspace: WorkspaceConfig;
2412
+ /** Build hints from project files */
2413
+ buildHints: BuildHints;
2414
+ /** Raw file contents for AI analysis */
2415
+ files: {
2416
+ packageJson?: string;
2417
+ tsconfigJson?: string;
2418
+ lockfile?: {
2419
+ name: string;
2420
+ content: string;
2421
+ };
2422
+ };
2423
+ }
2424
+ /**
2425
+ * Parse GitHub URL into owner and repo.
2426
+ * Uses the richer parseGitHubUrl from github/index.ts, returning null on error.
2427
+ */
2428
+ declare function parseGitHubUrl2(url: string): {
2429
+ owner: string;
2430
+ repo: string;
2431
+ } | null;
2432
+ /**
2433
+ * Options for fetching GitHub project context.
2434
+ */
2435
+ interface FetchGitHubContextOptions {
2436
+ /** Git ref (branch, tag, or SHA). Defaults to default branch. */
2437
+ ref?: string;
2438
+ /** Auth token for private repos (GitHub App installation token or PAT). */
2439
+ authToken?: string;
2440
+ }
2441
+ /**
2442
+ * Fetch complete project context from GitHub.
2443
+ */
2444
+ declare function fetchGitHubContext(repoUrl: string, refOrOptions?: string | FetchGitHubContextOptions): Promise<GitHubProjectContext>;
2445
+ /**
2446
+ * List packages in a monorepo workspace.
2447
+ */
2448
+ declare function listWorkspacePackages(owner: string, repo: string, ref: string, patterns: string[], authToken?: string): Promise<string[]>;
2449
+ /**
2141
2450
  * A documentation drift issue in a spec summary.
2142
2451
  */
2143
2452
  interface SummaryDriftIssue {
@@ -2295,81 +2604,6 @@ interface BuildPlanExecutionResult {
2295
2604
  error?: string;
2296
2605
  }
2297
2606
  /**
2298
- * Repository metadata from GitHub API.
2299
- */
2300
- interface GitHubRepoMetadata {
2301
- owner: string;
2302
- repo: string;
2303
- defaultBranch: string;
2304
- description: string | null;
2305
- language: string | null;
2306
- topics: string[];
2307
- isPrivate: boolean;
2308
- }
2309
- /**
2310
- * Detected package manager from lockfile.
2311
- */
2312
- type DetectedPackageManager = "npm" | "yarn" | "pnpm" | "bun" | "unknown";
2313
- /**
2314
- * Workspace/monorepo configuration.
2315
- */
2316
- interface WorkspaceConfig {
2317
- isMonorepo: boolean;
2318
- tool?: "npm" | "yarn" | "pnpm" | "lerna" | "turborepo" | "nx";
2319
- packages?: string[];
2320
- }
2321
- /**
2322
- * Build hints detected from project files.
2323
- */
2324
- interface BuildHints {
2325
- hasTypeScript: boolean;
2326
- hasWasm: boolean;
2327
- hasNativeModules: boolean;
2328
- hasBuildScript: boolean;
2329
- buildScript?: string;
2330
- frameworks: string[];
2331
- }
2332
- /**
2333
- * Complete project context for build plan generation.
2334
- */
2335
- interface GitHubProjectContext {
2336
- /** Repository metadata */
2337
- metadata: GitHubRepoMetadata;
2338
- /** Git ref being analyzed */
2339
- ref: string;
2340
- /** Detected package manager */
2341
- packageManager: DetectedPackageManager;
2342
- /** Workspace/monorepo configuration */
2343
- workspace: WorkspaceConfig;
2344
- /** Build hints from project files */
2345
- buildHints: BuildHints;
2346
- /** Raw file contents for AI analysis */
2347
- files: {
2348
- packageJson?: string;
2349
- tsconfigJson?: string;
2350
- lockfile?: {
2351
- name: string;
2352
- content: string;
2353
- };
2354
- };
2355
- }
2356
- /**
2357
- * Parse GitHub URL into owner and repo.
2358
- * Uses the richer parseGitHubUrl from github/index.ts, returning null on error.
2359
- */
2360
- declare function parseGitHubUrl2(url: string): {
2361
- owner: string;
2362
- repo: string;
2363
- } | null;
2364
- /**
2365
- * Fetch complete project context from GitHub.
2366
- */
2367
- declare function fetchGitHubContext(repoUrl: string, ref?: string): Promise<GitHubProjectContext>;
2368
- /**
2369
- * List packages in a monorepo workspace.
2370
- */
2371
- declare function listWorkspacePackages(owner: string, repo: string, ref: string, patterns: string[]): Promise<string[]>;
2372
- /**
2373
2607
  * Type-check a single example
2374
2608
  */
2375
2609
  declare function typecheckExample(example: string, packagePath: string, options?: TypecheckOptions): ExampleTypeError[];
@@ -2377,4 +2611,4 @@ declare function typecheckExample(example: string, packagePath: string, options?
2377
2611
  * Type-check multiple examples
2378
2612
  */
2379
2613
  declare function typecheckExamples(examples: string[], packagePath: string, options?: TypecheckOptions): TypecheckResult;
2380
- export { validateSpecCache, validateExamples, typecheckExamples, typecheckExample, shouldValidate, serializeJSDoc, saveSpecCache, saveReport, safeParseJson, runExamplesWithPackage, runExamples, runExample, resolveTarget, readPackageJson, parseGitHubUrl2 as parseScanGitHubUrl, parseMarkdownFiles, parseMarkdownFile, parseListFlag, parseJSDocToPatch, parseGitHubUrl, parseExamplesFlag, parseAssertions, mergeFixes, mergeFilters, mergeConfig, loadSpecCache, loadCachedReport, listWorkspacePackages, isFixableDrift, isExecutableLang, isCachedReportValid, installDependencies, hashString, hashFiles, hashFile, hasNonAssertionComments, hasDocsImpact, hasDocsForExport, groupDriftsByCategory, getUndocumentedExports, getSpecCachePath, getRunCommand, getRulesForKind, getRule, getReportPath, getPrimaryBuildScript, getInstallCommand, getDriftSummary, getDocumentedExports, getDocsImpactSummary, getDiffReportPath, getDefaultConfig, getCoverageRules, generateReportFromEnriched, generateReport, generateFixesForExport, generateFix, formatPackageList, formatDriftSummaryLine, findRemovedReferences, findPackageByName, findJSDocLocation, findExportReferences, findDeprecatedReferences, fetchSpecFromGitHub, fetchSpec, fetchGitHubContext, extractSpecSummary, extractPackageSpec, extractImports, extractFunctionCalls, evaluateQuality, evaluateExportQuality, ensureSpecCoverage, enrichSpec, diffSpecWithDocs, diffHashes, detectPackageManager, detectMonorepo, detectExampleRuntimeErrors, detectExampleAssertionFailures, detectEntryPoint, detectBuildInfo, defineConfig, createSourceFile, createNodeCommandRunner, computeExportDrift, computeDrift, clearSpecCache, categorizeDrifts, categorizeDrift, calculateAggregateCoverage, buildRawUrl, buildExportRegistry, buildDisplayUrl, buildCloneUrl, blockReferencesExport, applyPatchToJSDoc, applyEdits, analyzeProject2 as analyzeProject, analyzeFile, analyzeDocsImpact, analyze, WorkspacePackage, WorkspaceConfig, VALIDATION_INFO, TypecheckValidationResult, TypecheckResult, TypecheckOptions, SummaryDriftIssue, SpecSummary, SpecDiffWithDocs, SpecCacheConfig, SpecCache, SandboxFileSystem, STYLE_RULES, SPEC_CACHE_FILE, RuntimeDrift, RunValidationResult, RunExamplesWithPackageResult, RunExamplesWithPackageOptions, RunExampleOptions, RuleContext, ResolvedTarget, ResolvedFilters, ResolveTargetOptions, REPORT_VERSION, REPORT_EXTENSIONS, QualityViolation, QualitySeverity2 as QualitySeverity, QualityRulesConfig, QualityRule, QualityResult, QualityConfig, ProjectInfo, PresenceResult, ParsedGitHubUrl, PackageManagerInfo, PackageManager, PackageJson, PackageExports, OpenPkgSpec, NodeFileSystem, MonorepoType, MonorepoInfo, MemberChange, MarkdownDocFile, MarkdownCodeBlock, LLMAssertion, JSDocTag, JSDocReturn, JSDocPatch, JSDocParam, JSDocEdit, InstallResult, InstallOptions, GitHubRepoMetadata, GitHubProjectContext, FixType, FixSuggestion, FilterSource, FilterOptions, FileSystem, ExportReference, ExportDriftResult, ExportCoverageData, ExampleValidationTypeError, ExampleValidationResult, ExampleValidationOptions, ExampleValidationMode, ExampleValidation, ExampleTypeError, ExampleRunResult, EntryPointSource, EntryPointInfo, EnrichedOpenPkg, EnrichedExport, EnrichedDocsMetadata, EnrichOptions, DriftSummary, DriftResult, DriftReportSummary, DriftReport, DocsImpactResult, DocsImpactReference, DocsImpact, DocsConfig, DocsChangeType, DocCovReport, DocCovOptions, DocCovConfig, DocCov, DiffWithDocsOptions, Diagnostic2 as Diagnostic, DetectedPackageManager, DEFAULT_REPORT_PATH, DEFAULT_REPORT_DIR, CoverageSummary, CommandRunner, CommandResult, CheckConfig, CategorizedDrift, CacheValidationResult, CacheContext, CORE_RULES, CACHE_VERSION, BuildPlanTarget, BuildPlanStepResult, BuildPlanStep, BuildPlanExecutionResult, BuildPlanEnvironment, BuildPlan, BuildInfo, BuildHints, BUILTIN_RULES, ApplyEditsResult, AnalyzeProjectOptions, AnalyzeOptions, AnalysisResult, AggregateQualityResult, ALL_VALIDATIONS };
2614
+ export { validateSpecCache, validateExamples, typecheckExamples, typecheckExample, shouldValidate, serializeJSDoc, saveSpecCache, saveSnapshot, saveReport, safeParseJson, runExamplesWithPackage, runExamples, runExample, resolveTarget, resolveCompiledPath, renderSparkline, renderApiSurface, readPackageJson, pruneHistory, pruneByTier, parseGitHubUrl2 as parseScanGitHubUrl, parseMarkdownFiles, parseMarkdownFile, parseListFlag, parseJSDocToPatch, parseGitHubUrl, parseExamplesFlag, parseAssertions, mergeFixes, mergeFilters, loadSpecCache, loadSnapshotsForDays, loadSnapshots, loadCachedReport, listWorkspacePackages, isStandardJSONSchema, isSchemaType, isFixableDrift, isExecutableLang, isCachedReportValid, installDependencies, hashString, hashFiles, hashFile, hasNonAssertionComments, hasDocsImpact, hasDocsForExport, groupDriftsByCategory, getUndocumentedExports, getTrend, getSupportedLibraries, getSpecCachePath, getRunCommand, getReportPath, getRegisteredAdapters, getPrimaryBuildScript, getInstallCommand, getExtendedTrend, getDriftSummary, getDocumentedExports, getDocsImpactSummary, getDiffReportPath, generateWeeklySummaries, generateReportFromEnriched, generateReport, generateFixesForExport, generateFix, formatPackageList, formatDriftSummaryLine, formatDelta, findRemovedReferences, findPackageByName, findJSDocLocation, findExportReferences, findDeprecatedReferences, findAdapter, fetchSpecFromGitHub, fetchSpec, fetchGitHubContext, extractStandardSchemasFromProject, extractStandardSchemas, extractSpecSummary, extractSchemaType, extractSchemaOutputType, extractPackageSpec, extractImports, extractFunctionCalls, ensureSpecCoverage, enrichSpec, diffSpecWithDocs, diffHashes, detectRuntimeSchemas, detectPackageManager, detectMonorepo, detectExampleRuntimeErrors, detectExampleAssertionFailures, detectEntryPoint, detectBuildInfo, defineConfig, createSourceFile, createNodeCommandRunner, computeSnapshot, computeExportDrift, computeDrift, clearSpecCache, clearSchemaCache, categorizeDrifts, categorizeDrift, calculateAggregateCoverage, buildRawUrl, buildExportRegistry, buildDisplayUrl, buildCloneUrl, blockReferencesExport, applyPatchToJSDoc, applyEdits, analyzeProject2 as analyzeProject, analyzeFile, analyzeDocsImpact, analyze, WorkspacePackage, WorkspaceConfig, WeeklySummary, VALIDATION_INFO, TypecheckValidationResult, TypecheckResult, TypecheckOptions, SummaryDriftIssue, StandardSchemaExtractionResult, StandardSchemaExtractionOutput, StandardJSONSchemaV1, SpecSummary, SpecDiffWithDocs, SpecCacheConfig, SpecCache, SchemaExtractionResult, SchemaExtractionMode, SchemaDetectionResult, SchemaDetectionContext, SchemaAdapter, SandboxFileSystem, SPEC_CACHE_FILE, RuntimeDrift, RunValidationResult, RunExamplesWithPackageResult, RunExamplesWithPackageOptions, RunExampleOptions, RetentionTier, ResolvedTarget, ResolvedFilters, ResolveTargetOptions, ReleaseTag, RETENTION_DAYS, REPORT_VERSION, REPORT_EXTENSIONS, ProjectInfo, PresenceResult, ParsedGitHubUrl, PackageManagerInfo, PackageManager, PackageJson, PackageExports, OpenPkgSpec, NodeFileSystem, MonorepoType, MonorepoInfo, MemberChange, MarkdownDocFile, MarkdownCodeBlock, LLMAssertion, JSDocTag, JSDocReturn, JSDocPatch, JSDocParam, JSDocEdit, InstallResult, InstallOptions, HISTORY_DIR, GitHubRepoMetadata, GitHubProjectContext, FixType, FixSuggestion, FilterSource, FilterOptions, FileSystem, FetchGitHubContextOptions, ExtractStandardSchemasOptions, ExtendedTrendAnalysis, ExportReference, ExportDriftResult, ExportCoverageData, ExampleValidationTypeError, ExampleValidationResult, ExampleValidationOptions, ExampleValidationMode, ExampleValidation, ExampleTypeError, ExampleRunResult, EntryPointSource, EntryPointInfo, EnrichedOpenPkg, EnrichedExport, EnrichedDocsMetadata, EnrichOptions, DriftSummary, DriftResult, DriftReportSummary, DriftReport, DocsImpactResult, DocsImpactReference, DocsImpact, DocsConfig, DocsChangeType, DocCovReport, DocCovOptions, DocCovConfig, DocCov, DiffWithDocsOptions, Diagnostic2 as Diagnostic, DetectedSchemaEntry, DetectedPackageManager, DEFAULT_REPORT_PATH, DEFAULT_REPORT_DIR, CoverageTrend, CoverageSummary, CoverageSnapshot, CommandRunner, CommandResult, CheckConfig, CategorizedDrift, CacheValidationResult, CacheContext, CACHE_VERSION, BuildPlanTarget, BuildPlanStepResult, BuildPlanStep, BuildPlanExecutionResult, BuildPlanEnvironment, BuildPlan, BuildInfo, BuildHints, ApplyEditsResult, AnalyzeProjectOptions, AnalyzeOptions, AnalysisResult, ALL_VALIDATIONS };