api #

static analysis for TypeScript and Svelte

30 modules ยท 189 declarations

Modules
#

AnalysisLanguageService
#

typescript-program.ts view source

AnalysisLanguageService

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.

AnalysisLanguageServiceOptions
#

typescript-program.ts view source

AnalysisLanguageServiceOptions

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

AnalysisLog

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

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

AnalysisSession

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.

AnalysisSessionOptions
#

session.ts view source

AnalysisSessionOptions

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.)

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.

log

Optional logger for session-level messages.

analyze
#

analyze.ts view source

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

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; }[]; ... 17 more ...; sourceLine?: number | undefined; } | ... 7 more ... | { ...; })[]; ... 4 more .....

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; }[]; ... 17 more ...; sourceLine?: number | undefined; } | ... 7 more ... | { ...; })[]; ... 4 more ...; moduleComment?: string | undefined; }[]; diagnostics: ({ ...; } | ... 12 more ... | { ...; })[]; }

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; }[]; ... 17 more ...; sourceLine?: number | undefined; } | ... 7 more ... | { ...; })[]; ... 4 more ...; modul...

AnalyzeCoreInputs
#

analyze-core.ts view source

AnalyzeCoreInputs

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

program

type ts.Program

svelteVirtualFiles

type ReadonlyMap<string, SvelteVirtualFile>

transformFailedIds

Svelte file IDs whose svelte2tsx transform failed at ingest.

type ReadonlySet<string>

onDuplicates

log

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

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

Analyze all exports from a TypeScript source file.

Extracts the module-level comment via extractModuleComment, 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

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, and star exports

analyzeFromFiles
#

analyze.ts view source

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

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

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

1. Discovery โ€” discoverSourceFiles (exports-first, glob fallback) 2. Ingest โ€” push discovered files into a single-use session 3. Analysis โ€” session.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; }[]; ... 17 more ...; sourceLine?: number | undefined; } | ... 7 more ... | { ...; })[]; ... 4 more .....

analyzed modules + concatenated ingest, discovery, and query diagnostics

throws

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

AnalyzeFromFilesOptions
#

analyze.ts view source

AnalyzeFromFilesOptions

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.

log

Optional logger for status and diagnostic messages.

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

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.

discovery

Discovery strategy for source files.

distDir

Dist directory name for exports-based discovery.

type string

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): ModuleAnalyzeResult | undefined

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

ModuleAnalyzeResult | undefined

AnalyzeOptions
#

analyze.ts view source

AnalyzeOptions

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.

onDuplicates

Behavior when duplicate declaration names are found across modules.

log

Optional logger for status and diagnostic messages.

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.

AnalyzeResultJson
#

analyze-core.ts view source

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 .....

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.

AnalyzerType
#

source.ts view source

AnalyzerType

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

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

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

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

buildTypeReferencePatterns
#

declaration-helpers.ts view source

(declarationNames: ReadonlySet<string>): [string, RegExp][]

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

<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<...>)[]

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<...>)[]

ClassDeclarationJson
#

types.ts view source

ZodObject<{ kind: ZodLiteral<"class">; extends: ZodOptional<ZodString>; implements: ZodDefault<ZodArray<ZodString>>; ... 15 more ...; genericParams: ZodDefault<...>; }, $strict>

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>

Class member analysis failed.

cleanComment
#

tsdoc.ts view source

(commentText: string): string | undefined

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

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>.

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

(_key: string, value: unknown): unknown

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));

ComponentDeclarationJson
#

types.ts view source

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>

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

ComponentPropJson
#

types.ts view source

ZodObject<{ examples: ZodDefault<ZodArray<ZodString>>; deprecatedMessage: ZodOptional<ZodString>; seeAlso: ZodDefault<ZodArray<ZodString>>; ... 8 more ...; parameters: ZodOptional<...>; }, $strict>

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; }

computeDependents
#

postprocess.ts view source

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

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

ZodObject<{ kind: ZodLiteral<"constructor">; name: ZodUnion<readonly [ZodLiteral<"constructor">, ZodLiteral<"(construct)">]>; parameters: ZodDefault<ZodArray<ZodObject<...>>>; ... 12 more ...; genericParams: ZodDefault<...>; }, $strict>

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

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

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

(options: AnalysisSessionOptions): AnalysisSession

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

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).

Falls back to appending .svelte when the bare specifier doesn't resolve โ€” lets .svelte imports work without polluting the consumer's tsconfig.

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

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

(projectRoot: string, overrides?: Partial<SourceOptionsDefaults> | undefined): ModuleSourceOptions

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

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).

