Skip to content
GitHub

DevelopOther

@holtkeeper/usages

The usages analyzer and analysis kind: which packages (npm) and modules (Go) a repository’s code imports, at which versions, and which of their exports, members and JSX props it uses where, with a snippet of each use. The server joins the newest record of every repository into a fleet-wide index: “used by” for a package, the code behind each use, and the uses an upgrade breaks — for people in the web UI and for agents over MCP when they plan migrations.

  • usagesAnalyzer — Analyzer<UsagesData, UsagesOptions>, kind usages, scope repo, needs checkout. Applies (usagesApplies) to repositories with a root package.json or a Go module: a root go.mod or go.work, or, when the forge can list the tree, a go.mod up to four directories deep outside vendor/, testdata/, node_modules/, hidden and _-prefixed folders (hasGoModule(depth?)). Options (usagesOptionsSchema; lists also accept a comma-separated string, as the flags pass them):
    • packages: string[] (--packages) — glob patterns of package names (Go module paths) to keep, e.g. @acme/* or example.com/acme/**; every imported dependency when empty.
    • exclude: string[] (--exclude) — glob patterns of files to skip, e.g. **/*.stories.tsx.
    • types: 'auto' | 'off' (--types) — resolve names with the TypeScript checker when a tsconfig.json and installed dependencies exist, and with the Go type checker when the job has go (default auto). The analyzer passes its runner on, so the Go pass runs where the job’s toolchain lives.
    • install: boolean — install dependencies from the lockfile first, without lifecycle scripts, so the checker sees them (default true; skipped when node_modules exists, types is off or there is no root package.json). Uses installDependencies of @holtkeeper/coverage.
  • usagesAnalysis — the AnalysisKind (schema: usagesDataSchema, summarize, toReport); usagesReport(data, options) builds the report directly. Metrics: packages used, exports used, uses, files read and, when the checker ran, uses found by types. Sections: packages (versions, workspaces, counts, most used exports), most used exports of third-party packages with props, members and a snippet, how uses were found (checker status, unreadable files).
  • extractUsages({ dir, packages?, exclude?, types?, runner?, goTypesTimeoutMs?, signal?, log? }): Promise<UsagesData> — the extraction itself; installs nothing (the Go type checker compiles its helper and lets go list download modules). Runs the JavaScript pass when a root package.json exists and the Go pass when the checkout has a Go module, and concatenates their packages. types is combineTypes(js, go): either pass alone as it reported; with both, a skipped pass gives way to the other and two passes that ran merge (used when either was, reasons joined with ; , projects listed together, sites summed). Go reasons start with go: (go: turned off, go: no command runner, go: go is not available: …); a checkout with neither ecosystem reports skipped with no package.json, go.mod or go.work.
  • extractGoUsages({ dir, packages?, exclude?, types?, runner?, typesTimeoutMs?, signal?, log? }) → GoUsages { packages, files, modules, problems, types }, or undefined without a Go module — the Go pass alone (see below).
  • scanFile(file, code, known) → FileScan { sites, candidates, problem? } — the syntactic pass over one file; parseSpecifier(specifier) splits a bare import into package and entry point.
  • resolveTypes({ dir, workspaces, files, known, signal? }) → TypesOutcome — the type checker pass; packageOfPath(path, workspaces) maps a declaration file to its package.
  • Fleet views, all pure and generic over how a repository is identified (UsageEntry<Origin> { origin, data }):
    • packageUsage(entries, name) → PackageUsage { name, ecosystem?, subpath?, versions, repos, exports } — repositories using the package with versions and counts, and each export summed over them with kinds, members and props. name may be a Go module path (every package of the module) or a Go import path inside a module (resolveUsedPackage: the longest module path any record names, prefix at a / boundary); then subpath is set and only that package’s exports count. A Go module path without /vN that records also hold other majors of (example.com/kit and example.com/kit/v2) resolves as a family: every major counts, each repository’s majors merged into one entry.
    • findSites(entries, { package, export?, member?, prop?, kind?, origins?, limit? }) → { sites, total, more } — kept sites with snippets; package resolves like packageUsage. member matches a path or a run of its segments (reset finds ().reset).
    • upgradeImpact({ entries, package, changes, declarations? }) → UpgradeImpact { package, ecosystem?, items, affected, unaffected, widened?, untyped? } — see below. changes are UpgradeChanges, which PackageDiff.changes of @holtkeeper/api-surface satisfy.
    • repoPackages(data) — the packages of one record with ecosystem (npm when absent), versions and counts.
    • usedByCounts(entries, names) → Map<name, UsedByCount { repos, count, files }> — totals per package without the per-export breakdown; unused names map to zeros.
  • narrowImpact(impact, keep) → { impact, others }: the impact reduced to the repositories keep accepts (items keep only those uses and are dropped without any; affected, unaffected, widened and untyped filtered alike), with others counting the affected repositories left out.
  • Markdown for agents: renderPackageUsage(usage, { originLabel, teamOf?, repositories? }) (repositories: false leaves out the title and repository list, for callers that list repositories themselves), renderSites(found, originLabel?, teamOf?) (teamOf names each repository’s team), renderImpact(impact, originLabel?), impactNotes(impact, originLabel?) (one sentence per widened interface and one naming the users read without types; renderImpact appends them), renderSite(site, label?), snippetLanguage(file) (code fences are go for Go files).
  • Model: UsagesData { packages, files, types, problems? }, UsedPackage { name, ecosystem?, versions, ranges, workspaces, local?, count, files, exports } (ecosystem is 'Go' for Go modules, absent for npm), UsageEcosystem, UsedExport { name, subpath, count, files, kinds, members, props, spread, sites, truncated? }, UsageSite { file, line, column, kind, member?, props?, spread?, typed?, snippet, snippetLine }, TypeResolution { status, reason?, projects?, sites? }, UsageKind, usageKinds, isUsageKind(value), importPath(name, subpath), usageLimits.
  1. Files — every ts, tsx, mts, cts, js, jsx, mjs, cjs file of the checkout except declaration files and anything under node_modules, .git, dist, build, out, coverage and framework caches; at most 20 000. Each file belongs to the deepest workspace (package.json workspaces or pnpm-workspace.yaml) containing it.
  2. Packages — a bare import counts when some workspace declares the package in its dependencies (any field) or the package is one of the workspaces; a workspace importing itself does not count. Relative paths, Node built-ins, URLs, # imports and @/ / ~/ aliases are never packages.
  3. Imports (oxc parser, no type information) — named, aliased, default and namespace imports, require() and import() with or without destructuring, const { a } = ns, export … from and side-effect imports. Each reference to an imported name becomes a site with its kind: call, new, jsx, member, type (type references and typeof), extends (also implements and interface heritage), reexport, reference; names never referenced become import sites. Member chains are followed up to four segments with () for call results (useStore().level.up), destructuring of an export or its call result lists one site per property, a namespace’s first member names the export, and JSX sites carry the attribute names, children when the element has any, and whether props were spread. Shadowing of an imported name by a local one is not tracked.
  4. Types (optional) — names the imports do not explain (locals, member reads on values of unknown origin, JSX tags and type names without an import) go to the TypeScript 7 checker through its API (typescript/unstable/async, which spawns tsgo and talks to it over stdio; the sync API needs Node’s file descriptors and does not run on Bun). Every tsconfig*.json at the root and in each workspace is opened; files outside all projects are skipped. A name counts when its declaration (after following aliases) lies in node_modules/<package> (@types/x counts as x; TypeScript’s default libraries never count) or in another workspace, and the package is a declared dependency. The export is the outermost named declaration around it and the member the rest: store.reset() with store = useStore() is Store → reset, a component imported through a local barrel or a paths alias is the package’s component with its props. Members of type literals the package never names go under the export (anonymous). Sites found this way are typed and use subpath .. Offsets are UTF-16 in both parsers, so non-ASCII text before a use does not shift it. The checker needs installed dependencies and reports skipped without them or without a tsconfig.json, failed with the error when it cannot start or answer; uses from imports are kept either way.
  5. Versions — from the lockfile through @holtkeeper/depgraph-js for the workspaces importing the package (all workspaces when those resolve none), highest first; ranges are what the importing workspaces declare.
  6. Caps — 20 sites with a snippet per export (two lines around the use, common indentation removed, lines cut at 200 characters), 100 members and props per export, 50 problems. Counts always cover every use.

