Skip to content

Commit 5d18683

Browse files
agorischekCopilot
andauthored
typescript-public-api: entry points use the nearest tsconfig, so paths apply (#350)
* typescript-public-api: entry points use the nearest tsconfig, so paths apply With inputs.entrypoints and no inputs.tsconfig, the program used generic default options, so tsconfig paths aliases (`@/commands/config`) didn't resolve. Each entry point now takes the nearest tsconfig.json above it, as an editor does. typesVersions ranges also read caret, tilde and hyphen forms, so the table the compiler would apply is the one used. Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> * Name the changelog fragment after #350 Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> * Check each entry point under its own nearest tsconfig only An entry point belongs to the nearest tsconfig.json above it: another selected tsconfig that also includes it (a root one without the package's paths) no longer checks it, and an entry point without one gets the default options rather than the first package's. Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> * Suggest entry points whenever a program without them fails A package tsconfig that includes tests or scripts (with a lib or rootDir they don't fit) failed every extraction, and only unresolved modules got the advice to set inputs.entrypoints. Any analysis failure without entry points now suggests them. Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --------- Co-authored-by: agorischek <6295280+agorischek@users.noreply.github.com> Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
1 parent ee43662 commit 5d18683

8 files changed

Lines changed: 252 additions & 72 deletions

File tree

‎changelog.d/350.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
section: fixes
3+
---
4+
5+
- **`typescript-public-api` applies `paths` when only entry points are set** (#350). When `inputs.entrypoints` was set without `inputs.tsconfig`, the extractor used a default program and aliases like `@/commands/config` didn't resolve. It now uses the nearest `tsconfig.json` above each entry point. `typesVersions` ranges written with `^`, `~` or a hyphen (`^5.0`, `~5.9`, `5.0 - 5.9`) are now read as the compiler reads them, so the table that applies is the one used. When the program has errors and no entry points are set, the failure now suggests setting `inputs.entrypoints` to the package's source entry points, which keeps a tsconfig's tests and scripts out of the program.

‎docs/builtins/extractors/typescript-public-api.md‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -49,11 +49,14 @@ have much to show. For other languages, see
4949
and `rootDir`, or `typesVersions`. When nothing maps a target, set
5050
`entrypoints` to the source files.
5151
- **The TypeScript program.** Uses `inputs.tsconfig` (or `inputs.tsconfigs` for
52-
a list), falling back to a root `tsconfig.json` or a strict default program
53-
over all source files. A tsconfig in a package selects only that package.
54-
Entry points add to the tsconfig's ambient `.d.ts` files instead of replacing
55-
them. Imports of referenced projects read their sources without a build; a
56-
solution tsconfig (`"files": []` with `references`) covers those projects.
52+
a list). Without one, each entry point is checked under the nearest
53+
`tsconfig.json` above it, so `paths` and `baseUrl` apply, or under strict
54+
defaults if there is none. Without entry points either, it uses a root
55+
`tsconfig.json` or a strict default program over all source files. A tsconfig
56+
in a package selects only that package. Entry points add to the tsconfig's
57+
ambient `.d.ts` files instead of replacing them. Imports of referenced
58+
projects read their sources without a build; a solution tsconfig
59+
(`"files": []` with `references`) covers those projects.
5760
- **The compiler.** Uses your repository's installed `typescript` package (5.x
5861
or 6.x; TypeScript 7 projects also install `@typescript/typescript6`),
5962
resolved upward from the tsconfig directory in `node_modules`, along with

‎packages/extractors/typescript-public-api/README.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,11 @@ and files with `declare global`), with that tsconfig's options, so only what
3636
they import is parsed and checked. A tsconfig's tests and scripts, whose
3737
dependencies may not be installed, are left out. Without entry points, every
3838
file the tsconfig includes is checked, and an unresolved module fails the
39-
extraction with a hint to set `inputs.entrypoints`. A tsconfig inside a package
40-
selects only that package's API, even if it includes sources from another
41-
package.
39+
extraction with a hint to set `inputs.entrypoints`. When `inputs.tsconfig` is
40+
omitted, each entry point is checked under the nearest `tsconfig.json` above it
41+
only, so its `paths` and `baseUrl` apply, or under the default options if there
42+
is none. A tsconfig inside a package selects only that package's API, even if it
43+
includes sources from another package.
4244