nodocs

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

type boolean

DeclarationJson
#

types.ts view source

ZodDiscriminatedUnion<[ZodObject<{ kind: ZodLiteral<"function">; returnType: ZodOptional<ZodString>; returnDescription: ZodOptional<ZodString>; ... 16 more ...; genericParams: ZodDefault<...>; }, $strict>, ... 7 more ..., ZodObject<...>], "kind">

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

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

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

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; }[] | undefined; ... 14 more ...; gene...

DeclarationKind
#

types.ts view source

ZodEnum<{ function: "function"; type: "type"; variable: "variable"; class: "class"; interface: "interface"; enum: "enum"; component: "component"; snippet: "snippet"; namespace: "namespace"; }>

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

ZodEnum<{ public: "public"; protected: "protected"; readonly: "readonly"; static: "static"; abstract: "abstract"; getter: "getter"; setter: "setter"; }>

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

SourceOptionsDefaults

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

(sourcePaths: readonly string[]): string[]

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

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

ZodDiscriminatedUnion<[ZodObject<{ symbolName: ZodString; file: ZodString; line: ZodOptional<ZodNumber>; column: ZodOptional<ZodNumber>; message: ZodString; severity: ZodEnum<...>; kind: ZodLiteral<...>; }, $strict>, ... 12 more ..., ZodObject<...>], "kind">

Discriminated union of all diagnostic variants.

DiagnosticKind
#

diagnostics.ts view source

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"; }>

Discriminant for Diagnostic variant types.

DiagnosticSeverity
#

diagnostics.ts view source

ZodEnum<{ error: "error"; warning: "warning"; }>

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>

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

(options: DiscoverSourceFilesOptions): Promise<DiscoverSourceFilesResult>

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

DiscoverSourceFilesOptions

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()).

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.

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

log

Optional logger for status messages.

DiscoverSourceFilesResult
#

discovery.ts view source

DiscoverSourceFilesResult

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

Discovery

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>

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

DuplicateDeclaration

A duplicate declaration with its full metadata and module path.

declaration

The full declaration metadata.

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>

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

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

ensureLexerReady
#

dep-resolver.ts view source

(): Promise<void>

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

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...

An enum declaration. Has members for enum values.

errorsOf
#

diagnostics.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 ... | { ...; })[]): ({ ...; } | ... 12 more ... | { ...; })[]

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

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

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

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>

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

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

extractDependencies
#

source-config.ts view source

(sourceFile: SourceFileInfo & { dependents?: readonly string[] | undefined; }, options: ModuleSourceOptions): { dependencies: string[]; dependents: string[]; }

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

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

extractFunctionInfo
#

typescript-extract-function.ts view source

(node: Node, symbol: Symbol, checker: TypeChecker, declaration: DeclarationJsonBuild, tsdoc: TsdocParsedComment | undefined, diagnostics: ({ ...; } | ... 12 more ... | { ...; })[]): void

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

extractHtmlModuleComment
#

svelte.ts view source

(svelteSource: string): string | undefined

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")[]

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
#

extractPath
#

source-config.ts view source

(sourceId: string, options: ModuleSourceOptions): string

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

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; }[]

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; }[]

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; }[]

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; }[]

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

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.

scriptContent

the content of the <script> 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

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

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

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

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

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

filterIntersectionProperties
#

typescript-extract-shared.ts view source

(type: Type, typeNode: Node, checker: TypeChecker, isExternalFile: IsExternalFile): { properties: Symbol[]; intersectionTypes: string[]; } | null

Filter intersection type properties to exclude those from external sources, and extract type names for branches whose properties are all external.

Returns null for non-intersection types (caller should use unfiltered properties). For intersection types, returns filtered properties and external type names.

Per-property filtering works through utility types (Partial, Pick, Readonly) because TypeScript preserves original declaration sources on mapped type properties.

type

type Type

typeNode

type Node

checker

type TypeChecker

isExternalFile

returns

{ properties: Symbol[]; intersectionTypes: string[]; } | null

findDuplicates
#

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; }[]; ... 17 more ...; sourceLine?: number | undefined; } | ... 7 more ... | { ...; })[]; ... 4 more ...; moduleComment?: string | undefined; }[]): Map<...>

Find duplicate declaration names across modules.

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; }[]; ... 17 more ...; sourceLine?: number | undefined; } | ... 7 more ... | { ...; })[]; ... 4 more ...; moduleComment?: ...

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

(typeString: string, declarationNames: ReadonlySet<string> | [string, RegExp][]): string[]

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

