Repository navigation
Expand file tree
/
Copy pathapi-surface.js
More file actions
666 lines (636 loc) · 27.2 KB
/
Copy pathapi-surface.js
File metadata and controls
666 lines (636 loc) · 27.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
// packages/script-utils/api-surface.js
/**
* `@cosyte/script-utils/api-surface`: the export-surface record of a package and the check that
* a fresh build still agrees with it. ONE BODY, RUN BY EVERY LIBRARY THROUGH `cosyte-api-surface`.
*
* WHY IT EXISTS. A package's built declarations are what every consumer's editor and compiler
* read, and a bundler assembles them from a barrel: nothing in lint, typecheck or the tests fails
* when an export leaves them, changes shape, or arrives unnoticed. The record under `release/` is
* the written-down surface; this check says whether a build still matches it.
*
* THE ENTRY POINTS COME FROM `package.json`. Each key of `exports` that names declarations is an
* entry point: `.` is `index`, recorded in `release/public-api.json`, and `./<name>` is `<name>`,
* recorded in `release/public-api-<name>.json` (a `/` in the name becomes `-`). Its declarations
* are the `types` condition an `import` resolves (the first `.d.ts` found, else the first `types`).
* A key with a `*` pattern, or one with no `types` (`./package.json`), records nothing.
*
* WHAT IT REFUSES, AND WHY EACH REFUSAL IS THE POINT:
*
* 1. IT NEVER REWRITES THE RECORD WHILE CHECKING. A check that heals its own baseline always
* passes. Writing is `--write`, a separate act whose diff a reviewer reads.
* 2. IT NEVER REPORTS AN EMPTY SURFACE AS A MATCH. Declarations that are absent, empty, not a
* module, or a module with no exports are a missing input (exit 2), and so is a record with
* zero exports. `tsup` writes JavaScript before declarations, so every build has a window with
* no `.d.ts` in `dist/`, and a gate that cannot say its input was missing reports it as a pass.
* 3. IT NAMES EVERY DIFFERENCE: each export added, removed, or changed in kind, type or member.
* 4. A RUN THAT COULD NOT FINISH IS NEVER DRIFT. TypeScript missing, a compiler that threw, a
* record it could not write: each exits 2, so 1 always means the surface moved.
*
* WHAT A RECORD ENTRY HOLDS. One entry per export, sorted by name: `name`; `kind` (class, enum,
* function, interface, namespace, type, variable, or unknown); `type`, the printed type of a value
* export (a function's overloads, in declaration order) and empty otherwise; and `members`, sorted:
* an interface's or class's public properties (`name?: Type` when optional, a class's statics
* prefixed `static `), a union alias's constituents, any other alias's properties, a namespace's
* names. Private, protected and `#` members are left out: a consumer cannot reach them.
*
* THE LAYOUT IS BYTE FOR BYTE THE ONE THE PER-LIBRARY COPIES OF THIS CHECK WROTE: the keys
* `$comment`, `typescript`, `exportCount`, `exports` in that order, two-space indents, and a final
* newline. The check never compares `$comment`, so a record a copy wrote still checks clean; the
* first `--write` after a switch changes that one line, which now names this tool.
*
* THE TYPESCRIPT VERSION IS PART OF THE RECORD. Entries are printed by the compiler, so this loads
* the `typescript` the package itself installs, never one of its own (this package has no
* dependencies), and a record derived under another version is drift. Fully qualified names are not
* printed: they embed the absolute path of the declarations. A type the declarations use but do not
* export still prints as `import("<absolute path>/index").Name`, so the path is cut to the file's
* own name, `import("./index").Name`, and the record reads the same on every machine and from a
* build in any folder; a specifier that is not an absolute path is printed as the compiler wrote
* it. A member keyed by a well-known symbol is printed as `[Symbol.iterator]`, never as the
* compiler's internal `__@iterator@497`, whose number moves whenever the bundle changes size.
*
* Where a subpath's declarations import the package by its own name, that name resolves to the
* root entry's declarations in the same build, so a fresh build in a temporary folder is read
* whole. Every peer dependency the package declares, and `fast-check`, which a `/arbitraries` entry
* imports, resolves from the package root, so a build read from outside the package still sees the
* peers' types. A peer that is not optional and is not installed is a missing input (exit 2): its
* types would print as `any`, which is a run that could not finish, never drift.
*
* NOTHING HERE CALLS `process.exit`: `runApiSurface` returns the exit code. 0 the surface matches
* (or was written), 1 it drifted, 2 the check could not run.
*/
import { readFileSync, statSync, writeFileSync } from "node:fs";
import { createRequire } from "node:module";
import { dirname, join, relative, resolve } from "node:path";
/** The bin's name, which the record's comment and every hint name. */
const BIN = "cosyte-api-surface";
/** The usage line every refused argument prints. */
const USAGE = `Usage: ${BIN} [--entry <name> | --all] [--declarations <path>] [--inventory <path>] [--write]`;
/** An input the run needed and did not get. Distinct from drift, and exits 2. */
class MissingInputError extends Error {}
/** An argument the check does not take. Exits 2. */
class UsageError extends Error {}
/* -------------------------------------------------------------------------------------------- */
/* Entry points */
/* -------------------------------------------------------------------------------------------- */
/**
* Every `types` path under an `exports` value, in the order an object lists its conditions.
*
* @param {unknown} value An `exports` value: a path, a condition object, or a fallback array.
* @returns {string[]} The `types` paths, and a bare path that names declarations.
*/
function typesPaths(value) {
if (typeof value === "string") return /\.d\.[cm]?ts$/.test(value) ? [value] : [];
if (Array.isArray(value)) return value.flatMap(typesPaths);
if (typeof value !== "object" || value === null) return [];
return Object.entries(value).flatMap(([condition, inner]) =>
condition === "types" && typeof inner === "string" ? [inner] : typesPaths(inner),
);
}
/**
* The entry points a package publishes, each with the declarations it builds and its record.
*
* @param {Record<string, unknown>} manifest The package's `package.json`.
* @returns {Array<{entry: string, specifier: string, declarations: string, inventory: string}>}
*/
export function entryPoints(manifest) {
const name = String(manifest.name);
let exports = manifest.exports;
if (exports === undefined) {
const types = manifest.types ?? manifest.typings;
exports = typeof types === "string" ? { ".": types } : {};
} else if (
typeof exports !== "object" ||
exports === null ||
Array.isArray(exports) ||
!Object.keys(exports).some((key) => key.startsWith("."))
) {
exports = { ".": exports };
}
const entries = [];
for (const [key, value] of Object.entries(exports)) {
if (!(key === "." || key.startsWith("./")) || key.includes("*")) continue;
const paths = typesPaths(value);
const declarations = paths.find((path) => path.endsWith(".d.ts")) ?? paths[0];
if (declarations === undefined) continue;
const entry = key === "." ? "index" : key.slice(2);
entries.push({
entry,
specifier: key === "." ? name : `${name}/${entry}`,
declarations: declarations.replace(/^\.\//, ""),
inventory:
key === "."
? "release/public-api.json"
: `release/public-api-${entry.replaceAll("/", "-")}.json`,
});
}
return entries;
}
/**
* The command that regenerates one entry point's record.
*
* @param {string} entry The entry point.
* @returns {string}
*/
function regenerate(entry) {
return entry === "index" ? `${BIN} --write` : `${BIN} --entry ${entry} --write`;
}
/* -------------------------------------------------------------------------------------------- */
/* Deriving the surface */
/* -------------------------------------------------------------------------------------------- */
/**
* Read a built `.d.ts` and return one entry per export, sorted by name.
*
* Every way of ending up with nothing throws `MissingInputError` rather than returning an empty
* list: none of them is a verdict about the API.
*
* @param {typeof import("typescript")} ts The package's own TypeScript.
* @param {string} declarationsPath The declarations, absolute.
* @param {Record<string, string[]>} paths Where the declarations' package imports resolve.
* @returns {Array<{name: string, kind: string, type: string, members: string[]}>}
*/
function deriveSurface(ts, declarationsPath, paths) {
let size;
try {
size = statSync(declarationsPath).size;
} catch {
throw new MissingInputError(
`declarations not found at ${declarationsPath}. Build first (\`pnpm build\`), or pass --declarations.`,
);
}
if (size === 0) {
throw new MissingInputError(`declarations at ${declarationsPath} are empty (0 bytes).`);
}
// `skipLibCheck` keeps this from checking the standard library on every run: nothing here needs
// the declarations to be free of errors, only their symbols to resolve.
const program = ts.createProgram([declarationsPath], {
noEmit: true,
target: ts.ScriptTarget.ES2023,
module: ts.ModuleKind.ESNext,
moduleResolution: ts.ModuleResolutionKind.Bundler,
strict: true,
skipLibCheck: true,
paths,
});
const source = program.getSourceFile(declarationsPath);
if (source === undefined) {
throw new MissingInputError(`TypeScript could not read declarations at ${declarationsPath}.`);
}
const checker = program.getTypeChecker();
const moduleSymbol = checker.getSymbolAtLocation(source);
if (moduleSymbol === undefined) {
throw new MissingInputError(
`declarations at ${declarationsPath} are not a module: they export nothing a consumer could import.`,
);
}
const exports = checker.getExportsOfModule(moduleSymbol);
if (exports.length === 0) {
throw new MissingInputError(
`declarations at ${declarationsPath} resolved to a module with no exports. ` +
"Refusing to report an empty surface as a comparison result.",
);
}
const describe = describer(ts, checker);
return exports.map(describe).sort((a, b) => (a.name < b.name ? -1 : 1));
}
/**
* Cut every absolute path in a printed `import("...")` to the file's own name: the path names the
* machine and the folder the build was read from, not the API. A POSIX path (`/home/...`) and a
* Windows one (`C:/...` or `C:\...`) are both absolute; a package name or a relative path is left
* as printed.
*
* @param {string} text A printed type.
* @returns {string}
*/
function withoutAbsolutePaths(text) {
return text.replace(/import\("(?:[A-Za-z]:)?[\\/][^"]*?([^"\\/]+)"\)/g, 'import("./$1")');
}
/**
* The function that turns one exported symbol into its record entry.
*
* @param {typeof import("typescript")} ts The package's own TypeScript.
* @param {import("typescript").TypeChecker} checker The program's checker.
* @returns {(exported: import("typescript").Symbol) => {name: string, kind: string, type: string,
* members: string[]}}
*/
function describer(ts, checker) {
const F = ts.SymbolFlags;
/** @type {Array<[number, string]>} */
const kinds = [
[F.Class, "class"],
[F.Enum, "enum"],
[F.Function, "function"],
[F.Interface, "interface"],
[F.TypeAlias, "type"],
[F.ValueModule | F.NamespaceModule, "namespace"],
[F.Variable, "variable"],
];
// `NoTruncation` only: an elided type is a record that stops telling apart what it was written to.
const print = (type, at) =>
withoutAbsolutePaths(checker.typeToString(type, at, ts.TypeFormatFlags.NoTruncation));
const hidden = ts.ModifierFlags.Private | ts.ModifierFlags.Protected;
const isPublic = (property) =>
!property.getName().startsWith("#") &&
(property.declarations ?? []).every(
(declaration) => (ts.getCombinedModifierFlags(declaration) & hidden) === 0,
);
const memberName = (property) => {
const name = property.getName();
return name.startsWith("__@") ? checker.symbolToString(property) : name;
};
const typeAt = (property) => {
const declaration = property.declarations?.[0];
return {
declaration,
type:
declaration === undefined
? checker.getTypeOfSymbol(property)
: checker.getTypeOfSymbolAtLocation(property, declaration),
};
};
const propertyLines = (type) =>
checker
.getPropertiesOfType(type)
.filter(isPublic)
.map((property) => {
const { declaration, type: propertyType } = typeAt(property);
const optional = (property.flags & F.Optional) === 0 ? "" : "?";
return `${memberName(property)}${optional}: ${print(propertyType, declaration)}`;
})
.sort();
// The static side of a class, less `prototype`, which every class has.
const staticLines = (symbol) =>
checker
.getPropertiesOfType(checker.getTypeOfSymbolAtLocation(symbol, symbol.declarations[0]))
.filter((property) => property.getName() !== "prototype" && isPublic(property))
.map((property) => {
const { declaration, type } = typeAt(property);
return `static ${memberName(property)}: ${print(type, declaration)}`;
})
.sort();
return (exported) => {
const symbol = (exported.flags & F.Alias) === 0 ? exported : checker.getAliasedSymbol(exported);
const kind = kinds.find(([flags]) => (symbol.flags & flags) !== 0)?.[1] ?? "unknown";
const name = exported.getName();
if (kind === "namespace") {
const members = checker
.getExportsOfModule(symbol)
.map((member) => member.getName())
.sort();
return { name, kind, type: "", members };
}
if (kind === "interface") {
return {
name,
kind,
type: "",
members: propertyLines(checker.getDeclaredTypeOfSymbol(symbol)),
};
}
if (kind === "type") {
// A union alias carries the identifiers a consumer switches on (warning codes), so its
// constituents are the surface; any other alias is read by its properties.
const declared = checker.getDeclaredTypeOfSymbol(symbol);
const members = declared.isUnion()
? declared.types.map((member) => print(member, undefined)).sort()
: propertyLines(declared);
return { name, kind, type: "", members };
}
if (kind === "class") {
const members = [
...propertyLines(checker.getDeclaredTypeOfSymbol(symbol)),
...staticLines(symbol),
].sort();
return { name, kind, type: "", members };
}
const declaration = symbol.declarations?.[0];
const type =
declaration === undefined
? ""
: print(checker.getTypeOfSymbolAtLocation(symbol, declaration), declaration);
return { name, kind, type, members: [] };
};
}
/* -------------------------------------------------------------------------------------------- */
/* The committed record */
/* -------------------------------------------------------------------------------------------- */
/**
* Whether a value is a record entry.
*
* @param {unknown} value
* @returns {boolean}
*/
function isApiExport(value) {
return (
typeof value === "object" &&
value !== null &&
typeof value.name === "string" &&
typeof value.kind === "string" &&
typeof value.type === "string" &&
Array.isArray(value.members) &&
value.members.every((member) => typeof member === "string")
);
}
/**
* Read a committed record.
*
* @param {string} inventoryPath The record, absolute.
* @returns {{$comment: string, typescript: string, exportCount: number,
* exports: Array<{name: string, kind: string, type: string, members: string[]}>}}
* @throws {Error} When the record is absent, not JSON, has no usable exports, records none, or
* records no TypeScript version.
*/
export function readInventory(inventoryPath) {
let text;
try {
text = readFileSync(inventoryPath, "utf8");
} catch {
throw new MissingInputError(
`inventory not found at ${inventoryPath}. Generate it with \`${BIN} --write\`.`,
);
}
let parsed;
try {
parsed = JSON.parse(text);
} catch (error) {
throw new MissingInputError(
`inventory at ${inventoryPath} is not valid JSON: ${error.message}`,
);
}
if (typeof parsed !== "object" || parsed === null) {
throw new MissingInputError(`inventory at ${inventoryPath} did not parse to an object.`);
}
const { exports, typescript } = parsed;
if (!Array.isArray(exports) || !exports.every(isApiExport)) {
throw new MissingInputError(
`inventory at ${inventoryPath} has no usable \`exports\` list of {name, kind, type, members}.`,
);
}
if (exports.length === 0) {
throw new MissingInputError(
`inventory at ${inventoryPath} records zero exports. An empty baseline can only ever agree ` +
"with a build that produced nothing, so it is refused rather than compared.",
);
}
if (typeof typescript !== "string") {
throw new MissingInputError(`inventory at ${inventoryPath} records no \`typescript\` version.`);
}
return {
$comment: typeof parsed.$comment === "string" ? parsed.$comment : "",
typescript,
exportCount: exports.length,
exports,
};
}
/* -------------------------------------------------------------------------------------------- */
/* Comparing */
/* -------------------------------------------------------------------------------------------- */
/**
* One line per difference, in name order, naming the export and what about it moved.
*
* @param {ReadonlyArray<{name: string, kind: string, type: string, members: readonly string[]}>} committed
* @param {ReadonlyArray<{name: string, kind: string, type: string, members: readonly string[]}>} derived
* @returns {string[]}
*/
export function differences(committed, derived) {
const before = new Map(committed.map((entry) => [entry.name, entry]));
const after = new Map(derived.map((entry) => [entry.name, entry]));
const names = [...new Set([...before.keys(), ...after.keys()])].sort();
const lines = [];
for (const name of names) {
const was = before.get(name);
const now = after.get(name);
if (was === undefined) {
lines.push(`added: ${name} (${now.kind})`);
continue;
}
if (now === undefined) {
lines.push(`removed: ${name} (${was.kind})`);
continue;
}
if (was.kind !== now.kind) lines.push(`changed: ${name} kind ${was.kind} -> ${now.kind}`);
if (was.type !== now.type) {
lines.push(`changed: ${name} type\n was: ${was.type}\n now: ${now.type}`);
}
for (const member of was.members.filter((m) => !now.members.includes(m))) {
lines.push(`changed: ${name} lost member ${member}`);
}
for (const member of now.members.filter((m) => !was.members.includes(m))) {
lines.push(`changed: ${name} gained member ${member}`);
}
}
return lines;
}
/* -------------------------------------------------------------------------------------------- */
/* CLI */
/* -------------------------------------------------------------------------------------------- */
/**
* Read the arguments.
*
* @param {readonly string[]} argv
* @param {string[]} names The entry points the package publishes.
* @returns {{entries: string[], declarations?: string, inventory?: string, write: boolean}}
*/
function parseArgs(argv, names) {
let entry;
let all = false;
let declarations;
let inventory;
let write = false;
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i];
if (arg === "--write") {
write = true;
} else if (arg === "--all") {
all = true;
} else if (arg === "--entry") {
const value = argv[i + 1];
if (value === undefined || !names.includes(value)) {
throw new UsageError(`--entry needs one of ${names.join(", ")}`);
}
entry = value;
i += 1;
} else if (arg === "--declarations" || arg === "--inventory") {
const value = argv[i + 1];
if (value === undefined || value.startsWith("--"))
throw new UsageError(`${arg} needs a path`);
if (arg === "--declarations") declarations = value;
else inventory = value;
i += 1;
} else {
throw new UsageError(`unrecognized argument ${arg}`);
}
}
if (all && (entry !== undefined || declarations !== undefined || inventory !== undefined)) {
throw new UsageError(
"--all reads each entry point's own declarations and record, so it takes no --entry, " +
"--declarations or --inventory",
);
}
if (!all && entry === undefined && !names.includes("index")) {
throw new UsageError(
`the package has no root entry point, so --entry needs one of ${names.join(", ")}`,
);
}
return { entries: all ? names : [entry ?? "index"], declarations, inventory, write };
}
/**
* Where the declarations' imports of the package's peers resolve: each peer dependency, and
* `fast-check`, resolved from the package root. A build read from a folder outside the package
* would otherwise resolve them to nothing, and every type naming them would print as `any`.
*
* @param {typeof import("typescript")} ts The package's own TypeScript.
* @param {Record<string, unknown>} manifest The package's `package.json`.
* @param {string} cwd The package root.
* @returns {Record<string, string[]>}
* @throws {MissingInputError} When a peer that is not optional is not installed.
*/
function peerPaths(ts, manifest, cwd) {
const peers = Object.keys(manifest.peerDependencies ?? {});
const meta = manifest.peerDependenciesMeta ?? {};
/** @type {Record<string, string[]>} */
const paths = {};
for (const peer of new Set([...peers, "fast-check"])) {
const resolved = ts.resolveModuleName(
peer,
join(cwd, "package.json"),
{ moduleResolution: ts.ModuleResolutionKind.Bundler, module: ts.ModuleKind.ESNext },
ts.sys,
).resolvedModule?.resolvedFileName;
if (resolved !== undefined) {
paths[peer] = [resolved];
} else if (peers.includes(peer) && meta[peer]?.optional !== true) {
throw new MissingInputError(
`the peer dependency ${peer} is not installed in ${cwd}, so the types the declarations ` +
"take from it would print as `any`. Install it (`pnpm install`).",
);
}
}
return paths;
}
/**
* Check or write one entry point's record.
*
* @returns {number} The exit code for this entry point.
*/
function runEntry(ts, point, rootDeclarations, manifest, cwd, options, stdout, stderr) {
const packageName = manifest.name;
const declarations = resolve(cwd, options.declarations ?? point.declarations);
const inventoryPath = resolve(cwd, options.inventory ?? point.inventory);
/** @type {Record<string, string[]>} */
const paths = peerPaths(ts, manifest, cwd);
if (rootDeclarations !== undefined) {
// The root entry's declarations, at the same place relative to these as in the package.
const fromHere = relative(dirname(point.declarations), rootDeclarations);
paths[packageName] = [resolve(dirname(declarations), fromHere)];
}
const derived = deriveSurface(ts, declarations, paths);
if (options.write) {
const record = {
$comment:
`Generated by ${BIN} from a fresh build's ${point.declarations}. ` +
`Regenerate deliberately with \`${regenerate(point.entry)}\` and review the diff: ` +
`this file is the written-down public type surface of ${point.specifier}.`,
typescript: ts.version,
exportCount: derived.length,
exports: derived,
};
try {
writeFileSync(inventoryPath, `${JSON.stringify(record, null, 2)}\n`);
} catch (error) {
throw new MissingInputError(`could not write ${inventoryPath}: ${error.message}`);
}
stdout.write(`api-surface: wrote ${derived.length} exports to ${inventoryPath}\n`);
return 0;
}
const committed = readInventory(inventoryPath);
const lines = differences(committed.exports, derived);
const versionDrift = committed.typescript !== ts.version;
if (lines.length === 0 && !versionDrift) {
stdout.write(
`OK: public export surface matches ${inventoryPath} (${derived.length} exports)\n`,
);
return 0;
}
stderr.write(`DRIFT: the public export surface does not match ${inventoryPath}.\n`);
if (versionDrift) {
stderr.write(
` the inventory was derived under TypeScript ${committed.typescript}; this run used ` +
`${ts.version}. Entries are printed by the type checker, so regenerate deliberately ` +
"after reviewing the diff.\n",
);
}
for (const line of lines) stderr.write(` ${line}\n`);
stderr.write(
"Nothing was rewritten. If every difference above is intended, regenerate the inventory " +
`with \`${regenerate(point.entry)}\` and commit it with the change that caused it.\n`,
);
return 1;
}
/**
* Run the check from the command line, over the package in `cwd`.
*
* @param {{argv?: readonly string[], cwd?: string, stdout?: {write: (s: string) => unknown},
* stderr?: {write: (s: string) => unknown}}} [options]
* @returns {number} The exit code: 0 the surface matches or was written, 1 it drifted, 2 the
* check could not run.
*/
export function runApiSurface(options = {}) {
const stdout = options.stdout ?? process.stdout;
const stderr = options.stderr ?? process.stderr;
const cwd = resolve(options.cwd ?? process.cwd());
const refuse = (message, usage = false) => {
stderr.write(`REFUSED: api-surface: ${message}\n`);
if (usage) stderr.write(`${USAGE}\n`);
return 2;
};
let manifest;
try {
manifest = JSON.parse(readFileSync(join(cwd, "package.json"), "utf8"));
} catch (error) {
return refuse(`could not read ${join(cwd, "package.json")}: ${error.message}`);
}
if (typeof manifest?.name !== "string") {
return refuse(`${join(cwd, "package.json")} names no package.`);
}
const points = entryPoints(manifest);
if (points.length === 0) {
return refuse(
`${manifest.name} publishes no declarations in its exports, so there is no surface to record.`,
);
}
let args;
try {
args = parseArgs(
options.argv ?? [],
points.map((point) => point.entry),
);
} catch (error) {
return refuse(error.message, true);
}
let ts;
try {
ts = createRequire(join(cwd, "package.json"))("typescript");
} catch (error) {
return refuse(
`TypeScript could not be loaded from ${cwd}: ${error.message.split("\n")[0]} ` +
"The record is printed by the compiler the package builds with, so install `typescript` " +
"as a devDependency.",
);
}
const rootDeclarations = points.find((point) => point.entry === "index")?.declarations;
let worst = 0;
for (const name of args.entries) {
const point = points.find((candidate) => candidate.entry === name);
let code;
try {
code = runEntry(ts, point, rootDeclarations, manifest, cwd, args, stdout, stderr);
} catch (error) {
code =
error instanceof MissingInputError
? refuse(`inputs missing. ${error.message}`)
: refuse(`could not run: ${error.message}`);
}
worst = Math.max(worst, code);
}
return worst;
}