UNPKG

@jsdocs-io/extractor

Version:

The API extractor for npm packages powering jsdocs.io

43 lines (42 loc) 1.61 kB
import { types as resolveTypes } from "@es-joy/resolve.exports"; /** `getPackageTypes` returns the TypeScript type definition file (e.g., `index.d.ts`) that acts as the entry point for the package at the given subpath. */ export function getPackageTypes({ pkgJson, subpath = ".", }) { subpath = subpath.trim() || "."; return getExportsMapTypes({ pkgJson, subpath }) ?? getTypesOrTypings({ pkgJson, subpath }); } function getExportsMapTypes({ pkgJson, subpath, }) { try { // Try to resolve the `exports` map in `package.json` // with conditions `import` and `types` enabled to find // a valid TypeScript type definitions file. const entries = resolveTypes(pkgJson, subpath) ?? []; // Return first entry, if valid. const entry = entries.at(0); if (!entry || !isTypesFile(entry)) return undefined; return entry; } catch { // The package may not have an `exports` map. return undefined; } } function getTypesOrTypings({ pkgJson, subpath, }) { // Try to find the `package.json#/types` (or `typings`) file // but accept it only to describe the types for the root subpath. if (!isRootSubpath({ pkgJson, subpath })) return undefined; const entry = pkgJson.types || pkgJson.typings; if (!entry || !isTypesFile(entry)) return undefined; return entry; } function isRootSubpath({ pkgJson, subpath }) { return [".", pkgJson.name].includes(subpath); } function isTypesFile(filename) { return [".d.ts", ".d.mts", ".d.cts"].some((ext) => filename.endsWith(ext)); }