api #

static analysis for TypeScript and Svelte

32 modules · 198 declarations

Modules
#

AnalysisLanguageService
#

typescript-program.ts view source

AnalysisLanguageService import type {AnalysisLanguageService} from 'svelte-docinfo/typescript-program.js';

Persistent language-service handle that drives a ts.Program incrementally.

Owns the LS, document registry, and a Map<path, {content, version}> of "owned" files (real source files + virtuals pushed via setFile). Files not in the owned map are read from disk on demand by the LS host.

Each setFile(path, content) bumps the version when content differs from cache, so the next getProgram() reparses only the changed file. Calling getProgram() with no version bumps returns the same ts.Program as the previous call (reference-stable when nothing changed).

see also

  • ``createAnalysisSession`` in session.ts for the high-level API that wraps this with content cache + svelte virtual cache + analysis pipeline.

getProgram

Get the current ts.Program.

Returns the same reference as the previous call when no setFile / deleteFile invalidated state in between. Returns a fresh ts.Program (sharing parsed ASTs for unchanged files via the document registry) when versions changed.

type (): Program

returns Program

throws

  • Error - if the underlying LS returned undefined (should not happen

setFile

Set or replace a file's content (real path or virtual path).

  • New file: added to the owned map with version 1.
  • Existing file with identical content: no-op (version unchanged).
  • Existing file with new content: version bumped.

type (path: string, content: string): boolean

path

type string

content

type string
returns boolean

true when the file was added or its version bumped, false on no-op.

deleteFile

Remove a file from the owned set.

type (path: string): boolean

path

type string
returns boolean

true when the file was tracked, false when it was unknown.

hasFile

Whether the given path is currently tracked.

type (path: string): boolean

path

type string
returns boolean

dispose

Release LS resources.

Calls ts.LanguageService.dispose() and clears the owned map. The service must not be used after disposal.

type (): void

returns void

AnalysisLanguageServiceOptions
#

typescript-program.ts view source

AnalysisLanguageServiceOptions import type {AnalysisLanguageServiceOptions} from 'svelte-docinfo/typescript-program.js';

inheritance

documentRegistry?

Optional document registry for AST sharing across services.

Pass an explicit registry to share parsed source files when running multiple language services (e.g., LSP integration). Defaults to a fresh registry per service when omitted.

type ts.DocumentRegistry

AnalysisLog
#

log.ts view source

also exported from index.ts

AnalysisLog import type {AnalysisLog} from 'svelte-docinfo/log.js';

Minimal logger interface for analysis functions.

Intentionally narrow so that both @fuzdev/fuz_util's Logger class and Vite's built-in logger satisfy it without adapters or casts.

examples

// Stderr logger for CLI usage const log: AnalysisLog = { info: (msg) => console.error(msg), warn: (msg) => console.error(`warning: ${msg}`), error: (msg) => console.error(`error: ${msg}`), };

info

type (msg: string) => void

warn

type (msg: string) => void

error

type (msg: string) => void

AnalysisProgramOptions
#

typescript-program.ts view source

AnalysisProgramOptions import type {AnalysisProgramOptions} from 'svelte-docinfo/typescript-program.js';

inheritance

virtualFiles?

Virtual files to seed the program (maps virtual path to content).

Used to include svelte2tsx transformed outputs alongside real source files, enabling full type resolution for Svelte components via the checker.

On a LanguageService, virtuals can also be added/replaced/removed after construction via setFile / deleteFile.

type Map<string, string>

AnalysisSession
#

session.ts view source

also exported from index.ts

AnalysisSession import type {AnalysisSession} from 'svelte-docinfo/session.js';

Persistent analysis handle.

Concurrency: not safe across overlapping calls. Serialize externally (each caller awaits the previous setFile/setFiles before starting the next). The LS underneath is sync, but the resolver phase awaits I/O for async resolvers (Vite/Rollup), so the session does cross await boundaries.

Cache-hit semantics: per-entry, all-or-nothing. The implementation must not split the guarantee across separate caches (e.g. transform-cache hit + lex re-run). The match criterion is mode-discriminated:

  • lex+resolve mode: existing.content === incoming.content AND existing.resolverIdentity === incoming.resolverIdentity.
  • pre-resolved mode: existing.content === incoming.content AND arraysShallowEqual(existing.preResolvedDepsSnapshot, incoming.dependencies).

Mode flips (an entry previously ingested as lex+resolve now arrives with dependencies, or vice versa) always cache-miss.

Promise resolution: setFile / setFiles resolve only after the serial LS push (phase 3) completes for every file in the batch. Awaiting the returned promise is sufficient — no separate flush step.

setFile

Ingest one file's content into the session. Idempotent on cache hit.

type (file: SourceFileInfo, opts?: SetFileOptions | undefined): Promise<SetFileResult>

file

opts?

type SetFileOptions | undefined
optional
returns Promise<SetFileResult>

{changed, diagnostics}changed: false indicates a cache-hit no-op where the cached ingest diagnostics are returned.

setFiles

Ingest a batch of files. Additive — never removes; use deleteFile for removal. Cache hits are folded into the result with changed: false.

type (files: readonly SourceFileInfo[], opts?: SetFileOptions | undefined): Promise<SetFilesResult>

files

type readonly SourceFileInfo[]

opts?

type SetFileOptions | undefined
optional
returns Promise<SetFilesResult>

deleteFile

Drop a file from the session and evict from the LS.

type (id: string): Promise<void>

id

type string
returns Promise<void>

has

Whether the given file ID is currently owned by the session.

type (id: string): boolean

id

type string
returns boolean

list

Snapshot of currently-owned file IDs (sort order is insertion order).

type (): readonly string[]

returns readonly string[]

query

Run a two-phase analysis pass against the current owned set.

type (opts?: QueryOptions | undefined): { modules: { path: string; declarations: ({ kind: "function"; parameters: { name: string; type: string; optional: boolean; rest: boolean; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<...> | undefined; }[]; ... 17 more ...; sourceLine?: number | undefined; } | ... 7 more ... | { ...; })[]; ... 7 more ...; moduleComment?: string | undefined; }[]; diagnostics: ({ ...; } | ... 12 more ... | { ...; })[]; }

opts?

type QueryOptions | undefined
optional
returns { modules: { path: string; declarations: ({ kind: "function"; parameters: { name: string; type: string; optional: boolean; rest: boolean; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<...> | undefined; }[]; ... 17 more ...; sourceLine?: number | undefined; } | ......

analyzed modules and analysis-pass diagnostics. Ingest diagnostics from prior setFile/setFiles calls are NOT included here — concat with those returns for the full picture.

throws

  • Error - if `onDuplicates: 'throw'` and duplicates exist

allIngestDiagnostics

Concatenated ingest-time diagnostics across every owned entry — the cumulative view of every setFile/setFiles return, kept current as entries are added/replaced/deleted.

Lets long-lived consumers (Vite plugin, LSP) publish the full ingest picture without tracking per-batch returns themselves. Cheap: walks the owned map.

type (): ({ symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | { functionName: string; ... 5 more ...; column?: number | undefined; } | ... 11 more ... | { ...; })[]

returns ({ symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | { functionName: string; ... 5 more ...; column?: number | undefined; } | ... 11 more ... | { ...; })[]

dispose

Release LS resources and clear the owned set. The session must not be used after disposal.

type (): void

returns void

AnalysisSessionOptions
#

session.ts view source

also exported from index.ts

AnalysisSessionOptions import type {AnalysisSessionOptions} from 'svelte-docinfo/session.js';

Options for createAnalysisSession.

documentRegistry flows through to the underlying LanguageService only. tsconfig and compilerOptions flow to both the LS *and* the lazy default ImportResolver (getDefaultResolver re-invokes loadTsconfig with them to produce a merged ts.CompilerOptions for module resolution). The two paths share the same merge semantics — user-supplied compilerOptions override parsed tsconfig keys, but never bypass the tsconfig.json file requirement.

projectRoot and virtualFiles from the LS options shape are excluded — the session derives projectRoot from sourceOptions and manages svelte2tsx virtuals internally per file.

inheritance

extends: Omit< AnalysisLanguageServiceOptions, 'projectRoot' | 'virtualFiles' >

sourceOptions

Module source options for path extraction and source filtering.

Must be a fully-constructed ModuleSourceOptions — the session re-runs normalizeSourceOptions (idempotent) but does not apply any defaults. Pass through createSourceOptions(projectRoot, overrides?) to merge with DEFAULT_SOURCE_OPTIONS. (The Partial<SourceOptionsDefaults> ergonomic shape exists only on AnalyzeFromFilesOptions.sourceOptions, where the defaults merge happens inside analyzeFromFiles.)

type ModuleSourceOptions

resolveImport?

Session-default custom import resolver used when no per-call override is supplied — a bare ResolveImportFn or a token-paired ImportResolver (see ResolveImport). A bare function is normalized once at construction, so its synthesized identity is stable for the session's lifetime (cache reuse works). When omitted, the session lazily constructs the TS+tsconfig default on first use.

type ResolveImport

log?

Optional logger for session-level messages.

type AnalysisLog

analyze
#

analyze.ts view source

also exported from index.ts

(options: AnalyzeOptions): Promise<{ modules: { path: string; declarations: ({ kind: "function"; parameters: { name: string; type: string; optional: boolean; rest: boolean; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<...> | undefined; }[]; ... 17 more ...; sourceLine?: number | undefined; } | ... 7 more ... | { ...; })[]; ... 7 more ...; moduleComment?: string | undefined; }[]; diagnostics: ({ ...; } | ... 12 more ... | { ...; })[]; }> import {analyze} from 'svelte-docinfo/analyze.js';

Analyze library source files and extract metadata (one-shot).

Wraps a single-use AnalysisSession. For repeated analyses of the same source set (e.g., a Vite plugin reacting to file edits), use createAnalysisSession directly.

options

returns

Promise<{ modules: { path: string; declarations: ({ kind: "function"; parameters: { name: string; type: string; optional: boolean; rest: boolean; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<...> | undefined; }[]; ... 17 more ...; sourceLine?: number | undefined;...

analyzed modules (sorted alphabetically) + concatenated ingest + query diagnostics

throws

  • Error - if `sourceOptions` validation fails or `tsconfig.json` is

analyzeCore
#

analyze-core.ts view source

(inputs: AnalyzeCoreInputs): { modules: { path: string; declarations: ({ kind: "function"; parameters: { name: string; type: string; optional: boolean; rest: boolean; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<...> | undefined; }[]; ... 17 more ...; sourceLine?: number | undefined; } | ... 7 more ... | { ...; })[]; ... 7 more ...; moduleComment?: string | undefined; }[]; diagnostics: ({ ...; } | ... 12 more ... | { ...; })[]; } import {analyzeCore} from 'svelte-docinfo/analyze-core.js';

Run the two-phase analysis loop on pre-prepared inputs.

inputs

returns

{ modules: { path: string; declarations: ({ kind: "function"; parameters: { name: string; type: string; optional: boolean; rest: boolean; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<...> | undefined; }[]; ... 17 more ...; sourceLine?: number | undefined; } | ......

AnalyzeCoreInputs
#

analyze-core.ts view source

AnalyzeCoreInputs import type {AnalyzeCoreInputs} from 'svelte-docinfo/analyze-core.js';

Inputs to analyzeCore. The caller (one-shot wrapper or session.query) is responsible for normalizing sourceOptions, obtaining the program, and pre-transforming Svelte files into svelteVirtualFiles.

transformFailedIds carries the IDs of .svelte files whose svelte2tsx transform threw at ingest. The dispatch synthesizes a placeholder ModuleJson (partial: true, empty declarations) for each so consumers see the file's existence in modules even though analysis couldn't run. Identifying these via a sibling Set keeps svelteVirtualFiles a clean "files we can analyze" map; the failure side-channel doesn't pollute it.

sourceFiles

type ReadonlyArray<SourceFileInfo>

sourceOptions

type ModuleSourceOptions

program

type ts.Program

svelteVirtualFiles

type ReadonlyMap<string, SvelteVirtualFile>

transformFailedIds?

Svelte file IDs whose svelte2tsx transform failed at ingest.

type ReadonlySet<string>

onDuplicates?

type OnDuplicates

log?

type AnalysisLog

analyzeDeclaration
#

typescript-exports.ts view source

(symbol: Symbol, sourceFile: SourceFile, checker: TypeChecker, diagnostics: ({ symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | ... 12 more ... | { ...; })[], isExternalFile: IsExternalFile): DeclarationAnalysis import {analyzeDeclaration} from 'svelte-docinfo/typescript-exports.js';

Analyze a TypeScript symbol and extract rich metadata.

This is a high-level function that combines TSDoc parsing with TypeScript type analysis to produce complete declaration metadata. Suitable for use in documentation generators, IDE integrations, and other tooling.

symbol

the TypeScript symbol to analyze

type Symbol

sourceFile

the source file containing the symbol

type SourceFile

checker

the TypeScript type checker

type TypeChecker

diagnostics

diagnostics collector for non-fatal issues

type ({ symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | { functionName: string; ... 5 more ...; column?: number | undefined; } | ... 11 more ... | { ...; })[]

isExternalFile

predicate for determining whether a source file is external to the project

returns

DeclarationAnalysis

complete declaration metadata including docs, types, and parameters, plus nodocs flag

analyzeExports
#

typescript-exports.ts view source

(sourceFile: SourceFile, checker: TypeChecker, options: ModuleSourceOptions, diagnostics: ({ symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | ... 12 more ... | { ...; })[]): ModuleExportsAnalysis import {analyzeExports} from 'svelte-docinfo/typescript-exports.js';

Analyze all exports from a TypeScript source file.

Extracts the module-level comment via extractModuleComment (skipped for svelte2tsx virtual files — see the inline note), star exports via extractStarExports, and all exported declarations with complete metadata. Handles re-exports by:

  • Same-name re-exports: tracked in reExports for alsoExportedFrom building
  • Renamed re-exports: included as new declarations with aliasOf metadata
  • Star exports (export * from): tracked in starExports for namespace-level info
  • Direct external re-exports: tracked in externalReExports/externalStarExports (specifier as written; import-then-export and source-chained forms stay silent)

This is a mid-level function (above the individual extract* helpers, below analyze) suitable for building documentation, API explorers, or analysis tools. For standard SvelteKit library layouts, use createSourceOptions(process.cwd()).

sourceFile

the TypeScript source file to analyze

type SourceFile

checker

the TypeScript type checker

type TypeChecker

options

module source options for path extraction in re-exports

diagnostics

diagnostics collector for non-fatal issues

type ({ symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | { functionName: string; ... 5 more ...; column?: number | undefined; } | ... 11 more ... | { ...; })[]

returns

ModuleExportsAnalysis

module comment, declarations, re-exports (source + external), and star exports (source + external)

analyzeFromFiles
#

analyze.ts view source

also exported from index.ts

(options: AnalyzeFromFilesOptions): Promise<{ modules: { path: string; declarations: ({ kind: "function"; parameters: { name: string; type: string; optional: boolean; rest: boolean; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<...> | undefined; }[]; ... 17 more ...; sourceLine?: number | undefined; } | ... 7 more ... | { ...; })[]; ... 7 more ...; moduleComment?: string | undefined; }[]; diagnostics: ({ ...; } | ... 12 more ... | { ...; })[]; }> import {analyzeFromFiles} from 'svelte-docinfo/analyze.js';

Analyze a library from files on disk with automatic file discovery.

Recommended high-level API for one-shot use (CLI, build-time generation):

  1. DiscoverydiscoverSourceFiles (exports-first, glob fallback)
  2. Ingest — push discovered files into a single-use session
  3. Analysissession.query()

options

returns

Promise<{ modules: { path: string; declarations: ({ kind: "function"; parameters: { name: string; type: string; optional: boolean; rest: boolean; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<...> | undefined; }[]; ... 17 more ...; sourceLine?: number | undefined;...

analyzed modules + concatenated ingest, discovery, and query diagnostics

throws

  • Error - if `sourceOptions` validation fails or `tsconfig.json` is missing

AnalyzeFromFilesOptions
#

analyze.ts view source

also exported from index.ts

AnalyzeFromFilesOptions import type {AnalyzeFromFilesOptions} from 'svelte-docinfo/analyze.js';

Options for analyzeFromFiles.

see also

  • ``AnalyzeOptions`` for the build-tool-integration API where you supply sourceFiles and a fully-formed sourceOptions: ModuleSourceOptions directly.

projectRoot

Absolute path to project root directory.

type string

sourceOptions?

Partial overrides for default source options (SvelteKit src/lib layout).

type Partial<SourceOptionsDefaults>

onDuplicates?

Behavior when duplicate declaration names are found across modules.

type OnDuplicates

log?

Optional logger for status and diagnostic messages.

type AnalysisLog

include?

Glob patterns to include (relative to projectRoot).

Filters glob-based discovery. Providing include under the default discovery: 'auto' collapses the chain to glob immediately; combining with discovery: 'exports' throws.

When omitted, the glob fallback derives an include from sourceOptions.sourcePaths via deriveIncludePatterns, so custom sourcePaths (e.g., ['packages/foo']) survive the fallback instead of silently defaulting to src/lib.

type Array<string>

exclude?

Glob patterns to exclude — fully replaces sourceOptions.exclude (no merge).

type Array<string>

resolveDependencies?

Whether to resolve import dependencies (default true).

When false, the session uses a no-op resolver that always returns null, so ModuleJson.dependencies / dependents stay empty. analyzeFromFiles's discovery layer does not pre-populate SourceFileInfo.dependencies, so the session's pre-resolved fast path isn't reachable through this API — to exercise it, drive analyze or createAnalysisSession directly with files whose dependencies field is already filled in by your build tool.

type boolean

default `true`

resolveImport?

Optional custom import resolver — a bare ResolveImportFn or a token-paired ImportResolver (see ResolveImport). One-shot use doesn't benefit from a stable cache identity, so the bare function form is the natural choice here; for long-lived consumers (Vite plugin, LSP) construct an ImportResolver with a stable identity and pass it via createAnalysisSession so cache hits survive across calls.

Cannot be combined with resolveDependencies: false — resolution is then off, so the resolver would never be consulted; passing both throws.

type ResolveImport

discovery?

Discovery strategy for source files.

type Discovery

default 'auto'

distDir?

Dist directory name for exports-based discovery.

type string

default 'dist'

analyzeModule
#

analyze-core.ts view source

(sourceFile: SourceFileInfo & { dependents?: readonly string[] | undefined; }, program: Program, options: ModuleSourceOptions, diagnostics: ({ symbolName: string; ... 5 more ...; column?: number | undefined; } | ... 12 more ... | { ...; })[], log?: AnalysisLog | undefined): { ...; } | undefined import {analyzeModule} from 'svelte-docinfo/analyze-core.js';

Analyze a single non-Svelte source file and extract module metadata.

sourceFile

type SourceFileInfo & { dependents?: readonly string[] | undefined; }

program

type Program

options

diagnostics

type ({ symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | { functionName: string; ... 5 more ...; column?: number | undefined; } | ... 11 more ... | { ...; })[]

log?

type AnalysisLog | undefined
optional

returns

{ path: string; declarations: ({ kind: "function"; parameters: { name: string; type: string; optional: boolean; rest: boolean; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<...> | undefined; }[]; ... 17 more ...; sourceLine?: number | undefined; } | ... 7 more ......

AnalyzeOptions
#

analyze.ts view source

also exported from index.ts

AnalyzeOptions import type {AnalyzeOptions} from 'svelte-docinfo/analyze.js';

Options for analyze.

Requires pre-loaded SourceFileInfo arrays — use analyzeFromFiles for automatic file discovery and loading from disk, or createAnalysisSession for incremental use.

sourceFiles

Source files to analyze (must have content loaded).

type ReadonlyArray<SourceFileInfo>

sourceOptions

Module source options for path extraction and source filtering.

type ModuleSourceOptions

onDuplicates?

Behavior when duplicate declaration names are found across modules.

type OnDuplicates

log?

Optional logger for status and diagnostic messages.

type AnalysisLog

resolveImport?

Optional custom import resolver for the session default — a bare ResolveImportFn or a token-paired ImportResolver (see ResolveImport). For one-shot analyze() the session is single-use, so a bare function is the natural form; pass an ImportResolver with a stable identity only if you have a reason to control the cache scope.

type ResolveImport

AnalyzeResultJson
#

analyze-core.ts view source

also exported from index.ts

ZodObject<{ modules: ZodDefault<ZodArray<ZodObject<{ path: ZodString; declarations: ZodDefault<ZodArray<ZodDiscriminatedUnion<[ZodObject<{ kind: ZodLiteral<"function">; returnType: ZodOptional<ZodString>; returnDescription: ZodOptional<...>; ... 16 more ...; genericParams: ZodDefault<...>; }, $strict>, ... 7 more ..... import type {AnalyzeResultJson} from 'svelte-docinfo/analyze-core.js';

Result of analyze, analyzeFromFiles, and AnalysisSession.query.

Modules sorted alphabetically by path. Diagnostics are query-time (analysis-pass) diagnostics only when produced by session.query; one-shot wrappers concatenate ingest + query diagnostics into this same array.

Schema-validated round-trip

The envelope is a Zod schema (AnalyzeResultJson) — both fields default to [], so JSON.stringify(result, compactReplacer) strips empty arrays on the wire and AnalyzeResultJson.parse(JSON.parse(json)) restores them. Consumers programmatically ingesting analysis JSON should parse through the schema to get defaults restored; raw-JSON consumers (e.g., jq) treat missing keys as null-equivalent (jq '.diagnostics | length' returns 0 on {}) and don't need the parse step.

Construction sites (one-shot wrappers, session.query) hand back hand-built objects without re-running .parse() — the inner modules and diagnostics arrays are already Zod-validated upstream, and the envelope schema is the type contract, not a validation gate.

See AnalyzeResultJsonWire for the serialized input-side shape published on virtual:svelte-docinfo.

AnalyzeResultJsonWire
#

analyze-core.ts view source

also exported from index.ts

AnalyzeResultJsonWire import type {AnalyzeResultJsonWire} from 'svelte-docinfo/analyze-core.js';

Serialized wire shape of an analysis result, as published by the Vite plugin on virtual:svelte-docinfo — the input-side counterpart to AnalyzeResultJson (the validated output of .parse()).

The two fields are deliberately asymmetric:

  • modules is ModuleJsonInput (the z.input of ModuleJson) because the plugin runs it through compactReplacer, which strips .default([]) arrays and .default(false) booleans. Default-bearing fields therefore arrive undefined.
  • diagnostics is the output Diagnostic — the plugin serializes it without the replacer, and Diagnostic has no defaults to strip, so the array is always present and the shape matches runtime exactly.

Consumers restore defaults by parsing through AnalyzeResultJson.

Note this describes the Vite virtual module specifically. The CLI runs the whole envelope through compactReplacer, so its JSON may additionally omit an empty diagnostics array — CLI consumers should parse through AnalyzeResultJson rather than assume this shape.

modules

type Array<ModuleJsonInput>

diagnostics

type Array<Diagnostic>

AnalyzerType
#

source.ts view source

also exported from index.ts

AnalyzerType import type {AnalyzerType} from 'svelte-docinfo/source.js';

Analyzer type for source files.

  • 'typescript' — TypeScript/JS files analyzed via TypeScript compiler API
  • 'svelte' — Svelte components analyzed via svelte2tsx + TypeScript compiler API
  • 'css' — CSS files included as modules with no declarations
  • 'json' — JSON files included as modules with no declarations

analyzeSvelteModule
#

svelte.ts view source

(sourceFile: SourceFileInfo & { dependents?: readonly string[] | undefined; }, modulePath: string, checker: TypeChecker, options: ModuleSourceOptions, diagnostics: ({ ...; } | ... 12 more ... | { ...; })[], program: Program, virtualFile: SvelteVirtualFile): ModuleAnalysis | undefined import {analyzeSvelteModule} from 'svelte-docinfo/svelte.js';

Analyze a Svelte module using checker-backed analysis.

Requires the svelte2tsx virtual output to be included in the TypeScript program (via createAnalysisProgram({ virtualFiles })). Provides full type resolution for:

  • Imported prop types (let {x}: ImportedProps = $props())
  • <script module> exports (constants, types, re-exports)
  • Star exports and re-exports from Svelte files

sourceFile

the original Svelte source file

type SourceFileInfo & { dependents?: readonly string[] | undefined; }

modulePath

module path relative to source root

type string

checker

TypeScript type checker (from the program containing virtual files)

type TypeChecker

options

module source options for path extraction

diagnostics

diagnostics collector for non-fatal issues

type ({ symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | { functionName: string; ... 5 more ...; column?: number | undefined; } | ... 11 more ... | { ...; })[]

program

TypeScript program containing the virtual file

type Program

virtualFile

pre-transformed virtual file data

returns

ModuleAnalysis | undefined

module analysis with declarations, re-exports, and star exports; undefined if the virtual file is not found in the program

analyzeTypescriptModule
#

typescript-exports.ts view source

(sourceFileInfo: SourceFileInfo & { dependents?: readonly string[] | undefined; }, tsSourceFile: SourceFile, modulePath: string, checker: TypeChecker, options: ModuleSourceOptions, diagnostics: ({ ...; } | ... 12 more ... | { ...; })[]): ModuleAnalysis import {analyzeTypescriptModule} from 'svelte-docinfo/typescript-exports.js';

Analyze a TypeScript file and extract module metadata.

Wraps analyzeExports and adds dependency information via extractDependencies from the source file info if available.

This is a high-level function suitable for building documentation or library metadata. For lower-level analysis, use analyzeExports directly.

sourceFileInfo

the source file info (from file system, build pipeline, or other source)

type SourceFileInfo & { dependents?: readonly string[] | undefined; }

tsSourceFile

TypeScript source file from the program

type SourceFile

modulePath

the module path (relative to source root)

type string

checker

TypeScript type checker

type TypeChecker

options

module source options for path extraction

diagnostics

diagnostics collector for non-fatal issues

type ({ symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | { functionName: string; ... 5 more ...; column?: number | undefined; } | ... 11 more ... | { ...; })[]

returns

ModuleAnalysis

module metadata and re-export information

applyToDeclaration
#

tsdoc.ts view source

(declaration: MemberJsonBuild | DeclarationJsonBuild, tsdoc: TsdocParsedComment | undefined): void import {applyToDeclaration} from 'svelte-docinfo/tsdoc.js';

Apply parsed TSDoc metadata to a declaration.

Consolidates the common pattern of assigning TSDoc fields to declarations, with conditional assignment for array fields (only if non-empty).

declaration

declaration object to update

type MemberJsonBuild | DeclarationJsonBuild

tsdoc

parsed TSDoc comment (if available)

type TsdocParsedComment | undefined

returns

void

mutates

  • declaration — adds docComment, deprecatedMessage, examples, seeAlso, throws, since, mutates, defaultValue fields

buildTypeReferencePatterns
#

declaration-helpers.ts view source

also exported from index.ts

(declarationNames: ReadonlySet<string>): [string, RegExp][] import {buildTypeReferencePatterns} from 'svelte-docinfo/declaration-helpers.js';

Pre-compile identifier-boundary patterns for a set of declaration names.

When scanning many type strings against the same declaration set, call this once and pass the result to findTypeReferences to avoid recompiling regexes on every call.

declarationNames

set of known in-project declaration names

type ReadonlySet<string>

returns

[string, RegExp][]

array of [name, pattern] pairs for use with findTypeReferences

examples

const names = new Set(modules.flatMap(m => m.declarations.map(d => d.name))); const patterns = buildTypeReferencePatterns(names); for (const decl of declarations) { const refs = findTypeReferences(decl.typeSignature, patterns); }

byKind
#

diagnostics.ts view source

also exported from index.ts

<K extends DiagnosticKind>(diagnostics: ({ symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | ... 12 more ... | { ...; })[], kind: K): (Extract<...> | ... 12 more ... | Extract<...>)[] import {byKind} from 'svelte-docinfo/diagnostics.js';

Get diagnostics of a specific kind, narrowed to the matching variant.

diagnostics

type ({ symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | { functionName: string; ... 5 more ...; column?: number | undefined; } | ... 11 more ... | { ...; })[]

kind

type K

returns

(Extract<{ symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; }, { kind: K; }> | ... 12 more ... | Extract<...>)[]

generics

byKind<K extends DiagnosticKind>
K
constraint DiagnosticKind

ClassDeclarationJson
#

types.ts view source

also exported from index.ts

ZodObject<{ kind: ZodLiteral<"class">; extends: ZodOptional<ZodString>; implements: ZodDefault<ZodArray<ZodString>>; ... 15 more ...; genericParams: ZodDefault<...>; }, $strict> import type {ClassDeclarationJson} from 'svelte-docinfo/types.js';

A class declaration. Has members, extends, implements.

ClassMemberDiagnostic
#

diagnostics.ts view source

ZodObject<{ className: ZodString; memberName: ZodString; file: ZodString; line: ZodOptional<ZodNumber>; column: ZodOptional<ZodNumber>; message: ZodString; severity: ZodEnum<...>; kind: ZodLiteral<...>; }, $strict> import type {ClassMemberDiagnostic} from 'svelte-docinfo/diagnostics.js';

Class member analysis failed.

cleanComment
#

tsdoc.ts view source

(commentText: string): string | undefined import {cleanComment} from 'svelte-docinfo/tsdoc.js';

Clean raw JSDoc comment text by removing comment markers and leading asterisks.

Transforms /** ... *\/ style comments into clean text.

commentText

the raw comment text including /** and *\/ markers

type string

returns

string | undefined

cleaned comment text, or undefined if empty after cleaning

examples

cleanComment('/** Hello world *\/') // => 'Hello world' cleanComment('/**\n * Line 1\n * Line 2\n *\/') // => 'Line 1\nLine 2'

CliOptions
#

cli.ts view source

CliOptions import type {CliOptions} from 'svelte-docinfo/cli.js';

CLI options parsed from command line arguments.

include?

File patterns to include (undefined = use exports discovery or defaults).

type Array<string>

exclude?

File patterns to exclude (undefined = use defaults — test and spec files).

When provided, fully replaces the defaults — no array merge. Passing a custom --exclude pattern drops the default test/spec filters unless the caller re-includes them explicitly.

type Array<string>

output?

Output file path (undefined = stdout).

type string

resolveDependencies?

Whether to resolve dependencies. Mapped from the --no-resolve-dependencies flag (commander populates true by default; false when the flag is passed). Optional here so external callers can omit it; treated as true when undefined.

type boolean

discovery?

Discovery strategy (undefined = 'auto').

Mapped from --discovery <auto|exports|glob>.

type Discovery

distDir?

Dist directory name for exports-based discovery (undefined = 'dist').

type string

sourceDir?

Source directories relative to project root (undefined = ['src/lib']).

Repeatable. Drives the implicit include glob in the glob-discovery fallback (via deriveIncludePatterns inside discoverSourceFiles) so custom source directories survive without needing an explicit --include.

type Array<string>

sourceRoot?

Source root for module path extraction, relative to project root (undefined = single sourceDir or longest common prefix).

Module paths in output are stripped of <projectRoot>/<sourceRoot>/. Pass . (or "") to keep module paths project-relative — useful when sourceDir entries share no common prefix. The . form is normalized to "" inside normalizeSourceOptions.

type string

onDuplicates?

Behavior when duplicate declaration names are found across modules (undefined = emit duplicate_declaration diagnostic, no dispatch).

Duplicate detection always runs regardless of this option — the diagnostic is the data, this option is the dispatch action.

type OnDuplicatesFlag

only?

Glob patterns to filter the emitted modules array against ModuleJson.path (undefined = emit all analyzed modules).

Repeatable. Output-only filter: full-project analysis still runs so re-exports, dependents, and alsoExportedFrom stay correct against the complete owned set. Diagnostics aren't filtered — they may reference modules dropped from output.

type Array<string>

quiet?

Whether to suppress info messages to stderr. Treated as false when undefined.

type boolean

pretty?

Whether to pretty-print JSON output. Treated as false when undefined.

type boolean

compactReplacer
#

declaration-helpers.ts view source

also exported from index.ts

(_key: string, value: unknown): unknown import {compactReplacer} from 'svelte-docinfo/declaration-helpers.js';

JSON replacer that strips Zod default values for compact serialization.

Strips empty arrays and false booleans — both are Zod .default() values restored on .parse(), so the round-trip is lossless for svelte-docinfo types. Assumes all boolean fields in the schema default to false — a true-defaulted boolean would need its false values preserved, breaking the round-trip.

Root-value caveat: JSON.stringify([], compactReplacer) returns the JS undefined (not the string '[]'), and JSON.stringify(false, compactReplacer) returns the JS undefined too. Object-rooted callers (AnalyzeResultJson envelope, CLI output) don't hit this — empty inner arrays strip and AnalyzeResultJson.parse restores them on the consumer side. Array-rooted callers (Vite plugin, anyone splicing the JSON into a source template) must handle the empty case themselves before calling this; see vite.ts:updateOutputFromQuery for the pattern.

Two guard tests in declaration-helpers.test.ts lock this in:

  • every z.boolean().default in types.ts uses false — source-regex check that fails on a new z.boolean().default(true).
  • `parse → stringify(compactReplacer) → parse is a faithful round-trip across every variant` — exercises every variant and member through a full round-trip, catching regressions where a .default(false) or .default([]) is removed (or a new field is added that the replacer drops but Zod doesn't restore).

_key

type string

value

type unknown

returns

unknown

examples

const result = await analyze({sourceFiles, sourceOptions}); const json = JSON.stringify(result, compactReplacer); // On the consumer side, restore Zod defaults: const restored = AnalyzeResultJson.parse(JSON.parse(json));

compareStrings
#

postprocess.ts view source

(a: string, b: string): number import {compareStrings} from 'svelte-docinfo/postprocess.js';

Case-insensitive string comparator for deterministic output ordering.

Case-folded comparison first (so Analyze and analyze sort together instead of all uppercase before all lowercase), then a code-unit tiebreak — so equal-ignoring-case strings still compare unequal and the result is an exact total order. Unlike localeCompare (host-locale/ICU-dependent, so byte-identical input can serialize in different orders on different machines), both passes use Unicode default mappings only and are environment-independent. All output ordering goes through this comparator — never bare localeCompare or default Array.prototype.sort.

a

type string

b

type string

returns

number

ComponentDeclarationJson
#

types.ts view source

also exported from index.ts

ZodObject<{ kind: ZodLiteral<"component">; intersects: ZodDefault<ZodArray<ZodString>>; props: ZodDefault<ZodArray<ZodObject<{ examples: ZodDefault<ZodArray<ZodString>>; ... 10 more ...; parameters: ZodOptional<...>; }, $strict>>>; ... 16 more ...; genericParams: ZodDefault<...>; }, $strict> import type {ComponentDeclarationJson} from 'svelte-docinfo/types.js';

A Svelte component declaration. Has props, intersects, acceptsChildren.

ComponentPropJson
#

types.ts view source

also exported from index.ts

ZodObject<{ examples: ZodDefault<ZodArray<ZodString>>; deprecatedMessage: ZodOptional<ZodString>; seeAlso: ZodDefault<ZodArray<ZodString>>; ... 8 more ...; parameters: ZodOptional<...>; }, $strict> import type {ComponentPropJson} from 'svelte-docinfo/types.js';

Component prop information for Svelte components.

Standalone schema (not extending ParameterJson) because component props have different semantics: named attributes with no positional order (<Foo {a} {b} /> = <Foo {b} {a} />), no rest parameters, and support for two-way binding via $bindable rune.

ComponentPropJsonInput
#

types.ts view source

{ name: string; type: string; examples?: string[] | undefined; deprecatedMessage?: string | undefined; seeAlso?: string[] | undefined; throws?: { description: string; type?: string | undefined; }[] | undefined; ... 5 more ...; parameters?: { ...; }[] | undefined; } import type {ComponentPropJsonInput} from 'svelte-docinfo/types.js';

name

Prop name as declared in the component's $props() type.

type string

type

Resolved TypeScript type string.

type string

examples?

Code examples from @example tags.

type string[]

deprecatedMessage?

Deprecation message from @deprecated tag.

type string

seeAlso?

Related items from @see tags, in raw TSDoc format.

type string[]

throws?

Exceptions from @throws tags.

type { description: string; type?: string | undefined; }[]

since?

Version introduced, from @since tag.

type string

optional?

Whether the prop is optional in the component's props type.

type boolean

description?

Description from JSDoc on the prop's type declaration.

type string

defaultValue?

Default value expression from destructuring or @default tag.

type string

bindable?

Whether the prop uses the $bindable() rune, enabling two-way binding.

type boolean

parameters?

Structured parameters for callable props (e.g., Snippet<[text: string]>).

Present when the prop has extractable parameters, absent otherwise. Only populated when there are actual parameters — bare Snippet / Snippet<[]> does not set this field. Intentionally .optional() rather than .default([]) (see the array-field policy note above): absence is a meaningful signal, not an empty list.

type { name: string; type: string; optional?: boolean | undefined; rest?: boolean | undefined; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<...> | undefined; }[]

computeDependents
#

postprocess.ts view source

(files: readonly SourceFileInfo[]): (SourceFileInfo & { dependents?: readonly string[] | undefined; })[] import {computeDependents} from 'svelte-docinfo/postprocess.js';

Compute bidirectional dependencies from source files.

This function ensures that if file A has file B in its dependencies, then file B will have file A in its dependents. This provides consistent output regardless of whether callers provide one-directional or bidirectional dependency information.

Returns new SourceFileInfo objects when computed dependents exist or when paths needed posixification; otherwise the original input objects flow through ===-equal (fast path for session callers, who already pass POSIX paths and may have no inferable dependents for a given file).

files

source files with optional dependency information

type readonly SourceFileInfo[]

returns

(SourceFileInfo & { dependents?: readonly string[] | undefined; })[]

new array with bidirectional dependencies computed

examples

// Input: Calculator.svelte has dependencies: [math.ts] // Output: Calculator.svelte has dependencies: [math.ts] // math.ts has dependents: [Calculator.svelte] const filesWithBidirectional = computeDependents(files);

ConstructorMemberJson
#

types.ts view source

also exported from index.ts

ZodObject<{ kind: ZodLiteral<"constructor">; name: ZodUnion<readonly [ZodLiteral<"constructor">, ZodLiteral<"(construct)">]>; parameters: ZodDefault<ZodArray<ZodObject<...>>>; ... 12 more ...; genericParams: ZodDefault<...>; }, $strict> import type {ConstructorMemberJson} from 'svelte-docinfo/types.js';

A constructor member (class constructor, construct signature). Has parameters, overloads — but not returnType/returnDescription (constructors always return their class).

name is narrowed to two literal sentinels: 'constructor' for class constructors and '(construct)' for interface/type-alias construct signatures (which share kind: 'constructor' but originate from getConstructSignatures() on a non-class type — no user-chosen identifier exists). The literal is preserved (rather than omitted) so getDisplayName and consumer renderers reading member.name keep working without a constructor-specific branch.

createAnalysisLanguageService
#

typescript-program.ts view source

(options?: AnalysisLanguageServiceOptions | undefined, log?: AnalysisLog | undefined): AnalysisLanguageService import {createAnalysisLanguageService} from 'svelte-docinfo/typescript-program.js';

Create a persistent language service for incremental analysis.

The LS owns parsed source ASTs and checker state across calls. Use the returned handle to push file-content updates (setFile / deleteFile) between analysis passes; subsequent getProgram() calls return either the same ts.Program (no changes since last call) or a fresh one that reuses unchanged files via the document registry.

options?

configuration options

type AnalysisLanguageServiceOptions | undefined
optional

log?

optional logger for info messages

type AnalysisLog | undefined
optional

returns

AnalysisLanguageService

the language service handle

throws

  • Error - if tsconfig.json is not found

examples

const ls = createAnalysisLanguageService({projectRoot}); ls.setFile('/abs/path/to/foo.ts', 'export const x = 1;'); const program = ls.getProgram(); // ... use program ... ls.setFile('/abs/path/to/foo.ts', 'export const x = 2;'); // bumps version const program2 = ls.getProgram(); // fresh program, foo.ts reparsed ls.dispose();

createAnalysisProgram
#

typescript-program.ts view source

(options?: AnalysisProgramOptions | undefined, log?: AnalysisLog | undefined): Program import {createAnalysisProgram} from 'svelte-docinfo/typescript-program.js';

Create TypeScript program for one-shot analysis.

Use createAnalysisLanguageService instead when you need to analyze the same source set multiple times — the LS path reuses parsed ASTs and checker state across calls.

options?

configuration options for program creation

type AnalysisProgramOptions | undefined
optional

log?

optional logger for info messages

type AnalysisLog | undefined
optional

returns

Program

the TypeScript program

throws

  • Error - if tsconfig.json is not found

examples

const program = createAnalysisProgram({projectRoot: process.cwd()});

createAnalysisSession
#

session.ts view source

also exported from index.ts

(options: AnalysisSessionOptions): AnalysisSession import {createAnalysisSession} from 'svelte-docinfo/session.js';

Create a persistent analysis session.

options

returns

AnalysisSession

examples

Vite plugin integration

const session = createAnalysisSession({sourceOptions, resolveImport, log}); await session.setFiles(initialFiles); const result = session.query(); // on watcher events: await session.setFile({id, content}); await session.deleteFile(removedId); const next = session.query(); // on shutdown: session.dispose();

One-shot via the public wrapper

// Equivalent to `analyze(...)` — the wrapper goes through a session internally. const session = createAnalysisSession({sourceOptions}); try { await session.setFiles(sourceFiles); return session.query({onDuplicates: 'throw'}); } finally { session.dispose(); }

createDefaultResolver
#

dep-resolver.ts view source

(compilerOptions: CompilerOptions, projectRoot: string): ImportResolver import {createDefaultResolver} from 'svelte-docinfo/dep-resolver.js';

Create the default ImportResolver (TypeScript + tsconfig).

Uses ts.resolveModuleName against ts.sys directly — no ts.Program is built. Identity is a fresh symbol per call, so each session that constructs its own default gets a unique cache scope. Multiple sessions sharing one resolver instance share the cache scope (correct, since resolver state is shared too).

ts.resolveModuleName cannot resolve real .svelte files (no compiler option teaches it the extension), so relative and absolute .svelte specifiers — with or without the extension written — fall back to manual filesystem resolution against fromFile. Non-relative .svelte specifiers (tsconfig paths aliases, package subpaths) stay unresolved; supply a custom resolveImport for those setups.

compilerOptions

parsed tsconfig (from loadTsconfig)

type CompilerOptions

projectRoot

absolute project root for the module-resolution cache

type string

returns

ImportResolver

createIsExternalFile
#

typescript-program.ts view source

(options: ModuleSourceOptions): IsExternalFile import {createIsExternalFile} from 'svelte-docinfo/typescript-program.js';

Create an IsExternalFile predicate from ModuleSourceOptions.

A file is external if it is:

  • Outside the project root
  • Inside node_modules/
  • A .d.ts declaration file outside the source root (catches framework-generated declarations like .svelte-kit/non-ambient.d.ts while keeping user .d.ts files in the source tree)

options

returns

IsExternalFile

createSourceOptions
#

source-config.ts view source

also exported from index.ts

(projectRoot: string, overrides?: Partial<SourceOptionsDefaults> | undefined): ModuleSourceOptions import {createSourceOptions} from 'svelte-docinfo/source-config.js';

Create complete, normalized, validated source options from project root and optional overrides.

Merges overrides with DEFAULT_SOURCE_OPTIONS, then normalizes via normalizeSourceOptions — so the returned object always has an absolute projectRoot, slash-stripped path entries, and an explicit sourceRoot (auto-derived for multi-path layouts). Throws on validation failure.

projectRoot

path to project root (typically process.cwd()); resolved to absolute

type string

overrides?

optional overrides for default options

type Partial<SourceOptionsDefaults> | undefined
optional

returns

ModuleSourceOptions

throws

  • Error - if validation fails (empty `sourcePaths`, or `sourceRoot` not a prefix of all `sourcePaths`)

examples

// Standard SvelteKit library const options = createSourceOptions(process.cwd());
// Multiple source directories const options = createSourceOptions(process.cwd(), { sourcePaths: ['src/lib', 'src/routes'], sourceRoot: 'src', });
// Custom exclusions const options = createSourceOptions(process.cwd(), { exclude: ['**\/*.test.ts', '**\/*.internal.ts'], });

DeclarationAnalysis
#

declaration-build.ts view source

DeclarationAnalysis import type {DeclarationAnalysis} from 'svelte-docinfo/declaration-build.js';

Result of analyzing a single declaration.

Produced by analyzeDeclaration (in typescript-exports.ts) and Svelte component analysis. Used by analyzeModule to filter @nodocs declarations before output.

Uses DeclarationJsonBuild (not DeclarationJsonInput) because declarations are constructed incrementally — Zod validation happens at the ModuleJson.parse() boundary.

declaration

The analyzed declaration metadata (pre-validation).

type DeclarationJsonBuild

nodocs

Whether the declaration is marked @nodocs (should be excluded from documentation).

type boolean

DeclarationJson
#

types.ts view source

also exported from index.ts

ZodDiscriminatedUnion<[ZodObject<{ kind: ZodLiteral<"function">; returnType: ZodOptional<ZodString>; returnDescription: ZodOptional<ZodString>; ... 16 more ...; genericParams: ZodDefault<...>; }, $strict>, ... 7 more ..., ZodObject<...>], "kind"> import type {DeclarationJson} from 'svelte-docinfo/types.js';

Metadata for an exported declaration (function, type, class, component, etc.).

Discriminated union on kind — each variant has only the fields relevant to that kind. Use isKind (in declaration-helpers.ts) to narrow, or check declaration.kind directly.

DeclarationJsonBuild
#

declaration-build.ts view source

DeclarationJsonBuild import type {DeclarationJsonBuild} from 'svelte-docinfo/declaration-build.js';

Permissive type for constructing declarations incrementally before Zod validation.

Used by internal analysis functions (analyzeDeclaration, extractFunctionInfo, etc.) that build declarations by mutating a plain object. The discriminated union schema validates the final shape at the ModuleJson.parse() boundary.

name?

type string

kind

type DeclarationKind

docComment?

type string

typeSignature?

type string

modifiers?

type Array<DeclarationModifier>

sourceLine?

type number

parameters?

type Array<z.input<typeof ParameterJson>>

returnType?

type string

returnDescription?

type string

genericParams?

type Array<GenericParamJson>

overloads?

type Array<OverloadJsonInput>

examples?

type Array<string>

deprecatedMessage?

type string

seeAlso?

type Array<string>

throws?

type Array<{type?: string; description: string}>

since?

type string

mutates?

type Record<string, string>

extends?

type string | Array<string>

intersects?

type Array<string>

implements?

type Array<string>

members?

type Array<MemberJsonBuild>

props?

type Array<ComponentPropJsonInput>

acceptsChildren?

type boolean

lang?

type 'js'

alsoExportedFrom?

type Array<string>

aliasOf?

type {module: string; name: string}

reactivity?

type Reactivity

partial?

type boolean

module?

Source module path for kind: 'namespace' declarations (export * as ns from './x').

type string

defaultValue?

Default value documented via @default. Variable declarations only.

type string

DeclarationJsonInput
#

types.ts view source

{ kind: "function"; name: string; returnType?: string | undefined; returnDescription?: string | undefined; parameters?: { name: string; type: string; optional?: boolean | undefined; rest?: boolean | undefined; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<...> | u... import type {DeclarationJsonInput} from 'svelte-docinfo/types.js';

DeclarationKind
#

types.ts view source

also exported from index.ts

ZodEnum<{ function: "function"; type: "type"; variable: "variable"; class: "class"; interface: "interface"; enum: "enum"; component: "component"; snippet: "snippet"; namespace: "namespace"; }> import type {DeclarationKind} from 'svelte-docinfo/types.js';

The kind of top-level exported declaration.

Does not include 'constructor' — constructors only appear as MemberKind (nested in classes, interfaces, or types with construct signatures), never as top-level module exports.

DeclarationModifier
#

types.ts view source

also exported from index.ts

ZodEnum<{ public: "public"; protected: "protected"; readonly: "readonly"; static: "static"; abstract: "abstract"; getter: "getter"; setter: "setter"; }> import type {DeclarationModifier} from 'svelte-docinfo/types.js';

TypeScript modifier keywords extracted from declarations.

Only modifiers that appear on public API members are included. Private members (including #field syntax) are filtered out during analysis. Protected members are included as part of the extension API.

DEFAULT_SOURCE_OPTIONS
#

source-config.ts view source

also exported from index.ts

SourceOptionsDefaults import {DEFAULT_SOURCE_OPTIONS} from 'svelte-docinfo/source-config.js';

Default partial options for standard SvelteKit library structure.

Does not include projectRoot — use createSourceOptions to create complete options with your project root.

exclude is the single source of truth for filtering: globs applied at both discovery time (by globFiles/discoverFromExports) and analysis time (by isSource() against project-root-relative paths).

see also

  • ``createSourceOptions`` for the typical way to build complete options

deriveIncludePatterns
#

files.ts view source

also exported from index.ts

(sourcePaths: readonly string[]): string[] import {deriveIncludePatterns} from 'svelte-docinfo/files.js';

Build an include pattern array from source paths.

Each path becomes a <path>/**\/*.{ts,js,svelte,css,json} glob. Used by discoverSourceFiles to derive a default include from sourceOptions.sourcePaths when no explicit pattern is supplied — keeps the glob fallback consistent with custom sourcePaths instead of silently defaulting to src/lib.

sourcePaths

type readonly string[]

returns

string[]

examples

deriveIncludePatterns(['packages/foo', 'packages/bar']) // => ['packages/foo/**\/*.{ts,js,svelte,css,json}', 'packages/bar/**\/*.{ts,js,svelte,css,json}']

detectReactivity
#

typescript-extract-shared.ts view source

(initializer: Expression | undefined): "$state" | "$state.raw" | "$derived" | "$derived.by" | undefined import {detectReactivity} from 'svelte-docinfo/typescript-extract-shared.js';

Detect a Svelte 5 reactivity rune from a variable or property initializer.

Inspects the AST since runes erase to their inner type after type-checking. Returns undefined for any non-rune expression. See the Reactivity enum in types.ts for the rationale on running this on every file regardless of extension.

initializer

type Expression | undefined

returns

"$state" | "$state.raw" | "$derived" | "$derived.by" | undefined

Diagnostic
#

diagnostics.ts view source

also exported from index.ts

ZodDiscriminatedUnion<[ZodObject<{ symbolName: ZodString; file: ZodString; line: ZodOptional<ZodNumber>; column: ZodOptional<ZodNumber>; message: ZodString; severity: ZodEnum<...>; kind: ZodLiteral<...>; }, $strict>, ... 12 more ..., ZodObject<...>], "kind"> import type {Diagnostic} from 'svelte-docinfo/diagnostics.js';

Discriminated union of all diagnostic variants.

DiagnosticKind
#

diagnostics.ts view source

also exported from index.ts

ZodEnum<{ type_extraction_failed: "type_extraction_failed"; signature_analysis_failed: "signature_analysis_failed"; class_member_failed: "class_member_failed"; svelte_prop_failed: "svelte_prop_failed"; ... 9 more ...; resolver_failed: "resolver_failed"; }> import type {DiagnosticKind} from 'svelte-docinfo/diagnostics.js';

Discriminant for Diagnostic variant types.

DiagnosticSeverity
#

diagnostics.ts view source

also exported from index.ts

ZodEnum<{ error: "error"; warning: "warning"; }> import type {DiagnosticSeverity} from 'svelte-docinfo/diagnostics.js';

Diagnostic severity levels.

  • 'error' — analysis failed, declaration may be incomplete or missing data
  • 'warning' — partial success, something seems off but analysis continued

discoverFromExports
#

exports.ts view source

(options: ExportsDiscoveryOptions): Promise<ExportsDiscoveryResult> import {discoverFromExports} from 'svelte-docinfo/exports.js';

Discover source files using package.json exports field.

Reads package.json, parses exports, maps dist paths to source paths, expands wildcard patterns, and loads file content.

Returns {files: null} when no package.json or no exports field exists, signaling the caller to fall back to glob discovery. Returns {files: []} when exports exist but resolve no source files (likely misconfigured mapping).

For concrete exports, maps directly to source paths and verifies existence. For wildcard exports, globs the source directory for matching files.

options

discovery configuration

returns

Promise<ExportsDiscoveryResult>

ExportsDiscoveryResult with discovered files and any error diagnostics

discoverSourceFiles
#

discovery.ts view source

also exported from index.ts

(options: DiscoverSourceFilesOptions): Promise<DiscoverSourceFilesResult> import {discoverSourceFiles} from 'svelte-docinfo/discovery.js';

Discover source files from a project root.

Used internally by analyzeFromFiles for the discovery step. Standalone consumers can call it directly when they want the discovered file list without running full analysis.

Strategy is selected by discovery:

  • 'auto' (default) — try exports first, fall back to glob.
  • 'exports'exports only; throws if exports is missing or resolves to no source files. Combining with include is a configuration error and also throws.
  • 'glob' — glob only; include parameterizes the search.

Exclusion globs come from sourceOptions.exclude (the single source of truth, also applied at analysis time by isSource()).

options

discovery configuration

returns

Promise<DiscoverSourceFilesResult>

discovered files (content loaded) and any diagnostics from the exports step

throws

  • Error - in strict `'exports'` mode when `exports` is missing or

examples

const sourceOptions = createSourceOptions(process.cwd()); const {files, diagnostics} = await discoverSourceFiles({sourceOptions});

DiscoverSourceFilesOptions
#

discovery.ts view source

also exported from index.ts

DiscoverSourceFilesOptions import type {DiscoverSourceFilesOptions} from 'svelte-docinfo/discovery.js';

Options for discoverSourceFiles.

sourceOptions

Source options used to resolve the source directory for exports-based discovery.

sourceOptions.projectRoot is the resolution base for include globs and the sourceOptions.exclude glob patterns. Build via createSourceOptions (which normalizes) or pass a normalized return from normalizeSourceOptions.

sourceOptions.exclude is the single source of truth for exclusion globs — applied at both this discovery stage and analysis time (via isSource()).

type ModuleSourceOptions

include?

Glob patterns to include (relative to projectRoot).

Filter for glob-based discovery. When discovery is 'auto' (default), providing include collapses the chain to glob immediately. Combining include with discovery: 'exports' throws.

When omitted, the glob fallback derives an include pattern from sourceOptions.sourcePaths via deriveIncludePatterns, so custom sourcePaths (e.g., ['packages/foo']) discover files instead of silently defaulting to src/lib.

type Array<string>

discovery?

Discovery strategy.

type Discovery

default 'auto'

see also

  • {@link Discovery} for semantics of each variant

distDir?

Dist directory name relative to projectRoot, used for exports-based discovery.

Maps dist paths from package.json exports back to source paths.

type string

default 'dist'

log?

Optional logger for status messages.

type AnalysisLog

DiscoverSourceFilesResult
#

discovery.ts view source

also exported from index.ts

DiscoverSourceFilesResult import type {DiscoverSourceFilesResult} from 'svelte-docinfo/discovery.js';

files

Discovered source files with content already loaded.

type Array<SourceFileInfo>

diagnostics

Diagnostics collected during discovery (e.g., malformed package.json exports).

type Array<Diagnostic>

Discovery
#

discovery.ts view source

also exported from index.ts

Discovery import type {Discovery} from 'svelte-docinfo/discovery.js';

Discovery strategy for source files.

  • 'auto' (default) — try package.json exports first, fall back to glob patterns when exports is missing or resolves to nothing
  • 'exports' — package.json exports only, throw if exports is missing or resolves to no source files (strict mode for libraries that should always declare their public surface via exports)
  • 'glob' — skip exports entirely, use glob patterns

Providing include patterns implies 'glob' semantics regardless of mode — when discovery: 'auto' and include is set, the auto fallback chain collapses to glob immediately. Combining discovery: 'exports' with include is a configuration error (the modes are contradictory) and throws at discovery time.

DuplicateCommentDiagnostic
#

diagnostics.ts view source

ZodObject<{ commentType: ZodEnum<{ module_comment: "module_comment"; doc_comment: "doc_comment"; }>; file: ZodString; line: ZodOptional<ZodNumber>; column: ZodOptional<...>; message: ZodString; severity: ZodEnum<...>; kind: ZodLiteral<...>; }, $strict> import type {DuplicateCommentDiagnostic} from 'svelte-docinfo/diagnostics.js';

Duplicate comment sources detected (e.g., both HTML and JSDoc @module, or both HTML @component and JSDoc for component docComment).

DuplicateDeclaration
#

postprocess.ts view source

also exported from index.ts

DuplicateDeclaration import type {DuplicateDeclaration} from 'svelte-docinfo/postprocess.js';

A duplicate declaration with its full metadata and module path.

declaration

The full declaration metadata.

type DeclarationJson

module

Module path where this declaration is defined.

type string

DuplicateDeclarationDiagnostic
#

diagnostics.ts view source

ZodObject<{ declarationName: ZodString; modules: ZodArray<ZodString>; file: ZodString; line: ZodOptional<ZodNumber>; column: ZodOptional<...>; message: ZodString; severity: ZodEnum<...>; kind: ZodLiteral<...>; }, $strict> import type {DuplicateDeclarationDiagnostic} from 'svelte-docinfo/diagnostics.js';

A declaration name appears in more than one module.

Library docs assume a flat namespace — two modules exporting the same name collide when consumers import {name}. Emitted at warning severity so the analysis result remains usable; consumers who want it fatal can promote via onDuplicates: 'throw' or by inspecting the diagnostic. The default slot (name === 'default') is excluded — every module owns its own.

emitCallOrConstructSignature
#

typescript-extract-shared.ts view source

(getSignatures: () => readonly Signature[], signatureKind: "call" | "construct", resolveTsdocNode: (sig: Signature) => Node | undefined, paramValidationFallbackNode: Node, declaration: DeclarationJsonBuild, checker: TypeChecker, diagnostics: ({ ...; } | ... 12 more ... | { ...; })[], errorContext: { ...; }): void import {emitCallOrConstructSignature} from 'svelte-docinfo/typescript-extract-shared.js';

Append a (call) or (construct) signature member to a declaration.

Captures the extraction logic shared by interface processing (extractTypeInfo) and type-alias property processing (extractTypeAliasProperties): type signature, parameters, generics, overloads, and TSDoc. The TSDoc source node is supplied by the caller — interfaces look it up in node.members (skipping TSDoc when no inline signature is declared, even if one is inherited), type aliases use sig.getDeclaration().

getSignatures

thunk to retrieve getCallSignatures() / getConstructSignatures(); called inside the try so checker errors are captured as diagnostics

type () => readonly Signature[]

signatureKind

'call' (member kind: function, includes returnType) or 'construct' (member kind: constructor, no returnType)

type "call" | "construct"

resolveTsdocNode

callback returning the AST node to parse TSDoc from, or undefined to skip TSDoc resolution

type (sig: Signature) => Node | undefined

paramValidationFallbackNode

location used by validateParamKeys when resolveTsdocNode returns undefined

type Node

declaration

parent declaration (mutated; appended to members)

checker

type TypeChecker

diagnostics

type ({ symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | { functionName: string; ... 5 more ...; column?: number | undefined; } | ... 11 more ... | { ...; })[]

errorContext

type { node: Node; kindLabel: string; }

returns

void

mutates

  • declaration — appends a member when signatures are present;
  • diagnostics — adds `signature_analysis_failed` on checker error

ensureLexerReady
#

dep-resolver.ts view source

(): Promise<void> import {ensureLexerReady} from 'svelte-docinfo/dep-resolver.js';

Ensure es-module-lexer's wasm runtime is initialized.

Idempotent and cheap after the first call. The session awaits this once at the top of setFiles so phase 1's per-file lex is purely synchronous.

returns

Promise<void>

EnumDeclarationJson
#

types.ts view source

also exported from index.ts

ZodObject<{ kind: ZodLiteral<"enum">; members: ZodDefault<ZodArray<ZodDiscriminatedUnion<[ZodObject<{ kind: ZodLiteral<"function">; name: ZodString; optional: ZodDefault<ZodBoolean>; ... 15 more ...; genericParams: ZodDefault<...>; }, $strict>, ZodObject<...>, ZodObject<...>], "kind">>>; ... 14 more ...; genericPara... import type {EnumDeclarationJson} from 'svelte-docinfo/types.js';

An enum declaration. Has members for enum values.

errorsOf
#

diagnostics.ts view source

also exported from index.ts

(diagnostics: ({ symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | { functionName: string; ... 5 more ...; column?: number | undefined; } | ... 11 more ... | { ...; })[]): ({ ...; } | ... 12 more ... | { ...; })[] import {errorsOf} from 'svelte-docinfo/diagnostics.js';

Get all error-severity diagnostics.

diagnostics

type ({ symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | { functionName: string; ... 5 more ...; column?: number | undefined; } | ... 11 more ... | { ...; })[]

returns

({ symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | { functionName: string; ... 5 more ...; column?: number | undefined; } | ... 11 more ... | { ...; })[]

ExportEntry
#

exports.ts view source

ExportEntry import type {ExportEntry} from 'svelte-docinfo/exports.js';

A parsed entry from package.json exports field.

specifier

The export specifier (e.g., ".", "./*.js").

type string

isPattern

Whether the specifier contains a wildcard (*).

type boolean

conditions

Resolved dist paths by condition (e.g., {types: "./dist/index.d.ts", default: "./dist/index.js"}).

type Record<string, string>

ExportsDiscoveryOptions
#

exports.ts view source

ExportsDiscoveryOptions import type {ExportsDiscoveryOptions} from 'svelte-docinfo/exports.js';

Options for discoverFromExports.

projectRoot

Absolute path to project root.

type string

distDir?

Dist directory name relative to projectRoot. Default: 'dist'.

type string

sourceDir?

Source directory name relative to projectRoot. Default: 'src/lib'.

type string

exclude?

Glob patterns to exclude from discovered files.

type Array<string>

ExportsDiscoveryResult
#

exports.ts view source

ExportsDiscoveryResult import type {ExportsDiscoveryResult} from 'svelte-docinfo/exports.js';

Result of discovering source files from package.json exports.

Self-contained: includes both the discovered files and any error diagnostics (e.g., files that exist but could not be read).

files

Discovered source files, or null if no exports field found. Empty array means exports field exists but resolved no source files (likely a misconfigured dist-to-source mapping).

type Array<SourceFileInfo> | null

diagnostics

Error diagnostics for files that exist but could not be read.

type Array<Diagnostic>

ExportSurface
#

postprocess.ts view source

also exported from index.ts

ExportSurface import type {ExportSurface} from 'svelte-docinfo/postprocess.js';

A module's resolved export surface — see resolveExportSurface.

entries

Surface entries, sorted by name (case-insensitive order, compareStrings).

type Array<ExportSurfaceEntry>

unresolvedStarExports

Star targets (own or transitive) absent from the analyzed set — their projected names are unknown, so the surface is incomplete.

type Array<string>

externalStarExports

External star specifiers reachable from this module (own or transitive) — their projected names are unknowable without analyzing the package.

type Array<string>

ExportSurfaceEntry
#

postprocess.ts view source

also exported from index.ts

ExportSurfaceEntry import type {ExportSurfaceEntry} from 'svelte-docinfo/postprocess.js';

One name on a module's resolved export surface.

name

Exported name, in the docinfo model's terms — Svelte components appear under their filename-derived name (the model's convention for default exports of .svelte files), not 'default'.

type string

via

How the name reaches this module's surface: an own declaration (including synthesized aliases), a same-name re-export edge, a direct external re-export, or projection through export * from './x'.

type 'declaration' | 'reExport' | 'external' | 'star'

module?

Canonical module path, when known (undefined for external entries).

type string

declaration?

The canonical declaration, when present in the analyzed set.

type DeclarationJson

specifier?

Package specifier for external entries (as written in the statement).

type string

originalName?

Name inside the external package when renamed.

type string

typeOnly?

Type-only re-export — the name is erased at runtime.

type boolean

starFrom?

For star-projected entries: the starExports target the name arrived through.

type string

ExternalReExportJson
#

types.ts view source

also exported from index.ts

ZodObject<{ name: ZodString; specifier: ZodString; originalName: ZodOptional<ZodString>; typeOnly: ZodDefault<ZodBoolean>; sourceLine: ZodOptional<...>; }, $strict> import type {ExternalReExportJson} from 'svelte-docinfo/types.js';

A re-export whose immediate target is outside the analyzed source set — export {x} from 'pkg', export {x as y} from 'pkg', or export * as ns from 'pkg'.

specifier is the module specifier as written (usually a package name); there is no canonical declaration to resolve, so these entries are flat facts about the statement rather than edges into the module graph.

Only statements that *directly* reference the external specifier are captured. Forms that stay silent: import {x} from 'pkg'; export {x}; (import-then-export), re-export chains that reach a package through another source module (that module owns the entry), and specifiers the checker can't resolve. Statement-level @nodocs suppresses the entry.

ExternalReExportJsonInput
#

types.ts view source

{ name: string; specifier: string; originalName?: string | undefined; typeOnly?: boolean | undefined; sourceLine?: number | undefined; } import type {ExternalReExportJsonInput} from 'svelte-docinfo/types.js';

name

Public exported name from this module.

type string

specifier

Module specifier as written in the statement (e.g. 'pkg').

type string

originalName?

The name inside the external module when renamed (export {x as y} from 'pkg''x'). Omitted for same-name re-exports and namespace form (export * as ns).

type string

typeOnly?

Whether the statement or specifier is type-only — see ReExportJson.typeOnly.

type boolean

sourceLine?

1-based line of the export specifier in this module's source.

type number

extractClassInfo
#

typescript-extract-class.ts view source

(node: Node, checker: TypeChecker, declaration: DeclarationJsonBuild, diagnostics: ({ symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | ... 12 more ... | { ...; })[]): void import {extractClassInfo} from 'svelte-docinfo/typescript-extract-class.js';

Extract class information with rich member metadata.

node

the declaration AST node

type Node

checker

TypeScript type checker

type TypeChecker

declaration

the declaration to populate

diagnostics

diagnostics collector for non-fatal issues

type ({ symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | { functionName: string; ... 5 more ...; column?: number | undefined; } | ... 11 more ... | { ...; })[]

returns

void

mutates

  • declaration — adds extends, implements, genericParams, members

extractDependencies
#

source-config.ts view source

(sourceFile: SourceFileInfo & { dependents?: readonly string[] | undefined; }, options: ModuleSourceOptions): { dependencies: string[]; dependents: string[]; } import {extractDependencies} from 'svelte-docinfo/source-config.js';

Extract dependencies and dependents for a module from source file info.

Filters to only include source modules (excludes external packages, node_modules, tests). Returns sorted arrays of module paths (relative to sourceRoot) for deterministic output.

Native paths in sourceFile.dependencies/dependents are accepted — isSource and extractPath posixify their inputs, so direct callers with hand-built input need not pre-normalize.

Accepts SourceFileInfo plus an optional dependents field — the public input type carries only dependencies (caller-supplied opt-in), while dependents is computed downstream by computeDependents and flows through as an enriched shape.

sourceFile

the source file info to extract dependencies from

type SourceFileInfo & { dependents?: readonly string[] | undefined; }

options

module source options for filtering and path extraction

returns

{ dependencies: string[]; dependents: string[]; }

sorted arrays of module paths (relative to sourceRoot) for dependencies and dependents

extractEnumInfo
#

typescript-extract-type.ts view source

(node: Node, checker: TypeChecker, declaration: DeclarationJsonBuild, diagnostics: ({ symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | ... 12 more ... | { ...; })[]): void import {extractEnumInfo} from 'svelte-docinfo/typescript-extract-type.js';

Extract enum member information from an enum declaration.

Iterates node.members to extract each enum member's name, initializer value, type, and JSDoc. Members are represented as MemberJson with kind 'variable'.

node

type Node

checker

type TypeChecker

declaration

diagnostics

type ({ symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | { functionName: string; ... 5 more ...; column?: number | undefined; } | ... 11 more ... | { ...; })[]

returns

void

mutates

  • declaration — adds members and typeSignature

extractFunctionInfo
#

typescript-extract-function.ts view source

(node: Node, symbol: Symbol, checker: TypeChecker, declaration: DeclarationJsonBuild, tsdoc: TsdocParsedComment | undefined, diagnostics: ({ ...; } | ... 12 more ... | { ...; })[]): void import {extractFunctionInfo} from 'svelte-docinfo/typescript-extract-function.js';

Extract function/method information including parameters with descriptions and default values.

node

the declaration AST node

type Node

symbol

the TypeScript symbol

type Symbol

checker

TypeScript type checker

type TypeChecker

declaration

the declaration to populate

tsdoc

parsed TSDoc comment (if available)

type TsdocParsedComment | undefined

diagnostics

diagnostics collector for non-fatal issues

type ({ symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | { functionName: string; ... 5 more ...; column?: number | undefined; } | ... 11 more ... | { ...; })[]

returns

void

mutates

  • declaration — adds typeSignature, returnType, returnDescription, parameters, genericParams, overloads (and `partial: true` on signature failure)
  • diagnostics — adds `signature_analysis_failed` diagnostic on checker error

extractHtmlModuleComment
#

svelte.ts view source

(svelteSource: string): string | undefined import {extractHtmlModuleComment} from 'svelte-docinfo/svelte.js';

Extract @module comment from HTML comments in Svelte source.

Scans all <!-- ... --> comments for one containing @module at the start of a line. This allows @component and @module to coexist as separate HTML comments. Works for template-only components.

svelteSource

the full Svelte source code

type string

returns

string | undefined

the cleaned module comment text, or undefined if no @module HTML comment found

extractModifiers
#

typescript-extract-shared.ts view source

(modifiers: readonly ModifierLike[] | undefined): ("public" | "protected" | "readonly" | "static" | "abstract" | "getter" | "setter")[] import {extractModifiers} from 'svelte-docinfo/typescript-extract-shared.js';

Extract modifier keywords from a node's modifiers.

Returns an array of modifier strings like ['public', 'readonly', 'static'].

modifiers

type readonly ModifierLike[] | undefined

returns

("public" | "protected" | "readonly" | "static" | "abstract" | "getter" | "setter")[]

extractModuleComment
#

typescript-exports.ts view source

(sourceFile: SourceFile): string | undefined import {extractModuleComment} from 'svelte-docinfo/typescript-exports.js';

Extract module-level comment.

sourceFile

type SourceFile

returns

string | undefined

cleaned module comment text (with @module line removed), or undefined if no @module comment found

see also

extractModuleScriptContent
#

svelte.ts view source

(svelteSource: string): string | undefined import {extractModuleScriptContent} from 'svelte-docinfo/svelte.js';

Extract the content of the module <script> tag from Svelte source.

Counterpart of extractScriptContent with the same attribute test inverted: matches only module scripts (<script module>, <script context="module">), so the two partition a source's script tags consistently.

svelteSource

type string

returns

string | undefined

the module script tag content, or undefined if no module script is found

extractPath
#

source-config.ts view source

(sourceId: string, options: ModuleSourceOptions): string import {extractPath} from 'svelte-docinfo/source-config.js';

Extract module path relative to source root from absolute source ID.

Uses proper path semantics: strips projectRoot/sourceRoot/ prefix.

sourceId

absolute path to the source file

type string

options

module source options for path extraction

returns

string

examples

const options = createSourceOptions('/home/user/project'); extractPath('/home/user/project/src/lib/foo.ts', options) // => 'foo.ts' extractPath('/home/user/project/src/lib/nested/bar.svelte', options) // => 'nested/bar.svelte'
const options = createSourceOptions('/home/user/project', { sourcePaths: ['src/lib', 'src/routes'], sourceRoot: 'src', }); extractPath('/home/user/project/src/lib/foo.ts', options) // => 'lib/foo.ts' extractPath('/home/user/project/src/routes/page.svelte', options) // => 'routes/page.svelte'

extractScriptContent
#

svelte.ts view source

(svelteSource: string): string | undefined import {extractScriptContent} from 'svelte-docinfo/svelte.js';

Extract the content of the main <script> tag from Svelte source.

Matches <script> with any attributes (e.g., lang, generics) but excludes module scripts (<script module>, <script context="module">).

svelteSource

type string

returns

string | undefined

the script tag content, or undefined if no matching script tag is found

extractSignatureParameters
#

typescript-extract-shared.ts view source

(sig: Signature, checker: TypeChecker, tsdocParams: Record<string, string> | undefined): { name: string; type: string; optional: boolean; rest: boolean; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<...> | undefined; }[] import {extractSignatureParameters} from 'svelte-docinfo/typescript-extract-shared.js';

Extract parameters from a TypeScript signature with TSDoc descriptions and default values.

Shared helper for extracting parameter information from both standalone functions and class methods/constructors.

sig

the TypeScript signature to extract parameters from

type Signature

checker

TypeScript type checker for type resolution

type TypeChecker

tsdocParams

record of parameter names to TSDoc descriptions (from TsdocParsedComment.params)

type Record<string, string> | undefined

returns

{ name: string; type: string; optional: boolean; rest: boolean; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<string, string> | undefined; }[]

array of ParameterJson objects

extractSnippetParameters
#

svelte.ts view source

(snippetType: Type, checker: TypeChecker): { name: string; type: string; optional?: boolean | undefined; rest?: boolean | undefined; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<...> | undefined; }[] import {extractSnippetParameters} from 'svelte-docinfo/svelte.js';

Extract structured parameters from a Snippet<[...]> type.

Snippet is an interface, so type arguments are on TypeReference (accessed via checker.getTypeArguments), not on aliasTypeArguments (which is only for type aliases).

Returns full ParameterJson input objects (with optional and rest always set) for runtime consistency with extractSignatureParameters in typescript-extract-shared.ts.

snippetType

type Type

checker

type TypeChecker

returns

{ name: string; type: string; optional?: boolean | undefined; rest?: boolean | undefined; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<...> | undefined; }[]

array of parameter info for the snippet's tuple type arguments, or [] for bare Snippet / Snippet<[]>

extractSvelteModuleComment
#

svelte.ts view source

(scriptContent: string): string | undefined import {extractSvelteModuleComment} from 'svelte-docinfo/svelte.js';

Extract module-level comment from Svelte script content.

Parses the script content as TypeScript and delegates to extractModuleComment for the shared @module tag detection logic. Works on either script's content — instance <script> and <script module> (see extractScriptContent/extractModuleScriptContent).

scriptContent

the content of a <script> or <script module> tag

type string

returns

string | undefined

the cleaned module comment text, or undefined if none found

extractTypeAliasProperties
#

typescript-extract-type-properties.ts view source

(node: TypeAliasDeclaration, nodeType: Type, checker: TypeChecker, declaration: DeclarationJsonBuild, diagnostics: ({ ...; } | ... 12 more ... | { ...; })[], isExternalFile: IsExternalFile): void import {extractTypeAliasProperties} from 'svelte-docinfo/typescript-extract-type-properties.js';

Extract properties from a type alias via the TypeScript checker API.

Handles object literals, intersections, mapped types (Partial, Pick, Readonly, etc.), type references, and function types. Extracts:

  • Named properties (with readonly/optional detection, TSDoc from declarations)
  • Index signatures (string/number)
  • Call signatures ((call))
  • Construct signatures ((construct))

node

type TypeAliasDeclaration

nodeType

type Type

checker

type TypeChecker

declaration

diagnostics

type ({ symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | { functionName: string; ... 5 more ...; column?: number | undefined; } | ... 11 more ... | { ...; })[]

isExternalFile

returns

void

mutates

  • declaration — adds members

extractTypeInfo
#

typescript-extract-type.ts view source

(node: Node, checker: TypeChecker, declaration: DeclarationJsonBuild, diagnostics: ({ symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | ... 12 more ... | { ...; })[], isExternalFile: IsExternalFile): void import {extractTypeInfo} from 'svelte-docinfo/typescript-extract-type.js';

Extract type/interface information with rich property metadata.

node

the declaration AST node

type Node

checker

TypeScript type checker

type TypeChecker

declaration

the declaration to populate

diagnostics

diagnostics collector for non-fatal issues

type ({ symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | { functionName: string; ... 5 more ...; column?: number | undefined; } | ... 11 more ... | { ...; })[]

isExternalFile

returns

void

mutates

  • declaration — adds typeSignature, genericParams, extends, intersects, members (and `partial: true` on extraction failure)
  • diagnostics — adds `type_extraction_failed` / `signature_analysis_failed` diagnostics on checker errors

extractVariableInfo
#

typescript-extract-function.ts view source

(node: Node, symbol: Symbol, checker: TypeChecker, declaration: DeclarationJsonBuild, diagnostics: ({ symbolName: string; file: string; ... 4 more ...; column?: number | undefined; } | ... 12 more ... | { ...; })[]): void import {extractVariableInfo} from 'svelte-docinfo/typescript-extract-function.js';

Extract variable information.

node

the declaration AST node

type Node

symbol

the TypeScript symbol

type Symbol

checker

TypeScript type checker

type TypeChecker

declaration

the declaration to populate

diagnostics

diagnostics collector for non-fatal issues

type ({ symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | { functionName: string; ... 5 more ...; column?: number | undefined; } | ... 11 more ... | { ...; })[]

returns

void

mutates

  • declaration — adds typeSignature, reactivity (when initialized with a Svelte rune)

filterExternalProperties
#

typescript-extract-shared.ts view source

(type: Type, typeNode: Node, checker: TypeChecker, isExternalFile: IsExternalFile): { properties: Symbol[]; externalTypes: string[]; } import {filterExternalProperties} from 'svelte-docinfo/typescript-extract-shared.js';

Partition a type's properties into local (kept) and external (dropped), and collect the external type references that contributed the dropped ones.

Applies to any composition shape — intersection, union, bare reference, indexed-access — not only intersections. Membership is decided per property by declaration origin (isExternalProperty), which is structure-agnostic: TypeScript preserves original declaration sources on derived properties, so the test gives the right answer through utility-type wrappers (Partial, Pick, OmitStrict) too. A property with no declarations (synthesized) is treated as local and kept. The external-type labels for intersects come from an AST walk (collectExternalTypeRefs) — the authoritative source for the &/|/index-access shape inference would otherwise erase.

type

type Type

typeNode

type Node

checker

type TypeChecker

isExternalFile

returns

{ properties: Symbol[]; externalTypes: string[]; }

findDuplicates
#

postprocess.ts view source

also exported from index.ts

(modules: { path: string; declarations: ({ kind: "function"; parameters: { name: string; type: string; optional: boolean; rest: boolean; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<...> | undefined; }[]; ... 17 more ...; sourceLine?: number | undefined; } | ... 7 more ... | { ...; })[]; ... 7 more ...; moduleComment?: string | undefined; }[]): Map<...> import {findDuplicates} from 'svelte-docinfo/postprocess.js';

Find duplicate declaration names across modules.

A duplicate is two *different things* sharing a name in the flat namespace. Occurrences are compared by canonical identity — aliasOf chains are resolved first, so an alias and its canonical (or two aliases of the same canonical) are one thing, not a collision. Documenting a same-name re-export (which synthesizes an alias) or re-exporting a component under its own name (export {default as Foo} from './Foo.svelte') therefore doesn't flag. When a name does flag, all occurrences are reported, aliases included.

Callers can decide how to handle duplicates (throw, warn, ignore).

modules

type { path: string; declarations: ({ kind: "function"; parameters: { name: string; type: string; optional: boolean; rest: boolean; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<...> | undefined; }[]; ... 17 more ...; sourceLine?: number | undefined; } | ... 7 more ......

returns

Map<string, DuplicateDeclaration[]>

Map of declaration names to their DuplicateDeclaration occurrences (only includes duplicates)

examples

const duplicates = findDuplicates(modules); if (duplicates.size > 0) { for (const [name, occurrences] of duplicates) { console.error(`"${name}" found in:`); for (const {declaration, module} of occurrences) { console.error(` - ${module}:${declaration.sourceLine} (${declaration.kind})`); } } throw new Error(`Found ${duplicates.size} duplicate declaration names`); }

findTypeReferences
#

declaration-helpers.ts view source

also exported from index.ts

(typeString: string, declarationNames: ReadonlySet<string> | [string, RegExp][]): string[] import {findTypeReferences} from 'svelte-docinfo/declaration-helpers.js';

Find in-project declaration names referenced in a type string.

Uses identifier-boundary matching to find which known declaration names appear in an opaque type string (e.g., typeSignature, returnType, parameter type). Enables consumers to render clickable type links without needing access to the TypeScript type checker.

Handles identifiers starting with $ (e.g., $state) which \b does not recognize as word boundaries.

Accepts either a ReadonlySet<string> (convenience) or pre-compiled patterns from buildTypeReferencePatterns (performance). Use pre-compiled patterns when scanning many type strings against the same declaration set.

Known limitations: Identifier-boundary matching can produce false positives when a declaration name appears as a property key in an object literal type (e.g., { Foo: string } when Foo is a declaration). This is rare in practice.

typeString

opaque type string from analysis output

type string

declarationNames

set of names or pre-compiled patterns from buildTypeReferencePatterns

type ReadonlySet<string> | [string, RegExp][]

returns

string[]

array of declaration names found in the type string

examples

const names = new Set(modules.flatMap(m => m.declarations.map(d => d.name))); findTypeReferences('Map<string, ModuleJson[]>', names) // => ['ModuleJson']

formatDiagnostic
#

diagnostics.ts view source

also exported from index.ts

(diagnostic: { symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | { functionName: string; ... 5 more ...; column?: number | undefined; } | ... 11 more ... | { ...; }): string import {formatDiagnostic} from 'svelte-docinfo/diagnostics.js';

Format a diagnostic for display.

Assumes diagnostic.file is project-root-relative (the contract enforced by analyze / analyzeFromFiles). The displayed path is prefixed with ./.

diagnostic

the diagnostic to format

type { symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | { functionName: string; ... 5 more ...; column?: number | undefined; } | ... 11 more ... | { ...; }

returns

string

formatted string like './file.ts:10:5: error: message'

examples

for (const d of errorsOf(diagnostics)) { console.error(formatDiagnostic(d)); }

FunctionDeclarationJson
#

types.ts view source

also exported from index.ts

ZodObject<{ kind: ZodLiteral<"function">; returnType: ZodOptional<ZodString>; returnDescription: ZodOptional<ZodString>; ... 16 more ...; genericParams: ZodDefault<...>; }, $strict> import type {FunctionDeclarationJson} from 'svelte-docinfo/types.js';

A function declaration. Has parameters, returnType, returnDescription, overloads.

FunctionMemberJson
#

types.ts view source

also exported from index.ts

ZodObject<{ kind: ZodLiteral<"function">; name: ZodString; optional: ZodDefault<ZodBoolean>; returnType: ZodOptional<ZodString>; ... 14 more ...; genericParams: ZodDefault<...>; }, $strict> import type {FunctionMemberJson} from 'svelte-docinfo/types.js';

A function member (method, call signature, method signature). Has parameters, returnType, returnDescription, overloads.

optional reflects a ? token on the declaration (e.g., foo?(): void on an interface or type literal). Always false for index/call/construct signatures and for class methods (TypeScript disallows optional methods on classes).

name is the user-chosen method/property identifier, except for call signatures on interfaces and type aliases where it is the literal sentinel '(call)'.

generateImport
#

declaration-helpers.ts view source

also exported from index.ts

(declaration: { kind: "function"; parameters: { name: string; type: string; optional: boolean; rest: boolean; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<...> | undefined; }[]; ... 17 more ...; sourceLine?: number | undefined; } | ... 7 more ... | { ...; }, modulePath: string, libraryName: string): string import {generateImport} from 'svelte-docinfo/declaration-helpers.js';

Generate TypeScript import statement for a declaration.

Produces import type for type/interface declarations, import for values.

Default export handling: when declaration.name === 'default', emits import X from '...' with the binding derived by PascalCasing the module path. ('default' is the symbol's actual name in JS — import X from 'mod' is sugar for import {default as X} from 'mod'.)

declaration

the DeclarationJson to generate an import for

type { kind: "function"; parameters: { name: string; type: string; optional: boolean; rest: boolean; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<...> | undefined; }[]; ... 17 more ...; sourceLine?: number | undefined; } | ... 7 more ... | { ...; }

modulePath

module path relative to source root (e.g., foo.ts)

type string

libraryName

package name for the import specifier (e.g., @pkg/lib)

type string

returns

string

formatted import statement string

examples

generateImport({name: 'Foo', kind: 'type'}, 'foo.ts', '@pkg/lib') // => "import type {Foo} from '@pkg/lib/foo.js';" generateImport({name: 'default', kind: 'function'}, 'foo-bar.ts', '@pkg/lib') // => "import FooBar from '@pkg/lib/foo-bar.js';"

see also

  • ``getDisplayName`` for the divergent default-slot fallback used as a display label (the literal 'default', since a label has no use for a synthesized JS binding).

GenericParamJson
#

types.ts view source

also exported from index.ts

ZodObject<{ name: ZodString; constraint: ZodOptional<ZodString>; defaultType: ZodOptional<ZodString>; }, $strict> import type {GenericParamJson} from 'svelte-docinfo/types.js';

Generic type parameter metadata extracted from declarations like <T extends string = unknown>.

Present on functions, classes, interfaces, type aliases, and Svelte components that declare generic type parameters.

getComponentName
#

source.ts view source

(modulePath: string): string import {getComponentName} from 'svelte-docinfo/source.js';

Extract component name from a Svelte module path.

modulePath

type string

returns

string

examples

getComponentName('Alert.svelte') // => 'Alert' getComponentName('components/Button.svelte') // => 'Button'

getDefaultAnalyzer
#

source.ts view source

(path: string): AnalyzerType | null import {getDefaultAnalyzer} from 'svelte-docinfo/source.js';

Default analyzer resolver based on file extension.

  • .svelte'svelte'
  • .ts, .js'typescript'
  • .css'css'
  • .json'json'
  • Other extensions → null (skip)

path

type string

returns

AnalyzerType | null

getDisplayName
#

declaration-helpers.ts view source

also exported from index.ts

(declaration: { kind: "function"; name: string; optional: boolean; parameters: { name: string; type: string; optional: boolean; rest: boolean; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<...> | undefined; }[]; ... 14 more ...; sourceLine?: number | undefined; } | ... 10 more ... | { ...; }): string import {getDisplayName} from 'svelte-docinfo/declaration-helpers.js';

Format declaration or member name with generic parameters for display.

Default-slot entries return the literal 'default' (the symbol's actual name in JS). Renderers that want a richer label (PascalCased module path, an explicit "default export" header) should branch on name === 'default' themselves before calling this.

declaration

the DeclarationJson or MemberJson to format

type { kind: "function"; name: string; optional: boolean; parameters: { name: string; type: string; optional: boolean; rest: boolean; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<...> | undefined; }[]; ... 14 more ...; sourceLine?: number | undefined; } | ... 10 more ...

returns

string

name with generic parameters appended (e.g., Map<K, V>)

examples

getDisplayName({name: 'Map', kind: 'type', genericParams: [{name: 'K'}, {name: 'V'}]}) // => 'Map<K, V>'

see also

  • ``generateImport`` for the divergent default-slot fallback used in import-statement generation (PascalCased module path, since an import needs a JS identifier binding, not a label).

getNodeLocation
#

typescript-extract-shared.ts view source

(node: Node): { file: string; line: number; column: number; } import {getNodeLocation} from 'svelte-docinfo/typescript-extract-shared.js';

Extract line and column from a TypeScript node. Returns 1-based line and column numbers.

node

type Node

returns

{ file: string; line: number; column: number; }

getSourceRoot
#

source-config.ts view source

(options: ModuleSourceOptions): string import {getSourceRoot} from 'svelte-docinfo/source-config.js';

Get the effective sourceRoot from options.

Returns sourceRoot if provided, otherwise:

  • Single sourcePath: returns that path
  • Multiple sourcePaths: derives the longest common directory prefix

options

returns

string

the effective source root path

globFiles
#

files.ts view source

(options: GlobFilesOptions): Promise<SourceFileInfo[]> import {globFiles} from 'svelte-docinfo/files.js';

Discover source files via glob patterns.

options

glob configuration

returns

Promise<SourceFileInfo[]>

array of source files with content loaded

throws

  • Error - if any matched file cannot be read — `Promise.all` rejects on the first read failure

examples

const files = await globFiles({ projectRoot: process.cwd(), include: deriveIncludePatterns(['src/lib']), exclude: DEFAULT_SOURCE_OPTIONS.exclude, });

GlobFilesOptions
#

files.ts view source

GlobFilesOptions import type {GlobFilesOptions} from 'svelte-docinfo/files.js';

Options for globFiles.

projectRoot

Absolute path to project root.

type string

include

Glob patterns to include (relative to projectRoot).

type Array<string>

exclude?

Optional glob patterns to exclude.

type Array<string>

hasErrors
#

diagnostics.ts view source

also exported from index.ts

(diagnostics: ({ symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | { functionName: string; ... 5 more ...; column?: number | undefined; } | ... 11 more ... | { ...; })[]): boolean import {hasErrors} from 'svelte-docinfo/diagnostics.js';

Check if any error-severity diagnostics were collected.

diagnostics

type ({ symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | { functionName: string; ... 5 more ...; column?: number | undefined; } | ... 11 more ... | { ...; })[]

returns

boolean

hasWarnings
#

diagnostics.ts view source

also exported from index.ts

(diagnostics: ({ symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | { functionName: string; ... 5 more ...; column?: number | undefined; } | ... 11 more ... | { ...; })[]): boolean import {hasWarnings} from 'svelte-docinfo/diagnostics.js';

Check if any warning-severity diagnostics were collected.

diagnostics

type ({ symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | { functionName: string; ... 5 more ...; column?: number | undefined; } | ... 11 more ... | { ...; })[]

returns

boolean

ImportParseDiagnostic
#

diagnostics.ts view source

ZodObject<{ file: ZodString; line: ZodOptional<ZodNumber>; column: ZodOptional<ZodNumber>; message: ZodString; severity: ZodEnum<...>; kind: ZodLiteral<...>; }, $strict> import type {ImportParseDiagnostic} from 'svelte-docinfo/diagnostics.js';

Import parsing failed during dependency resolution.

ImportResolver
#

dep-resolver.ts view source

also exported from index.ts

ImportResolver import type {ImportResolver} from 'svelte-docinfo/dep-resolver.js';

Token-paired import resolver.

identity is a stable opaque token that keys the session's resolve cache alongside content. Cache hits require both (a) byte-for-byte identical source content and (b) identity equality. Naive function-reference keys would silently destroy cache reuse when callers wrap the resolver in fresh closures (a very common pattern in Vite/Rollup plugins) — opaque tokens lift the responsibility to the caller, where it can be done correctly.

resolve

Resolve an import specifier to an absolute file path, or null.

type ResolveImportFn

identity

Stable opaque token identifying this resolver's cache scope.

Two ImportResolvers with identity === to each other are treated as cache-equivalent. string for human-readable identities (e.g., 'vite-plugin-container'); symbol for generated sentinels.

type string | symbol

inferDeclarationKind
#

typescript-extract-shared.ts view source

(symbol: Symbol, node: Node): "function" | "type" | "variable" | "class" | "interface" | "enum" | "component" | "snippet" | "namespace" import {inferDeclarationKind} from 'svelte-docinfo/typescript-extract-shared.js';

Infer declaration kind from symbol and node.

Maps TypeScript constructs to DeclarationKind:

  • Classes → 'class'
  • Functions (declarations, expressions, arrows) → 'function'
  • Interfaces → 'interface'
  • Type aliases → 'type'
  • Enums (regular and const) → 'enum'
  • Variables → 'variable' (unless function-valued → 'function')

Note: namespace re-exports (export * as ns from './x') have no inline declaration form in TypeScript and are caught upstream in analyzeExports via classifyNamespaceReExport. They never reach this function. A direct call here on a ValueModule symbol would fall through to 'variable' and leak typeof import("/abs/path") into the output — keep the namespace dispatch in analyzeExports.

symbol

type Symbol

node

type Node

returns

"function" | "type" | "variable" | "class" | "interface" | "enum" | "component" | "snippet" | "namespace"

InterfaceDeclarationJson
#

types.ts view source

also exported from index.ts

ZodObject<{ kind: ZodLiteral<"interface">; extends: ZodDefault<ZodArray<ZodString>>; members: ZodDefault<ZodArray<ZodDiscriminatedUnion<[ZodObject<{ kind: ZodLiteral<"function">; ... 17 more ...; genericParams: ZodDefault<...>; }, $strict>, ZodObject<...>, ZodObject<...>], "kind">>>; ... 14 more ...; genericParams: ... import type {InterfaceDeclarationJson} from 'svelte-docinfo/types.js';

An interface declaration. Has members, extends.

isCss
#

source.ts view source

(path: string): boolean import {isCss} from 'svelte-docinfo/source.js';

Check if a path is a CSS file.

path

type string

returns

boolean

IsExternalFile
#

typescript-program.ts view source

IsExternalFile import type {IsExternalFile} from 'svelte-docinfo/typescript-program.js';

Predicate for determining whether a TypeScript source file is external to the project. Used by intersection type filtering to separate user-authored properties from library/framework properties.

Constructed from ModuleSourceOptions at analysis entry points — files under the source root (e.g., src/lib/) are internal, everything else is external.

(call)

type (sourceFile: SourceFile): boolean

sourceFile

type SourceFile
returns boolean

isExternalIntersectionBranch
#

typescript-extract-shared.ts view source

(branchNode: TypeNode, checker: TypeChecker, isExternalFile: IsExternalFile): boolean import {isExternalIntersectionBranch} from 'svelte-docinfo/typescript-extract-shared.js';

Determine whether an intersection branch refers to a type whose declarations all live in external files (e.g., HTMLAttributes<HTMLDivElement> from svelte's d.ts). Inline object-literal branches and unrecognized node shapes return false (treated as local).

branchNode

type TypeNode

checker

type TypeChecker

isExternalFile

returns

boolean

isJson
#

source.ts view source

(path: string): boolean import {isJson} from 'svelte-docinfo/source.js';

Check if a path is a JSON file.

path

type string

returns

boolean

isKind
#

declaration-helpers.ts view source

also exported from index.ts

<K extends DeclarationKind | MemberKind>(declaration: { kind: "function"; name: string; optional: boolean; parameters: { name: string; type: string; optional: boolean; rest: boolean; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<...> | undefined; }[]; ... 14 more ...; sourceLine?: number | undefined; } | ... 10 more ... | { ...; }, kind: K): declaration is Extract<...> | ... 10 more ... | Extract<...> import {isKind} from 'svelte-docinfo/declaration-helpers.js';

Narrow a declaration by kind for type-safe field access.

Works with both DeclarationJson (top-level) and MemberJson (nested). Accepts DeclarationKind | MemberKind so isKind(member, 'constructor') compiles.

declaration

type { kind: "function"; name: string; optional: boolean; parameters: { name: string; type: string; optional: boolean; rest: boolean; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<...> | undefined; }[]; ... 14 more ...; sourceLine?: number | undefined; } | ... 10 more ...

kind

type K

returns

boolean

generics

isKind<K extends DeclarationKind | MemberKind>
K
constraint DeclarationKind | MemberKind

examples

if (isKind(declaration, 'function')) { declaration.parameters; // FunctionDeclarationJson — has parameters declaration.returnType; // has returnType } if (isKind(member, 'constructor')) { member.parameters; // ConstructorMemberJson — has parameters }

isNodeBuiltin
#

dep-resolver.ts view source

(specifier: string): boolean import {isNodeBuiltin} from 'svelte-docinfo/dep-resolver.js';

Whether a lexed specifier names a Node builtin (fs, node:fs/promises, …).

Builtins can never be a project source file, so resolving them is pointless — and routing them through a host resolver (Vite/Rollup) makes that host emit "externalized for browser compatibility" warnings for browser-targeted configs. Callers skip resolution for these and treat them as unresolved (null), which the downstream isSource filter would do anyway.

specifier

type string

returns

boolean

isSnippetReturnType
#

svelte.ts view source

(returnType: string): boolean import {isSnippetReturnType} from 'svelte-docinfo/svelte.js';

Check if a return type string matches svelte2tsx's snippet return type pattern.

svelte2tsx transforms exported snippets into arrow functions with ReturnType<import('svelte').Snippet> as the return type annotation. The resolved return type includes unique symbol (from Svelte's non-exported SnippetReturn unique symbol) intersected with the branded render message. We match on both parts to avoid false positives — the branded message alone could theoretically be crafted by user code, but the unique symbol intersection cannot since SnippetReturn is not exported from svelte.

returnType

type string

returns

boolean

isSnippetTypeString
#

svelte.ts view source

(typeString: string): boolean import {isSnippetTypeString} from 'svelte-docinfo/svelte.js';

Check if a type string represents a Snippet type.

Uses the already-resolved type string (from checker.typeToString) for reliable detection. Snippet is an interface (not a type alias), so aliasSymbol is not available — type string matching is the reliable detection path.

typeString

type string

returns

boolean

isSource
#

source-config.ts view source

(path: string, options: ModuleSourceOptions): boolean import {isSource} from 'svelte-docinfo/source-config.js';

Check if a path is an analyzable source file.

Combines all filtering: source directory paths, exclude globs, and analyzer availability. This is the single check for whether a file should be included in library analysis.

Uses proper path semantics with startsWith matching against projectRoot/sourcePath/. No heuristics needed — nested directories are correctly excluded by the prefix check.

Order is sourceDir-then-exclude: the prefix check guarantees the path lives under projectRoot before relativization, so relative() always produces a clean glob-shaped string for the matcher. Files outside projectRoot (rare; would require monorepo path mapping) short-circuit at the prefix check before reaching the matcher.

path

full absolute path to check

type string

options

module source options for filtering

returns

boolean

true if the path is an analyzable source file

examples

const options = createSourceOptions('/home/user/project'); isSource('/home/user/project/src/lib/foo.ts', options) // => true isSource('/home/user/project/src/lib/styles.css', options) // => true isSource('/home/user/project/src/lib/data.json', options) // => true isSource('/home/user/project/src/lib/foo.test.ts', options) // => false (excluded) isSource('/home/user/project/src/fixtures/mini/src/lib/bar.ts', options) // => false (wrong prefix)

isSvelte
#

source.ts view source

(path: string): boolean import {isSvelte} from 'svelte-docinfo/source.js';

Check if a path is a Svelte component file.

path

type string

returns

boolean

isTypescript
#

source.ts view source

(path: string): boolean import {isTypescript} from 'svelte-docinfo/source.js';

Check if a path is a TypeScript or JS file.

Includes both .ts and .js files since JS files are valid in TS projects. Excludes .d.ts declaration files — use a custom getAnalyzerType to include them.

path

type string

returns

boolean

lexImports
#

dep-resolver.ts view source

(content: string, fileId: string): string[] import {lexImports} from 'svelte-docinfo/dep-resolver.js';

Lex import specifiers from prepared content.

Sync — caller must have awaited ensureLexerReady at least once before invoking. For .svelte files, pass the svelte2tsx-transformed virtual content, not the raw .svelte source (which isn't lex-able as JS/TS).

Dynamic imports (import(specifier) with non-literal arg) are omitted.

content

prepared file content (TS/JS, or svelte2tsx virtual)

type string

fileId

absolute file path (used for error messages)

type string

returns

string[]

specifiers in declaration order

throws

  • Error - if lexing fails (malformed source). Callers should catch and

loadFile
#

files.ts view source

(path: string, projectRoot: string): Promise<SourceFileInfo> import {loadFile} from 'svelte-docinfo/files.js';

Load a single source file from disk.

Accepts either relative or absolute paths. Relative paths are resolved against projectRoot.

path

file path (relative to projectRoot or absolute)

type string

projectRoot

absolute path to project root

type string

returns

Promise<SourceFileInfo>

source file info with content loaded

throws

  • Error - if the file cannot be read (e.g., missing or permission denied)

examples

const file = await loadFile('src/lib/math.ts', process.cwd()); // {id: '/abs/path/to/src/lib/math.ts', content: '...'}

loadTsconfig
#

typescript-program.ts view source

(options?: LoadTsconfigOptions | undefined, log?: AnalysisLog | undefined): { compilerOptions: CompilerOptions; rootFileNames: string[]; } import {loadTsconfig} from 'svelte-docinfo/typescript-program.js';

Load and parse tsconfig.json into compiler options + initial file list.

Shared by createAnalysisProgram and createAnalysisLanguageService so tsconfig-resolution behavior stays identical across the two paths. Also useful directly when a caller needs only CompilerOptions (e.g., import resolution via ts.resolveModuleName) without the cost of building a full ts.Program.

options?

type LoadTsconfigOptions | undefined
optional

log?

type AnalysisLog | undefined
optional

returns

{ compilerOptions: CompilerOptions; rootFileNames: string[]; }

throws

  • Error - if tsconfig.json (or the requested `tsconfigName`) is not found.

LoadTsconfigOptions
#

typescript-program.ts view source

LoadTsconfigOptions import type {LoadTsconfigOptions} from 'svelte-docinfo/typescript-program.js';

Base configuration shared by every entry point in this module.

projectRoot + tsconfig + compilerOptions together drive loadTsconfig, which is also exposed publicly. AnalysisProgramOptions and AnalysisLanguageServiceOptions extend this with their own fields.

projectRoot?

Absolute path to project root directory.

type string

default process.cwd()

tsconfig?

Path to tsconfig.json (relative to projectRoot).

type string

default 'tsconfig.json'

compilerOptions?

Compiler options merged on top of those parsed from tsconfig.json (per-key override; user-supplied keys win). Does not bypass the tsconfig.json file requirement — loadTsconfig still throws when no config file is found.

type ts.CompilerOptions

logo_svelte_docinfo
#

logo.ts view source

{ label: string; fill: string; paths: { d: string; }[]; } import {logo_svelte_docinfo} from 'svelte-docinfo/logo.js';

map_concurrent
#

concurrency.ts view source

<T, R>(items: readonly T[], concurrency: number, fn: (item: T, index: number) => Promise<R>): Promise<R[]> import {map_concurrent} from 'svelte-docinfo/concurrency.js';

Maps over items with a bounded number of in-flight promises, preserving input order.

Fail-fast: when fn rejects, the outer promise rejects with that error and idle workers stop pulling from the queue (already-in-flight fn calls run to completion — there's no AbortSignal plumbing). Subsequent rejections from in-flight calls are swallowed by Promise.all (only the first wins), so a misbehaving fn can't surface a second error after the function returns.

items

input array

type readonly T[]

concurrency

maximum number of concurrent operations

type number

fn

mapping function (receives item and index)

type (item: T, index: number) => Promise<R>

returns

Promise<R[]>

array of results in input order

generics

map_concurrent<T, R>
T
R

mapDistToSource
#

exports.ts view source

(distPath: string, condition: string, options: { distDir: string; sourceDir: string; }): string | null import {mapDistToSource} from 'svelte-docinfo/exports.js';

Map a dist file path to its source file path.

Replaces the dist directory prefix with the source directory and maps file extensions based on the export condition.

distPath

the dist path from exports (e.g., "./dist/index.js")

type string

condition

the export condition (e.g., "default", "svelte", "types")

type string

options

mapping configuration

type { distDir: string; sourceDir: string; }

returns

string | null

source path relative to project root, or null if not mappable

MAX_FILE_CONCURRENCY
#

MAX_RESOLVE_CONCURRENCY
#

MemberJson
#

types.ts view source

also exported from index.ts

ZodDiscriminatedUnion<[ZodObject<{ kind: ZodLiteral<"function">; name: ZodString; optional: ZodDefault<ZodBoolean>; returnType: ZodOptional<ZodString>; ... 14 more ...; genericParams: ZodDefault<...>; }, $strict>, ZodObject<...>, ZodObject<...>], "kind"> import type {MemberJson} from 'svelte-docinfo/types.js';

Metadata for a nested declaration within a class, interface, type, or enum.

Discriminated union on kind with 3 variants: FunctionMemberJson, VariableMemberJson, ConstructorMemberJson. Use isKind (in declaration-helpers.ts) to narrow, or check member.kind directly.

Does not include fields that exist on declarations but not on members (extends, intersects, implements, props, alsoExportedFrom, aliasOf).

Nesting is exactly one level deep — members never contain their own members.

MemberJsonBuild
#

declaration-build.ts view source

MemberJsonBuild import type {MemberJsonBuild} from 'svelte-docinfo/declaration-build.js';

Permissive type for constructing members incrementally before Zod validation.

Used by internal analysis functions in typescript-extract-*.ts that build members by mutating a plain object. The discriminated union schema (MemberJson) validates the final shape at the ModuleJson.parse() boundary.

Mirrors DeclarationJsonBuild for the same reason: construction sites determine kind at runtime, so TypeScript can't narrow the union during incremental field assignment.

name?

type string

kind

type MemberKind

docComment?

type string

typeSignature?

type string

modifiers?

type Array<DeclarationModifier>

sourceLine?

type number

genericParams?

type Array<GenericParamJson>

parameters?

type Array<z.input<typeof ParameterJson>>

returnType?

type string

returnDescription?

type string

overloads?

type Array<OverloadJsonInput>

examples?

type Array<string>

deprecatedMessage?

type string

seeAlso?

type Array<string>

throws?

type Array<{type?: string; description: string}>

since?

type string

mutates?

type Record<string, string>

reactivity?

type Reactivity

partial?

type boolean

optional?

Whether the member has a ? token in its declaration. Function and variable members only.

type boolean

defaultValue?

Default value documented via @default. Variable members only.

type string

MemberJsonInput
#

types.ts view source

{ kind: "function"; name: string; optional?: boolean | undefined; returnType?: string | undefined; returnDescription?: string | undefined; parameters?: { name: string; type: string; optional?: boolean | undefined; rest?: boolean | undefined; description?: string | undefined; defaultValue?: string | undefined; proper... import type {MemberJsonInput} from 'svelte-docinfo/types.js';

MemberKind
#

types.ts view source

also exported from index.ts

ZodEnum<{ function: "function"; variable: "variable"; constructor: "constructor"; }> import type {MemberKind} from 'svelte-docinfo/types.js';

The subset of declaration kinds that appear as nested members in classes, interfaces, and types.

Class members include constructors ('constructor'), methods ('function'), and properties/accessors ('variable'). Interface/type properties use the same kinds for property signatures, method signatures, index signatures, and call/construct signatures.

Top-level-only kinds ('class', 'interface', 'type', 'enum', 'component') never appear as members — nesting is exactly one level deep.

mergeReExports
#

postprocess.ts view source

also exported from index.ts

(modules: { path: string; declarations: ({ kind: "function"; parameters: { name: string; type: string; optional: boolean; rest: boolean; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<...> | undefined; }[]; ... 17 more ...; sourceLine?: number | undefined; } | ... 7 more ... | { ...; })[]; ... 7 more ...; moduleComment?: string | undefined; }[]): void import {mergeReExports} from 'svelte-docinfo/postprocess.js';

Build alsoExportedFrom arrays from the modules' forward re-export edges.

Each module carries its same-name re-export edges as ModuleJson.reExports (collected in phase 1); this phase-2 pass inverts them onto the canonical declarations so both directions of the same fact are queryable. Edges whose canonical module or declaration is absent from modules are skipped — the forward entry remains without a back-link (see ReExportJson for the presence caveats).

Component-only fields on renamed component aliases (props, acceptsChildren, etc.) are populated separately by resolveComponentAliases — call it after this function. They split because they touch disjoint fields and have different inputs.

modules

the modules array with all modules (will be mutated). Must be parsed ModuleJsons — wire JSON strips empty arrays, so run raw JSON through AnalyzeResultJson.parse first or reExports may be undefined

type { path: string; declarations: ({ kind: "function"; parameters: { name: string; type: string; optional: boolean; rest: boolean; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<...> | undefined; }[]; ... 17 more ...; sourceLine?: number | undefined; } | ... 7 more ......

returns

void

mutates

  • modules — unions re-exporters into `declaration.alsoExportedFrom`

examples

// helpers.ts exports: foo, bar // index.ts does: export {foo, bar} from './helpers.js' // (so index.ts's ModuleJson carries reExports: // [{name: 'foo', module: 'helpers.ts'}, {name: 'bar', module: 'helpers.ts'}]) // // After processing: // - helpers.ts foo declaration gets: alsoExportedFrom: ['index.ts'] // - helpers.ts bar declaration gets: alsoExportedFrom: ['index.ts']

MisplacedTagDiagnostic
#

diagnostics.ts view source

ZodObject<{ tagName: ZodEnum<{ default: "default"; mutates: "mutates"; throws: "throws"; since: "since"; example: "example"; deprecated: "deprecated"; see: "see"; nodocs: "nodocs"; }>; functionName: ZodOptional<...>; ... 5 more ...; kind: ZodLiteral<...>; }, $strict> import type {MisplacedTagDiagnostic} from 'svelte-docinfo/diagnostics.js';

A JSDoc tag found somewhere it has no effect.

Two contexts emit this:

  • Non-primary overload signature — symbol-scope tags (@example, @deprecated, @since, @see, @throws, @mutates, @default, @nodocs) describe the function as a whole, not individual signatures. The primary signature's JSDoc feeds the parent declaration's symbol-level extraction; tags on non-primary overload signatures are silently dropped from output. This diagnostic surfaces them so authors can move them to the primary signature. @default and @nodocs are included even though overloads never carry a defaultValue or per-overload exclusion: their presence on a non-primary signature is always a misplacement.
  • Module comment@nodocs has no module-level meaning (it applies to declarations and export statements); in a @module comment the tag does nothing except remain verbatim in moduleComment text. To omit a module from analysis, use exclude patterns instead.

ModuleAnalysis
#

declaration-build.ts view source

ModuleAnalysis import type {ModuleAnalysis} from 'svelte-docinfo/declaration-build.js';

Result of analyzing a module (TypeScript or Svelte).

Produced by analyzeTypescriptModule and analyzeSvelteModule. Both analyzers return this same structure for uniform handling by analyzeModule in analyze-core.ts.

inheritance

path

Module path relative to source root.

type string

dependencies

Dependencies (other source modules this module imports). Empty if none.

type Array<string>

dependents

Dependents (other source modules that import this module). Empty if none.

type Array<string>

ModuleExportsAnalysis
#

declaration-build.ts view source

ModuleExportsAnalysis import type {ModuleExportsAnalysis} from 'svelte-docinfo/declaration-build.js';

Result of analyzing a module's exports.

Produced by analyzeExports in typescript-exports.ts.

moduleComment?

Module-level documentation comment. Always undefined for svelte2tsx virtual files — analyzeSvelteModule extracts Svelte module comments from the original source instead.

type string

declarations

All exported declarations with @nodocs flags — consumer filters based on policy.

type Array<DeclarationAnalysis>

reExports

Same-name re-exports. Published as ModuleJson.reExports and consumed by mergeReExports in phase 2 to build alsoExportedFrom arrays on canonical declarations. Unsorted here and may contain exact duplicates (Svelte default-slot re-keying) — ordering and dedup are applied at publication in analyze-core.ts.

type Array<ReExportJsonInput>

starExports

Star exports (export * from './module') — module paths that are fully re-exported.

type Array<string>

externalReExports

Direct re-exports from external packages. Published as ModuleJson.externalReExports; unsorted here, sorted at publication.

type Array<ExternalReExportJsonInput>

externalStarExports

External star exports (export * from 'pkg') — specifiers as written.

type Array<string>

ModuleJson
#

types.ts view source

also exported from index.ts

ZodObject<{ path: ZodString; declarations: ZodDefault<ZodArray<ZodDiscriminatedUnion<[ZodObject<{ kind: ZodLiteral<"function">; returnType: ZodOptional<ZodString>; returnDescription: ZodOptional<...>; ... 16 more ...; genericParams: ZodDefault<...>; }, $strict>, ... 7 more ..., ZodObject<...>], "kind">>>; ... 7 more... import type {ModuleJson} from 'svelte-docinfo/types.js';

Metadata for a source module — the top-level container in the data model.

analyze and analyzeFromFiles return Array<ModuleJson> sorted alphabetically by path. Each module contains its exported declarations, dependency graph, and optional moduleComment.

ModuleJsonInput
#

types.ts view source

{ path: string; declarations?: ({ kind: "function"; name: string; returnType?: string | undefined; returnDescription?: string | undefined; parameters?: { name: string; type: string; optional?: boolean | undefined; rest?: boolean | undefined; description?: string | undefined; defaultValue?: string | undefined; proper... import type {ModuleJsonInput} from 'svelte-docinfo/types.js';

path

Path relative to sourceRoot (e.g., helpers.ts for the default SvelteKit src/lib layout). sourceRoot is configurable via createSourceOptions / the CLI --source-root flag — consumers with a custom layout (e.g., sourcePaths: ['src/lib', 'src/routes'], sourceRoot: 'src') see prefixes like lib/foo.ts here.

type string

declarations?

Exported declarations from this module.

type ({ kind: "function"; name: string; returnType?: string | undefined; returnDescription?: string | undefined; parameters?: { name: string; type: string; optional?: boolean | undefined; rest?: boolean | undefined; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<...> | ...

moduleComment?

File-level JSDoc comment (from @module tag).

type string

dependencies?

Modules this imports (paths relative to sourceRoot).

type string[]

dependents?

Modules that import this (paths relative to sourceRoot).

type string[]

starExports?

Modules fully re-exported via export * from './module'. Paths are relative to sourceRoot. Statement-level @nodocs suppresses the entry, like the other re-export encodings.

type string[]

reExports?

Same-name re-exports in this module's source, sorted by name then module (names can collide — see ReExportJson). The forward view of alsoExportedFrom — see ReExportJson for the full contract (canonical resolution, Svelte default-slot naming, @nodocs suppression, presence caveats).

type { name: string; module: string; typeOnly?: boolean | undefined; sourceLine?: number | undefined; }[]

externalReExports?

Re-exports whose immediate target is an external package, sorted by name then specifier. See ExternalReExportJson for which forms are captured.

type { name: string; specifier: string; originalName?: string | undefined; typeOnly?: boolean | undefined; sourceLine?: number | undefined; }[]

externalStarExports?

External modules fully re-exported via export * from 'pkg', as written (statement order). The projected names are unknown — the package isn't analyzed. Statement-level @nodocs suppresses the entry; unresolvable specifiers are skipped.

type string[]

partial?

Whether the module is a placeholder for a file that couldn't be analyzed.

Currently only set for Svelte files where svelte2tsx threw at ingest (the transform_failed diagnostic carries the error). Placeholder modules have declarations: [] and serve as a structural slot so the modules array reflects the full owned set; consumers render them as "broken" entries.

type boolean

ModuleSkippedDiagnostic
#

diagnostics.ts view source

ZodObject<{ reason: ZodEnum<{ not_in_program: "not_in_program"; no_analyzer: "no_analyzer"; requires_program: "requires_program"; }>; file: ZodString; line: ZodOptional<ZodNumber>; column: ZodOptional<...>; message: ZodString; severity: ZodEnum<...>; kind: ZodLiteral<...>; }, $strict> import type {ModuleSkippedDiagnostic} from 'svelte-docinfo/diagnostics.js';

Module was skipped during the analysis pass.

Always warning severity — the rest of the analysis still runs and the module's absence in modules reflects the skip. Reasons:

  • not_in_program — the file wasn't in the ts.Program (race between session ingest and query, or virtual file missing for a .svelte)
  • no_analyzer — file extension didn't match any analyzer
  • requires_program — Svelte file reached the non-Svelte dispatcher (caller should use the session API instead of analyzeModule directly)

Discovery-time file-read failures are a separate kind: module_unreadable.

ModuleSourceOptions
#

source-config.ts view source

also exported from index.ts

ModuleSourceOptions import type {ModuleSourceOptions} from 'svelte-docinfo/source-config.js';

Configuration for module source detection and path extraction.

Uses proper path semantics with projectRoot as the base for all path operations. Paths are matched using startsWith rather than substring search, which correctly handles nested directories without special heuristics.

examples

const options = createSourceOptions(process.cwd(), { sourcePaths: ['src/lib', 'src/routes'], sourceRoot: 'src', });

projectRoot

Path to the project root directory.

All sourcePaths are relative to this. Typically process.cwd(). Normalized (resolved to absolute, posixified to forward slashes, trailing slash stripped) by normalizeSourceOptions, which returns a new options object. Internal callers (isSource, extractPath) assume this is already POSIX form — construct via createSourceOptions / normalizeSourceOptions rather than building ModuleSourceOptions literals by hand on Windows.

type string

'/home/user/my-project'

sourcePaths

Source directory paths to include, relative to projectRoot.

Normalized (leading/trailing slashes stripped) by normalizeSourceOptions, which returns a new options object.

type Array<string>

['src/lib'] // single source directory
['src/lib', 'src/routes'] // multiple directories

sourceRoot?

Source root for extracting relative module paths, relative to projectRoot.

Normalized (leading/trailing slashes stripped; '.' collapsed to '') by normalizeSourceOptions, which returns a new options object.

When omitted:

  • Single sourcePath: defaults to that path
  • Multiple sourcePaths: auto-derived as the longest common directory prefix (or '' when paths share no common prefix — produces project-relative module paths)

type string

'src/lib' // module paths like 'foo.ts', 'utils/bar.ts'
'src' // module paths like 'lib/foo.ts', 'routes/page.svelte'
'' // or '.': module paths stay project-relative, e.g. 'src/lib/foo.ts'

exclude

Glob patterns to exclude from analysis, relative to projectRoot.

Applied at both stages of the pipeline:

  • Discovery time by globFiles/discoverFromExports, preventing matched files from being loaded.
  • Analysis time by isSource() against relative(projectRoot, absolutePath), catching files that enter through TypeScript import resolution (e.g., a source file imports a test helper).

analyzeFromFiles accepts a top-level exclude shortcut that merges into this field.

Compiled to a matcher once per options object via picomatch and cached by reference; mutating this array post-isSource-call has no effect — pass through normalizeSourceOptions (which returns a fresh object) or otherwise build a new options object to apply changes.

type Array<string>

default `['**\/*.test.ts', '**\/*.spec.ts']`

getAnalyzerType

Determine which analyzer to use for a file path.

Called for files in source directories. Return an AnalyzerType or null to skip:

  • 'typescript' — TypeScript/JS files analyzed via TypeScript compiler API
  • 'svelte' — Svelte components analyzed via svelte2tsx + TypeScript compiler API
  • 'css' — CSS files included as modules with no declarations
  • 'json' — JSON files included as modules with no declarations
  • null — skip the file

type (path: string) => AnalyzerType | null

default Uses file extension: `.svelte` → svelte, `.ts`/`.js` → typescript, `.css` → css, `.json` → json
// Add MDsveX support getAnalyzerType: (path) => { if (path.endsWith('.svelte') || path.endsWith('.svx')) return 'svelte'; if (path.endsWith('.ts') || path.endsWith('.js')) return 'typescript'; if (path.endsWith('.css')) return 'css'; if (path.endsWith('.json')) return 'json'; return null; }
// Include .d.ts files getAnalyzerType: (path) => { if (path.endsWith('.svelte')) return 'svelte'; if (path.endsWith('.ts') || path.endsWith('.d.ts') || path.endsWith('.js')) return 'typescript'; if (path.endsWith('.css')) return 'css'; if (path.endsWith('.json')) return 'json'; return null; }

ModuleUnreadableDiagnostic
#

diagnostics.ts view source

ZodObject<{ file: ZodString; line: ZodOptional<ZodNumber>; column: ZodOptional<ZodNumber>; message: ZodString; severity: ZodEnum<...>; kind: ZodLiteral<...>; }, $strict> import type {ModuleUnreadableDiagnostic} from 'svelte-docinfo/diagnostics.js';

File discovered via package.json exports exists but couldn't be read.

Always error severity — discovery-time, emitted by discoverFromExports when readFile fails (permission denied, FS error). Distinct from module_skipped so severity is a stable per-kind property and downstream consumers can route discovery failures separately from analysis-pass skips.

NamespaceDeclarationJson
#

types.ts view source

also exported from index.ts

ZodObject<{ kind: ZodLiteral<"namespace">; module: ZodString; alsoExportedFrom: ZodDefault<ZodArray<ZodString>>; aliasOf: ZodOptional<ZodObject<{ ...; }, $strict>>; ... 12 more ...; genericParams: ZodDefault<...>; }, $strict> import type {NamespaceDeclarationJson} from 'svelte-docinfo/types.js';

A namespace re-export binding: export * as ns from './x'.

Carries no inline members — module points to the source module whose declarations are projected under this name. Consumers that want to render ns.a can deref by reading the source module's declarations array.

noDepsResolver
#

dep-resolver.ts view source

ImportResolver import {noDepsResolver} from 'svelte-docinfo/dep-resolver.js';

Shared no-op ImportResolver for the "dependency resolution disabled" case.

Stable string identity ('no-deps') instead of a per-call symbol so that repeated ingests within a long-lived session cache-hit on identity. Each session still owns its own cache (entries live on the per-session owned map; sessions don't share state), but within one session every reference to noDepsResolver is === to every other — so a Vite re-save of byte-identical content with resolveDependencies: false exercises the cache-hit branch. The resolver always returns null, so any two calls with identical content under this identity produce identical resolution results — string identity correctly captures that. Used by both the one-shot analyzeFromFiles path and the long-lived Vite plugin (resolveDependencies: false).

normalizeDiagnosticPaths
#

analyze-core.ts view source

(diagnostics: ({ symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | { functionName: string; ... 5 more ...; column?: number | undefined; } | ... 11 more ... | { ...; })[], projectRoot: string): void import {normalizeDiagnosticPaths} from 'svelte-docinfo/analyze-core.js';

Normalize Diagnostic.file to project-root-relative form, in place.

Producers inside the analysis pipeline can write absolute paths or virtual paths (svelte2tsx output like Foo.svelte.__svelte2tsx__.ts). This pass collapses both to the public contract: a path relative to projectRoot with no leading slash and no ./ prefix.

Exposed for build-tool integrations that bypass the session and collect their own discovery/dep diagnostics — they need the same normalization to match the public contract.

diagnostics

type ({ symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | { functionName: string; ... 5 more ...; column?: number | undefined; } | ... 11 more ... | { ...; })[]

projectRoot

type string

returns

void

mutates

  • diagnostics — — rewrites each diagnostic's `file` field

normalizeResolveImport
#

dep-resolver.ts view source

also exported from index.ts

(value: ResolveImport | undefined): ImportResolver | undefined import {normalizeResolveImport} from 'svelte-docinfo/dep-resolver.js';

Normalize the public ResolveImport union to an ImportResolver.

Wraps a bare function via wrapResolveImport (fresh synthesized identity); passes a token-paired resolver through unchanged. undefined in, undefined out — callers fall back to the session default. Call once per logical resolver scope: at session construction for the default, per call for an override.

value

type ResolveImport | undefined

returns

ImportResolver | undefined

normalizeSourceOptions
#

source-config.ts view source

(options: ModuleSourceOptions): ModuleSourceOptions import {normalizeSourceOptions} from 'svelte-docinfo/source-config.js';

Normalize and validate ModuleSourceOptions, returning a new options object.

Normalization:

  • projectRoot resolved to absolute via path.resolve (relative paths resolve against cwd)
  • Trailing slash stripped from projectRoot
  • Leading/trailing slashes stripped from sourcePaths entries
  • Leading/trailing slashes stripped from sourceRoot (if provided)
  • sourceRoot of '.' is normalized to '' (project root sentinel)

Validation (after normalization):

  1. sourcePaths has at least one entry
  2. sourceRoot (if provided and non-empty) is a prefix of all sourcePaths

When sourceRoot is omitted and multiple sourcePaths are provided, sourceRoot is auto-derived as their longest common path prefix. If the paths share no common prefix, the derived root is '' and extractPath produces project-relative module paths.

Returns a fresh object — the input is not mutated. Re-normalization produces a fresh identity, which naturally invalidates the excludeMatcherCache (keyed by options-object identity) without a separate "rebuild a fresh object" rule.

options

returns

ModuleSourceOptions

a new ModuleSourceOptions with normalized fields

throws

  • Error - if validation fails

examples

// Normalization: slashes stripped, relative projectRoot resolved const normalized = normalizeSourceOptions({projectRoot: '.', sourcePaths: ['/src/lib/'], ...}); // normalized.projectRoot is now absolute, normalized.sourcePaths is ['src/lib']

OnDuplicates
#

analyze-core.ts view source

also exported from index.ts

OnDuplicates import type {OnDuplicates} from 'svelte-docinfo/analyze-core.js';

Behavior selector for duplicate declaration names across modules.

  • 'throw' — throw an Error listing every duplicate (strict flat-namespace enforcement)
  • 'warn' — log to log.error and continue
  • OnDuplicatesCallback — custom handler

Omitted entirely: no dispatch runs, but a duplicate_declaration diagnostic is still emitted into the diagnostics array for every collision (the diagnostic is the data; this option is the action).

'throw' trade-off: the throw fires after diagnostics are emitted but before the result is returned, so 'throw' callers never reach the diagnostics array. Callers that want fail-fast *and* diagnostic access should omit onDuplicates and inspect themselves:

const result = await analyze({...}); if (hasErrors(result.diagnostics)) throw new Error('analysis errors');

Or use an OnDuplicatesCallback and stash the data before throwing.

OnDuplicatesCallback
#

analyze-core.ts view source

also exported from index.ts

OnDuplicatesCallback import type {OnDuplicatesCallback} from 'svelte-docinfo/analyze-core.js';

Custom callback for handling duplicate declaration names.

Use the 'throw' or 'warn' shortcuts on onDuplicates for the common cases. Pass a function to fully control reporting.

(call)

type (duplicates: Map<string, DuplicateDeclaration[]>, log: Pick<AnalysisLog, "error">): void

duplicates

type Map<string, DuplicateDeclaration[]>

log

type Pick<AnalysisLog, "error">
returns void

OverloadJson
#

types.ts view source

also exported from index.ts

ZodObject<{ typeSignature: ZodString; parameters: ZodDefault<ZodArray<ZodObject<{ name: ZodString; type: ZodString; optional: ZodDefault<ZodBoolean>; rest: ZodDefault<...>; description: ZodOptional<...>; defaultValue: ZodOptional<...>; propertyDescriptions: ZodOptional<...>; }, $strict>>>; returnType: ZodOptional<..... import type {OverloadJson} from 'svelte-docinfo/types.js';

A single function overload signature.

When a function has multiple overload signatures, each public overload is captured here. The implementation signature is excluded.

OverloadJsonInput
#

types.ts view source

{ typeSignature: string; parameters?: { name: string; type: string; optional?: boolean | undefined; rest?: boolean | undefined; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<...> | undefined; }[] | undefined; returnType?: string | undefined; genericParams?: { ...;... import type {OverloadJsonInput} from 'svelte-docinfo/types.js';

typeSignature

Full TypeScript type signature for this overload.

type string

parameters?

Parameters for this overload.

type { name: string; type: string; optional?: boolean | undefined; rest?: boolean | undefined; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<...> | undefined; }[]

returnType?

Return type for this overload.

type string

genericParams?

Generic type parameters for this overload.

type { name: string; constraint?: string | undefined; defaultType?: string | undefined; }[]

docComment?

JSDoc/TSDoc comment specific to this overload.

type string

returnDescription?

Return value description from @returns tag on this overload.

type string

ParameterJson
#

types.ts view source

also exported from index.ts

ZodObject<{ name: ZodString; type: ZodString; optional: ZodDefault<ZodBoolean>; rest: ZodDefault<ZodBoolean>; description: ZodOptional<...>; defaultValue: ZodOptional<...>; propertyDescriptions: ZodOptional<...>; }, $strict> import type {ParameterJson} from 'svelte-docinfo/types.js';

Parameter information for functions and methods.

Kept distinct from ComponentPropJson despite structural similarity. Function parameters form a tuple with positional semantics: calling order matters (fn(a, b) vs fn(b, a)), may include rest parameters and destructuring patterns.

ParameterJsonInput
#

types.ts view source

{ name: string; type: string; optional?: boolean | undefined; rest?: boolean | undefined; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<...> | undefined; } import type {ParameterJsonInput} from 'svelte-docinfo/types.js';

name

Parameter name (e.g., options, ...args).

type string

type

Resolved TypeScript type string (e.g., string, Record<string, unknown>).

type string

optional?

Whether the parameter has a ? token.

type boolean

rest?

Whether the parameter uses rest syntax (...args).

type boolean

description?

Description from @param tag.

type string

defaultValue?

Default value expression from the source (e.g., 'hello', 42).

type string

propertyDescriptions?

Descriptions for properties of a named object parameter, from dotted @param tags (@param obj.prop - ...).

Keyed by the sub-path relative to this parameter — @param obj.prop becomes {prop: '...'}, @param obj.a.b becomes {'a.b': '...'}. Keys are unvalidated against the parameter's actual type (matching the @mutates philosophy); absent when no dotted @param tags reference this parameter. Only populated for function/method/constructor signature parameters.

Matching is by the parameter's name, so destructured parameters (fn({a, b}: T)) are not covered — TypeScript names them __0, with no author-facing identifier for a @param key to reference.

type Record<string, string>

parseComment
#

tsdoc.ts view source

(node: Node, sourceFile: SourceFile): TsdocParsedComment | undefined import {parseComment} from 'svelte-docinfo/tsdoc.js';

Parse JSDoc comment from a TypeScript node.

Extracts and parses all JSDoc tags including:

  • @param - parameter descriptions
  • @returns - return value description
  • @throws - error documentation
  • @example - code examples
  • @deprecated - deprecation warnings
  • @see - related references
  • @since - version information
  • @default - default value
  • @mutates - mutation documentation (non-standard)
  • @nodocs - exclusion flag (non-standard)

JSDoc blocks tagged @module are excluded entirely (text and tags): a module comment attaches to the file's first statement in the AST, and without the filter it would read as that statement's own docs. extractModuleComment (typescript-exports.ts) owns module comments.

node

the TypeScript node to extract JSDoc from

type Node

sourceFile

source file (used for extracting full @see tag text)

type SourceFile

returns

TsdocParsedComment | undefined

parsed comment with structured metadata, or undefined if no JSDoc found (or only @module blocks)

examples

const tsdoc = parseComment(declarationNode, sourceFile); if (tsdoc) { console.log(tsdoc.text); // main comment text console.log(tsdoc.params); // {paramName: 'description'} }

ParsedExports
#

exports.ts view source

ParsedExports import type {ParsedExports} from 'svelte-docinfo/exports.js';

Result of reading and parsing package.json exports.

entries

All parsed export entries.

type Array<ExportEntry>

hasExports

Whether the package.json had an exports field.

type boolean

parseGenericParam
#

typescript-extract-shared.ts view source

(param: TypeParameterDeclaration): { name: string; constraint?: string | undefined; defaultType?: string | undefined; } import {parseGenericParam} from 'svelte-docinfo/typescript-extract-shared.js';

Parse a TypeScript generic type parameter declaration into structured info.

param

the TypeScript type parameter declaration node

type TypeParameterDeclaration

returns

{ name: string; constraint?: string | undefined; defaultType?: string | undefined; }

structured GenericParamJson with name, constraint, and default type

parsePackageExports
#

exports.ts view source

(projectRoot: string): Promise<ParsedExports> import {parsePackageExports} from 'svelte-docinfo/exports.js';

Read and parse the exports field from package.json.

Handles all Node.js export formats: strings, objects with conditions, nested conditions, null exclusions, and wildcard patterns.

projectRoot

absolute path to project root

type string

returns

Promise<ParsedExports>

parsed ParsedExports, or {entries: [], hasExports: false} if no exports field

populateCallableMember
#

typescript-extract-shared.ts view source

(target: MemberJsonBuild | DeclarationJsonBuild, signatures: readonly Signature[], checker: TypeChecker, tsdoc: TsdocParsedComment | undefined, paramValidationNode: Node, name: string, diagnostics: ({ ...; } | ... 12 more ... | { ...; })[], includeReturn?: boolean): void import {populateCallableMember} from 'svelte-docinfo/typescript-extract-shared.js';

Populate the callable fields of a declaration or member from its call/construct signatures: typeSignature, parameters, overloads, and (unless includeReturn is false) returnType / returnDescription.

The shared core of every named-callable extractor — standalone functions, interface methods, class methods/constructors, and type-alias function properties. Callers differ in how they obtain signatures (symbol type, constructor declarations, property call signatures) and in their own try/catch + diagnostic kind, so those stay at the callsite; this captures only the identical projection from a resolved signature list onto the build target. No-op when signatures is empty.

target

declaration or member build object (mutated)

type MemberJsonBuild | DeclarationJsonBuild

signatures

public call/construct signatures (signatures[0] is primary)

type readonly Signature[]

checker

type TypeChecker

tsdoc

parsed TSDoc for the target (supplies @param/@returns)

type TsdocParsedComment | undefined

paramValidationNode

node validateParamKeys reports unknown_param against

type Node

name

target name, for diagnostic messages

type string

diagnostics

type ({ symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | { functionName: string; ... 5 more ...; column?: number | undefined; } | ... 11 more ... | { ...; })[]

includeReturn

set false for constructors (no return type/description)

type boolean
default true

returns

void

mutates

  • target — sets typeSignature, parameters, overloads, returnType, returnDescription
  • diagnostics — via `validateParamKeys` / `extractOverloads`

QueryOptions
#

session.ts view source

also exported from index.ts

QueryOptions import type {QueryOptions} from 'svelte-docinfo/session.js';

Per-call input to query.

onDuplicates?

Behavior when duplicate declaration names are found across modules.

type OnDuplicates

log?

Per-call logger override (defaults to the session-level logger).

type AnalysisLog

Reactivity
#

types.ts view source

also exported from index.ts

ZodEnum<{ $state: "$state"; "$state.raw": "$state.raw"; $derived: "$derived"; "$derived.by": "$derived.by"; }> import type {Reactivity} from 'svelte-docinfo/types.js';

Reactivity flavor for a variable declaration or class field, captured from the rune call at the initializer (e.g., let count = $state(0)).

Only the value-producing reactivity runes are represented here — $props and $bindable are modeled separately as ComponentPropJson.bindable (and prop-presence on the props array). A renderer wanting "all rune annotations across declarations and props" needs to read both this field and ComponentPropJson.bindable.

  • $state — deeply reactive proxy
  • $state.raw — reference-only reactive (no proxy)
  • $derived — recomputed from dependencies (re-assignable)
  • $derived.by — same as $derived, with a function argument

Detection is syntactic (AST-based) and runs on every analyzed file regardless of extension. Most reactive declarations live in .svelte, .svelte.ts, or .svelte.js, but the field will also surface on any .ts/.js file that uses the same rune call patterns — by design, so documentation pipelines can capture any rune-shaped declaration their conventions choose to expose.

ReExportJson
#

types.ts view source

also exported from index.ts

ZodObject<{ name: ZodString; module: ZodString; typeOnly: ZodDefault<ZodBoolean>; sourceLine: ZodOptional<ZodNumber>; }, $strict> import type {ReExportJson} from 'svelte-docinfo/types.js';

A same-name re-export edge, from the re-exporting module's side.

Each entry on ModuleJson.reExports records that the module's source contains export {name} from ... where the canonical declaration lives in module. This is the forward view of the same fact that alsoExportedFrom records on the canonical declaration — consumers resolve the canonical by (module, name), the same lookup contract as aliasOf.

Same-name re-exports of analyzed source only. Renamed re-exports appear as declarations with aliasOf in the re-exporting module; star exports live in ModuleJson.starExports; external re-exports in ModuleJson.externalReExports / externalStarExports. Use resolveExportSurface (in postprocess.ts) to combine all of these into a module's full export surface — it handles the name dedup (a documented same-name re-export appears both here and as a synthesized alias declaration) and the ES star semantics (explicit exports shadow star-projected ones, names ambiguous between stars are excluded, default doesn't project).

module points at the *canonical* module (multi-hop chains are resolved), not the immediate specifier in the export statement. For Svelte default-slot re-exports (export {default} from './X.svelte'), name is the component name derived from the filename ('X'), matching the canonical declaration's name — the same exception documented on aliasOf. Because of that re-keying, two entries in one module can share a name (a re-keyed component colliding with a same-name re-export from another module); (module, name) pairs remain unique (exact duplicates are deduped at construction).

@nodocs on the export statement suppresses the entry (and the alsoExportedFrom back-link). When the canonical declaration itself is @nodocs, or the canonical module isn't part of the analyzed set, the entry still exists but has no matching back-link — the same presence caveat as aliasOf.module and starExports.

ReExportJsonInput
#

types.ts view source

{ name: string; module: string; typeOnly?: boolean | undefined; sourceLine?: number | undefined; } import type {ReExportJsonInput} from 'svelte-docinfo/types.js';

name

Exported name — the canonical declaration's name in module.

type string

module

Module path (relative to sourceRoot) where the canonical declaration lives.

type string

typeOnly?

Whether the statement (export type {A} from ...) or specifier (export {type A} from ...) is type-only — the name is erased at runtime and importable only via import type.

type boolean

sourceLine?

1-based line of the export specifier in this module's source. When identical (name, module) edges are deduped (Svelte default-slot re-keying), the smallest line is kept.

type number

resolveComponentAliases
#

postprocess.ts view source

also exported from index.ts

(modules: { path: string; declarations: ({ kind: "function"; parameters: { name: string; type: string; optional: boolean; rest: boolean; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<...> | undefined; }[]; ... 17 more ...; sourceLine?: number | undefined; } | ... 7 more ... | { ...; })[]; ... 7 more ...; moduleComment?: string | undefined; }[]): void import {resolveComponentAliases} from 'svelte-docinfo/postprocess.js';

Copy props/acceptsChildren/lang/etc. from canonical component declarations onto synthesized component-aliased declarations.

Renamed Svelte component re-exports (export {default as Foo} from './X.svelte') are emitted as kind: 'component' placeholders by analyzeExports, with aliasOf pointing at the canonical. The canonical's component-specific fields are only available after analyzeSvelteModule synthesizes the canonical declaration, so the copy happens here in phase 2 once all modules are analyzed.

Call this *after* mergeReExports — both walk the same modules array but read/write disjoint fields, so order between them only matters for clarity.

modules

type { path: string; declarations: ({ kind: "function"; parameters: { name: string; type: string; optional: boolean; rest: boolean; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<...> | undefined; }[]; ... 17 more ...; sourceLine?: number | undefined; } | ... 7 more ......

returns

void

mutates

  • modules — fills component-only fields on aliased component declarations

resolveExportSurface
#

postprocess.ts view source

also exported from index.ts

(modules: { path: string; declarations: ({ kind: "function"; parameters: { name: string; type: string; optional: boolean; rest: boolean; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<...> | undefined; }[]; ... 17 more ...; sourceLine?: number | undefined; } | ... 7 more ... | { ...; })[]; ... 7 more ...; moduleComment?: string | undefined; }[], path: string): ExportSurface | null import {resolveExportSurface} from 'svelte-docinfo/postprocess.js';

Resolve a module's full export surface from the analyzed model, applying ES module semantics to star exports.

Combines the module's own declarations (including synthesized aliases), reExports edges, externalReExports, and transitively-resolved starExports into one deduped, name-sorted list. The ES rules applied to star projection:

  • explicit exports (declarations, edges, externals) shadow star-projected names
  • a name projected by two stars that resolve to *different* canonicals is ambiguous and excluded (same canonical through a diamond is included once)
  • default is never star-projected — including canonical Svelte component declarations, which represent their file's default export. (Caveat: a star-projected re-export edge whose canonical is a component is treated as a default-slot re-export and skipped; a <script module> const sharing the component's exact name would be skipped with it.)

A Position-3 alias and its reExports edge are the same fact — the declaration entry wins, inheriting the edge's typeOnly.

Cyclic star graphs terminate by contributing nothing along the back-edge (an approximation of ES fixpoint resolution — fine in practice). Surfaces resolved inside a cycle are path-relative and not memoized, so sibling star paths resolve independently rather than inheriting them. Star targets missing from modules are reported in unresolvedStarExports rather than guessed at; externalStarExports aggregates external star specifiers reachable from the module, whose names are unknowable.

modules

the analyzed modules (parsed ModuleJsons — run wire JSON through AnalyzeResultJson.parse first)

type { path: string; declarations: ({ kind: "function"; parameters: { name: string; type: string; optional: boolean; rest: boolean; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<...> | undefined; }[]; ... 17 more ...; sourceLine?: number | undefined; } | ... 7 more ......

path

the module to resolve, as a ModuleJson.path value

type string

returns

ExportSurface | null

the resolved surface, or null when path isn't in modules

ResolveImport
#

dep-resolver.ts view source

also exported from index.ts

ResolveImport import type {ResolveImport} from 'svelte-docinfo/dep-resolver.js';

Public resolver shape accepted across the API — a bare ResolveImportFn or the token-paired ImportResolver.

Every entry point that accepts resolveImport (analyze, analyzeFromFiles, createAnalysisSession, and the session's setFile/setFiles per-call override) takes this union, so the same value copy-pastes between them. Pass:

  • a bare function for the common case — a fresh cache identity is synthesized at the boundary. Correct for one-shot use (analyze, analyzeFromFiles) and for a session default (wrapped once at construction, so identity is stable for the session's lifetime).
  • an ImportResolver with a stable identity when you need the session to reuse its resolve cache across calls where the same logical resolver is rebuilt as a fresh closure (Vite/Rollup plugins). A bare function handed to a *per-call* setFile/setFiles override is treated as a distinct resolver each call (fresh identity → touched files re-resolve), which is the expected behavior for a deliberate one-off override.

ResolveImportFn
#

dep-resolver.ts view source

also exported from index.ts

ResolveImportFn import type {ResolveImportFn} from 'svelte-docinfo/dep-resolver.js';

Bare import-resolver function — the convenience form.

Resolve an import specifier to an absolute file path, or null if the specifier is unresolvable (external package, missing file, etc.). May return synchronously or asynchronously; sync returns are awaited harmlessly in the session's parallel resolve phase.

(call)

type (specifier: string, fromFile: string): string | Promise<string | null> | null

specifier

type string

fromFile

type string
returns string | Promise<string | null> | null

resolveIntersectionTypeNode
#

typescript-extract-shared.ts view source

(type: Type, typeNode: Node): IntersectionTypeNode | undefined import {resolveIntersectionTypeNode} from 'svelte-docinfo/typescript-extract-shared.js';

Resolve the IntersectionTypeNode for a type node, walking through type alias indirection. Returns undefined when the underlying type is an intersection but no AST node is recoverable (rare — synthesized intersections).

type

type Type

typeNode

type Node

returns

IntersectionTypeNode | undefined

ResolverFailedDiagnostic
#

diagnostics.ts view source

ZodObject<{ specifier: ZodString; file: ZodString; line: ZodOptional<ZodNumber>; column: ZodOptional<ZodNumber>; message: ZodString; severity: ZodEnum<...>; kind: ZodLiteral<...>; }, $strict> import type {ResolverFailedDiagnostic} from 'svelte-docinfo/diagnostics.js';

Import resolver threw while resolving a specifier.

Distinguishes a buggy resolver from a legitimately unresolvable specifier: resolvers that return null for unknown specifiers stay silent (the normal "external package" case); resolvers that *throw* surface here so consumers can fix the resolver. Recoverable — the session treats the throw as null and continues, so analysis still runs but with a missing dependency edge.

Emitted at ingest time by the session's resolve phase.

runCli
#

cli.ts view source

(argv?: string[]): Promise<number> import {runCli} from 'svelte-docinfo/cli.js';

Run the CLI with the given arguments.

argv

command line arguments (defaults to process.argv)

type string[]
default process.argv

returns

Promise<number>

exit code: 0 for success, 1 if errors in diagnostics, 2 for CLI errors

SetFileOptions
#

session.ts view source

also exported from index.ts

SetFileOptions import type {SetFileOptions} from 'svelte-docinfo/session.js';

Options for a per-file or per-batch resolver override.

Identity is required (not optional) — silently coalescing missing identities to a function reference would destroy cache reuse when the same logical resolver is wrapped in fresh closures across calls.

resolveImport?

Per-call override of the session-default resolver — a bare ResolveImportFn or a token-paired ImportResolver (see ResolveImport).

A bare function is normalized with a fresh identity on each call, so the files touched by this call re-resolve rather than cache-hitting — the expected behavior for a deliberate one-off override. To reuse the resolve cache across calls, pass an ImportResolver with a stable identity.

type ResolveImport

SetFileResult
#

session.ts view source

also exported from index.ts

SetFileResult import type {SetFileResult} from 'svelte-docinfo/session.js';

Result of setFile (single-file ingest).

changed is true when content or the mode-specific cache key (resolver identity for lex+resolve; dependency snapshot for pre-resolved) differed from the cached entry — the owned entry was rewritten. An LS push accompanies the entry write only when the file is TS/JS or has a successful Svelte virtual; CSS/JSON and transform-failed Svelte rewrite the entry without touching the LS. false indicates a cache-hit no-op: the cached ingestDiagnostics are returned but no work ran.

changed

Whether content or the mode-specific cache key differed from the cached entry.

type boolean

diagnostics

Ingest-time diagnostics for this file (durable on the entry).

type Array<Diagnostic>

SetFilesResult
#

session.ts view source

also exported from index.ts

SetFilesResult import type {SetFilesResult} from 'svelte-docinfo/session.js';

Result of setFiles (batch ingest).

Carries both aggregate views (changedIds, pre-flattened diagnostics) and a structured perFile map. HMR-style consumers want changedIds.size > 0 as the hot check; LSP-style consumers want per-file diagnostic association via perFile. Both are populated in the same single-pass walk over the batch — no extra cost.

changedIds

IDs whose content or mode-specific cache key differed from the cached entry — the subset of input file IDs that actually triggered work. Empty when every file was a cache-hit no-op.

type ReadonlySet<string>

diagnostics

Pre-flattened union of every file's ingestDiagnostics. Consumers can group by Diagnostic.file for per-file publish.

type Array<Diagnostic>

perFile

Per-file SetFileResult keyed by input file ID. Use this when the grouping Diagnostic.file would do isn't enough — e.g., LSP wanting to publish empty-diagnostic-list updates for files that ingested cleanly.

type ReadonlyMap<string, SetFileResult>

SignatureAnalysisDiagnostic
#

diagnostics.ts view source

ZodObject<{ functionName: ZodString; file: ZodString; line: ZodOptional<ZodNumber>; column: ZodOptional<ZodNumber>; message: ZodString; severity: ZodEnum<...>; kind: ZodLiteral<...>; }, $strict> import type {SignatureAnalysisDiagnostic} from 'svelte-docinfo/diagnostics.js';

Function/method signature analysis failed.

SnippetDeclarationJson
#

types.ts view source

also exported from index.ts

ZodObject<{ kind: ZodLiteral<"snippet">; parameters: ZodDefault<ZodArray<ZodObject<{ name: ZodString; type: ZodString; optional: ZodDefault<ZodBoolean>; rest: ZodDefault<...>; description: ZodOptional<...>; defaultValue: ZodOptional<...>; propertyDescriptions: ZodOptional<...>; }, $strict>>>; ... 14 more ...; generi... import type {SnippetDeclarationJson} from 'svelte-docinfo/types.js';

A Svelte snippet declaration exported from <script module>. Has parameters.

sortModules
#

postprocess.ts view source

(modules: { path: string; declarations: ({ kind: "function"; parameters: { name: string; type: string; optional: boolean; rest: boolean; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<...> | undefined; }[]; ... 17 more ...; sourceLine?: number | undefined; } | ... 7 more ... | { ...; })[]; ... 7 more ...; moduleComment?: string | undefined; }[]): { ...; }[] import {sortModules} from 'svelte-docinfo/postprocess.js';

Sort modules alphabetically by path for deterministic output and cleaner diffs.

Case-insensitive order (compareStrings) so the output is environment-independent.

modules

the modules to sort

type { path: string; declarations: ({ kind: "function"; parameters: { name: string; type: string; optional: boolean; rest: boolean; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<...> | undefined; }[]; ... 17 more ...; sourceLine?: number | undefined; } | ... 7 more ......

returns

{ path: string; declarations: ({ kind: "function"; parameters: { name: string; type: string; optional: boolean; rest: boolean; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<...> | undefined; }[]; ... 17 more ...; sourceLine?: number | undefined; } | ... 7 more ......

a new sorted array (does not mutate input)

SourceFileInfo
#

source.ts view source

also exported from index.ts

SourceFileInfo import type {SourceFileInfo} from 'svelte-docinfo/source.js';

File information for source analysis.

Provides file content to analysis functions from any source: file system, build pipeline, or in-memory.

Note: content is required to keep analysis functions pure (no hidden I/O). Callers are responsible for reading file content before analysis.

id

Absolute path to the file.

type string

content

File content (required - analysis functions don't read from disk).

type string

dependencies?

Pre-resolved absolute file paths of modules this file imports.

Opt-in optimization — when supplied, the session treats this as the authoritative dependency set for the file and skips its own lex+resolve pass for this entry. Build-tool integrations (e.g., Gro's filer) that already maintain a dependency graph can hand it over directly instead of paying the lex+resolve cost twice.

Omit (undefined) → default behavior — the session lexes import specifiers from content and resolves them via its ImportResolver. This is the right choice when the caller doesn't already have a graph.

Only include resolved local imports — node_modules paths are filtered out at storage time by the configured isSource predicate either way.

Trust contract — the session treats this array as authoritative and does not cross-check against the file's content. Edges declared here are accepted as-is, even if the source code doesn't actually import them; edges that *are* in content but missing from this array are silently omitted. The lex+resolve fallback path has no such hole — its edges are always grounded in syntactic imports. Build-tool integrations that supply this field own the correctness of the graph they hand over.

Type-only imports (import type {...}) are the most common asymmetry versus the lex+resolve path: the default lex (es-module-lexer) keeps them; pre-resolved callers backed by a Gro-style filer typically drop them. Both are intentional within their respective contracts.

Cache semantics: the session compares this array element-wise (shallow equality) against the snapshot stored from the prior call — a fresh array with identical contents cache-hits, while any length, element, or order difference invalidates. Callers that produce fresh arrays per call (e.g., Gro's [...filer.dependencies.keys()]) reuse the cache cleanly across persistent-session calls.

Order is significant. Reordering without a content change is treated as a real change — sort upstream if you want order-insensitive caching. Map-iteration-order callers (e.g., a Gro filer emitting [...filer.dependencies.keys()]) are naturally stable across calls for the same content, so no defensive sort is needed there.

type ReadonlyArray<string>

SourceMapFailedDiagnostic
#

diagnostics.ts view source

ZodObject<{ file: ZodString; line: ZodOptional<ZodNumber>; column: ZodOptional<ZodNumber>; message: ZodString; severity: ZodEnum<...>; kind: ZodLiteral<...>; }, $strict> import type {SourceMapFailedDiagnostic} from 'svelte-docinfo/diagnostics.js';

Source map parsing failed for a Svelte virtual file.

Analysis continues using virtual-file positions, so downstream line/column fields on other diagnostics may point into the svelte2tsx-generated TS rather than the original .svelte source. Rare; usually signals a malformed or incompatible svelte2tsx output.

Emitted at ingest time by transformSvelteSource (in svelte.ts); flows through setFile/setFiles ingest diagnostics rather than the analysis pass.

SourceOptionsDefaults
#

source-config.ts view source

also exported from index.ts

SourceOptionsDefaults import type {SourceOptionsDefaults} from 'svelte-docinfo/source-config.js';

Default source options preset (without projectRoot).

Use with createSourceOptions to build complete options. Contains all ModuleSourceOptions fields except projectRoot, which is provided separately as the first argument to createSourceOptions.

sourcePaths

Source directory paths to include, relative to projectRoot.

Normalized (leading/trailing slashes stripped) by normalizeSourceOptions, which returns a new options object.

type string[]

['src/lib'] // single source directory
['src/lib', 'src/routes'] // multiple directories

sourceRoot?

Source root for extracting relative module paths, relative to projectRoot.

Normalized (leading/trailing slashes stripped; '.' collapsed to '') by normalizeSourceOptions, which returns a new options object.

When omitted:

  • Single sourcePath: defaults to that path
  • Multiple sourcePaths: auto-derived as the longest common directory prefix (or '' when paths share no common prefix — produces project-relative module paths)

type string

'src/lib' // module paths like 'foo.ts', 'utils/bar.ts'
'src' // module paths like 'lib/foo.ts', 'routes/page.svelte'
'' // or '.': module paths stay project-relative, e.g. 'src/lib/foo.ts'

exclude

Glob patterns to exclude from analysis, relative to projectRoot.

Applied at both stages of the pipeline:

  • Discovery time by globFiles/discoverFromExports, preventing matched files from being loaded.
  • Analysis time by isSource() against relative(projectRoot, absolutePath), catching files that enter through TypeScript import resolution (e.g., a source file imports a test helper).

analyzeFromFiles accepts a top-level exclude shortcut that merges into this field.

Compiled to a matcher once per options object via picomatch and cached by reference; mutating this array post-isSource-call has no effect — pass through normalizeSourceOptions (which returns a fresh object) or otherwise build a new options object to apply changes.

type string[]

default `['**\/*.test.ts', '**\/*.spec.ts']`

getAnalyzerType

Determine which analyzer to use for a file path.

Called for files in source directories. Return an AnalyzerType or null to skip:

  • 'typescript' — TypeScript/JS files analyzed via TypeScript compiler API
  • 'svelte' — Svelte components analyzed via svelte2tsx + TypeScript compiler API
  • 'css' — CSS files included as modules with no declarations
  • 'json' — JSON files included as modules with no declarations
  • null — skip the file

type (path: string): AnalyzerType | null

path

type string
returns AnalyzerType | null
// Add MDsveX support getAnalyzerType: (path) => { if (path.endsWith('.svelte') || path.endsWith('.svx')) return 'svelte'; if (path.endsWith('.ts') || path.endsWith('.js')) return 'typescript'; if (path.endsWith('.css')) return 'css'; if (path.endsWith('.json')) return 'json'; return null; }
// Include .d.ts files getAnalyzerType: (path) => { if (path.endsWith('.svelte')) return 'svelte'; if (path.endsWith('.ts') || path.endsWith('.d.ts') || path.endsWith('.js')) return 'typescript'; if (path.endsWith('.css')) return 'css'; if (path.endsWith('.json')) return 'json'; return null; }

stripVirtualSuffix
#

source.ts view source

(path: string): string import {stripVirtualSuffix} from 'svelte-docinfo/source.js';

Strip the svelte2tsx virtual file suffix from a path, if present.

Maps Component.svelte.__svelte2tsx__.ts back to Component.svelte. Returns the path unchanged if the suffix is not present.

path

type string

returns

string

SVELTE_VIRTUAL_SUFFIX
#

source.ts view source

".__svelte2tsx__.ts" import {SVELTE_VIRTUAL_SUFFIX} from 'svelte-docinfo/source.js';

Suffix appended to .svelte file paths to create virtual TypeScript file paths.

Used by svelte2tsx integration: Component.svelteComponent.svelte.__svelte2tsx__.ts.

SveltePropDiagnostic
#

diagnostics.ts view source

ZodObject<{ componentName: ZodString; propName: ZodString; file: ZodString; line: ZodOptional<ZodNumber>; column: ZodOptional<ZodNumber>; message: ZodString; severity: ZodEnum<...>; kind: ZodLiteral<...>; }, $strict> import type {SveltePropDiagnostic} from 'svelte-docinfo/diagnostics.js';

Svelte prop type resolution failed.

SvelteVirtualFile
#

svelte.ts view source

SvelteVirtualFile import type {SvelteVirtualFile} from 'svelte-docinfo/svelte.js';

Pre-transformed Svelte virtual file data.

Produced by transformSvelteSource and consumed by analyzeSvelteModule to provide checker-backed analysis of Svelte components.

virtualPath

Path used for the virtual file in the TypeScript program.

type string

content

svelte2tsx transformed TypeScript content.

type string

sourceMap

Source map for position mapping back to the original .svelte file.

type SourceMap | null

lang

Script language. undefined means TypeScript (default), 'js' for JavaScript-only components.

type 'js' | undefined

synthesizeSnippetTypeSignature
#

svelte.ts view source

(parameters: { name: string; type: string; optional?: boolean | undefined; rest?: boolean | undefined; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<...> | undefined; }[]): string import {synthesizeSnippetTypeSignature} from 'svelte-docinfo/svelte.js';

Synthesize a Snippet<[...]> type string from structured parameters.

Used for kind: 'snippet' declarations where the raw svelte2tsx type is implementation noise. Produces type strings consistent with how the checker formats Snippet types on props.

parameters

type { name: string; type: string; optional?: boolean | undefined; rest?: boolean | undefined; description?: string | undefined; defaultValue?: string | undefined; propertyDescriptions?: Record<...> | undefined; }[]

returns

string

throwOnDuplicates
#

analyze-core.ts view source

also exported from index.ts

(duplicates: Map<string, DuplicateDeclaration[]>, log: Pick<AnalysisLog, "error">): void import {throwOnDuplicates} from 'svelte-docinfo/analyze-core.js';

Convenience OnDuplicatesCallback that throws on any duplicate.

duplicates

type Map<string, DuplicateDeclaration[]>

log

type Pick<AnalysisLog, "error">

returns

void

throws

  • Error - listing every duplicate name and module location

to_error_message
#

error.ts view source

(value: unknown, fallback?: string | undefined): string import {to_error_message} from 'svelte-docinfo/error.js';

Extract a human-readable message from an unknown thrown value.

value

type unknown

fallback?

type string | undefined
optional

returns

string

toPosixPath
#

paths.ts view source

(p: string): string import {toPosixPath} from 'svelte-docinfo/paths.js';

Normalize a path to POSIX form (forward slashes).

Replaces every backslash with a forward slash. Idempotent: forward-slash input returns unchanged. Empty string returns empty string.

p

type string

returns

string

examples

toPosixPath('C:\\proj\\src\\lib\\foo.ts') // => 'C:/proj/src/lib/foo.ts' toPosixPath('/home/user/proj/foo.ts') // => '/home/user/proj/foo.ts' (unchanged) toPosixPath('') // => ''

TransformFailedDiagnostic
#

diagnostics.ts view source

ZodObject<{ file: ZodString; line: ZodOptional<ZodNumber>; column: ZodOptional<ZodNumber>; message: ZodString; severity: ZodEnum<...>; kind: ZodLiteral<...>; }, $strict> import type {TransformFailedDiagnostic} from 'svelte-docinfo/diagnostics.js';

svelte2tsx transform threw for a .svelte file.

Unrecoverable at ingest — the file's owned-entry stays in the session (virtual: undefined, unfilteredDeps: [], transformFailed: true) so query() can synthesize a placeholder ModuleJson (partial: true, empty declarations). The originating error message lives in message; this diagnostic is the authoritative cause-of-failure signal.

TransformResult
#

svelte.ts view source

TransformResult import type {TransformResult} from 'svelte-docinfo/svelte.js';

Result of transformSvelteSource — a virtual file (when transform succeeded) plus any ingest-time diagnostics produced during the transform.

virtual is undefined when svelte2tsx threw; in that case diagnostics contains a transform_failed entry. When the transform succeeded but source map construction failed, virtual is populated and diagnostics contains a source_map_failed entry. The session's owned-entry stores both — the virtual (or transformFailed: true flag) and the ingest diagnostics.

virtual

type SvelteVirtualFile | undefined

diagnostics

type Array<Diagnostic>

transformSvelteSource
#

svelte.ts view source

(sourceFile: SourceFileInfo): TransformResult import {transformSvelteSource} from 'svelte-docinfo/svelte.js';

Pre-transform a Svelte source file via svelte2tsx.

Produces a SvelteVirtualFile containing the transformed TypeScript content and source map. The virtual file can be included in a TypeScript program (via createAnalysisProgram({ virtualFiles })) so that the checker can resolve imported types, <script module> exports, and re-exports.

Errors at ingest are returned via diagnostics rather than thrown:

  • svelte2tsx throws → transform_failed, virtual: undefined
  • source map construction fails → source_map_failed, virtual populated

Diagnostic file paths are the original .svelte source ID; downstream normalization rewrites them to project-root-relative form.

sourceFile

the Svelte source file with content loaded

returns

TransformResult

virtual file data (or undefined on transform failure) plus ingest diagnostics

throws

  • Error - if Svelte version is below 5 (checked once on first call)

TsdocParsedComment
#

tsdoc.ts view source

TsdocParsedComment import type {TsdocParsedComment} from 'svelte-docinfo/tsdoc.js';

Parsed JSDoc/TSDoc comment with structured metadata.

Returned by parseComment — consumers typically pass this to applyToDeclaration to populate DeclarationJsonBuild fields.

text

Comment text (excluding comment markers).

type string

params

Parameter descriptions mapped by parameter name.

type Record<string, string>

returns?

Return value description from @returns.

type string

throws?

Thrown errors from @throws.

type Array<{type?: string; description: string}>

examples?

Code examples from @example.

type Array<string>

deprecatedMessage?

Deprecation message from @deprecated.

type string

seeAlso?

Related references from @see.

type Array<string>

since?

Version information from @since.

type string

defaultValue?

Default value from @default tag.

type string

mutates?

Mutation documentation from @mutates (non-standard), mapped by parameter name.

type Record<string, string>

nodocs?

Whether to exclude from documentation. From @nodocs tag.

type boolean

TypeDeclarationJson
#

types.ts view source

also exported from index.ts

ZodObject<{ kind: ZodLiteral<"type">; intersects: ZodDefault<ZodArray<ZodString>>; members: ZodDefault<ZodArray<ZodDiscriminatedUnion<[ZodObject<{ kind: ZodLiteral<"function">; ... 17 more ...; genericParams: ZodDefault<...>; }, $strict>, ZodObject<...>, ZodObject<...>], "kind">>>; ... 14 more ...; genericParams: Zo... import type {TypeDeclarationJson} from 'svelte-docinfo/types.js';

A type alias declaration. Has members, intersects.

TypeExtractionDiagnostic
#

diagnostics.ts view source

ZodObject<{ symbolName: ZodString; file: ZodString; line: ZodOptional<ZodNumber>; column: ZodOptional<ZodNumber>; message: ZodString; severity: ZodEnum<...>; kind: ZodLiteral<...>; }, $strict> import type {TypeExtractionDiagnostic} from 'svelte-docinfo/diagnostics.js';

Type extraction failed (e.g., complex or recursive types).

UnknownParamDiagnostic
#

diagnostics.ts view source

ZodObject<{ paramName: ZodString; functionName: ZodString; file: ZodString; line: ZodOptional<ZodNumber>; column: ZodOptional<ZodNumber>; message: ZodString; severity: ZodEnum<...>; kind: ZodLiteral<...>; }, $strict> import type {UnknownParamDiagnostic} from 'svelte-docinfo/diagnostics.js';

@param tag references a name that doesn't match any actual parameter.

Usually a typo (@param argz for parameter args) or stale doc after a rename. The description is dropped; analysis continues.

VariableDeclarationJson
#

types.ts view source

also exported from index.ts

ZodObject<{ kind: ZodLiteral<"variable">; reactivity: ZodOptional<ZodEnum<{ $state: "$state"; "$state.raw": "$state.raw"; $derived: "$derived"; "$derived.by": "$derived.by"; }>>; ... 15 more ...; genericParams: ZodDefault<...>; }, $strict> import type {VariableDeclarationJson} from 'svelte-docinfo/types.js';

A variable declaration. Has optional reactivity for top-level rune-module exports (e.g., export let count = $state(0) in .svelte.ts or <script module>).

VariableMemberJson
#

types.ts view source

also exported from index.ts

ZodObject<{ kind: ZodLiteral<"variable">; optional: ZodDefault<ZodBoolean>; reactivity: ZodOptional<ZodEnum<{ $state: "$state"; "$state.raw": "$state.raw"; $derived: "$derived"; "$derived.by": "$derived.by"; }>>; ... 13 more ...; genericParams: ZodDefault<...>; }, $strict> import type {VariableMemberJson} from 'svelte-docinfo/types.js';

A variable member (property, accessor, index signature, enum value). Shared fields plus optional reactivity for class fields initialized with a Svelte rune ($state, $state.raw, $derived, $derived.by).

optional reflects a ? token on the declaration (e.g., x?: string). Always false for index signatures and enum values.

VitePluginSvelteDocinfoOptions
#

vite.ts view source

VitePluginSvelteDocinfoOptions import type {VitePluginSvelteDocinfoOptions} from 'svelte-docinfo/vite.js';

Options for the svelteDocinfo Vite plugin.

projectRoot?

Absolute path to project root directory. Defaults to Vite's resolved config.root.

type string

include?

Glob patterns to include (relative to projectRoot).

When provided under the default discovery: 'auto', collapses the chain to glob (exports discovery is skipped). Combining include with discovery: 'exports' throws at config-resolve time — exports mode has no concept of include patterns.

When omitted, the glob fallback derives an include from sourceOptions.sourcePaths via deriveIncludePatterns, so custom sourcePaths survive the fallback instead of silently defaulting to src/lib.

type Array<string>

exclude?

Glob patterns to exclude, applied at both discovery and analysis time.

When provided, fully replaces sourceOptions.exclude (no array merge) — the default test and spec filters are dropped unless re-included explicitly.

type Array<string>

resolveDependencies?

Whether to resolve import dependencies.

When false, the session's resolver returns null for every specifier, so module dependencies/dependents stay empty.

type boolean

default true

discovery?

Discovery strategy for source files.

type Discovery

default 'auto'

see also

distDir?

Dist directory name relative to project root, used for exports-based discovery.

type string

default 'dist'

sourceOptions?

Partial overrides for default source options (SvelteKit src/lib layout).

type Partial<SourceOptionsDefaults>

onDuplicates?

Behavior when duplicate declaration names are found across modules.

type OnDuplicates

hmrDebounceMs?

HMR debounce delay in milliseconds. Coalesces rapid file changes during dev.

type number

default 100

warningsOf
#

diagnostics.ts view source

also exported from index.ts

(diagnostics: ({ symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | { functionName: string; ... 5 more ...; column?: number | undefined; } | ... 11 more ... | { ...; })[]): ({ ...; } | ... 12 more ... | { ...; })[] import {warningsOf} from 'svelte-docinfo/diagnostics.js';

Get all warning-severity diagnostics.

diagnostics

type ({ symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | { functionName: string; ... 5 more ...; column?: number | undefined; } | ... 11 more ... | { ...; })[]

returns

({ symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | { functionName: string; ... 5 more ...; column?: number | undefined; } | ... 11 more ... | { ...; })[]

warnModuleCommentNodocs
#

typescript-exports.ts view source

(moduleComment: string | undefined, file: string, diagnostics: ({ symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | ... 12 more ... | { ...; })[]): void import {warnModuleCommentNodocs} from 'svelte-docinfo/typescript-exports.js';

Warn when a module comment carries @nodocs.

The tag has no module-level meaning — it applies to declarations and export statements — so its presence in a @module comment is always author confusion: it does nothing except remain verbatim in moduleComment text. Same line-start detection as extractModuleComment's @module test, so a backticked or mid-prose mention doesn't trigger.

moduleComment

type string | undefined

file

type string

diagnostics

type ({ symbolName: string; file: string; message: string; severity: "error" | "warning"; kind: "type_extraction_failed"; line?: number | undefined; column?: number | undefined; } | { functionName: string; ... 5 more ...; column?: number | undefined; } | ... 11 more ... | { ...; })[]

returns

void

wrapResolveImport
#

dep-resolver.ts view source

(resolveImport: ResolveImportFn, identity?: string | symbol): ImportResolver import {wrapResolveImport} from 'svelte-docinfo/dep-resolver.js';

Wrap a bare resolveImport function into an ImportResolver token.

identity is optional; when omitted, a fresh Symbol('wrapped') is synthesized per call. The synthesized default suits single-use scopes — normalizeResolveImport relies on it to wrap a bare function for a one-shot analyze call or for a session default (wrapped once at construction, so the identity stays stable for the session's lifetime).

For a long-lived session that re-wraps the *same* logical resolver across calls (Vite plugin, LSP), a throwaway identity cache-misses every time — the fresh Symbol('wrapped') never compares equal. Pass a stable identity here, or — simpler — construct an ImportResolver ({resolve, identity}) directly and pass it through the ResolveImport union.

resolveImport

identity

type string | symbol
default Symbol('wrapped')

returns

ImportResolver