(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

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

ZodObject<{ kind: ZodLiteral<"function">; returnType: ZodOptional<ZodString>; returnDescription: ZodOptional<ZodString>; ... 16 more ...; genericParams: ZodDefault<...>; }, $strict>

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

FunctionMemberJson
#

types.ts view source

ZodObject<{ kind: ZodLiteral<"function">; name: ZodString; optional: ZodDefault<ZodBoolean>; returnType: ZodOptional<ZodString>; ... 14 more ...; genericParams: ZodDefault<...>; }, $strict>

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

(declaration: { kind: "function"; parameters: { name: string; type: string; optional: boolean; rest: boolean; description?: string | undefined; defaultValue?: string | undefined; }[]; overloads: { typeSignature: string; ... 4 more ...; returnDescription?: string | undefined; }[]; ... 16 more ...; sourceLine?: number | undefined; } | ... 7 more ... | { ...; }, modulePath: string, libraryName: string): string

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; }[]; overloads: { typeSignature: string; ... 4 more ...; returnDescription?: string | undefined; }[]; ... 16 more ...; sourceLine?: number | undefined; ...

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

ZodObject<{ name: ZodString; constraint: ZodOptional<ZodString>; defaultType: ZodOptional<ZodString>; }, $strict>

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

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

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

(declaration: { kind: "function"; name: string; optional: boolean; parameters: { name: string; type: string; optional: boolean; rest: boolean; description?: string | undefined; defaultValue?: string | undefined; }[]; ... 14 more ...; sourceLine?: number | undefined; } | ... 10 more ... | { ...; }): string

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; }[]; ... 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; }

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

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[]>

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

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

(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

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

hasModuleTag
#

tsdoc.ts view source

(node: Node): boolean

Check if a TypeScript node has a @module JSDoc tag.

Used to prevent @module comments from leaking into declaration docComment fields. Module-level comments are extracted separately by extractModuleComment.

node

the TypeScript node to check

type Node

returns

boolean

true if any JSDoc tag on the node is @module

hasWarnings
#

diagnostics.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 ... | { ...; })[]): boolean

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 parsing failed during dependency resolution.

ImportResolver
#

dep-resolver.ts view source

ImportResolver

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.

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"

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

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: ...

An interface declaration. Has members, extends.

isCss
#

source.ts view source

(path: string): boolean

Check if a path is a CSS file.

path

type string

returns

boolean

IsExternalFile
#

typescript-program.ts view source

IsExternalFile

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.

isExternalIntersectionBranch
#

typescript-extract-shared.ts view source

(branchNode: TypeNode, checker: TypeChecker, isExternalFile: IsExternalFile): boolean

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

Check if a path is a JSON file.

path

type string

returns

boolean

isKind
#

declaration-helpers.ts view source

<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; }[]; ... 14 more ...; sourceLine?: number | undefined; } | ... 10 more ... | { ...; }, kind: K): declaration is Extract<...> | ... 10 more ... | Extract<...>

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; }[]; ... 14 more ...; sourceLine?: number | undefined; } | ... 10 more ... | { ...; }

kind

type K

returns

boolean

examples

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

isSnippetReturnType
#

svelte.ts view source

(returnType: string): boolean

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

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

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

Check if a path is a Svelte component file.

path

type string

returns

boolean

isTypescript
#

source.ts view source

(path: string): boolean

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[]

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>

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[]; }

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

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

tsconfig

Path to tsconfig.json (relative to projectRoot).

type string

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
#

map_concurrent
#

concurrency.ts view source

<T, R>(items: readonly T[], concurrency: number, fn: (item: T, index: number) => Promise<R>): Promise<R[]>

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

mapDistToSource
#

exports.ts view source

(distPath: string, condition: string, options: { distDir: string; sourceDir: string; }): string | null

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
#

concurrency.ts view source

100

Internal concurrency helpers โ€” bounded Promise.all for the few sites where unbounded fan-out would risk resource exhaustion.

- MAX_FILE_CONCURRENCY โ€” parallel readFile cap. Bounds FD pressure so projects with thousands of source files don't trip EMFILE against the typical 1024-FD ulimit. Used by files.globFiles and exports.discoverFromExports. - MAX_RESOLVE_CONCURRENCY โ€” parallel resolver-call cap for session phase 2. Async resolvers (Vite/Rollup resolveId, user-supplied) get backpressure instead of a 20k+ task fan-out at once. Sync resolvers (TS default, no-deps stub) settle in microtasks regardless of the bound.

Same numerical value today, separately named so a future tuning pass can move them independently (FD pressure and resolver backpressure are unrelated limits that happen to coincide at this cap).