extractGoUsages reads Go code with the scanner of @holtkeeper/go-source, which needs neither the go command nor the network, then optionally asks the Go type checker:

  1. Modules — the use directories of a root go.work plus every other go.mod up to four directories deep (vendor, testdata, node_modules and hidden folders skipped). Each .go file, _test.go included, belongs to the deepest module containing it; files under vendor, testdata, hidden or _-prefixed folders are skipped, as are files outside every module. At most 20 000 files.
  2. Imports — each import path resolves through the owning go.mod (resolveGoImport): the repository’s own, nested and go.work modules and modules replaced by a local directory are local; require and module replace entries give the module and version; paths whose first element has no dot are the standard library and skipped; paths nothing covers are logged and skipped. Imports of the owning module itself are skipped, as a JavaScript workspace importing itself is.
  3. Records — one UsedPackage per module: name is the module path with its /vN, ecosystem: 'Go', each export’s subpath is the package directory inside the module (. for the root package), so importPath(name, subpath) is the Go import path and matches ApiPackage.name of @holtkeeper/api-surface. versions is the version of that module path the owning modules build with (a same-path replace target’s version, else require; a replace by another module path keeps the require version, because the fork’s version means nothing for the original path), ranges the require versions, workspaces the importing module paths. A module that is local only through a directory replace the module discovery did not find (a fork or a sibling checkout) also gets replaced: true, so fleet views do not treat it as a module the repository defines. A local package whose package clause differs from its directory name is matched by its declared name.
  4. Kinds — pkg.F(...) (also pkg.F[T](...)) is call; pkg.T{...} and &pkg.T{...} are new with the keys of a keyed literal as props; type positions are type; struct and interface embedding extends; type X = pkg.Y reexport; pkg.V.X and pkg.T.M member (export V/T, member X/M); anything else reference. Blank and dot imports, and imports never referred to, are one import site with export *.
  5. Types (optional) — with types on (default) and a runner, goTypedUsages of @holtkeeper/go-source type-checks the modules: the go.work members in one run in workspace mode, every other module alone with GOWORK=off. It reports fields and methods reached through values (c := canvas.New(); c.Draw(s) is export Canvas, member Draw, kind call; a field read is member) as typed sites, attributed to the exported type declaring the member, or to the exported type embedding the unexported one that does, and mapped to a module through the owning go.mod like any import. Chains rooted at a package name (pkg.V.X) stay with the syntactic pass; a typed site in a file the syntactic pass skipped (excluded, vendor, outside every module) or at a position it already holds is dropped; the standard library and the owning modules never count. types is used with the module paths as projects and the sites added, skipped without Go (go: go is not available: …) or a runner, failed when no run succeeded (a download or go list error); type errors in some packages keep the run used and show in reason. The syntactic result stands in every case, and the job never fails because of this pass. Bounded by typesTimeoutMs (default 5 minutes over all runs) and 100 000 sites.