4345
Project references resolve like an editor: imports read a referenced project's
4446
source files without built declarations, and a `composite` project does not have

‎packages/extractors/typescript-support/src/typescript/programs.ts‎

Lines changed: 56 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import type {SourceFiles} from './files.js'
55
import type {Hosts} from './hosts.js'
66

77
interface Configuration {
8+
/** The selected tsconfig it is, or a solution among them stands for it through references. */
9+
origin: string
810
roots: string[]
911
options: ts.CompilerOptions
1012
/** The projects it references, whose sources stand in for their unbuilt output. */
@@ -44,36 +46,58 @@ function uncomposite(options: ts.CompilerOptions, directory: string): ts.Compile
4446
return {...options, composite: false, declaration: options.declaration ?? true, rootDir: options.rootDir ?? directory}
4547
}
4648

49+
/** The options of a program without a tsconfig. */
50+
const defaults = (): ts.CompilerOptions => ({
51+
target: ts.ScriptTarget.ES2022,
52+
module: ts.ModuleKind.ESNext,
53+
moduleResolution: ts.ModuleResolutionKind.Bundler,
54+
strict: true,
55+
allowJs: true,
56+
skipLibCheck: true,
57+
noEmit: true,
58+
types: [],
59+
})
60+
4761
/**
4862
* With entry points, each configuration's roots are the entry points it covers,
4963
* so the program holds only what they reach: a tsconfig's tests and scripts,
5064
* whose dependencies may not be installed, are neither parsed nor checked. Its
5165
* ambient declarations (a `deno.d.ts`) stay, since what they declare is used
52-
* without an import. An entry point no configuration covers takes the first
53-
* one's options.
66+
* without an import. With `owners`, an entry point belongs to its own tsconfig
67+
* only, and one without (or outside what its tsconfig includes) gets the default
68+
* options; without, an entry point no configuration covers takes the first one's.
5469
*/
55-
function scopeToEntries(result: Configuration[], entries: string[], texts: Map<string, string>): void {
70+
function scopeToEntries(result: Configuration[], entries: string[], texts: Map<string, string>, owners?: Map<string, string>): void {
5671
const covered = new Set<string>()
5772
for (const configuration of result) {
5873
const files = new Set(configuration.roots.map(file => path.resolve(file)))
59-
const own = entries.filter(file => files.has(file))
74+
const own = entries.filter(file => files.has(file) && (!owners || owners.get(file) === configuration.origin))
6075
configuration.roots = own.length ? [...own, ...[...files].filter(file => !own.includes(file) && ambient(file, texts.get(file)))] : []
6176
for (const file of own) covered.add(file)
6277
}
6378
const uncovered = entries.filter(file => !covered.has(file))
64-
if (uncovered.length && result[0]) result[0].roots.push(...uncovered)
79+
if (!uncovered.length) return
80+
if (owners || !result[0]) result.push({origin: '', roots: uncovered, options: defaults(), references: []})
81+
else result[0].roots.push(...uncovered)
6582
}
6683

6784
/**
6885
* The configurations `configs` name; without any, one over the entry points or every source. A solution
6986
* configuration, which has no files of its own, stands for the projects it references. Any other configuration's
7087
* references are its dependencies: their sources stand in for their output, which may not be built.
7188
*/
72-
function configurations(files: SourceFiles, hosts: Hosts, configs: string[], entryFiles: string[], diagnostics: ts.Diagnostic[]) {
89+
function configurations(
90+
files: SourceFiles,
91+
hosts: Hosts,
92+
configs: string[],
93+
entryFiles: string[],
94+
diagnostics: ts.Diagnostic[],
95+
owners?: Map<string, string>,
96+
) {
7397
const {root, texts, aliases, within} = files
7498
const result: Configuration[] = []
7599
const visited = new Set<string>()
76-
const parseConfig = (file: string): void => {
100+
const parseConfig = (file: string, origin: string): void => {
77101
if (visited.has(file)) return
78102
visited.add(file)
79103
const loaded = ts.readConfigFile(file, hosts.lookup)
@@ -90,48 +114,47 @@ function configurations(files: SourceFiles, hosts: Hosts, configs: string[], ent
90114
throw new Error('TypeScript project references must stay within the repository')
91115
}
92116
}
93-
result.push({roots: parsed.fileNames, options: uncomposite(parsed.options, path.dirname(file)), references})
117+
result.push({origin, roots: parsed.fileNames, options: uncomposite(parsed.options, path.dirname(file)), references})
94118
if (!parsed.fileNames.length) {
95-
for (const reference of references) parseConfig(ts.resolveProjectReferencePath(reference))
119+
for (const reference of references) parseConfig(ts.resolveProjectReferencePath(reference), origin)
96120
}
97121
}
98-
for (const file of configs) parseConfig(path.resolve(root, file))
122+
for (const file of configs) parseConfig(path.resolve(root, file), path.resolve(root, file))
99123
if (configs.length && entryFiles.length) {
100124
scopeToEntries(
101125
result,
102126
entryFiles.map(file => path.resolve(root, file)),
103127
texts,
128+
owners,
104129
)
105130
}
106131
if (!configs.length) {
107132
result.push({
133+
origin: '',
108134
roots: entryFiles.length
109135
? entryFiles.map(file => path.resolve(root, file))
110136
: [...texts.keys()].filter(
111137
file => sourceExtension.test(file) && !aliases.has(file) && !file.includes(`${path.sep}node_modules${path.sep}`),
112138
),
113-
options: {
114-
target: ts.ScriptTarget.ES2022,
115-
module: ts.ModuleKind.ESNext,
116-
moduleResolution: ts.ModuleResolutionKind.Bundler,
117-
strict: true,
118-
allowJs: true,
119-
skipLibCheck: true,
120-
noEmit: true,
121-
types: [],
122-
},
139+
options: defaults(),
123140
references: [],
124141
})
125142
}
126143
return result
127144
}
128145

129146
/**
130-
* The checked programs of the selected configurations. Each pass builds them
147+
* The checked programs of the selected configurations (each entry point in its owner's, given `owners`). Each pass builds them
131148
* from the loaded texts and loads what the compiler asked for; the passes repeat
132149
* until resolution settles.
133150
*/
134-
export async function buildPrograms(files: SourceFiles, hosts: Hosts, configs: string[], entryFiles: string[]): Promise<ts.Program[]> {
151+
export async function buildPrograms(
152+
files: SourceFiles,
153+
hosts: Hosts,
154+
configs: string[],
155+
entryFiles: string[],
156+
owners?: Map<string, string>,
157+
): Promise<ts.Program[]> {
135158
// Loaded texts never change, so each configuration parses (and binds) a file once
136159
// across resolution passes, as the language service's document registry does.
137160
// Programs themselves are rebuilt: reusing one would keep its failed resolutions.
@@ -142,7 +165,7 @@ export async function buildPrograms(files: SourceFiles, hosts: Hosts, configs: s
142165
for (let iteration = 0; iteration < 64; iteration++) {
143166
files.clearRequests()
144167
diagnostics = []
145-
programs = configurations(files, hosts, configs, entryFiles, diagnostics)
168+
programs = configurations(files, hosts, configs, entryFiles, diagnostics, owners)
146169
.filter(configuration => configuration.roots.length)
147170
.map(configuration => {
148171
const key = JSON.stringify(configuration.options)
@@ -174,9 +197,16 @@ export async function buildPrograms(files: SourceFiles, hosts: Hosts, configs: s
174197
const errors = diagnostics.filter(diagnostic => diagnostic.category === ts.DiagnosticCategory.Error)
175198
if (errors.length) {
176199
const unresolved = errors.some(diagnostic => UNRESOLVED_MODULE.has(diagnostic.code))
177-
const guidance = unresolved
178-
? "Public API collection requires resolved dependencies and valid types. Some modules didn't resolve: install the repository's dependencies, or set `inputs.entrypoints` so the program holds only what the public API reaches."
179-
: 'Public API collection requires resolved dependencies and valid types.'
200+
// Without entry points the program is everything the tsconfig includes, so its tests and scripts fail it too.
201+
const guidance = [
202+
'Public API collection requires resolved dependencies and valid types.',
203+
...(unresolved ? ["Some modules didn't resolve: install the repository's dependencies."] : []),
204+
...(entryFiles.length
205+
? []
206+
: [
207+
'If the errors are in files the public API doesn\'t import, such as tests or scripts, set `inputs.entrypoints` to its source entry points (for example `{".": "src/index.ts"}`), so the program holds only what they import.',
208+
]),
209+
].join(' ')
180210
throw new Error(
181211
`TypeScript analysis failed. Fix the project or select \`inputs.tsconfig\` or \`inputs.entrypoints\`. ${guidance}\n${diagnosticText(files.root, errors)}`,
182212
)

‎packages/extractors/typescript-support/src/typescript/project.ts‎

Lines changed: 36 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,48 @@
11
import path from 'node:path'
22
import {containedPath, record, sourcePath, type ExtractorContext} from '../shared.js'
33
import {compareIds} from '../values.js'
4-
import {inputs, native, sourceExtension, strings, type Project} from './model.js'
4+
import {inputs, native, slash, sourceExtension, strings, type Project} from './model.js'
55
import {SourceFiles} from './files.js'
66
import {createHosts, readLibraries} from './hosts.js'
77
import {apiPackages} from './packages.js'
88
import {buildPrograms} from './programs.js'
99

10-
/** The tsconfig files `inputs.tsconfig` or `inputs.tsconfigs` select, or the root `tsconfig.json` when present. */
11-
function selectedConfigs(options: ReturnType<typeof inputs>, files: SourceFiles): string[] {
10+
/**
11+
* The tsconfig files `inputs.tsconfig` or `inputs.tsconfigs` select, or those nearest the entry points (with the
12+
* entry points each owns), or the root's.
13+
*/
14+
function selectedConfigs(
15+
options: ReturnType<typeof inputs>,
16+
files: SourceFiles,
17+
entryFiles: string[],
18+
): {configs: string[]; owners?: Map<string, string>} {
1219
if (options.tsconfig !== undefined && options.tsconfigs !== undefined) {
1320
throw new Error('Use `inputs.tsconfig` or `inputs.tsconfigs`, not both')
1421
}
15-
return options.tsconfig !== undefined
16-
? strings([options.tsconfig], 'inputs.tsconfig')
17-
: options.tsconfigs !== undefined
18-
? strings(options.tsconfigs, 'inputs.tsconfigs')
19-
: files.texts.has(path.join(files.root, 'tsconfig.json'))
20-
? ['tsconfig.json']
21-
: []
22+
if (options.tsconfig !== undefined) return {configs: strings([options.tsconfig], 'inputs.tsconfig')}
23+
if (options.tsconfigs !== undefined) return {configs: strings(options.tsconfigs, 'inputs.tsconfigs')}
24+
return nearestConfigs(files, entryFiles)
25+
}
26+
27+
/**
28+
* Without a selected tsconfig, the one an editor would use for each entry point: the nearest `tsconfig.json` above it,
29+
* so its `paths` and `baseUrl` apply, and only it; an entry point without one gets the default options. Without entry
30+
* points, the root's, if any.
31+
*/
32+
function nearestConfigs(files: SourceFiles, entryFiles: string[]): {configs: string[]; owners?: Map<string, string>} {
33+
if (!entryFiles.length) return {configs: files.texts.has(path.join(files.root, 'tsconfig.json')) ? ['tsconfig.json'] : []}
34+
const owners = new Map<string, string>()
35+
for (const file of entryFiles) {
36+
for (let directory = path.dirname(path.resolve(files.root, file)); files.within(directory); directory = path.dirname(directory)) {
37+
if (files.texts.has(path.join(directory, 'tsconfig.json'))) {
38+
owners.set(path.resolve(files.root, file), path.join(directory, 'tsconfig.json'))
39+
break
40+
}
41+
if (directory === files.root) break
42+
}
43+
}
44+
const configs = [...new Set(owners.values())].map(config => slash(path.relative(files.root, config))).toSorted()
45+
return {configs, owners}
2246
}
2347

2448
/** The files `inputs.entrypoints` names, as an array or a subpath-to-path object. */
@@ -80,14 +104,14 @@ export async function projectFor(context: ExtractorContext): Promise<Project> {
80104
const root = await sourcePath(context, '.')
81105
const files = new SourceFiles(context, root)
82106
await loadTracked(context, files)
83-
const configs = selectedConfigs(options, files)
84107
const entryFiles = selectedEntryFiles(options)
108+
const {configs, owners} = selectedConfigs(options, files, entryFiles)
85109
for (const file of [...configs, ...entryFiles]) {
86110
await containedPath(context, file)
87111
await files.load(path.join(root, file), true)
88112
}
89113
const libraries = await readLibraries()
90-
const programs = await buildPrograms(files, createHosts(files, libraries), configs, entryFiles)
114+
const programs = await buildPrograms(files, createHosts(files, libraries), configs, entryFiles, owners)
91115
const packages = apiPackages(files, programs, entryFiles, configs)
92116
return {
93117
context,

‎packages/extractors/typescript-support/src/typescript/versions.ts‎

Lines changed: 53 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -11,33 +11,61 @@ const versionParts = (text: string): (number | undefined)[] | undefined =>
1111
?.slice(1, 4)
1212
.map(part => (part && /\d/u.test(part) ? Number(part) : undefined))
1313

14-
/** Whether the compiler's version satisfies a `typesVersions` range (`>=5.0`, `<4.8 || >=5`, `*`), as the compiler reads one. */
14+
type Parts = (number | undefined)[]
15+
16+
/** A range's token as comparisons: `^` and `~` as the pair of bounds each stands for. */
17+
function comparisons(token: string): [string, Parts][] | undefined {
18+
if (token === '' || token === '*' || token === 'x') return []
19+
const [, prefix = '', text = ''] = /^([=^~]|[<>]=?)?(.*)$/u.exec(token) ?? []
20+
const parts = versionParts(text)
21+
if (!parts) return undefined
22+
const [major = 0, minor = 0, patch = 0] = parts.map(part => part ?? 0)
23+
const lower: Parts = [major, minor, patch]
24+
if (prefix === '^') {
25+
const upper =
26+
major > 0 || parts[1] === undefined ? [major + 1, 0, 0] : minor > 0 || parts[2] === undefined ? [0, minor + 1, 0] : [0, 0, patch + 1]
27+
return [
28+
['>=', lower],
29+
['<', upper],
30+
]
31+
}
32+
if (prefix === '~') {
33+
return [
34+
['>=', lower],
35+
['<', parts[1] === undefined ? [major + 1, 0, 0] : [major, minor + 1, 0]],
36+
]
37+
}
38+
return [[prefix || '=', parts]]
39+
}
40+
41+
/**
42+
* Whether the compiler's version satisfies a `typesVersions` range as the compiler reads one: `*`, comparators
43+
* (`>=5.0 <6`), caret and tilde ranges (`^5.4`, `~5.9`), hyphen ranges (`5.0 - 5.9`) and alternatives (`<4.8 || >=5`).
44+
*/
1545
export function inRange(range: string, version: string): boolean {
1646
const current = versionParts(version)?.map(part => part ?? 0) ?? [0, 0, 0]
17-
return range.split('||').some(alternative =>
18-
alternative
19-
.trim()
20-
.split(/\s+/u)
21-
.every(comparator => {
22-
if (comparator === '' || comparator === '*' || comparator === 'x') return true
23-
const [, operator = '', text = ''] = /^([<>]=?|=)?(.*)$/u.exec(comparator) ?? []
24-
const parts = versionParts(text)
25-
if (!parts) return false
26-
const order = parts.reduce<number>(
27-
(found, part, index) => found || (part === undefined ? 0 : Math.sign((current[index] ?? 0) - part)),
28-
0,
29-
)
30-
return operator === '>='
31-
? order >= 0
32-
: operator === '>'
33-
? order > 0
34-
: operator === '<='
35-
? order <= 0
36-
: operator === '<'
37-
? order < 0
38-
: order === 0
39-
}),
40-
)
47+
return range.split('||').some(alternative => {
48+
const hyphen = /^\s*(\S+)\s+-\s+(\S+)\s*$/u.exec(alternative)
49+
const tokens = hyphen ? [`>=${hyphen[1]}`, `<=${hyphen[2]}`] : alternative.trim().split(/\s+/u)
50+
return tokens.every(
51+
token =>
52+
comparisons(token)?.every(([operator, parts]) => {
53+
const order = parts.reduce<number>(
54+
(found, part, index) => found || (part === undefined ? 0 : Math.sign((current[index] ?? 0) - part)),
55+
0,
56+
)
57+
return operator === '>='
58+
? order >= 0
59+
: operator === '>'
60+
? order > 0
61+
: operator === '<='
62+
? order <= 0
63+
: operator === '<'
64+
? order < 0
65+
: order === 0
66+
}) === true,
67+
)
68+
})
4169
}
4270

4371
/**

0 commit comments

Comments
 (0)