MAX_RESOLVE_CONCURRENCY
#

MemberJson
#

types.ts view source

ZodDiscriminatedUnion<[ZodObject<{ kind: ZodLiteral<"function">; name: ZodString; optional: ZodDefault<ZodBoolean>; returnType: ZodOptional<ZodString>; ... 14 more ...; genericParams: ZodDefault<...>; }, $strict>, ZodObject<...>, ZodObject<...>], "kind">

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

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

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

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; }[] | ...

MemberKind
#

types.ts view source

ZodEnum<{ function: "function"; variable: "variable"; constructor: "constructor"; }>

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

(modules: { path: string; declarations: ({ kind: "function"; parameters: { name: string; type: string; optional: boolean; rest: boolean; description?: string | undefined; defaultValue?: string | undefined; }[]; ... 17 more ...; sourceLine?: number | undefined; } | ... 7 more ... | { ...; })[]; ... 4 more ...; moduleComment?: string | undefined; }[], collectedReExports: ReExportEntry[]): void

Build alsoExportedFrom arrays from collected re-export data.

This function resolves the two-phase re-export problem:

Problem: When module A re-exports from module B, we discover this while analyzing A, but need to update B's declarations. However, B may already be processed or may be processed later.

Solution: Collect all re-exports in phase 1, then merge them in phase 2 after all modules are analyzed.

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)

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

collectedReExports

array of re-exports collected during phase 1

type ReExportEntry[]

returns

void

examples

// helpers.ts exports: foo, bar // index.ts does: export {foo, bar} from './files.js' // // 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: ZodString; ... 5 more ...; kind: ZodLiteral<...>; }, $strict>

Symbol-scope JSDoc tag (@example, @deprecated, @since, @see, @throws, @mutates, @default, @nodocs) found on a non-primary overload signature.

Symbol-scope tags 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 here even though overloads never carry a defaultValue or per-overload exclusion: their presence on a non-primary signature is always a misplacement.

ModuleAnalysis
#

declaration-build.ts view source

ModuleAnalysis

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>

ModuleAnalyzeResult
#

analyze-core.ts view source

ModuleAnalyzeResult

Result of analyzing a single module.

alsoExportedFrom on declarations is always empty from this path โ€” cross-module re-export resolution requires all modules.

module

reExports

type Array<ReExportInfo>

ModuleExportsAnalysis
#

declaration-build.ts view source

ModuleExportsAnalysis

Result of analyzing a module's exports.

Produced by analyzeExports in typescript-exports.ts.

moduleComment

Module-level documentation comment.

type string

declarations

All exported declarations with @nodocs flags โ€” consumer filters based on policy.

type Array<DeclarationAnalysis>

reExports

Same-name re-exports (for building alsoExportedFrom in post-processing).

type Array<ReExportInfo>

starExports

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

type Array<string>

ModuleJson
#

types.ts view source

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">>>; ... 4 more...

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; }[] | ...

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>

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

ModuleSourceOptions

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

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>

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

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>

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

ModuleUnreadableDiagnostic
#

diagnostics.ts view source

ZodObject<{ file: ZodString; line: ZodOptional<ZodNumber>; column: ZodOptional<ZodNumber>; message: ZodString; severity: ZodEnum<...>; kind: ZodLiteral<...>; }, $strict>

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

ZodObject<{ kind: ZodLiteral<"namespace">; module: ZodString; alsoExportedFrom: ZodDefault<ZodArray<ZodString>>; aliasOf: ZodOptional<ZodObject<{ ...; }, $strict>>; ... 12 more ...; genericParams: ZodDefault<...>; }, $strict>

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

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

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

normalizeResolveImport
#

dep-resolver.ts view source

(value: ResolveImport | undefined): ImportResolver | undefined

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

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

OnDuplicates

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

OnDuplicatesCallback

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.

OverloadJson
#

types.ts view source

ZodObject<{ typeSignature: ZodString; parameters: ZodDefault<ZodArray<ZodObject<{ name: ZodString; type: ZodString; optional: ZodDefault<ZodBoolean>; rest: ZodDefault<...>; description: ZodOptional<...>; defaultValue: ZodOptional<...>; }, $strict>>>; returnType: ZodOptional<...>; genericParams: ZodDefault<...>; docC...

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; }[] | undefined; returnType?: string | undefined; genericParams?: { ...; }[] | undefined; docComment?: string | undefine...

ParameterJson
#

types.ts view source

