@mui/internal-code-infra 0.1.1-canary.34 → 0.1.1-canary.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  export type OctokitType = import('@octokit/rest').Octokit;
2
- export type FetchedCommitDetails = import('./types').FetchedCommitDetails;
2
+ export type FetchedCommitDetails = import('./types.js').FetchedCommitDetails;
3
3
  export type FetchCommitsOptions = {
4
4
  repo: string;
5
5
  lastRelease: string;
@@ -21,7 +21,7 @@ export type FetchCommitsOptions = {
21
21
  * @typedef {import('@octokit/rest').Octokit} OctokitType
22
22
  */
23
23
  /**
24
- * @typedef {import('./types').FetchedCommitDetails} FetchedCommitDetails
24
+ * @typedef {import('./types.js').FetchedCommitDetails} FetchedCommitDetails
25
25
  */
26
26
  /**
27
27
  * @typedef {Object} FetchCommitsOptions
@@ -1,3 +1,15 @@
1
+ /**
2
+ * Resolves the native/JS TypeScript CLI pair from the workspace root's
3
+ * `node_modules/.bin`: tsgo/tsc when the legacy `tsgo` shim exists, tsc/tsc6
4
+ * otherwise, with bare `tsc` from PATH as the JS fallback.
5
+ *
6
+ * @param {string} cwd
7
+ * @returns {Promise<{ native: string | null, js: string }>}
8
+ */
9
+ export declare function findTscPair(cwd: string): Promise<{
10
+ native: string | null;
11
+ js: string;
12
+ }>;
1
13
  /**
2
14
  * Emits TypeScript declaration files.
3
15
  * @param {string} tsconfig - The path to the tsconfig.json file.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mui/internal-code-infra",
3
- "version": "0.1.1-canary.34",
3
+ "version": "0.1.1-canary.35",
4
4
  "author": "MUI Team",
5
5
  "description": "Infra scripts and configs to be used across MUI repos.",
6
6
  "license": "MIT",
@@ -78,9 +78,13 @@
78
78
  "@octokit/plugin-retry": "^8.1.1",
79
79
  "@octokit/plugin-throttling": "^11.0.5",
80
80
  "@octokit/rest": "^22.0.1",
81
+ "@octokit/types": "^18.0.0",
81
82
  "@pnpm/config.version-policy": "^1100.2.10",
82
83
  "@pnpm/find-workspace-dir": "^1000.1.5",
83
84
  "@pnpm/parse-wanted-dependency": "^1001.0.0",
85
+ "@types/babel__core": "^7.20.5",
86
+ "@types/estree": "^1.0.10",
87
+ "@types/mdast": "^4.0.4",
84
88
  "@typescript-eslint/types": "^8.72.2",
85
89
  "@typescript-eslint/utils": "^8.72.2",
86
90
  "@vitest/eslint-plugin": "^1.6.28",
@@ -162,14 +166,10 @@
162
166
  }
163
167
  },
164
168
  "devDependencies": {
165
- "@octokit/types": "18.0.0",
166
- "@types/babel__core": "7.20.5",
167
169
  "@types/babel__preset-env": "7.10.0",
168
170
  "@types/env-ci": "3.1.4",
169
171
  "@types/eslint-plugin-jsx-a11y": "6.10.1",
170
- "@types/estree": "1.0.10",
171
172
  "@types/estree-jsx": "1.0.5",
172
- "@types/mdast": "4.0.4",
173
173
  "@types/regexp.escape": "2.0.0",
174
174
  "@types/yargs": "17.0.35",
175
175
  "@typescript-eslint/parser": "8.72.2",
@@ -197,7 +197,7 @@
197
197
  "publishConfig": {
198
198
  "access": "public"
199
199
  },
200
- "gitSha": "2246a9a019ec4fd884ec987403c2db99e9a6d1e9",
200
+ "gitSha": "648d5a45da76163e2153dfc37431b1e4df7bb868",
201
201
  "scripts": {
202
202
  "build": "tsc -p tsconfig.build.json",
203
203
  "typescript": "tsc -noEmit",
@@ -25,7 +25,7 @@ function shouldRetryRateLimit(retryAfter, options, octokit, retryCount) {
25
25
  */
26
26
 
27
27
  /**
28
- * @typedef {import('./types').FetchedCommitDetails} FetchedCommitDetails
28
+ * @typedef {import('./types.js').FetchedCommitDetails} FetchedCommitDetails
29
29
  */
30
30
 
31
31
  /**
@@ -180,7 +180,7 @@ async function fetchCommitsRest({ octokit, repo, lastRelease, release, org = 'mu
180
180
  /**
181
181
  *
182
182
  * @param {import('@octokit/rest').RestEndpointMethodTypes["pulls"]["get"]["response"]["data"]["author_association"]} input
183
- * @returns {Exclude<import('./types').FetchedCommitDetails["author"], null>["association"]}
183
+ * @returns {Exclude<import('./types.js').FetchedCommitDetails["author"], null>["association"]}
184
184
  */
185
185
  function getAuthorAssociation(input) {
186
186
  switch (input) {
@@ -1,48 +1,463 @@
1
1
  /* eslint-disable no-console */
2
- import { globby } from 'globby';
2
+ import { $ } from 'execa';
3
3
  import * as fs from 'node:fs/promises';
4
+ import * as os from 'node:os';
5
+ import * as path from 'node:path';
6
+ import { mapAsync, uniqBy } from 'es-toolkit/array';
7
+ import { isEqual } from 'es-toolkit/predicate';
4
8
  import { findWorkspaceDir } from '@pnpm/find-workspace-dir';
5
- import { mapAsync } from 'es-toolkit/array';
9
+ import { resolveExports } from 'resolve-pkg-maps';
10
+ import * as semver from 'semver';
11
+ import { stringify } from 'yaml';
12
+ import { getWorkspacePackages, readPackageJson, writePackageJson } from '../utils/pnpm.mjs';
13
+ import { findTscPair } from '../utils/typescript.mjs';
6
14
 
7
- const DYNAMIC_PACKAGES_IMPORT_REGEX = /import\((['"])packages\//gm;
15
+ /**
16
+ * @typedef {import('./packageJson').PackageJson} PackageJson
17
+ */
18
+
19
+ /**
20
+ * @typedef {Object} TypeScriptError
21
+ * @property {string} file `<package>/<path>` for files inside a packed package, otherwise relative
22
+ * to the consumer project.
23
+ * @property {string} code
24
+ * @property {string} message
25
+ */
26
+
27
+ /**
28
+ * @typedef {Map<string, string>} EntryPoints Import specifier to the declaration file it resolves
29
+ * to.
30
+ */
31
+
32
+ /**
33
+ * The kinds of consumers, with the runtime `exports` conditions each matches besides `default`.
34
+ * `types` comes first in every published manifest, so matching it in all modes is what TypeScript
35
+ * does too.
36
+ */
37
+ const CONSUMERS = [
38
+ { kind: 'esm', extension: 'mts', conditions: ['import', 'node'], module: 'nodenext' },
39
+ { kind: 'cjs', extension: 'cts', conditions: ['require', 'node'], module: 'nodenext' },
40
+ {
41
+ kind: 'bundler',
42
+ extension: 'mts',
43
+ conditions: ['import'],
44
+ module: 'esnext',
45
+ moduleResolution: 'bundler',
46
+ },
47
+ ];
48
+
49
+ /**
50
+ * @param {unknown} packageExports
51
+ * @param {string} subpath `''` for the package itself.
52
+ * @param {string[]} conditions
53
+ * @returns {string | undefined} The first target, or `undefined` when the subpath doesn't resolve.
54
+ */
55
+ function resolveTarget(packageExports, subpath, conditions) {
56
+ try {
57
+ return resolveExports(
58
+ /** @type {Parameters<typeof resolveExports>[0]} */ (packageExports),
59
+ subpath,
60
+ conditions,
61
+ )[0];
62
+ } catch (error) {
63
+ if (/** @type {{ code?: string }} */ (error).code === 'ERR_PACKAGE_PATH_NOT_EXPORTED') {
64
+ return undefined;
65
+ }
66
+ throw error;
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Lists the modules consumers can import types from under `conditions`. Glob subpaths are skipped:
72
+ * `code-infra build` expands them into concrete entries. Entry points without a runtime target,
73
+ * such as code-infra's `build-env`, are left out: nothing imports them.
74
+ *
75
+ * @param {PackageJson} packageJson A published manifest.
76
+ * @param {string[]} conditions
77
+ * @returns {EntryPoints}
78
+ */
79
+ function getTypedEntryPoints(packageJson, conditions) {
80
+ const name = /** @type {string} */ (packageJson.name);
81
+ const types = packageJson.types ?? packageJson.typings;
82
+ const packageExports =
83
+ packageJson.exports ?? (types ? { types, default: packageJson.main ?? './index.js' } : null);
84
+ if (!packageExports) {
85
+ return new Map();
86
+ }
87
+ const subpaths =
88
+ typeof packageExports === 'object' &&
89
+ !Array.isArray(packageExports) &&
90
+ Object.keys(packageExports).some((key) => key.startsWith('.'))
91
+ ? Object.keys(packageExports)
92
+ .filter((key) => !key.includes('*'))
93
+ .map((key) => key.slice(2))
94
+ : [''];
95
+ /** @type {EntryPoints} */
96
+ const entryPoints = new Map();
97
+ for (const subpath of subpaths) {
98
+ const declarations = resolveTarget(packageExports, subpath, ['types', ...conditions]);
99
+ if (
100
+ declarations &&
101
+ /\.d\.[cm]?ts$/.test(declarations) &&
102
+ resolveTarget(packageExports, subpath, conditions)
103
+ ) {
104
+ entryPoints.set(subpath ? `${name}/${subpath}` : name, declarations);
105
+ }
106
+ }
107
+ return entryPoints;
108
+ }
109
+
110
+ /**
111
+ * @param {EntryPoints} entryPoints
112
+ * @returns {string}
113
+ */
114
+ function createEntryFile(entryPoints) {
115
+ return `${Array.from(entryPoints.keys())
116
+ .map((specifier, index) => `import type * as entry${index} from '${specifier}';`)
117
+ .join('\n')}\nexport {};\n`;
118
+ }
119
+
120
+ /**
121
+ * `@scope/pkg` → `scope+pkg`, the same file names as @mui/internal-benchmark's `packWorkspace`.
122
+ * `+` cannot appear in a package name, so no two collide.
123
+ *
124
+ * @param {string} packageName
125
+ */
126
+ function toFileStem(packageName) {
127
+ return packageName.replace(/^@/, '').replace('/', '+');
128
+ }
8
129
 
9
130
  /**
10
- * Validates if there are no missing exports from TS files that would
11
- * result in an import from a local file.
131
+ * The range of versions that satisfy both `a` and `b`.
132
+ *
133
+ * @param {string} name
134
+ * @param {string} a
135
+ * @param {string} b
136
+ * @returns {string}
12
137
  */
13
- async function validateFiles() {
14
- const cwd = process.cwd();
15
- const workspaceRoot = await findWorkspaceDir(cwd);
16
- const declarationFiles = await globby(['**/build/**/*.d.{ts,cts,mts}'], {
17
- absolute: true,
18
- ignore: ['node_modules'],
19
- followSymbolicLinks: false,
20
- cwd: workspaceRoot,
138
+ function intersectRanges(name, a, b) {
139
+ if (!semver.validRange(a) || !semver.validRange(b)) {
140
+ return a;
141
+ }
142
+ const setsOf = (/** @type {string} */ range) =>
143
+ new semver.Range(range).set.map((comparators) => comparators.map(String).join(' '));
144
+ const intersection = setsOf(a)
145
+ .flatMap((setA) => setsOf(b).map((setB) => `${setA} ${setB}`.trim()))
146
+ .filter((range) => semver.intersects(range, range));
147
+ if (intersection.length === 0) {
148
+ throw new Error(`No version of "${name}" satisfies every peer range: "${a}" and "${b}".`);
149
+ }
150
+ return intersection.join(' || ');
151
+ }
152
+
153
+ /**
154
+ * Parses the errors in `tsc --pretty false` output that point at a file.
155
+ *
156
+ * @param {string} output
157
+ * @returns {TypeScriptError[]}
158
+ */
159
+ function parseTypeScriptErrors(output) {
160
+ /** @type {TypeScriptError[]} */
161
+ const errors = [];
162
+ for (const line of output.split(/\r?\n/)) {
163
+ const match = /^(.+?)\(\d+,\d+\): error (TS\d+): (.*)$/.exec(line);
164
+ if (match) {
165
+ errors.push({ file: match[1], code: match[2], message: match[3] });
166
+ } else if (line.startsWith(' ') && errors.length > 0) {
167
+ errors[errors.length - 1].message += `\n${line}`;
168
+ }
169
+ }
170
+ return errors;
171
+ }
172
+
173
+ /**
174
+ * Keeps the errors in the packed packages and the generated entry files. Errors inside a packed
175
+ * package are reported relative to that package, so the output doesn't depend on the store layout.
176
+ *
177
+ * @param {TypeScriptError[]} errors
178
+ * @param {string[]} packageNames
179
+ * @param {string} tempDir Stripped from messages.
180
+ * @returns {TypeScriptError[]}
181
+ */
182
+ function getOwnErrors(errors, packageNames, tempDir) {
183
+ return errors.flatMap((error) => {
184
+ const message = error.message.replaceAll(`${tempDir}/`, '');
185
+ const index = error.file.lastIndexOf('node_modules/');
186
+ if (index === -1) {
187
+ return [{ ...error, message }];
188
+ }
189
+ const modulePath = error.file.slice(index + 'node_modules/'.length);
190
+ const owner = packageNames.find((name) => modulePath.startsWith(`${name}/`));
191
+ // Errors in third-party declarations are not ours to fix.
192
+ return owner ? [{ ...error, file: modulePath, message }] : [];
21
193
  });
194
+ }
22
195
 
23
- const invalidFiles = (
24
- await mapAsync(
25
- declarationFiles,
26
- async (declarationFile) => {
27
- const content = await fs.readFile(declarationFile, 'utf-8');
28
- const matches = Array.from(content.matchAll(DYNAMIC_PACKAGES_IMPORT_REGEX));
29
- return matches.length > 0 ? declarationFile : undefined;
30
- },
31
- { concurrency: 20 },
32
- )
33
- ).filter((file) => typeof file === 'string');
196
+ /**
197
+ * @param {string} tarball
198
+ * @returns {Promise<PackageJson>}
199
+ */
200
+ async function readPackedManifest(tarball) {
201
+ const { stdout } = await $`tar -xzOf ${tarball} package/package.json`;
202
+ return JSON.parse(stdout);
203
+ }
34
204
 
35
- if (invalidFiles.length > 0) {
36
- console.error('❌ Found invalid imports in the following files:');
37
- console.log(invalidFiles.join('\n'));
38
- process.exit(1);
205
+ /**
206
+ * Installs the packed public packages into a fresh project, the way a consumer would, and
207
+ * type-checks an import of every typed entry point with `skipLibCheck` off.
208
+ *
209
+ * @param {Object} options
210
+ * @param {string} options.workspaceRoot
211
+ * @param {string} options.tempDir An empty directory outside the workspace.
212
+ * @returns {Promise<{ errors: TypeScriptError[], entryPointCount: number, packageCount: number }>}
213
+ */
214
+ async function validateBuiltTypes({ workspaceRoot, tempDir }) {
215
+ const packages = await getWorkspacePackages({ cwd: workspaceRoot, publicOnly: true });
216
+ if (packages.length === 0) {
217
+ throw new Error('No public packages found.');
218
+ }
219
+ const tarballDir = path.join(tempDir, 'tarballs');
220
+ const projectDir = path.join(tempDir, 'project');
221
+ await Promise.all([
222
+ fs.mkdir(tarballDir, { recursive: true }),
223
+ fs.mkdir(path.join(projectDir, 'checks'), { recursive: true }),
224
+ ]);
225
+
226
+ // Packed like @mui/internal-benchmark's `packWorkspace`, so each tarball is what `pnpm publish`
227
+ // would upload.
228
+ const packed = await mapAsync(
229
+ packages,
230
+ async (pkg) => {
231
+ const tarball = path.join(tarballDir, `${toFileStem(pkg.name)}.tgz`);
232
+ await $({ cwd: pkg.path })`pnpm pack --out ${tarball}`;
233
+ return { tarball, manifest: await readPackedManifest(tarball), dir: pkg.path };
234
+ },
235
+ { concurrency: os.availableParallelism() },
236
+ );
237
+
238
+ /** @type {Record<string, string>} */
239
+ const tarballs = Object.fromEntries(
240
+ packed.map(({ manifest, tarball }) => [manifest.name, `file:${tarball}`]),
241
+ );
242
+ const packageNames = Object.keys(tarballs);
243
+ // Consumers provide every peer, optional ones included, at a version in range of every package.
244
+ // The versions the workspace installed for its packages come first: they are fixed by the
245
+ // lockfile, so a new upstream release can't change the outcome until the workspace updates.
246
+ const declaredPeers = await Promise.all(
247
+ packed.flatMap(({ manifest, dir }) =>
248
+ Object.entries(manifest.peerDependencies ?? {})
249
+ .filter(([name, range]) => range && !tarballs[name])
250
+ .map(async ([name, range]) => {
251
+ const installed = await readPackageJson(path.join(dir, 'node_modules', name)).catch(
252
+ () => undefined,
253
+ );
254
+ return {
255
+ name,
256
+ range: /** @type {string} */ (range),
257
+ version: installed?.version,
258
+ // An aliased install, such as `typescript: npm:@typescript/typescript6@6.0.2`.
259
+ spec:
260
+ installed?.name === name
261
+ ? installed.version
262
+ : `npm:${installed?.name}@${installed?.version}`,
263
+ };
264
+ }),
265
+ ),
266
+ );
267
+ /** @type {Record<string, string>} */
268
+ const peerRanges = {};
269
+ for (const { name, range } of declaredPeers) {
270
+ peerRanges[name] = peerRanges[name] ? intersectRanges(name, peerRanges[name], range) : range;
271
+ }
272
+ /** @type {Record<string, string>} */
273
+ const peers = {};
274
+ for (const [name, range] of Object.entries(peerRanges)) {
275
+ peers[name] =
276
+ declaredPeers.find(
277
+ (peer) => peer.name === name && peer.version && semver.satisfies(peer.version, range),
278
+ )?.spec ?? range;
279
+ }
280
+ // Installed as in any project that uses Node packages, but not made ambient: a program only loads
281
+ // Node types when declarations reference them, so they don't reach sources that shouldn't see them.
282
+ peers['@types/node'] ??= await readPackageJson(
283
+ path.join(workspaceRoot, 'node_modules', '@types/node'),
284
+ ).then(
285
+ (packageJson) => packageJson.version ?? '*',
286
+ () => '*',
287
+ );
288
+
289
+ // One program per package and consumer kind. A consumer is either ESM or CommonJS, and installs
290
+ // one package rather than all of them: a shared program would check the global augmentations of
291
+ // unrelated packages, and of a package's CommonJS and ESM declarations, against each other.
292
+ // CommonJS and bundler consumers only get a program of their own when they resolve other
293
+ // declarations than ESM consumers; on the same files, they find nothing an ESM program misses.
294
+ const checks = packed.flatMap(({ manifest }) => {
295
+ const stem = path.join('checks', toFileStem(/** @type {string} */ (manifest.name)));
296
+ const [esm, ...others] = CONSUMERS.map(({ kind, extension, conditions, ...options }) => ({
297
+ file: `${stem}.${kind}.${extension}`,
298
+ entryPoints: getTypedEntryPoints(manifest, conditions),
299
+ ...options,
300
+ }));
301
+ return [
302
+ esm,
303
+ ...others.filter(({ entryPoints }) => !isEqual(entryPoints, esm.entryPoints)),
304
+ ].filter(({ entryPoints }) => entryPoints.size > 0);
305
+ });
306
+ const entryPointCount = new Set(
307
+ checks.flatMap(({ entryPoints }) => Array.from(entryPoints.keys())),
308
+ ).size;
309
+ if (entryPointCount === 0) {
310
+ throw new Error(
311
+ `No entry points with types found in ${packed.length} packages. Build the packages first.`,
312
+ );
39
313
  }
40
314
 
41
- console.log('✅ Found no invalid import statements in built declaration files.');
315
+ await writePackageJson(projectDir, { private: true, dependencies: { ...peers, ...tarballs } });
316
+ // Every package and peer is a dependency of the project, so a package that looked them up from
317
+ // the project's node_modules would resolve what it never declared. With hoisting off and the
318
+ // virtual store outside the project, it only finds the dependencies pnpm linked for it.
319
+ await fs.writeFile(
320
+ path.join(projectDir, 'pnpm-workspace.yaml'),
321
+ stringify({
322
+ virtualStoreDir: '../virtual-store',
323
+ enableGlobalVirtualStore: false,
324
+ hoistPattern: [],
325
+ publicHoistPattern: [],
326
+ autoInstallPeers: false,
327
+ strictPeerDependencies: false,
328
+ blockExoticSubdeps: false,
329
+ ignoreScripts: true,
330
+ overrides: tarballs,
331
+ }),
332
+ );
333
+ await $({ cwd: projectDir })`pnpm install --lockfile=false --prefer-offline`;
334
+
335
+ const compilerOptions = {
336
+ strict: true,
337
+ skipLibCheck: false,
338
+ noEmit: true,
339
+ types: [],
340
+ lib: ['esnext', 'dom', 'dom.iterable'],
341
+ jsx: 'react-jsx',
342
+ };
343
+ const { native, js } = await findTscPair(workspaceRoot);
344
+ const tsc = native ?? js;
345
+ const realTempDir = await fs.realpath(tempDir);
346
+ const ownErrors = await mapAsync(
347
+ checks,
348
+ async ({ file, entryPoints, module, moduleResolution }) => {
349
+ const tsconfigFile = `${file}.json`;
350
+ await Promise.all([
351
+ fs.writeFile(path.join(projectDir, file), createEntryFile(entryPoints)),
352
+ fs.writeFile(
353
+ path.join(projectDir, tsconfigFile),
354
+ `${JSON.stringify({ compilerOptions: { ...compilerOptions, module, moduleResolution }, files: [path.basename(file)] }, null, 2)}\n`,
355
+ ),
356
+ ]);
357
+ const result = await $({
358
+ cwd: projectDir,
359
+ reject: false,
360
+ })`${tsc} -p ${tsconfigFile} --pretty false`;
361
+ const fileErrors = parseTypeScriptErrors(result.stdout);
362
+ // Errors in third-party declarations also fail tsc, but a failure without any error in a
363
+ // file means tsc didn't check the program at all.
364
+ if (result.failed && fileErrors.length === 0) {
365
+ throw new Error(
366
+ `TypeScript failed to check ${tsconfigFile}:\n${result.stdout || result.stderr || result.message}`,
367
+ );
368
+ }
369
+ return getOwnErrors(fileErrors, packageNames, realTempDir);
370
+ },
371
+ // Native tsc checks on several threads of its own and takes hundreds of MB per program.
372
+ {
373
+ concurrency: native
374
+ ? Math.max(1, Math.floor(os.availableParallelism() / 4))
375
+ : os.availableParallelism(),
376
+ },
377
+ );
378
+
379
+ return {
380
+ errors: uniqBy(ownErrors.flat(), (error) => `${error.file}\0${error.code}\0${error.message}`),
381
+ entryPointCount,
382
+ packageCount: packed.length,
383
+ };
42
384
  }
43
385
 
44
- export default /** @type {import('yargs').CommandModule<{}, {}>} */ ({
386
+ /**
387
+ * @typedef {Object} Args
388
+ * @property {boolean} keep
389
+ * @property {string[]} [expectError]
390
+ */
391
+
392
+ export default /** @type {import('yargs').CommandModule<{}, Args>} */ ({
45
393
  command: 'validate-built-types',
46
- describe: 'Validate built TypeScript declaration files for invalid imports from local files.',
47
- handler: validateFiles,
394
+ describe:
395
+ 'Install the packed public packages into a fresh project and type-check every entry point that has types, as a consumer would. Run after building.',
396
+ builder: (yargs) =>
397
+ yargs
398
+ .option('keep', {
399
+ type: 'boolean',
400
+ default: false,
401
+ description: 'Keep the consumer project for inspection.',
402
+ })
403
+ .option('expect-error', {
404
+ type: 'string',
405
+ array: true,
406
+ default: [],
407
+ description:
408
+ 'A path in a package, such as `@scope/pkg/subdir`, whose declarations are known to fail. Errors in files under it are not reported, and the check fails once there are none. Repeatable.',
409
+ }),
410
+ handler: async ({ keep, expectError = [] }) => {
411
+ const workspaceRoot = await findWorkspaceDir(process.cwd());
412
+ if (!workspaceRoot) {
413
+ throw new Error('Workspace directory not found');
414
+ }
415
+ const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'code-infra-built-types-'));
416
+ let failed = false;
417
+ try {
418
+ const { errors, entryPointCount, packageCount } = await validateBuiltTypes({
419
+ workspaceRoot,
420
+ tempDir,
421
+ });
422
+ // Errors are matched by the file they are in rather than by entry point: declarations can
423
+ // fail only next to another entry point's, such as conflicting module augmentations.
424
+ const expectedPaths = expectError.map((expected) => expected.replace(/\/+$/, ''));
425
+ const isUnder = (/** @type {string} */ file, /** @type {string} */ prefix) =>
426
+ file === prefix || file.startsWith(`${prefix}/`);
427
+ const unexpectedErrors = errors.filter(
428
+ (error) => !expectedPaths.some((prefix) => isUnder(error.file, prefix)),
429
+ );
430
+ for (const expected of expectedPaths) {
431
+ const count = errors.filter((error) => isUnder(error.file, expected)).length;
432
+ if (count > 0) {
433
+ console.log(`Ignoring ${count} expected type errors in ${expected}.`);
434
+ } else {
435
+ failed = true;
436
+ console.error(`❌ No type errors in ${expected}: remove it from --expect-error.`);
437
+ }
438
+ }
439
+ if (unexpectedErrors.length > 0) {
440
+ failed = true;
441
+ console.error(
442
+ `❌ Found ${unexpectedErrors.length} type errors in ${entryPointCount} entry points of ${packageCount} packages.\n`,
443
+ );
444
+ for (const error of unexpectedErrors) {
445
+ console.error(`${error.file}: ${error.code} ${error.message}`);
446
+ }
447
+ }
448
+ if (failed) {
449
+ process.exitCode = 1;
450
+ } else {
451
+ console.log(
452
+ `✅ ${entryPointCount} entry points of ${packageCount} packages type-check for consumers.`,
453
+ );
454
+ }
455
+ } finally {
456
+ if (keep || failed) {
457
+ console.error(`\nConsumer project: ${path.join(tempDir, 'project')}`);
458
+ } else {
459
+ await fs.rm(tempDir, { recursive: true, force: true });
460
+ }
461
+ }
462
+ },
48
463
  });
@@ -37,7 +37,7 @@ async function findBin(dir, name) {
37
37
  * @param {string} cwd
38
38
  * @returns {Promise<{ native: string | null, js: string }>}
39
39
  */
40
- async function findTscPair(cwd) {
40
+ export async function findTscPair(cwd) {
41
41
  const workspaceDir = await findWorkspaceDir(cwd);
42
42
  if (!workspaceDir) {
43
43
  return { native: null, js: 'tsc' };
@@ -1,18 +0,0 @@
1
- #!/usr/bin/env node
2
- export type Args = {
3
- /**
4
- * - Run with verbose logging
5
- */
6
- verbose?: boolean;
7
- /**
8
- * - Screenshots folder path
9
- */
10
- folder: string;
11
- };
12
- /**
13
- * @typedef {Object} Args
14
- * @property {boolean} [verbose] - Run with verbose logging
15
- * @property {string} folder - Screenshots folder path
16
- */
17
- declare const _default: import('yargs').CommandModule<{}, Args>;
18
- export default _default;
@@ -1,18 +0,0 @@
1
- #!/usr/bin/env node
2
- export type Args = {
3
- /**
4
- * - Branch pull requests fork from
5
- */
6
- baseBranch?: string;
7
- /**
8
- * - Remote the base branch is fetched from
9
- */
10
- remote?: string;
11
- };
12
- /**
13
- * @typedef {Object} Args
14
- * @property {string} [baseBranch] - Branch pull requests fork from
15
- * @property {string} [remote] - Remote the base branch is fetched from
16
- */
17
- declare const _default: import('yargs').CommandModule<{}, Args>;
18
- export default _default;
@@ -1,68 +0,0 @@
1
- export type Args = {
2
- /**
3
- * - The bundles to build.
4
- */
5
- bundle: import('../utils/build.mjs').BundleType[];
6
- /**
7
- * - The large files to build.
8
- */
9
- hasLargeFiles: boolean;
10
- /**
11
- * - Whether to skip generating a package.json file in the /esm folder.
12
- */
13
- skipBundlePackageJson: boolean;
14
- /**
15
- * - Whether to enable verbose logging.
16
- */
17
- verbose: boolean;
18
- /**
19
- * - Whether to build types for the package.
20
- */
21
- buildTypes: boolean;
22
- /**
23
- * - Whether to build types for the package.
24
- */
25
- skipTsc: boolean;
26
- /**
27
- * - Whether to skip checking for Babel runtime dependencies in the package.
28
- */
29
- skipBabelRuntimeCheck: boolean;
30
- /**
31
- * - Whether to skip generating the package.json file in the bundle output.
32
- */
33
- skipPackageJson: boolean;
34
- /**
35
- * - Whether to skip checking for main field in package.json.
36
- */
37
- skipMainCheck: boolean;
38
- /**
39
- * - Whether to skip validating the output directory with publint.
40
- */
41
- skipPublint: boolean;
42
- /**
43
- * - Globs to be ignored by Babel.
44
- */
45
- ignore: string[];
46
- /**
47
- * - Files/Directories to be copied. Can be a glob pattern.
48
- */
49
- copy?: string[];
50
- /**
51
- * - Whether to use the React compiler.
52
- */
53
- enableReactCompiler?: boolean;
54
- /**
55
- * - Whether to build types using the native TypeScript compiler.
56
- */
57
- tsgo?: boolean;
58
- /**
59
- * - Deprecated no-op; flat builds are always used.
60
- */
61
- flat?: boolean;
62
- /**
63
- * - Whether to enumerate glob patterns in exports/imports into concrete entries.
64
- */
65
- expand: boolean;
66
- };
67
- declare const _default: import('yargs').CommandModule<{}, Args>;
68
- export default _default;
@@ -1,20 +0,0 @@
1
- export type Args = {
2
- /**
3
- * Run in silent mode without logging
4
- */
5
- silent?: boolean;
6
- /**
7
- * Exclude default files from the copy operation
8
- */
9
- excludeDefaults?: boolean;
10
- /**
11
- * Glob patterns to copy
12
- */
13
- glob?: string[];
14
- /**
15
- * Extra files to copy
16
- */
17
- files?: string[];
18
- };
19
- declare const _default: import('yargs').CommandModule<{}, Args>;
20
- export default _default;
@@ -1,6 +0,0 @@
1
- export type Args = import('../utils/extractErrorCodes.mjs').Args;
2
- /**
3
- * @typedef {import('../utils/extractErrorCodes.mjs').Args} Args
4
- */
5
- declare const _default: import('yargs').CommandModule<{}, Args>;
6
- export default _default;
@@ -1,32 +0,0 @@
1
- export type Args = {
2
- /**
3
- * Path to the changelog configuration file
4
- */
5
- config: string;
6
- /**
7
- * The git reference (tag/commit) of the last release
8
- */
9
- lastRelease: string;
10
- /**
11
- * The git reference (tag/commit) of the new release
12
- */
13
- release: string;
14
- /**
15
- * The version number for the new release
16
- */
17
- releaseVersion: string;
18
- /**
19
- * The current working directory to run the command in
20
- */
21
- cwd: string;
22
- };
23
- /**
24
- * @typedef {Object} Args
25
- * @property {string} config Path to the changelog configuration file
26
- * @property {string} lastRelease The git reference (tag/commit) of the last release
27
- * @property {string} release The git reference (tag/commit) of the new release
28
- * @property {string} releaseVersion The version number for the new release
29
- * @property {string} cwd The current working directory to run the command in
30
- */
31
- declare const _default: import('yargs').CommandModule<{}, Args>;
32
- export default _default;
@@ -1,11 +0,0 @@
1
- export type Args = {
2
- authorize: boolean;
3
- clear: boolean;
4
- };
5
- /**
6
- * @typedef {Object} Args
7
- * @property {boolean} authorize
8
- * @property {boolean} clear
9
- */
10
- declare const _default: import('yargs').CommandModule<{}, Args>;
11
- export default _default;
@@ -1,29 +0,0 @@
1
- #!/usr/bin/env node
2
- export type PublicPackage = import('../utils/pnpm.mjs').PublicPackage;
3
- export type Args = {
4
- /**
5
- * - Whether to filter to only public packages
6
- */
7
- publicOnly?: boolean;
8
- /**
9
- * - Output format (name, path, or json)
10
- */
11
- output?: 'json' | 'path' | 'name';
12
- /**
13
- * - Git reference to filter changes since
14
- */
15
- sinceRef?: string;
16
- /**
17
- * - Same as filtering packages with --filter in pnpm. Only include packages matching the filter. See https://pnpm.io/filtering.
18
- */
19
- filter?: string[];
20
- };
21
- /**
22
- * @typedef {Object} Args
23
- * @property {boolean} [publicOnly] - Whether to filter to only public packages
24
- * @property {'json'|'path'|'name'} [output] - Output format (name, path, or json)
25
- * @property {string} [sinceRef] - Git reference to filter changes since
26
- * @property {string[]} [filter] - Same as filtering packages with --filter in pnpm. Only include packages matching the filter. See https://pnpm.io/filtering.
27
- */
28
- declare const _default: import('yargs').CommandModule<{}, Args>;
29
- export default _default;
@@ -1,17 +0,0 @@
1
- #!/usr/bin/env node
2
- export type Args = {
3
- /**
4
- * - Workspace names or root-relative paths to process
5
- */
6
- workspaces: string[];
7
- /**
8
- * - Check mode - error if the generated content differs from current
9
- */
10
- check?: boolean;
11
- /**
12
- * - Branch to compare PRs against (default: master)
13
- */
14
- baseBranch?: string;
15
- };
16
- declare const _default: import('yargs').CommandModule<{}, Args>;
17
- export default _default;
@@ -1,32 +0,0 @@
1
- #!/usr/bin/env node
2
- export type PublicPackage = import('../utils/pnpm.mjs').PublicPackage;
3
- export type PublishOptions = import('../utils/pnpm.mjs').PublishOptions;
4
- export type PublishSummaryEntry = import('../utils/pnpm.mjs').PublishSummaryEntry;
5
- export type Args = {
6
- /**
7
- * Run in dry-run mode without publishing
8
- */
9
- "dry-run": boolean;
10
- /**
11
- * Create a GitHub draft release after publishing
12
- */
13
- "github-release": boolean;
14
- /**
15
- * NPM dist tag to publish to
16
- */
17
- tag: string;
18
- /**
19
- * Runs in CI environment
20
- */
21
- ci: boolean;
22
- /**
23
- * Git SHA to use for the GitHub release workflow (local only)
24
- */
25
- sha?: string;
26
- /**
27
- * Same as filtering packages with --filter in pnpm. Only publish packages matching the filter. See https://pnpm.io/filtering.
28
- */
29
- filter?: string[];
30
- };
31
- declare const _default: import('yargs').CommandModule<{}, Args>;
32
- export default _default;
@@ -1,34 +0,0 @@
1
- #!/usr/bin/env node
2
- export type PublicPackage = import('../utils/pnpm.mjs').PublicPackage;
3
- export type VersionInfo = import('../utils/pnpm.mjs').VersionInfo;
4
- export type PublishOptions = import('../utils/pnpm.mjs').PublishOptions;
5
- export type Args = {
6
- /**
7
- * - Whether to run in dry-run mode
8
- */
9
- dryRun?: boolean;
10
- /**
11
- * - Whether to create GitHub releases for canary packages
12
- */
13
- githubRelease?: boolean;
14
- /**
15
- * - Same as filtering packages with --filter in pnpm. Only publish packages matching the filter. See https://pnpm.io/filtering.
16
- */
17
- filter?: string[];
18
- };
19
- export type Commit = {
20
- /**
21
- * - Commit SHA
22
- */
23
- sha: string;
24
- /**
25
- * - Commit message
26
- */
27
- message: string;
28
- /**
29
- * - Commit author
30
- */
31
- author: string;
32
- };
33
- declare const _default: import('yargs').CommandModule<{}, Args>;
34
- export default _default;
@@ -1,17 +0,0 @@
1
- export type Args = {
2
- /**
3
- * If true, will only log the commands without executing them
4
- */
5
- dryRun?: boolean;
6
- /**
7
- * 6 digit auth code to forward to npm for two-factor authentication
8
- */
9
- otp?: string;
10
- };
11
- /**
12
- * @typedef {Object} Args
13
- * @property {boolean} [dryRun] If true, will only log the commands without executing them
14
- * @property {string} [otp] 6 digit auth code to forward to npm for two-factor authentication
15
- */
16
- declare const _default: import('yargs').CommandModule<{}, Args>;
17
- export default _default;
@@ -1,18 +0,0 @@
1
- #!/usr/bin/env node
2
- export type Args = {
3
- /**
4
- * Source and target scope
5
- */
6
- alias: [string, string];
7
- };
8
- /**
9
- * @typedef {Object} Args
10
- * @property {[string, string]} alias Source and target scope
11
- */
12
- /**
13
- * @param {string} alias
14
- * @returns {[string, string]}
15
- */
16
- export declare function parseAlias(alias: string): [string, string];
17
- declare const _default: import('yargs').CommandModule<{}, Args>;
18
- export default _default;
@@ -1,9 +0,0 @@
1
- #!/usr/bin/env node
2
- export type Args = {
3
- /**
4
- * - Package version specifiers in format 'package@version'
5
- */
6
- pkg?: string[];
7
- };
8
- declare const _default: import('yargs').CommandModule<{}, Args>;
9
- export default _default;
@@ -1,46 +0,0 @@
1
- export type ValeOS = 'Linux' | 'macOS' | 'Windows';
2
- export type ValeArch = '64-bit' | 'arm64';
3
- /**
4
- * Extracts the replacement text from a vale alert.
5
- * Returns null if no replacement can be determined.
6
- * @param {{ Action: { Name: string; Params: string[] | null }; Message: string }} alert
7
- * @returns {string | null}
8
- */
9
- export declare function getReplacementText(alert: {
10
- Action: {
11
- Name: string;
12
- Params: string[] | null;
13
- };
14
- Message: string;
15
- }): string | null;
16
- /**
17
- * Applies auto-fixes from vale alerts to the source files.
18
- * Processes alerts in reverse order within each line to preserve column positions.
19
- * @param {Record<string, Array<{ Action: { Name: string; Params: string[] | null }; Span: [number, number]; Check: string; Message: string; Severity: string; Match: string; Line: number }>>} results
20
- * @param {'all' | 'error'} fixLevel
21
- * @returns {Promise<{ fixed: number; skipped: number }>}
22
- */
23
- export declare function applyFixes(results: Record<string, Array<{
24
- Action: {
25
- Name: string;
26
- Params: string[] | null;
27
- };
28
- Span: [number, number];
29
- Check: string;
30
- Message: string;
31
- Severity: string;
32
- Match: string;
33
- Line: number;
34
- }>>, fixLevel: 'all' | 'error'): Promise<{
35
- fixed: number;
36
- skipped: number;
37
- }>;
38
- export type Args = {
39
- 'vale-version': string;
40
- 'auto-fix': 'all' | 'error' | undefined;
41
- };
42
- /**
43
- * @typedef {{ 'vale-version': string; 'auto-fix': 'all' | 'error' | undefined; }} Args
44
- */
45
- declare const _default: import('yargs').CommandModule<{}, Args>;
46
- export default _default;
@@ -1,2 +0,0 @@
1
- declare const _default: import('yargs').CommandModule<{}, {}>;
2
- export default _default;
@@ -1 +0,0 @@
1
- export {};