@mark1russell7/api-report 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,1268 @@
1
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
2
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
3
+ // src/declarations.ts
4
+ const BLOCK_HEADER = /^(?:export\s+)?(?:default\s+)?(?:declare\s+)?(?:abstract\s+class|class|interface|const\s+enum|enum|namespace|module|global)\b/;
5
+ /**
6
+ * This function splits the text of a declaration file into its top-level statements. It removes the
7
+ * comments, the blank lines and the spaces at the ends of the lines.
8
+ */
9
+ function statementsOf(source) {
10
+ const text = source.replace(/\r\n?/g, "\n").replace(/^#![^\n]*\n?/, "");
11
+ const statements = [];
12
+ let current = "";
13
+ let depth = 0;
14
+ let angle = 0;
15
+ let body = false;
16
+ const modes = [];
17
+ const finish = () => {
18
+ const lines = current.split("\n").map((line) => line.trimEnd()).filter((line) => line.trim() !== "");
19
+ if (lines.length > 0) statements.push(lines.join("\n"));
20
+ current = "";
21
+ angle = 0;
22
+ body = false;
23
+ };
24
+ let index = 0;
25
+ while (index < text.length) {
26
+ const char = text.charAt(index);
27
+ const next = text.charAt(index + 1);
28
+ const mode = modes.at(-1);
29
+ if (mode?.kind === "template") {
30
+ if (char === "\\") {
31
+ current += char + next;
32
+ index += 2;
33
+ } else if (char === "`") {
34
+ modes.pop();
35
+ current += char;
36
+ index++;
37
+ } else if (char === "$" && next === "{") {
38
+ modes.push({
39
+ kind: "part",
40
+ depth
41
+ });
42
+ current += "${";
43
+ index += 2;
44
+ } else {
45
+ current += char;
46
+ index++;
47
+ }
48
+ continue;
49
+ }
50
+ if (char === "/" && next === "/") {
51
+ while (index < text.length && text.charAt(index) !== "\n") index++;
52
+ continue;
53
+ }
54
+ if (char === "/" && next === "*") {
55
+ const end = text.indexOf("*/", index + 2);
56
+ index = end < 0 ? text.length : end + 2;
57
+ current += " ";
58
+ continue;
59
+ }
60
+ if (char === "\"" || char === "'") {
61
+ let end = index + 1;
62
+ while (end < text.length && text.charAt(end) !== char) end += text.charAt(end) === "\\" ? 2 : 1;
63
+ current += text.slice(index, end + 1);
64
+ index = end + 1;
65
+ continue;
66
+ }
67
+ if (char === "`") {
68
+ modes.push({ kind: "template" });
69
+ current += char;
70
+ index++;
71
+ continue;
72
+ }
73
+ if (modes.length === 0 && depth === 0) {
74
+ if (char === "<") angle++;
75
+ else if (char === ">" && text.charAt(index - 1) !== "=") angle = Math.max(0, angle - 1);
76
+ else if (char === "{" && angle === 0 && !body && BLOCK_HEADER.test(current.trim())) body = true;
77
+ }
78
+ if (char === "{" || char === "(" || char === "[") depth++;
79
+ if (char === "}" || char === ")" || char === "]") {
80
+ if (char === "}" && mode?.kind === "part" && depth === mode.depth) {
81
+ modes.pop();
82
+ current += char;
83
+ index++;
84
+ continue;
85
+ }
86
+ depth--;
87
+ }
88
+ current += char;
89
+ index++;
90
+ if (modes.length > 0 || depth !== 0) continue;
91
+ if (char === ";" || char === "}" && body) finish();
92
+ }
93
+ finish();
94
+ return statements;
95
+ }
96
+ /** This function splits `text` at each comma outside brackets, type arguments and strings. */
97
+ function splitTopLevel(text) {
98
+ const parts = [];
99
+ let depth = 0;
100
+ let start = 0;
101
+ for (let index = 0; index < text.length; index++) {
102
+ const char = text.charAt(index);
103
+ if (char === "\"" || char === "'" || char === "`") {
104
+ let end = index + 1;
105
+ while (end < text.length && text.charAt(end) !== char) end += text.charAt(end) === "\\" ? 2 : 1;
106
+ index = end;
107
+ } else if (char === "(" || char === "[" || char === "{" || char === "<") depth++;
108
+ else if (char === ")" || char === "]" || char === "}" || char === ">" && text.charAt(index - 1) !== "=") depth--;
109
+ else if (char === "," && depth === 0) {
110
+ parts.push(text.slice(start, index));
111
+ start = index + 1;
112
+ }
113
+ }
114
+ parts.push(text.slice(start));
115
+ return parts;
116
+ }
117
+ /** The names of an export or import list: `a, type b, c as d`. */
118
+ function specifiersOf(list, typeOnly) {
119
+ return list.split(",").map((part) => part.trim()).filter((part) => part !== "").map((part) => {
120
+ const match = /^(type\s+)?([\w$]+)(?:\s+as\s+([\w$]+|"[^"]*"))?$/.exec(part);
121
+ if (!match?.[2]) throw new Error(`An export list part that the report does not know: ${part}`);
122
+ return {
123
+ imported: match[2],
124
+ exported: match[3] ?? match[2],
125
+ typeOnly: typeOnly || match[1] !== void 0
126
+ };
127
+ });
128
+ }
129
+ /** This function removes the private members of a class: they are not part of the API. */
130
+ function withoutPrivateMembers(statement) {
131
+ return statement.split("\n").filter((line) => !/^\s+(?:private\s+(?:static\s+)?(?:readonly\s+)?[\w$]+\??;|#private;)$/.test(line)).join("\n");
132
+ }
133
+ /** A capture group of a match that the pattern always sets. */
134
+ const group = (match, index) => match[index] ?? "";
135
+ /**
136
+ * This function sorts the statements of the text of one declaration file by their kind. `file`
137
+ * names the file in the errors. An unknown form of statement throws.
138
+ */
139
+ function parseDeclarations(source, file = "<text>") {
140
+ const info = {
141
+ locals: /* @__PURE__ */ new Map(),
142
+ exported: /* @__PURE__ */ new Map(),
143
+ reexports: [],
144
+ stars: [],
145
+ namespaces: [],
146
+ imports: /* @__PURE__ */ new Map(),
147
+ ambient: /* @__PURE__ */ new Map(),
148
+ references: /* @__PURE__ */ new Set()
149
+ };
150
+ const addLocal = (name, statement) => {
151
+ info.locals.set(name, [...info.locals.get(name) ?? [], statement]);
152
+ };
153
+ const addAmbient = (label, statement) => {
154
+ info.ambient.set(label, [...info.ambient.get(label) ?? [], statement]);
155
+ };
156
+ for (const statement of statementsOf(source)) {
157
+ const flat = statement.replace(/\s+/g, " ");
158
+ for (const found of flat.matchAll(/\bimport\(\s*["']([^"']+)["']\s*\)/g)) info.references.add(found[1] ?? "");
159
+ let match;
160
+ if (match = /^import (type )?(.+?) from ["']([^"']+)["'];?$/.exec(flat)) {
161
+ const typeOnly = match[1] !== void 0;
162
+ const from = group(match, 3);
163
+ info.references.add(from);
164
+ let clause = group(match, 2).trim();
165
+ const defaultName = /^([\w$]+)\s*(?:,|$)/.exec(clause);
166
+ if (defaultName) {
167
+ info.imports.set(group(defaultName, 1), {
168
+ from,
169
+ imported: "default",
170
+ typeOnly
171
+ });
172
+ clause = clause.slice(defaultName[0].length).trim();
173
+ }
174
+ const namespace = /^\* as ([\w$]+)$/.exec(clause);
175
+ if (namespace) info.imports.set(group(namespace, 1), {
176
+ from,
177
+ imported: "*",
178
+ typeOnly
179
+ });
180
+ const braces = /^\{(.*)\}$/.exec(clause);
181
+ if (braces) for (const specifier of specifiersOf(group(braces, 1), typeOnly)) info.imports.set(specifier.exported, {
182
+ from,
183
+ imported: specifier.imported,
184
+ typeOnly: specifier.typeOnly
185
+ });
186
+ continue;
187
+ }
188
+ if (match = /^import ["']([^"']+)["'];?$/.exec(flat)) {
189
+ info.references.add(group(match, 1));
190
+ continue;
191
+ }
192
+ if (match = /^(export )?import (type )?([\w$]+) = require\(["']([^"']+)["']\);?$/.exec(flat)) {
193
+ const name = group(match, 3);
194
+ info.references.add(group(match, 4));
195
+ info.imports.set(name, {
196
+ from: group(match, 4),
197
+ imported: "export=",
198
+ typeOnly: match[2] !== void 0
199
+ });
200
+ if (match[1] !== void 0) info.exported.set(name, {
201
+ local: name,
202
+ typeOnly: false
203
+ });
204
+ continue;
205
+ }
206
+ if (match = /^(export )?import ([\w$]+) = [\w$.]+;?$/.exec(flat)) {
207
+ const name = group(match, 2);
208
+ addLocal(name, statement);
209
+ if (match[1] !== void 0) info.exported.set(name, {
210
+ local: name,
211
+ typeOnly: false
212
+ });
213
+ continue;
214
+ }
215
+ if (match = /^export (type )?\* as ([\w$]+) from ["']([^"']+)["'];?$/.exec(flat)) {
216
+ info.references.add(group(match, 3));
217
+ info.namespaces.push({
218
+ name: group(match, 2),
219
+ from: group(match, 3),
220
+ typeOnly: match[1] !== void 0
221
+ });
222
+ continue;
223
+ }
224
+ if (match = /^export (type )?\* from ["']([^"']+)["'];?$/.exec(flat)) {
225
+ info.references.add(group(match, 2));
226
+ info.stars.push({
227
+ from: group(match, 2),
228
+ typeOnly: match[1] !== void 0
229
+ });
230
+ continue;
231
+ }
232
+ if (match = /^export (type )?\{(.*)\} from ["']([^"']+)["'];?$/.exec(flat)) {
233
+ const from = group(match, 3);
234
+ info.references.add(from);
235
+ for (const specifier of specifiersOf(group(match, 2), match[1] !== void 0)) info.reexports.push({
236
+ ...specifier,
237
+ from
238
+ });
239
+ continue;
240
+ }
241
+ if (match = /^export (type )?\{(.*)\};?$/.exec(flat)) {
242
+ for (const specifier of specifiersOf(group(match, 2), match[1] !== void 0)) info.exported.set(specifier.exported, {
243
+ local: specifier.imported,
244
+ typeOnly: specifier.typeOnly
245
+ });
246
+ continue;
247
+ }
248
+ if (match = /^export = ([\w$]+);?$/.exec(flat)) {
249
+ info.exported.set("export=", {
250
+ local: group(match, 1),
251
+ typeOnly: false
252
+ });
253
+ continue;
254
+ }
255
+ if (/^export = /.test(flat)) {
256
+ addLocal("export=", statement);
257
+ info.exported.set("export=", {
258
+ local: "export=",
259
+ typeOnly: false
260
+ });
261
+ continue;
262
+ }
263
+ if (match = /^(?:export )?declare module (["'][^"']+["'])/.exec(flat)) {
264
+ addAmbient(`declare module ${group(match, 1).replaceAll("'", "\"")}`, statement);
265
+ continue;
266
+ }
267
+ if (/^(?:export )?(?:declare )?global \{/.test(flat)) {
268
+ addAmbient("declare global", statement);
269
+ continue;
270
+ }
271
+ if (match = /^export as namespace ([\w$]+);?$/.exec(flat)) {
272
+ addAmbient(`export as namespace ${group(match, 1)}`, statement);
273
+ continue;
274
+ }
275
+ if (match = /^export default ([\w$]+);?$/.exec(flat)) {
276
+ info.exported.set("default", {
277
+ local: group(match, 1),
278
+ typeOnly: false
279
+ });
280
+ continue;
281
+ }
282
+ match = /^export default (?:declare )?(?:abstract )?(?:class|function\*?)(?![\w$])\s*([\w$]*)/.exec(flat);
283
+ if (match && (match[1] === "" || match[1] === "extends" || match[1] === "implements")) {
284
+ addLocal("default", withoutPrivateMembers(statement));
285
+ info.exported.set("default", {
286
+ local: "default",
287
+ typeOnly: false
288
+ });
289
+ continue;
290
+ }
291
+ if (match = /^(export )?(?:declare )?(?:const|let|var) (?!enum\b)(.*?);?$/.exec(flat)) {
292
+ const exported = match[1] !== void 0;
293
+ for (const part of splitTopLevel(group(match, 2))) {
294
+ const name = /^\s*([\w$]+)/.exec(part);
295
+ if (!name) throw new Error(`A declaration that the report does not know, in ${file}:\n${statement}`);
296
+ addLocal(group(name, 1), statement);
297
+ if (exported) info.exported.set(group(name, 1), {
298
+ local: group(name, 1),
299
+ typeOnly: false
300
+ });
301
+ }
302
+ continue;
303
+ }
304
+ match = /^(export )?(default )?(?:declare )?(?:abstract )?(?:const (?=enum))?(?:function|class|interface|type|enum|namespace|module) ([\w$]+)/.exec(flat);
305
+ if (match) {
306
+ const name = group(match, 3);
307
+ addLocal(name, withoutPrivateMembers(statement));
308
+ if (match[1] !== void 0) info.exported.set(match[2] !== void 0 ? "default" : name, {
309
+ local: name,
310
+ typeOnly: false
311
+ });
312
+ continue;
313
+ }
314
+ if (/^export default /.test(flat)) {
315
+ addLocal("default", statement);
316
+ info.exported.set("default", {
317
+ local: "default",
318
+ typeOnly: false
319
+ });
320
+ continue;
321
+ }
322
+ throw new Error(`A statement that the report does not know, in ${file}:\n${statement}`);
323
+ }
324
+ return info;
325
+ }
326
+ // src/diff.ts
327
+ /** Above this number of changes, the diff replaces the whole changed part, so the memory stays small. */
328
+ const MAX_EDITS = 2e3;
329
+ /** This function gives the shortest edit script that changes the lines `before` into the lines `after`. */
330
+ function diffLines(before, after) {
331
+ let start = 0;
332
+ while (start < before.length && start < after.length && before[start] === after[start]) start++;
333
+ let end = 0;
334
+ while (end < before.length - start && end < after.length - start && before[before.length - 1 - end] === after[after.length - 1 - end]) end++;
335
+ const a = before.slice(start, before.length - end);
336
+ const b = after.slice(start, after.length - end);
337
+ const kept = (lines) => lines.map((text) => ({
338
+ kind: " ",
339
+ text
340
+ }));
341
+ return [
342
+ ...kept(before.slice(0, start)),
343
+ ...middle(a, b),
344
+ ...kept(before.slice(before.length - end))
345
+ ];
346
+ }
347
+ /** This function gives the edit script of two lists that have different first lines and different last lines. */
348
+ function middle(a, b) {
349
+ const n = a.length;
350
+ const m = b.length;
351
+ const replace = () => [...a.map((text) => ({
352
+ kind: "-",
353
+ text
354
+ })), ...b.map((text) => ({
355
+ kind: "+",
356
+ text
357
+ }))];
358
+ if (n === 0 || m === 0) return replace();
359
+ const max = Math.min(n + m, MAX_EDITS);
360
+ const offset = max + 1;
361
+ const v = new Int32Array(2 * max + 3);
362
+ const trace = [];
363
+ for (let d = 0; d <= max; d++) {
364
+ trace.push(v.slice(offset - d, offset + d + 1));
365
+ for (let k = -d; k <= d; k += 2) {
366
+ let x = k === -d || k !== d && (v[offset + k - 1] ?? 0) < (v[offset + k + 1] ?? 0) ? v[offset + k + 1] ?? 0 : (v[offset + k - 1] ?? 0) + 1;
367
+ let y = x - k;
368
+ while (x < n && y < m && a[x] === b[y]) {
369
+ x++;
370
+ y++;
371
+ }
372
+ v[offset + k] = x;
373
+ if (x >= n && y >= m) return backtrack(a, b, trace);
374
+ }
375
+ }
376
+ return replace();
377
+ }
378
+ /** This function follows the trace of the search back from the end, and gives the operations in order. */
379
+ function backtrack(a, b, trace) {
380
+ const result = [];
381
+ let x = a.length;
382
+ let y = b.length;
383
+ for (let d = trace.length - 1; d >= 0; d--) {
384
+ const v = trace[d] ?? /* @__PURE__ */ new Int32Array(0);
385
+ const at = (k) => v[k + d] ?? 0;
386
+ const k = x - y;
387
+ const down = k === -d || k !== d && at(k - 1) < at(k + 1);
388
+ const previousK = down ? k + 1 : k - 1;
389
+ const previousX = d === 0 ? 0 : at(previousK);
390
+ const previousY = d === 0 ? 0 : previousX - previousK;
391
+ while (x > previousX && y > previousY) {
392
+ result.push({
393
+ kind: " ",
394
+ text: a[x - 1] ?? ""
395
+ });
396
+ x--;
397
+ y--;
398
+ }
399
+ if (d === 0) break;
400
+ if (down) result.push({
401
+ kind: "+",
402
+ text: b[y - 1] ?? ""
403
+ });
404
+ else result.push({
405
+ kind: "-",
406
+ text: a[x - 1] ?? ""
407
+ });
408
+ x = previousX;
409
+ y = previousY;
410
+ }
411
+ return result.reverse();
412
+ }
413
+ /**
414
+ * This function gives the change from the text `before` to the text `after` in the unified format.
415
+ * The result is an empty string when the texts are the same.
416
+ */
417
+ function unifiedDiff(before, after, options = {}) {
418
+ const split = (text) => text === "" ? [] : text.replace(/\n$/, "").split("\n");
419
+ const ops = diffLines(split(before), split(after));
420
+ const context = options.context ?? 3;
421
+ const positions = [];
422
+ let a = 0;
423
+ let b = 0;
424
+ for (const op of ops) {
425
+ positions.push({
426
+ a,
427
+ b
428
+ });
429
+ if (op.kind !== "+") a++;
430
+ if (op.kind !== "-") b++;
431
+ }
432
+ const changes = ops.flatMap((op, index) => op.kind === " " ? [] : [index]);
433
+ if (changes.length === 0) return "";
434
+ const lines = [`--- ${options.from ?? "before"}`, `+++ ${options.to ?? "after"}`];
435
+ let index = 0;
436
+ while (index < changes.length) {
437
+ const first = changes[index] ?? 0;
438
+ let last = first;
439
+ while (index + 1 < changes.length && (changes[index + 1] ?? 0) - last <= 2 * context) last = changes[++index] ?? last;
440
+ index++;
441
+ const from = Math.max(0, first - context);
442
+ const to = Math.min(ops.length - 1, last + context);
443
+ const hunk = ops.slice(from, to + 1);
444
+ const start = positions[from] ?? {
445
+ a: 0,
446
+ b: 0
447
+ };
448
+ const countA = hunk.filter((op) => op.kind !== "+").length;
449
+ const countB = hunk.filter((op) => op.kind !== "-").length;
450
+ const range = (line, count) => `${count === 0 ? line : line + 1}${count === 1 ? "" : `,${count}`}`;
451
+ lines.push(`@@ -${range(start.a, countA)} +${range(start.b, countB)} @@`);
452
+ for (const op of hunk) lines.push(`${op.kind}${op.text}`);
453
+ }
454
+ return `${lines.join("\n")}\n`;
455
+ }
456
+ // src/entries.ts
457
+ /**
458
+ * The entries of a package for its report: the subpaths of the `exports` field (or `types` and
459
+ * `main`), each with its declaration file, and the bins.
460
+ */
461
+ /** The conditions of the `exports` field that a TypeScript consumer can use, in no order. */
462
+ const CONDITIONS = /* @__PURE__ */ new Set([
463
+ "types",
464
+ "import",
465
+ "node",
466
+ "default",
467
+ "require"
468
+ ]);
469
+ /**
470
+ * The fields of `publishConfig` that pnpm puts in the published `package.json`. A source package of
471
+ * the template has `main: ./src/index.ts`, and its `publishConfig` gives the built entries.
472
+ */
473
+ const PUBLISH_CONFIG_FIELDS = [
474
+ "bin",
475
+ "main",
476
+ "module",
477
+ "exports",
478
+ "imports",
479
+ "types",
480
+ "typings",
481
+ "typesVersions",
482
+ "browser"
483
+ ];
484
+ /** The order of the code units: the same on each machine, with no locale. */
485
+ const byCode = (a, b) => a < b ? -1 : a > b ? 1 : 0;
486
+ /** This function gives a path relative to `root`, with `/`. */
487
+ const relativePath = (root, file) => relative(root, file).split(sep).join("/");
488
+ /** This function gives the manifest as pnpm publishes it: the fields of `publishConfig` replace the fields of the source. */
489
+ function publishedManifest(manifest) {
490
+ const config = manifest.publishConfig;
491
+ if (!config) return manifest;
492
+ const result = { ...manifest };
493
+ for (const field of PUBLISH_CONFIG_FIELDS) if (config[field] !== void 0) result[field] = config[field];
494
+ return result;
495
+ }
496
+ /**
497
+ * This function gives the declaration file of a JavaScript or declaration path: `a.js` gives
498
+ * `a.d.ts`, and `a.mjs` gives `a.d.mts`. The result is undefined for a file of another kind.
499
+ */
500
+ function declarationPathOf(path) {
501
+ if (/\.d\.[mc]?ts$/.test(path)) return path;
502
+ const js = /\.([mc]?)js$/.exec(path);
503
+ if (js) return `${path.slice(0, -js[0].length)}.d.${js[1] ?? ""}ts`;
504
+ }
505
+ /** This function matches `subpath` with the key `pattern` of an `exports` or `imports` field. It gives the part of the `*`. */
506
+ function patternMatch(pattern, subpath) {
507
+ const star = pattern.indexOf("*");
508
+ if (star < 0) return pattern === subpath ? "" : void 0;
509
+ const prefix = pattern.slice(0, star);
510
+ const suffix = pattern.slice(star + 1);
511
+ if (subpath.length < prefix.length + suffix.length || !subpath.startsWith(prefix) || !subpath.endsWith(suffix)) return void 0;
512
+ return subpath.slice(prefix.length, subpath.length - suffix.length);
513
+ }
514
+ /**
515
+ * This function gives the target of an `exports` value for a TypeScript consumer: the first known
516
+ * condition, in the order of the object. The result is `null` for an excluded subpath, and undefined
517
+ * when no condition fits.
518
+ */
519
+ function targetOf(value) {
520
+ if (value === null) return null;
521
+ if (typeof value === "string") return value;
522
+ if (Array.isArray(value)) {
523
+ for (const item of value) {
524
+ const target = targetOf(item);
525
+ if (typeof target === "string") return target;
526
+ }
527
+ return;
528
+ }
529
+ if (typeof value === "object") for (const [condition, inner] of Object.entries(value)) {
530
+ if (!CONDITIONS.has(condition)) continue;
531
+ const target = targetOf(inner);
532
+ if (target !== void 0) return target;
533
+ }
534
+ }
535
+ /** This function gives the `exports` field as a map of subpaths. */
536
+ function subpathMap(exportsField) {
537
+ if (typeof exportsField !== "object" || Array.isArray(exportsField) || exportsField === null) return { ".": exportsField };
538
+ const keys = Object.keys(exportsField);
539
+ if (keys.length > 0 && keys.every((key) => !key.startsWith("."))) return { ".": exportsField };
540
+ return exportsField;
541
+ }
542
+ /** This function gives each file under `dir`, relative to `root` with `/`, without `node_modules`. */
543
+ function filesUnder(root, dir) {
544
+ const start = join(root, dir);
545
+ if (!existsSync(start) || !statSync(start).isDirectory()) return [];
546
+ const found = [];
547
+ const walk = (folder) => {
548
+ for (const entry of readdirSync(folder, { withFileTypes: true })) {
549
+ if (entry.name === "node_modules" || entry.name === ".git") continue;
550
+ const path = join(folder, entry.name);
551
+ if (entry.isDirectory()) walk(path);
552
+ else found.push(relativePath(root, path));
553
+ }
554
+ };
555
+ walk(start);
556
+ return found.sort(byCode);
557
+ }
558
+ /**
559
+ * This function gives the entries of a package, in the order of the `exports` field. The
560
+ * `./package.json` entry is not part of the API. A subpath pattern (`./*`) gives one entry for each
561
+ * declaration file that it matches. `root` is the package folder.
562
+ */
563
+ function entriesOf(manifest, root) {
564
+ const entries = [];
565
+ const exists = (path) => existsSync(resolve(root, path));
566
+ if (manifest.exports === void 0) {
567
+ const field = manifest.types ?? manifest.typings;
568
+ if (typeof field === "string") return [{
569
+ subpath: ".",
570
+ types: field
571
+ }];
572
+ const types = declarationPathOf(typeof manifest.main === "string" ? manifest.main : "./index.js");
573
+ if (types && exists(types)) return [{
574
+ subpath: ".",
575
+ types
576
+ }];
577
+ if (typeof manifest.main === "string") return [{
578
+ subpath: ".",
579
+ note: `no declaration file for main ${manifest.main}`
580
+ }];
581
+ return [];
582
+ }
583
+ const map = subpathMap(manifest.exports);
584
+ const excluded = Object.entries(map).filter(([, value]) => value === null).map(([key]) => key);
585
+ const isExcluded = (subpath) => excluded.some((pattern) => patternMatch(pattern, subpath) !== void 0);
586
+ for (const [subpath, value] of Object.entries(map)) {
587
+ if (subpath === "./package.json" || value === null) continue;
588
+ const target = targetOf(value);
589
+ if (typeof target !== "string") {
590
+ entries.push({
591
+ subpath,
592
+ note: "no condition for a TypeScript consumer"
593
+ });
594
+ continue;
595
+ }
596
+ const declared = declarationPathOf(target);
597
+ if (!subpath.includes("*")) {
598
+ if (isExcluded(subpath)) continue;
599
+ if (!declared) entries.push({
600
+ subpath,
601
+ note: `no declaration file for ${target}`
602
+ });
603
+ else if (declared !== target && !exists(declared) && exists(target)) entries.push({
604
+ subpath,
605
+ note: `no declaration file for ${target}`
606
+ });
607
+ else entries.push({
608
+ subpath,
609
+ types: declared
610
+ });
611
+ continue;
612
+ }
613
+ if (!declared?.includes("*")) {
614
+ entries.push({
615
+ subpath,
616
+ note: `no declaration pattern for ${target}`
617
+ });
618
+ continue;
619
+ }
620
+ const pattern = declared.replace(/^\.\//, "");
621
+ const folder = pattern.slice(0, pattern.indexOf("*")).replace(/[^/]*$/, "");
622
+ const matched = [];
623
+ for (const file of filesUnder(root, folder)) {
624
+ const part = patternMatch(pattern, file);
625
+ if (part === void 0) continue;
626
+ const expanded = subpath.split("*").join(part);
627
+ if (!isExcluded(expanded)) matched.push({
628
+ subpath: expanded,
629
+ types: `./${file}`
630
+ });
631
+ }
632
+ if (matched.length === 0) entries.push({
633
+ subpath,
634
+ note: `no file matches ${declared}`
635
+ });
636
+ entries.push(...matched.sort((a, b) => byCode(a.subpath, b.subpath)));
637
+ }
638
+ return entries;
639
+ }
640
+ /** This function gives the commands of the `bin` field, in name order. A string `bin` has the name of the package without its scope. */
641
+ function binsOf(manifest) {
642
+ const { bin } = manifest;
643
+ if (typeof bin === "string") return [{
644
+ name: (manifest.name ?? "").replace(/^@[^/]+\//, ""),
645
+ path: bin
646
+ }];
647
+ if (typeof bin !== "object" || bin === null) return [];
648
+ return Object.entries(bin).filter((entry) => typeof entry[1] === "string").map(([name, path]) => ({
649
+ name,
650
+ path
651
+ })).sort((a, b) => byCode(a.name, b.name));
652
+ }
653
+ // src/report.ts
654
+ /**
655
+ * The report of the public API of a package, from its built `.d.ts` files.
656
+ *
657
+ * The report lists the names that each entry of the `exports` field gives, and the declaration of
658
+ * each name. It follows `export *`, `export { a as b } from`, `export * as ns` and the imports that
659
+ * a module exports again. It also lists the ambient declarations of each file that an entry reaches,
660
+ * and the bins. The report has no comments and no private members. Thus a change of a comment or of
661
+ * a private field does not change it.
662
+ *
663
+ * The text is the same on Windows and on Linux. The line ends
664
+ * are LF, the paths use `/`, and the sort does not use the locale.
665
+ */
666
+ /** The command that the header of a report names, when the options give no other command. */
667
+ const DEFAULT_TOOL = "api-report";
668
+ /** The reader of the declaration files of one package. */
669
+ var Reader = class {
670
+ #infos = /* @__PURE__ */ new Map();
671
+ #bindings = /* @__PURE__ */ new Map();
672
+ #visiting = /* @__PURE__ */ new Set();
673
+ #root;
674
+ #manifest;
675
+ constructor(root, manifest) {
676
+ this.#root = root;
677
+ this.#manifest = manifest;
678
+ }
679
+ info(file) {
680
+ let info = this.#infos.get(file);
681
+ if (!info) {
682
+ info = parseDeclarations(readFileSync(file, "utf8"), relativePath(this.#root, file));
683
+ this.#infos.set(file, info);
684
+ }
685
+ return info;
686
+ }
687
+ /** This method gives the candidate declaration files of a module path. */
688
+ #candidates(base) {
689
+ const declared = declarationPathOf(base);
690
+ if (declared) return [declared];
691
+ const source = /\.([mc]?)ts$/.exec(base);
692
+ if (source) return [`${base.slice(0, -source[0].length)}.d.${source[1] ?? ""}ts`];
693
+ return [`${base}.d.ts`, join(base, "index.d.ts")];
694
+ }
695
+ /**
696
+ * This method gives the declaration file of a module specifier of `from`: a relative path, or a
697
+ * `#` name of the `imports` field. The result is undefined for a module of a different package. A
698
+ * missing file throws, or gives `null` when `soft` is true.
699
+ */
700
+ fileOf(from, specifier, soft = false) {
701
+ let base;
702
+ if (specifier.startsWith(".")) base = resolve(dirname(from), specifier);
703
+ else if (specifier.startsWith("#") && typeof this.#manifest.imports === "object" && this.#manifest.imports !== null) {
704
+ for (const [pattern, value] of Object.entries(this.#manifest.imports)) {
705
+ const part = patternMatch(pattern, specifier);
706
+ const target = part === void 0 ? void 0 : targetOf(value);
707
+ if (part !== void 0 && typeof target === "string" && target.startsWith(".")) {
708
+ base = resolve(this.#root, target.split("*").join(part));
709
+ break;
710
+ }
711
+ }
712
+ if (base === void 0) return void 0;
713
+ } else return void 0;
714
+ const file = this.#candidates(base).find((candidate) => existsSync(candidate));
715
+ if (file) return file;
716
+ if (soft) return null;
717
+ throw new Error(`No declaration file for "${specifier}" from ${relativePath(this.#root, from)}`);
718
+ }
719
+ /** This method gives the binding of `imported` in the module `specifier` of `from`. */
720
+ #bindingIn(from, specifier, imported, typeOnly) {
721
+ const file = this.fileOf(from, specifier);
722
+ if (!file) return {
723
+ kind: "external",
724
+ module: specifier,
725
+ name: imported,
726
+ typeOnly
727
+ };
728
+ if (imported === "*") return {
729
+ kind: "namespace",
730
+ file,
731
+ typeOnly
732
+ };
733
+ const binding = this.exportsOf(file).get(imported);
734
+ if (!binding) throw new Error(`"${specifier}" from ${relativePath(this.#root, from)} does not export ${imported}`);
735
+ return typeOnly ? {
736
+ ...binding,
737
+ typeOnly: true
738
+ } : binding;
739
+ }
740
+ /** This method gives the names that a module exports, and their bindings. */
741
+ exportsOf(file) {
742
+ const known = this.#bindings.get(file);
743
+ if (known) return known;
744
+ if (this.#visiting.has(file)) return /* @__PURE__ */ new Map();
745
+ this.#visiting.add(file);
746
+ const info = this.info(file);
747
+ const result = /* @__PURE__ */ new Map();
748
+ for (const [name, { local, typeOnly }] of info.exported) {
749
+ const imported = info.imports.get(local);
750
+ if (info.locals.has(local)) result.set(name, {
751
+ kind: "declaration",
752
+ file,
753
+ local,
754
+ typeOnly
755
+ });
756
+ else if (imported) result.set(name, this.#bindingIn(file, imported.from, imported.imported, typeOnly || imported.typeOnly));
757
+ else throw new Error(`${relativePath(this.#root, file)} exports ${local}, and has no declaration or import of it`);
758
+ }
759
+ for (const reexport of info.reexports) result.set(reexport.exported, this.#bindingIn(file, reexport.from, reexport.imported, reexport.typeOnly));
760
+ for (const namespace of info.namespaces) result.set(namespace.name, this.#bindingIn(file, namespace.from, "*", namespace.typeOnly));
761
+ const explicit = new Set(result.keys());
762
+ for (const { from: star, typeOnly } of info.stars) {
763
+ const target = this.fileOf(file, star);
764
+ if (!target) {
765
+ const name = `* from "${star}"`;
766
+ if (!result.has(name)) result.set(name, {
767
+ kind: "external",
768
+ module: star,
769
+ name: "*",
770
+ typeOnly
771
+ });
772
+ continue;
773
+ }
774
+ for (const [name, binding] of this.exportsOf(target)) if (name !== "default" && !explicit.has(name) && !result.has(name)) result.set(name, typeOnly ? {
775
+ ...binding,
776
+ typeOnly: true
777
+ } : binding);
778
+ }
779
+ this.#visiting.delete(file);
780
+ this.#bindings.set(file, result);
781
+ return result;
782
+ }
783
+ /**
784
+ * This method gives each declaration file of the package that `file` reaches through its module
785
+ * specifiers, and `file`. A file outside the package folder or in `node_modules` is not part of it.
786
+ */
787
+ reached(file) {
788
+ const seen = /* @__PURE__ */ new Set();
789
+ const pending = [file];
790
+ for (let next = pending.pop(); next !== void 0; next = pending.pop()) {
791
+ if (seen.has(next)) continue;
792
+ seen.add(next);
793
+ for (const specifier of this.info(next).references) {
794
+ const target = this.fileOf(next, specifier, true);
795
+ if (!target) continue;
796
+ const path = relativePath(this.#root, target);
797
+ if (path.startsWith("../") || path.split("/").includes("node_modules")) continue;
798
+ pending.push(target);
799
+ }
800
+ }
801
+ return [...seen];
802
+ }
803
+ };
804
+ /** This function gives the lines of the header of a report. */
805
+ function header(packageName, tool) {
806
+ return [
807
+ `# The public API of ${packageName}`,
808
+ "#",
809
+ "# The names of each entry of the exports field, and the declaration of each name, without comments",
810
+ `# and private members. The command \`${tool} check\` compares this file with the built .d.ts files.`,
811
+ `# To accept a change of the API, start the build, then \`${tool} update\`, and review the diff.`
812
+ ];
813
+ }
814
+ /** The number of lines of the header of a report. */
815
+ const HEADER_LINES = 5;
816
+ /**
817
+ * This function gives the report of the public API of a package. `entries` gives the subpath and
818
+ * the declaration file of each entry, relative to `root`. The report has the exported names of each
819
+ * entry, the bins of the manifest, and then the declaration of each name.
820
+ */
821
+ function apiReport(packageName, root, entries, options = {}) {
822
+ const manifest = options.manifest ?? {};
823
+ const reader = new Reader(root, manifest);
824
+ const path = (file) => relativePath(root, file);
825
+ const keyOf = (binding) => binding.kind === "declaration" ? `${path(binding.file)}#${binding.local}` : binding.kind === "namespace" ? `${path(binding.file)}#*` : `${binding.module}#${binding.name}`;
826
+ const declarations = /* @__PURE__ */ new Map();
827
+ const lines = header(packageName, options.tool ?? "api-report");
828
+ if (entries.every((entry) => entry.types === void 0)) lines.push("", "This package has no type declarations: no entry of its package.json gives a .d.ts file.");
829
+ /** The lines of the names of a module, and the names of each namespace in it, with `prefix`. */
830
+ const names = (bindings, prefix, parents, typeOnly) => {
831
+ for (const [name, binding] of [...bindings].sort(([a], [b]) => byCode(a, b))) {
832
+ const key = keyOf(binding);
833
+ const isType = typeOnly || binding.typeOnly;
834
+ lines.push(`${isType ? "type " : ""}${prefix}${name}: ${key}${binding.kind === "declaration" ? "" : ` (${binding.kind})`}`);
835
+ if (binding.kind === "declaration" && !declarations.has(key)) declarations.set(key, (reader.info(binding.file).locals.get(binding.local) ?? []).join("\n"));
836
+ if (binding.kind === "namespace" && !parents.has(binding.file)) names(reader.exportsOf(binding.file), `${prefix}${name}.`, /* @__PURE__ */ new Set([...parents, binding.file]), isType);
837
+ }
838
+ };
839
+ for (const entry of entries) {
840
+ if (entry.types === void 0) {
841
+ lines.push("", `## ${entry.subpath}: ${entry.note ?? "no declaration file"}`);
842
+ continue;
843
+ }
844
+ const file = resolve(root, entry.types);
845
+ if (!existsSync(file)) throw new Error(`${entry.subpath}: ${entry.types} is missing. Build the package first.`);
846
+ const bindings = reader.exportsOf(file);
847
+ lines.push("", `## ${entry.subpath} (${path(file)}): ${bindings.size} names`, "");
848
+ names(bindings, "", /* @__PURE__ */ new Set([file]), false);
849
+ const ambient = [];
850
+ for (const reached of reader.reached(file)) for (const [label, statements] of reader.info(reached).ambient) {
851
+ const key = `${path(reached)}#${label}`;
852
+ ambient.push(key);
853
+ if (!declarations.has(key)) declarations.set(key, statements.join("\n"));
854
+ }
855
+ for (const key of ambient.sort(byCode)) lines.push(`ambient: ${key}`);
856
+ }
857
+ const bins = binsOf(manifest);
858
+ if (bins.length > 0) {
859
+ lines.push("", `## bin: ${bins.length} commands`, "");
860
+ for (const bin of bins) lines.push(`${bin.name}: ${bin.path}`);
861
+ }
862
+ if (declarations.size > 0 || entries.some((entry) => entry.types !== void 0)) {
863
+ lines.push("", "## Declarations");
864
+ for (const key of [...declarations.keys()].sort(byCode)) lines.push("", `### ${key}`, declarations.get(key) ?? "");
865
+ }
866
+ return `${lines.join("\n")}\n`;
867
+ }
868
+ /** This function gives the report of the package in the folder `dir`. */
869
+ function packageReport(dir, options = {}) {
870
+ const source = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
871
+ const manifest = options.publishConfig === false ? source : publishedManifest(source);
872
+ return apiReport(typeof manifest.name === "string" ? manifest.name : basename(dir), dir, entriesOf(manifest, dir), {
873
+ manifest,
874
+ ...options.tool === void 0 ? {} : { tool: options.tool }
875
+ });
876
+ }
877
+ // src/workspace.ts
878
+ /**
879
+ * The package folders of a repository: the folders that the globs of the workspace name, with a
880
+ * `package.json` file.
881
+ */
882
+ /** The characters that have a meaning in a regular expression. */
883
+ const SPECIAL = /* @__PURE__ */ new Set([..."\\^$.|+()[]{}*?/"]);
884
+ /**
885
+ * This function gives a regular expression for a glob of `/` paths. `*` matches a part of one path
886
+ * segment, `?` matches one character, `**` matches zero or more segments, and `{a,b}` matches one of
887
+ * its parts. The function escapes each other special character.
888
+ */
889
+ function globToRegExp(glob) {
890
+ let source = "";
891
+ let braces = 0;
892
+ for (let index = 0; index < glob.length; index++) {
893
+ const char = glob.charAt(index);
894
+ if (char === "/" && glob.slice(index + 1) === "**") {
895
+ source += "(?:/.*)?";
896
+ break;
897
+ }
898
+ if (char === "*" && glob.charAt(index + 1) === "*") {
899
+ const atStart = index === 0 || glob.charAt(index - 1) === "/";
900
+ const after = glob.charAt(index + 2);
901
+ if (atStart && after === "/") {
902
+ source += "(?:[^/]+/)*";
903
+ index += 2;
904
+ } else if (atStart && after === "") {
905
+ source += ".*";
906
+ index += 1;
907
+ } else {
908
+ source += "[^/]*";
909
+ index += 1;
910
+ }
911
+ } else if (char === "*") source += "[^/]*";
912
+ else if (char === "?") source += "[^/]";
913
+ else if (char === "{") {
914
+ braces++;
915
+ source += "(?:";
916
+ } else if (char === "}" && braces > 0) {
917
+ braces--;
918
+ source += ")";
919
+ } else if (char === "," && braces > 0) source += "|";
920
+ else if (SPECIAL.has(char)) source += `\\${char}`;
921
+ else source += char;
922
+ }
923
+ if (braces > 0) throw new Error(`A glob with a "{" that has no "}": ${glob}`);
924
+ return new RegExp(`^${source}$`);
925
+ }
926
+ /** The characters that make a path segment a pattern. */
927
+ const GLOB_CHARS = /[*?{]/;
928
+ /**
929
+ * This function gives the folders under `root` that a glob names, as `/` paths relative to `root`,
930
+ * in the order of the code units. It does not go into `node_modules` or a folder that starts with `.`.
931
+ */
932
+ function globFolders(root, glob) {
933
+ const clean = glob.replace(/^\.\//, "").replace(/\/+$/, "");
934
+ const segments = clean.split("/");
935
+ const firstPattern = segments.findIndex((segment) => GLOB_CHARS.test(segment));
936
+ if (firstPattern < 0) return existsSync(join(root, clean)) ? [clean] : [];
937
+ const base = segments.slice(0, firstPattern).join("/");
938
+ const depth = clean.includes("**") ? Number.POSITIVE_INFINITY : segments.length - firstPattern;
939
+ const pattern = globToRegExp(clean);
940
+ const start = join(root, base);
941
+ if (!existsSync(start)) return [];
942
+ const found = [];
943
+ const walk = (folder, level) => {
944
+ for (const entry of readdirSync(folder, { withFileTypes: true })) {
945
+ if (!entry.isDirectory() || entry.name === "node_modules" || entry.name.startsWith(".")) continue;
946
+ const path = join(folder, entry.name);
947
+ if (pattern.test(relativePath(root, path))) found.push(relativePath(root, path));
948
+ if (level < depth) walk(path, level + 1);
949
+ }
950
+ };
951
+ if (base !== "" && pattern.test(base)) found.push(base);
952
+ walk(start, 1);
953
+ return found.sort(byCode);
954
+ }
955
+ /**
956
+ * This function gives the globs of the workspace at `root`: the `packages` list of
957
+ * `pnpm-workspace.yaml`, then the `workspaces` field of `package.json`. The result is undefined when
958
+ * the repository has no workspace.
959
+ */
960
+ function workspaceGlobs(root) {
961
+ const yaml = join(root, "pnpm-workspace.yaml");
962
+ if (existsSync(yaml)) {
963
+ const lines = readFileSync(yaml, "utf8").split(/\r?\n/);
964
+ const start = lines.findIndex((line) => /^packages\s*:/.test(line));
965
+ if (start >= 0) {
966
+ const unquote = (text) => text.replace(/\s+#.*$/, "").trim().replace(/^["']|["']$/g, "");
967
+ const inline = /^packages\s*:\s*\[(.*)\]/.exec(lines[start] ?? "");
968
+ if (inline) return (inline[1] ?? "").split(",").map(unquote).filter(Boolean);
969
+ const globs = [];
970
+ for (const line of lines.slice(start + 1)) {
971
+ if (/^\s*(#.*)?$/.test(line)) continue;
972
+ const item = /^\s+-\s+(.+)$/.exec(line);
973
+ if (!item) break;
974
+ globs.push(unquote(item[1] ?? ""));
975
+ }
976
+ return globs;
977
+ }
978
+ }
979
+ const manifestFile = join(root, "package.json");
980
+ if (existsSync(manifestFile)) {
981
+ const { workspaces } = JSON.parse(readFileSync(manifestFile, "utf8"));
982
+ if (Array.isArray(workspaces)) return workspaces.filter((glob) => typeof glob === "string");
983
+ if (typeof workspaces === "object" && workspaces !== null && "packages" in workspaces && Array.isArray(workspaces.packages)) return workspaces.packages.filter((glob) => typeof glob === "string");
984
+ }
985
+ }
986
+ /**
987
+ * This function gives the package folders of the repository at `root`: the folders of the globs
988
+ * that have a `package.json` file. A glob that starts with `!` removes folders. Without globs, the
989
+ * function reads the globs of the workspace, and a repository with no workspace is one package.
990
+ * The result has absolute paths, in the order of the code units.
991
+ */
992
+ function packageFolders(root, globs = workspaceGlobs(root)) {
993
+ if (globs === void 0) return existsSync(join(root, "package.json")) ? [root] : [];
994
+ const included = /* @__PURE__ */ new Set();
995
+ for (const glob of globs.filter((item) => !item.startsWith("!"))) for (const folder of globFolders(root, glob)) included.add(folder);
996
+ for (const glob of globs.filter((item) => item.startsWith("!"))) for (const folder of globFolders(root, glob.slice(1))) included.delete(folder);
997
+ return [...included].filter((folder) => existsSync(join(root, folder, "package.json"))).sort(byCode).map((folder) => join(root, folder));
998
+ }
999
+ // src/run.ts
1000
+ /**
1001
+ * The commands `check` and `update` of the bin `api-report`, as functions. `runReports` compares or
1002
+ * writes the reports of each package, and `runCli` reads the arguments and writes the result.
1003
+ */
1004
+ /** The path of the report in a package folder, when the configuration gives no other path. */
1005
+ const REPORT_FILE = "test/api/public-api.txt";
1006
+ /**
1007
+ * This function reads the field `apiReport` of the `package.json` file at `root`. The result is an
1008
+ * empty configuration when the field does not exist.
1009
+ *
1010
+ * @throws Error when the field is not an object, or a value has the wrong type
1011
+ */
1012
+ function readConfig(root) {
1013
+ const file = join(root, "package.json");
1014
+ if (!existsSync(file)) return {};
1015
+ const value = JSON.parse(readFileSync(file, "utf8"))["apiReport"];
1016
+ if (value === void 0) return {};
1017
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error("The field apiReport of package.json must be an object.");
1018
+ const config = value;
1019
+ const result = {};
1020
+ const packages = config["packages"];
1021
+ if (packages !== void 0) {
1022
+ if (!Array.isArray(packages) || !packages.every((glob) => typeof glob === "string")) throw new Error("apiReport.packages must be an array of globs.");
1023
+ result.packages = packages;
1024
+ }
1025
+ for (const key of ["report", "tool"]) {
1026
+ const item = config[key];
1027
+ if (item === void 0) continue;
1028
+ if (typeof item !== "string" || item === "") throw new Error(`apiReport.${key} must be a string.`);
1029
+ result[key] = item;
1030
+ }
1031
+ for (const key of ["includePrivate", "publishConfig"]) {
1032
+ const item = config[key];
1033
+ if (item === void 0) continue;
1034
+ if (typeof item !== "boolean") throw new Error(`apiReport.${key} must be true or false.`);
1035
+ result[key] = item;
1036
+ }
1037
+ const unknown = Object.keys(config).filter((key) => ![
1038
+ "packages",
1039
+ "report",
1040
+ "tool",
1041
+ "includePrivate",
1042
+ "publishConfig"
1043
+ ].includes(key));
1044
+ if (unknown.length > 0) throw new Error(`apiReport has unknown fields: ${unknown.join(", ")}.`);
1045
+ return result;
1046
+ }
1047
+ /** This function makes sure that the path of a report stays in its package folder. */
1048
+ function checkReportPath(report) {
1049
+ const clean = report.replaceAll("\\", "/").replace(/^\.\//, "");
1050
+ if (clean === "" || isAbsolute(report) || clean.split("/").includes("..")) throw new Error(`The path of a report must be relative to the package folder, with no "..": ${report}`);
1051
+ return clean;
1052
+ }
1053
+ /** This function compares (`check`) or writes (`update`) the report of each package. It writes nothing in `check` mode. */
1054
+ function runReports(options) {
1055
+ const root = resolve(options.root);
1056
+ const report = checkReportPath(options.report ?? "test/api/public-api.txt");
1057
+ const named = options.folders !== void 0 && options.folders.length > 0;
1058
+ const folders = named ? (options.folders ?? []).map((folder) => resolve(root, folder)) : packageFolders(root, options.packages);
1059
+ const results = [];
1060
+ for (const folder of folders) {
1061
+ const shown = relativePath(root, folder) || ".";
1062
+ const file = join(folder, report);
1063
+ const shownFile = relativePath(root, file);
1064
+ const manifestFile = join(folder, "package.json");
1065
+ if (!existsSync(manifestFile)) {
1066
+ results.push({
1067
+ folder: shown,
1068
+ file: shownFile,
1069
+ status: "error",
1070
+ error: "no package.json"
1071
+ });
1072
+ continue;
1073
+ }
1074
+ const current = existsSync(file) ? readFileSync(file, "utf8").replace(/\r\n/g, "\n") : void 0;
1075
+ let manifest;
1076
+ try {
1077
+ manifest = JSON.parse(readFileSync(manifestFile, "utf8"));
1078
+ } catch (error) {
1079
+ results.push({
1080
+ folder: shown,
1081
+ file: shownFile,
1082
+ status: "error",
1083
+ error: error instanceof Error ? error.message : String(error)
1084
+ });
1085
+ continue;
1086
+ }
1087
+ if (manifest.private === true && !named && options.includePrivate !== true) {
1088
+ if (current === void 0) results.push({
1089
+ folder: shown,
1090
+ file: shownFile,
1091
+ status: "private"
1092
+ });
1093
+ else {
1094
+ if (options.mode === "update") rmSync(file);
1095
+ results.push({
1096
+ folder: shown,
1097
+ file: shownFile,
1098
+ status: "stale"
1099
+ });
1100
+ }
1101
+ continue;
1102
+ }
1103
+ let text;
1104
+ try {
1105
+ text = packageReport(folder, {
1106
+ tool: options.tool ?? "api-report",
1107
+ ...options.publishConfig === void 0 ? {} : { publishConfig: options.publishConfig }
1108
+ });
1109
+ } catch (error) {
1110
+ results.push({
1111
+ folder: shown,
1112
+ file: shownFile,
1113
+ status: "error",
1114
+ error: error instanceof Error ? error.message : String(error)
1115
+ });
1116
+ continue;
1117
+ }
1118
+ if (current === text) {
1119
+ results.push({
1120
+ folder: shown,
1121
+ file: shownFile,
1122
+ status: "same"
1123
+ });
1124
+ continue;
1125
+ }
1126
+ if (options.mode === "update") {
1127
+ mkdirSync(dirname(file), { recursive: true });
1128
+ writeFileSync(file, text);
1129
+ }
1130
+ const diff = unifiedDiff(current ?? "", text, {
1131
+ from: current === void 0 ? "/dev/null" : `a/${shownFile}`,
1132
+ to: `b/${shownFile}`
1133
+ });
1134
+ results.push({
1135
+ folder: shown,
1136
+ file: shownFile,
1137
+ status: current === void 0 ? "new" : "changed",
1138
+ diff
1139
+ });
1140
+ }
1141
+ const failed = results.some((result) => result.status === "error" || options.mode === "check" && (result.status === "changed" || result.status === "new" || result.status === "stale"));
1142
+ return {
1143
+ mode: options.mode,
1144
+ packages: results,
1145
+ failed
1146
+ };
1147
+ }
1148
+ /** The most lines of the diff of one package in the output. */
1149
+ const MAX_DIFF_LINES = 400;
1150
+ /** This function shortens a diff to `MAX_DIFF_LINES` lines. */
1151
+ function shortDiff(diff) {
1152
+ const lines = diff.replace(/\n$/, "").split("\n");
1153
+ if (lines.length <= MAX_DIFF_LINES) return `${lines.join("\n")}\n`;
1154
+ return `${lines.slice(0, MAX_DIFF_LINES).join("\n")}\n... ${lines.length - MAX_DIFF_LINES} more lines. Start the command update and read the diff in git.\n`;
1155
+ }
1156
+ /** This function gives the text of a result for a terminal or a CI log. */
1157
+ function formatResult(result, tool = DEFAULT_TOOL) {
1158
+ const by = (status) => result.packages.filter((item) => item.status === status);
1159
+ const out = [`${result.packages.filter((item) => item.status !== "private" && item.status !== "stale" && item.status !== "error").length} public packages with a report of the API, ${by("private").length} private packages without a report.`];
1160
+ const list = (title, items, line) => {
1161
+ if (items.length === 0) return;
1162
+ out.push(`${title}:`);
1163
+ for (const item of items) out.push(` ${line(item)}`);
1164
+ };
1165
+ const update = result.mode === "update";
1166
+ list(update ? "Written" : "The report differs from the built .d.ts files", by("changed"), (item) => item.file);
1167
+ list(update ? "Written (new)" : "No report", by("new"), (item) => update ? item.file : `${item.folder} (${item.file})`);
1168
+ list(update ? "Removed (the package is private)" : "A report of a private package", by("stale"), (item) => item.file);
1169
+ list("Errors", by("error"), (item) => `${item.folder}: ${item.error ?? "unknown error"}`);
1170
+ let text = `${out.join("\n")}\n`;
1171
+ if (!update) {
1172
+ for (const item of by("changed")) text += `\n${shortDiff(item.diff ?? "")}`;
1173
+ if (by("changed").length + by("new").length + by("stale").length > 0) text += `\nTo accept a change of the API, start the build, then \`${tool} update\`, review the diff, and commit the reports.\n`;
1174
+ }
1175
+ return text;
1176
+ }
1177
+ /** This function gives the result as Markdown for the summary of a GitHub Actions run. It gives an empty string when all reports are current. */
1178
+ function summaryMarkdown(result) {
1179
+ const changed = result.packages.filter((item) => item.status === "changed" || item.status === "new");
1180
+ const other = result.packages.filter((item) => item.status === "stale" || item.status === "error");
1181
+ if (changed.length === 0 && other.length === 0) return "";
1182
+ const out = ["### Public API reports", ""];
1183
+ for (const item of changed) out.push(`<details><summary><code>${item.file}</code> (${item.status})</summary>`, "", "```diff", shortDiff(item.diff ?? "").replace(/\n$/, ""), "```", "", "</details>", "");
1184
+ for (const item of other) out.push(`- \`${item.file}\`: ${item.status === "stale" ? "a report of a private package" : item.error ?? "error"}`);
1185
+ return `${out.join("\n")}\n`;
1186
+ }
1187
+ /** The help text of the bin. */
1188
+ const USAGE = `Usage: api-report <check | update> [options] [<package folder>...]
1189
+
1190
+ check Compare each report with the built .d.ts files. Exit code 1 when a report differs or is missing.
1191
+ update Write each report again.
1192
+
1193
+ --root <folder> The root of the repository. The default is the current folder.
1194
+ --packages <glob> A glob of package folders. Use it again for more globs. The default is the globs of the workspace.
1195
+ --report <path> The path of the report in each package folder. The default is ${REPORT_FILE}.
1196
+ --include-private Also make a report for each private package.
1197
+ --no-publish-config Read the fields of package.json without publishConfig.
1198
+ -h, --help Show this text.
1199
+
1200
+ The field "apiReport" of the root package.json can set packages, report, includePrivate, publishConfig and tool.
1201
+ `;
1202
+ /** An error of the arguments: exit code 2 and the help text. */
1203
+ var UsageError = class extends Error {};
1204
+ /** This function starts the bin with the arguments `args`, and gives its exit code. */
1205
+ function runCli(args, io) {
1206
+ let mode;
1207
+ let root = io.cwd;
1208
+ const packages = [];
1209
+ const folders = [];
1210
+ const flags = {};
1211
+ for (let index = 0; index < args.length; index++) {
1212
+ const arg = args[index] ?? "";
1213
+ const value = () => {
1214
+ const next = args[++index];
1215
+ if (next === void 0 || next.startsWith("-")) throw new UsageError(`The option ${arg} needs a value.`);
1216
+ return next;
1217
+ };
1218
+ try {
1219
+ if (arg === "check" || arg === "--check") mode = "check";
1220
+ else if (arg === "update" || arg === "--update") mode = "update";
1221
+ else if (arg === "--root") root = resolve(io.cwd, value());
1222
+ else if (arg === "--packages") packages.push(value());
1223
+ else if (arg === "--report") flags.report = value();
1224
+ else if (arg === "--include-private") flags.includePrivate = true;
1225
+ else if (arg === "--no-publish-config") flags.publishConfig = false;
1226
+ else if (arg === "--help" || arg === "-h") {
1227
+ io.stdout(USAGE);
1228
+ return 0;
1229
+ } else if (arg.startsWith("-")) throw new UsageError(`An unknown option: ${arg}`);
1230
+ else folders.push(arg);
1231
+ } catch (error) {
1232
+ if (!(error instanceof UsageError)) throw error;
1233
+ io.stderr(`api-report: ${error.message}\n\n${USAGE}`);
1234
+ return 2;
1235
+ }
1236
+ }
1237
+ if (mode === void 0) {
1238
+ io.stderr(`api-report: give the command check or update.\n\n${USAGE}`);
1239
+ return 2;
1240
+ }
1241
+ let result;
1242
+ let tool;
1243
+ try {
1244
+ const config = readConfig(root);
1245
+ tool = config.tool ?? "api-report";
1246
+ result = runReports({
1247
+ ...config,
1248
+ ...flags,
1249
+ ...packages.length > 0 ? { packages } : {},
1250
+ mode,
1251
+ root,
1252
+ folders: folders.map((folder) => resolve(io.cwd, folder))
1253
+ });
1254
+ } catch (error) {
1255
+ io.stderr(`api-report: ${error instanceof Error ? error.message : String(error)}\n`);
1256
+ return 1;
1257
+ }
1258
+ io.stdout(formatResult(result, tool));
1259
+ const summary = io.env["GITHUB_STEP_SUMMARY"];
1260
+ if (summary && mode === "check") {
1261
+ const markdown = summaryMarkdown(result);
1262
+ if (markdown !== "") appendFileSync(summary, markdown);
1263
+ }
1264
+ return result.failed ? 1 : 0;
1265
+ }
1266
+ export { targetOf as C, statementsOf as D, parseDeclarations as E, publishedManifest as S, unifiedDiff as T, binsOf as _, runCli as a, entriesOf as b, globFolders as c, workspaceGlobs as d, DEFAULT_TOOL as f, PUBLISH_CONFIG_FIELDS as g, packageReport as h, readConfig as i, globToRegExp as l, apiReport as m, USAGE as n, runReports as o, HEADER_LINES as p, formatResult as r, summaryMarkdown as s, REPORT_FILE as t, packageFolders as u, byCode as v, diffLines as w, patternMatch as x, declarationPathOf as y };
1267
+
1268
+ //# sourceMappingURL=run-Crc3nL8C.js.map