ZodObject<{ name: ZodString; type: ZodString; optional: ZodDefault<ZodBoolean>; rest: ZodDefault<ZodBoolean>; description: ZodOptional<...>; defaultValue: ZodOptional<...>; }, $strict>

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; }

parseComment
#

tsdoc.ts view source

(node: Node, sourceFile: SourceFile): TsdocParsedComment | undefined

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)

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

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

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; }

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>

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

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

QueryOptions
#

session.ts view source

QueryOptions

Per-call input to query.

onDuplicates

Behavior when duplicate declaration names are found across modules.

log

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

Reactivity
#

types.ts view source

ZodEnum<{ $state: "$state"; "$state.raw": "$state.raw"; $derived: "$derived"; "$derived.by": "$derived.by"; }>

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.

ReExportEntry
#

postprocess.ts view source

ReExportEntry

A collected re-export with its source module context.

Used during the two-phase re-export resolution: 1. Phase 1: Collect re-exports from each module during analysis 2. Phase 2: Group by original module and merge into alsoExportedFrom

reExportingModule

The module that re-exports the declaration.

type string

reExport

The re-export info (name and original module).

ReExportInfo
#

declaration-build.ts view source

ReExportInfo

Information about a same-name re-export.

Collected during phase 1 of analysis and passed to mergeReExports in phase 2 to build alsoExportedFrom arrays on canonical declarations.

name

Name of the re-exported declaration. 'default' for default-slot re-exports (export {default} from './x') โ€” that's the canonical's actual symbol name in the original module.

type string

originalModule

Module path (relative to sourceRoot) where the declaration is originally declared.

type string

resolveComponentAliases
#

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; }[]; ... 17 more ...; sourceLine?: number | undefined; } | ... 7 more ... | { ...; })[]; ... 4 more ...; moduleComment?: string | undefined; }[]): void

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; }[]; ... 17 more ...; sourceLine?: number | undefined; } | ... 7 more ... | { ...; })[]; ... 4 more ...; moduleComment?: ...

returns

void

ResolveImport
#

dep-resolver.ts view source

ResolveImport

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

ResolveImportFn

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.

resolveIntersectionTypeNode
#

typescript-extract-shared.ts view source

(type: Type, typeNode: Node): IntersectionTypeNode | undefined

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 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>

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

SetFileOptions

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.

SetFileResult
#

session.ts view source

SetFileResult

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

SetFilesResult

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>

Function/method signature analysis failed.

SnippetDeclarationJson
#

types.ts view source

ZodObject<{ kind: ZodLiteral<"snippet">; parameters: ZodDefault<ZodArray<ZodObject<{ name: ZodString; type: ZodString; optional: ZodDefault<ZodBoolean>; rest: ZodDefault<...>; description: ZodOptional<...>; defaultValue: ZodOptional<...>; }, $strict>>>; ... 14 more ...; genericParams: ZodDefault<...>; }, $strict>

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; }[]; ... 17 more ...; sourceLine?: number | undefined; } | ... 7 more ... | { ...; })[]; ... 4 more ...; moduleComment?: string | undefined; }[]): { ...; }[]

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

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; }[]; ... 17 more ...; sourceLine?: number | undefined; } | ... 7 more ... | { ...; })[]; ... 4 more ...; moduleComment?: ...

returns

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

a new sorted array (does not mutate input)

SourceFileInfo
#

source.ts view source

SourceFileInfo

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>

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
#

stripVirtualSuffix
#

source.ts view source

(path: string): string

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"

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

Used by svelte2tsx integration: Component.svelte โ†’ Component.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>

Svelte prop type resolution failed.

SvelteVirtualFile
#

svelte.ts view source

SvelteVirtualFile

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; }[]): string

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; }[]

returns

string

throwOnDuplicates
#

analyze-core.ts view source

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

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

toPosixPath
#

paths.ts view source

(p: string): string

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>

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

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

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

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

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...

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>

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>

@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

ZodObject<{ kind: ZodLiteral<"variable">; reactivity: ZodOptional<ZodEnum<{ $state: "$state"; "$state.raw": "$state.raw"; $derived: "$derived"; "$derived.by": "$derived.by"; }>>; ... 15 more ...; genericParams: ZodDefault<...>; }, $strict>

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

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>

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

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

discovery

Discovery strategy for source files.

distDir

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

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.

hmrDebounceMs

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

type number

warningsOf
#

diagnostics.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 ... | { ...; })[]): ({ ...; } | ... 12 more ... | { ...; })[]

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 ... | { ...; })[]

wrapResolveImport
#

dep-resolver.ts view source

(resolveImport: ResolveImportFn, identity?: string | symbol): ImportResolver

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