Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

scan-dangling-dts.mjs

136 lines4.3 KB

1#!/usr/bin/env node
2/**
3 * Scan built package declarations for dangling relative imports.
4 *
5 * Under bundler/node16/nodenext resolution, an explicit `.js` specifier is
6 * remapped to a sibling `.d.ts` and does **not** fall back to `/index`.
7 * Directory-barrel imports emitted as `../utils.js` therefore fail to resolve
8 * (the real file is `utils/index.d.ts`). Consumers usually set
9 * `skipLibCheck: true`, so the unresolved import silently becomes `any`
10 * instead of erroring — degrading public types without a signal.
11 *
12 * This check runs on the producer side over built package dist declarations so
13 * regressions fail CI regardless of consumer tsconfig.
14 *
15 * Run after a packages build:
16 * pnpm build:all && pnpm test:dts
17 */
18import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
19import { dirname, join, relative, resolve } from 'node:path'
20import { fileURLToPath } from 'node:url'
21​
22const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')
23const PACKAGES_DIR = join(ROOT, 'packages')
24​
25/** @param {string} dir @param {string[]} out */
26function walkDts(dir, out = []) {
27 for (const entry of readdirSync(dir)) {
28 const path = join(dir, entry)
29 const st = statSync(path)
30 if (st.isDirectory()) {
31 if (entry !== 'node_modules') walkDts(path, out)
32 } else if (entry.endsWith('.d.ts') && !entry.endsWith('.d.ts.map')) {
33 out.push(path)
34 }
35 }
36 return out
38​
39/**
40 * Whether a relative declaration import resolves to a real file.
41 * Explicit `.js`/`.mjs`/`.cjs` extensions do **not** fall back to `/index`
42 * (matching TypeScript bundler/node16/nodenext behavior).
43 *
44 * @param {string} fromFile
45 * @param {string} specifier
46 */
47function resolves(fromFile, specifier) {
48 const abs = resolve(dirname(fromFile), specifier)
49​
50 if (/\.(js|mjs|cjs)$/.test(specifier)) {
51 const noext = abs.replace(/\.(js|mjs|cjs)$/, '')
52 return ['.d.ts', '.d.mts', '.d.cts', '.ts', '.tsx'].some((ext) =>
53 existsSync(noext + ext),
54 )
55 }
56​
57 return (
58 ['.d.ts', '.ts', '.tsx'].some((ext) => existsSync(abs + ext)) ||
59 ['/index.d.ts', '/index.ts'].some((suffix) => existsSync(abs + suffix))
60 )
62​
63const IMPORT_RE = /(?:from|import)\s*\(?\s*['"](\.\.?\/[^'"]+)['"]/g
64​
65/**
66 * Strip block and line comments so import statements inside JSDoc `@example`
67 * fences (which the declaration emit also rewrites to `.js` specifiers) are
68 * not scanned as real imports.
69 *
70 * @param {string} src
71 */
72function stripComments(src) {
73 return src.replace(/\/\*[\s\S]*?\*\//g, '').replace(/^\s*\/\/.*$/gm, '')
75​
76const packageNames = existsSync(PACKAGES_DIR)
77 ? readdirSync(PACKAGES_DIR).filter((name) => {
78 try {
79 return statSync(join(PACKAGES_DIR, name)).isDirectory()
80 } catch {
81 return false
82 }
83 })
84 : []
85​
86const dists = packageNames
87 .map((name) => join(PACKAGES_DIR, name, 'dist'))
88 .filter((dir) => existsSync(dir))
89​
90if (dists.length === 0) {
91 // No built declarations to scan. This is the normal state when `nx affected`
92 // built nothing — e.g. a docs / skill / CI-only PR that touches no package.
93 // There are no `.d.ts` files, so nothing could have regressed; skip cleanly.
94 // (Running standalone? Build first — `pnpm build:all` — then re-run.)
95 console.log(
96 'scan-dangling-dts: no packages/*/dist directories found — nothing to scan (no packages built). Skipping.',
97 )
98 process.exit(0)
100​
101/** @type {string[]} */
102const findings = []
103let filesScanned = 0
104​
105for (const dist of dists) {
106 for (const file of walkDts(dist)) {
107 filesScanned += 1
108 const src = stripComments(readFileSync(file, 'utf8'))
109 IMPORT_RE.lastIndex = 0
110 let match
111 while ((match = IMPORT_RE.exec(src))) {
112 const specifier = match[1]
113 if (!resolves(file, specifier)) {
114 findings.push(`${specifier} <- ${relative(ROOT, file)}`)
115 }
116 }
117 }
119​
120const unique = [...new Set(findings)].sort()
121​
122if (unique.length === 0) {
123 console.log(
124 `scan-dangling-dts: clean (${filesScanned} .d.ts files across ${dists.length} package dist dirs)`,
125 )
126 process.exit(0)
128​
129console.error(
130 'scan-dangling-dts: dangling relative imports in published .d.ts:\n',
132console.error(unique.join('\n'))
133console.error(
134 `\n${unique.length} dangling specifier(s). Prefer concrete module paths (e.g. '../utils/client') or explicit '/index' so the declaration emit resolves under bundler/node16/nodenext.`,
136process.exit(1)