upgradeImpact joins an API diff with the uses of every repository, matching by export name:

  • a removed export is breaking wherever it is used;
  • a changed declaration is breaking where a use touches a member or prop the new declaration no longer lists (declaredMembers of @holtkeeper/api-surface, which no longer is exported here: those of before minus those of after) — through the export itself or through any export whose old declaration mentions it, e.g. props passed to Button for a changed ButtonProps; other uses of it are check;
  • a deprecated export is deprecated wherever used; added exports are ignored.

For Go, package is the import path of one Go package (ApiPackage.name) and only uses where importPath(module, subpath) equals it count. A method symbol Type.Method matches uses of export Type that read member Method (breaking when removed, check when changed); struct fields and interface methods are members, keyed composite literal fields props.

A changed Go interface whose new declaration keeps every line of the old one and only adds methods (addedInterfaceMethods(before, after)) breaks no use: code that accepts or calls it keeps compiling, only types implementing it outside the library must add the methods, and usage records do not show implementations. Such a change is no item and its users stay unaffected; it is listed in widened (name, subpath, added members, the repositories using it). For Go, untyped lists the users whose record ran without the type checker (types.status other than used, with its reason), whose uses miss methods called on values the package returns.

Items are sorted by level, then by uses; each lists the repositories with their versions, the export the uses go through (via), the members touched and up to ten sites. Which repositories still need the upgrade is the caller’s choice; the server leaves out those already on the target version.

  • JavaScript, TypeScript and Go; other ecosystems need their own scanner. Without the Go type checker, Go uses are syntactic: methods on returned values, dot-imported names and uses through local wrappers are invisible. With it, members reached through values count, but dot-imported names used without a selector and type arguments of instantiations still do not; packages that need cgo are checked with CGO_ENABLED=0, so cgo-only files are left out.
  • Records keep a sample of sites per export; findSites returns kept sites only, total counts all uses where the query does not narrow below an export. When limit cuts, imports of the package are kept before uses reached through other packages’ types, in repository order.
  • Without the checker, uses through local wrappers, re-exporting barrels, paths aliases or values a package returned are invisible; with it, uses typed as any still are.
  • Member-level impact reads declarations as text: members declared one per line inside the outer braces are found, mapped or computed types are not.