@antelopejs/tooling-configs 0.2.5 → 0.2.7

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,384 @@
1
+ import { c as trackedManifests, s as resolveRevision } from "./files-BMxKg5IR.mjs";
2
+ import { n as revisionSuppressions, t as countSuppressions } from "./suppressions-CgGa-kh7.mjs";
3
+ import { createRequire } from "node:module";
4
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
5
+ import { dirname, join, matchesGlob, relative, resolve, sep } from "node:path";
6
+ import { execFileSync, spawnSync } from "node:child_process";
7
+ import { tmpdir } from "node:os";
8
+ //#region src/guardrails/added-entries.ts
9
+ function createAddedPolicy(globs) {
10
+ return {
11
+ globs,
12
+ verdicts: /* @__PURE__ */ new Map(),
13
+ allowed: /* @__PURE__ */ new Map(),
14
+ problems: /* @__PURE__ */ new Set()
15
+ };
16
+ }
17
+ function entryKey(directory, subpath) {
18
+ return `${directory}\0${subpath}`;
19
+ }
20
+ function allowedByGlob(policy, subpath) {
21
+ return policy.globs.some((glob) => matchesGlob(subpath, glob));
22
+ }
23
+ /** Substitutes each export star in order with its capture, as the published target pattern did. */
24
+ function fillStars(pattern, captures, format = (capture) => capture) {
25
+ let index = 0;
26
+ return pattern.replaceAll("*", () => format(captures[index++] ?? captures[0] ?? ""));
27
+ }
28
+ const INTERNAL_TAG = /@internal\b/u;
29
+ const MODULE_TAG = /@(?:packageDocumentation|module|fileoverview)\b/u;
30
+ function exportedLocalNames(compiler, source) {
31
+ const names = /* @__PURE__ */ new Set();
32
+ for (const statement of source.statements) {
33
+ if (compiler.isExportDeclaration(statement) && statement.moduleSpecifier === void 0 && statement.exportClause !== void 0 && compiler.isNamedExports(statement.exportClause)) for (const element of statement.exportClause.elements) names.add((element.propertyName ?? element.name).text);
34
+ if (compiler.isExportAssignment(statement) && compiler.isIdentifier(statement.expression)) names.add(statement.expression.text);
35
+ }
36
+ return names;
37
+ }
38
+ function declaredNames(compiler, statement) {
39
+ if (compiler.isVariableStatement(statement)) return statement.declarationList.declarations.flatMap((declaration) => compiler.isIdentifier(declaration.name) ? [declaration.name.text] : []);
40
+ if ((compiler.isFunctionDeclaration(statement) || compiler.isClassDeclaration(statement) || compiler.isInterfaceDeclaration(statement) || compiler.isTypeAliasDeclaration(statement) || compiler.isEnumDeclaration(statement) || compiler.isModuleDeclaration(statement)) && statement.name !== void 0 && compiler.isIdentifier(statement.name)) return [statement.name.text];
41
+ return [];
42
+ }
43
+ function isExportedDeclaration(compiler, statement, locals) {
44
+ if (compiler.isExportAssignment(statement)) return !compiler.isIdentifier(statement.expression);
45
+ if ((compiler.canHaveModifiers(statement) ? compiler.getModifiers(statement) : void 0)?.some((modifier) => modifier.kind === compiler.SyntaxKind.ExportKeyword)) return true;
46
+ return declaredNames(compiler, statement).some((name) => locals.has(name));
47
+ }
48
+ function hasInternalTag(compiler, statement) {
49
+ return compiler.getJSDocTags(statement).some((tag) => tag.tagName.text === "internal");
50
+ }
51
+ /** Whether a module's text carries `@internal` on the module (with `@packageDocumentation`, `@module` or `@fileoverview`) or on every exported declaration. */
52
+ function isInternalModule(compiler, text) {
53
+ const source = compiler.createSourceFile("module.ts", text, compiler.ScriptTarget.Latest, true);
54
+ if ((compiler.getLeadingCommentRanges(text, 0) ?? []).map((range) => text.slice(range.pos, range.end)).some((comment) => comment.startsWith("/**") && INTERNAL_TAG.test(comment) && MODULE_TAG.test(comment))) return true;
55
+ const locals = exportedLocalNames(compiler, source);
56
+ const exported = source.statements.filter((statement) => isExportedDeclaration(compiler, statement, locals));
57
+ return exported.length > 0 && exported.every((statement) => hasInternalTag(compiler, statement));
58
+ }
59
+ /** Records why an allowed added entry is not internal, or `undefined` when its module is. */
60
+ function recordVerdict(policy, compiler, entry) {
61
+ const internal = isInternalModule(compiler, readFileSync(entry.module, "utf8"));
62
+ policy.verdicts.set(entryKey(entry.directory, entry.subpath), internal ? void 0 : `${entry.label}: added entry ./${entry.subpath} is allowed by --allow-added but is not marked @internal. Add a leading "/** @internal @packageDocumentation */" comment to the file, or tag every exported declaration with "/** @internal */".`);
63
+ }
64
+ /** Lets matching, `@internal` additions through by removing them from the head output; returns how many files were removed. */
65
+ function applyAllowance(policy, base, head, remove) {
66
+ const existing = new Set(base.map(({ path }) => path));
67
+ let removed = 0;
68
+ for (const entry of head) {
69
+ if (existing.has(entry.path) || !allowedByGlob(policy, entry.subpath)) continue;
70
+ const key = entryKey(entry.directory, entry.subpath);
71
+ const problem = policy.verdicts.has(key) ? policy.verdicts.get(key) : `${entry.directory}: added entry ./${entry.subpath} has no emitted declaration, so @internal cannot be verified.`;
72
+ if (problem !== void 0) {
73
+ policy.problems.add(problem);
74
+ continue;
75
+ }
76
+ remove(entry.path);
77
+ removed += 1;
78
+ policy.allowed.set(key, {
79
+ directory: entry.directory,
80
+ subpath: entry.subpath
81
+ });
82
+ }
83
+ return removed;
84
+ }
85
+ /** The "Added (allowed)" list with its count, or the problems that kept additions from passing. */
86
+ function describeAllowance(policy) {
87
+ const lines = [...policy.allowed.values()].map(({ directory, subpath }) => ` ${directory}: ./${subpath}\n`).sort();
88
+ return `Added (allowed): ${lines.length}\n${lines.join("")}${[...policy.problems].map((problem) => `Not internal: ${problem}\n`).join("")}`;
89
+ }
90
+ //#endregion
91
+ //#region src/guardrails/revisions.ts
92
+ const DIRECTORY_LINK = process.platform === "win32" ? "junction" : "dir";
93
+ function linkDependencies(root, worktree) {
94
+ const directories = /* @__PURE__ */ new Set([".", ...trackedManifests(root).map(dirname)]);
95
+ for (const directory of directories) {
96
+ const source = join(root, directory, "node_modules");
97
+ const target = join(worktree, directory, "node_modules");
98
+ if (existsSync(source) && existsSync(dirname(target)) && !existsSync(target)) symlinkSync(source, target, DIRECTORY_LINK);
99
+ }
100
+ }
101
+ /** Compares isolated committed revisions and removes both worktrees even when compilation fails; a policy lets matching `@internal` additions through. */
102
+ function compareRevisions(root, baseRef, label, emit, policy) {
103
+ const temporary = mkdtempSync(join(tmpdir(), "antelope-proof-"));
104
+ const worktrees = [];
105
+ const results = [];
106
+ try {
107
+ for (const [side, ref] of [["base", baseRef], ["head", "HEAD"]]) {
108
+ const revision = execFileSync("git", [
109
+ "rev-parse",
110
+ "--verify",
111
+ "--end-of-options",
112
+ `${ref}^{commit}`
113
+ ], {
114
+ cwd: root,
115
+ encoding: "utf8",
116
+ stdio: [
117
+ "ignore",
118
+ "pipe",
119
+ "pipe"
120
+ ]
121
+ }).trim();
122
+ const worktree = join(temporary, "worktrees", side);
123
+ execFileSync("git", [
124
+ "worktree",
125
+ "add",
126
+ "--quiet",
127
+ "--detach",
128
+ worktree,
129
+ revision
130
+ ], {
131
+ cwd: root,
132
+ stdio: [
133
+ "ignore",
134
+ "pipe",
135
+ "pipe"
136
+ ]
137
+ });
138
+ worktrees.push(worktree);
139
+ linkDependencies(root, worktree);
140
+ const output = join(temporary, side);
141
+ mkdirSync(output, { recursive: true });
142
+ results.push(emit(worktree, output, join(temporary, "emit", side)));
143
+ }
144
+ const allowedAdditions = policy === void 0 ? 0 : applyAllowance(policy, results[0].published ?? [], results[1].published ?? [], (path) => rmSync(join(temporary, "head", path), { force: true }));
145
+ const diff = spawnSync("git", [
146
+ "diff",
147
+ "--no-index",
148
+ "--no-color",
149
+ "--no-renames",
150
+ "--no-ext-diff",
151
+ "--no-textconv",
152
+ "--",
153
+ "base",
154
+ "head"
155
+ ], {
156
+ cwd: temporary,
157
+ encoding: "utf8",
158
+ maxBuffer: 67108864
159
+ });
160
+ if (diff.error) throw diff.error;
161
+ if (diff.status !== 0 && diff.status !== 1) throw new Error(diff.stderr || "Could not compare revision outputs.");
162
+ const packages = new Set(results.flatMap((result) => result.packages)).size;
163
+ return {
164
+ different: diff.status === 1,
165
+ output: diff.status === 1 ? `${label}: differences against ${baseRef} (committed HEAD).\n${diff.stdout}` : `${label}: ${packages} packages, ${results[1].entries - allowedAdditions} entries unchanged against ${baseRef} (committed HEAD).\n`
166
+ };
167
+ } finally {
168
+ for (const worktree of worktrees.reverse()) execFileSync("git", [
169
+ "worktree",
170
+ "remove",
171
+ "--force",
172
+ worktree
173
+ ], {
174
+ cwd: root,
175
+ stdio: "pipe"
176
+ });
177
+ rmSync(temporary, {
178
+ recursive: true,
179
+ force: true
180
+ });
181
+ }
182
+ }
183
+ function countRows(base, head) {
184
+ const total = (counts) => Object.values(counts.rules).reduce((sum, count) => sum + count, 0);
185
+ const rules = [.../* @__PURE__ */ new Set([...Object.keys(base.rules), ...Object.keys(head.rules)])].sort((a, b) => a.localeCompare(b));
186
+ return [
187
+ [
188
+ "Lint suppressions, all rules",
189
+ total(base),
190
+ total(head)
191
+ ],
192
+ ...rules.map((rule) => [
193
+ `Lint suppressions, \`${rule}\``,
194
+ base.rules[rule] ?? 0,
195
+ head.rules[rule] ?? 0
196
+ ]),
197
+ [
198
+ "`@ts-expect-error`",
199
+ base.tsExpectError,
200
+ head.tsExpectError
201
+ ],
202
+ [
203
+ "`@ts-ignore`",
204
+ base.tsIgnore,
205
+ head.tsIgnore
206
+ ],
207
+ [
208
+ "`SAFETY:` comments",
209
+ base.safety,
210
+ head.safety
211
+ ]
212
+ ];
213
+ }
214
+ /** Counts suppressions in authored code files at the base and at committed HEAD with the shared suppression counter, so a PR body copies them instead of typing them. */
215
+ function revisionCounts(root, baseRef) {
216
+ const [base, head] = [baseRef, "HEAD"].map((ref) => countSuppressions(revisionSuppressions(root, resolveRevision(root, ref))));
217
+ return `\nSuppressions in authored code files (${baseRef} and committed HEAD). A lint directive counts once per rule it names; \`*\` is a directive naming none.\n| Suppressions | base | HEAD |\n| --- | ---: | ---: |\n${countRows(base, head).map(([label, before, after]) => `| ${label} | ${before} | ${after} |`).join("\n")}\n`;
218
+ }
219
+ //#endregion
220
+ //#region src/guardrails/typescript.ts
221
+ /** A proof analyses only packages that publish something: not private, and declaring at least one of `exports`, `main`, `types`, `typings` or `typesVersions`. */
222
+ function unpublishedReason(manifest) {
223
+ if (manifest.private === true) return "private";
224
+ return [
225
+ manifest.exports,
226
+ manifest.main,
227
+ manifest.types,
228
+ manifest.typings,
229
+ manifest.typesVersions
230
+ ].some((field) => field != null) ? void 0 : "no exports, main or types";
231
+ }
232
+ function trackedPackages(root) {
233
+ return trackedManifests(root).flatMap((file) => {
234
+ const directory = dirname(file);
235
+ if (!existsSync(join(root, directory, "tsconfig.json"))) return [];
236
+ return [{
237
+ directory,
238
+ manifest: JSON.parse(readFileSync(join(root, file), "utf8"))
239
+ }];
240
+ });
241
+ }
242
+ function packagesAt(root, publishedOnly) {
243
+ return trackedPackages(root).filter(({ manifest }) => !publishedOnly || unpublishedReason(manifest) === void 0);
244
+ }
245
+ /** The packages a published-only proof leaves out, each with the reason, so a skip is reported rather than silent. */
246
+ function unpublishedAt(root) {
247
+ return trackedPackages(root).flatMap(({ directory, manifest }) => {
248
+ const reason = unpublishedReason(manifest);
249
+ return reason === void 0 ? [] : [{
250
+ directory,
251
+ reason
252
+ }];
253
+ });
254
+ }
255
+ function packageRoot(file) {
256
+ let directory = dirname(file);
257
+ while (!existsSync(join(directory, "package.json"))) {
258
+ const parent = dirname(directory);
259
+ if (parent === directory) return dirname(file);
260
+ directory = parent;
261
+ }
262
+ return directory;
263
+ }
264
+ /** Loads the compiler a package builds with, including a package-local installation in a workspace, falling back to the one `dts-bundle-generator` brings. A TypeScript without the programmatic API (7 and later) is an error rather than a crash. */
265
+ function loadTypeScript(directory) {
266
+ const own = createRequire(import.meta.url);
267
+ let file;
268
+ try {
269
+ file = createRequire(join(directory, "package.json")).resolve("typescript");
270
+ } catch {
271
+ file = createRequire(own.resolve("dts-bundle-generator")).resolve("typescript");
272
+ }
273
+ const compiler = createRequire(file)("typescript");
274
+ const root = packageRoot(file);
275
+ if (compiler.sys === void 0 || !("createProgram" in compiler)) throw new Error(`TypeScript ${compiler.version} at ${root} has no programmatic compiler API (sys, createProgram), so this package cannot be analysed. Build it with a TypeScript that has one, or mark the package private.`);
276
+ return {
277
+ compiler,
278
+ root
279
+ };
280
+ }
281
+ const TEST_SOURCE_GLOBS = [
282
+ "**/*.test.*",
283
+ "**/*.spec.*",
284
+ "**/__tests__/**",
285
+ "test/**",
286
+ "tests/**"
287
+ ];
288
+ function isTestSource(root, file) {
289
+ const path = relative(root, file).split("\\").join("/");
290
+ return TEST_SOURCE_GLOBS.some((pattern) => matchesGlob(path, pattern));
291
+ }
292
+ function failDiagnostics(compiler, diagnostics) {
293
+ const errors = diagnostics.filter((item) => item.category === compiler.DiagnosticCategory.Error);
294
+ if (errors.length) throw new Error(compiler.formatDiagnostics(errors, {
295
+ getCanonicalFileName: (file) => file,
296
+ getCurrentDirectory: () => process.cwd(),
297
+ getNewLine: () => "\n"
298
+ }));
299
+ }
300
+ /** Declaration inputs are part of the local closure but TypeScript does not emit copies of them. */
301
+ function copyDeclarations(program, directory, output) {
302
+ const sources = program.getSourceFiles().filter((source) => !program.isSourceFileDefaultLibrary(source) && !program.isSourceFileFromExternalLibrary(source) && !relative(directory, source.fileName).startsWith(`..${sep}`) && !isTestSource(directory, source.fileName));
303
+ const authored = sources.filter((source) => !source.isDeclarationFile);
304
+ let root = dirname((authored[0] ?? sources[0])?.fileName ?? join(directory, "index.ts"));
305
+ for (const source of authored.length ? authored : sources) while (relative(root, source.fileName).startsWith(`..${sep}`)) root = dirname(root);
306
+ root = program.getCompilerOptions().rootDir ?? root;
307
+ const files = [];
308
+ for (const source of sources) {
309
+ if (!source.isDeclarationFile) continue;
310
+ const path = relative(root, source.fileName);
311
+ if (path.startsWith(`..${sep}`)) continue;
312
+ const target = join(output, path);
313
+ mkdirSync(dirname(target), { recursive: true });
314
+ writeFileSync(target, source.text);
315
+ files.push(target);
316
+ }
317
+ return files;
318
+ }
319
+ function parseConfig(directory) {
320
+ const { compiler, root } = loadTypeScript(directory);
321
+ const config = compiler.readConfigFile(join(directory, "tsconfig.json"), compiler.sys.readFile);
322
+ if (config.error) failDiagnostics(compiler, [config.error]);
323
+ const parsed = compiler.parseJsonConfigFileContent(config.config, compiler.sys, directory);
324
+ failDiagnostics(compiler, parsed.errors);
325
+ return {
326
+ compiler,
327
+ root,
328
+ parsed
329
+ };
330
+ }
331
+ /** The configured `outDir`, the root under which the declaration half already judges a built path as test output. */
332
+ function outputRoot(directory) {
333
+ return resolve(directory, parseConfig(directory).parsed.options.outDir ?? ".");
334
+ }
335
+ /** Emits with the package's compiler and config; test roots and outputs never enter either proof. `modules` maps each emitted file to its source module. */
336
+ function emitPackage(directory, output, declarations) {
337
+ const { compiler, root, parsed } = parseConfig(directory);
338
+ const options = {
339
+ ...parsed.options,
340
+ rootDir: parsed.options.rootDir ?? (parsed.options.outDir ? void 0 : directory),
341
+ outDir: output,
342
+ declarationDir: declarations ? output : void 0,
343
+ declaration: declarations,
344
+ emitDeclarationOnly: declarations,
345
+ removeComments: true,
346
+ declarationMap: false,
347
+ sourceMap: false,
348
+ inlineSourceMap: false,
349
+ noEmit: false,
350
+ noEmitOnError: false,
351
+ composite: false,
352
+ incremental: false,
353
+ tsBuildInfoFile: void 0,
354
+ outFile: void 0,
355
+ allowImportingTsExtensions: declarations ? parsed.options.allowImportingTsExtensions : false
356
+ };
357
+ const program = compiler.createProgram({
358
+ rootNames: parsed.fileNames.filter((file) => !isTestSource(directory, file)),
359
+ options,
360
+ projectReferences: parsed.projectReferences
361
+ });
362
+ if (declarations) failDiagnostics(compiler, compiler.getPreEmitDiagnostics(program));
363
+ const files = [];
364
+ const modules = /* @__PURE__ */ new Map();
365
+ const result = program.emit(void 0, (file, text, _bom, _onError, sources) => {
366
+ if (sources?.some((source) => isTestSource(directory, source.fileName))) return;
367
+ if (declarations ? !/\.d\.[cm]?ts$/.test(file) : !/\.[cm]?jsx?$/.test(file)) return;
368
+ mkdirSync(dirname(file), { recursive: true });
369
+ writeFileSync(file, text);
370
+ files.push(file);
371
+ if (sources?.[0] !== void 0) modules.set(resolve(file), sources[0].fileName);
372
+ });
373
+ if (declarations) failDiagnostics(compiler, result.diagnostics);
374
+ if (declarations) files.push(...copyDeclarations(program, directory, output));
375
+ return {
376
+ compiler,
377
+ compilerRoot: root,
378
+ files,
379
+ modules,
380
+ options: parsed.options
381
+ };
382
+ }
383
+ //#endregion
384
+ export { unpublishedAt as a, revisionCounts as c, describeAllowance as d, fillStars as f, packagesAt as i, allowedByGlob as l, isTestSource as n, DIRECTORY_LINK as o, recordVerdict as p, outputRoot as r, compareRevisions as s, emitPackage as t, createAddedPolicy as u };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@antelopejs/tooling-configs",
3
- "version": "0.2.5",
3
+ "version": "0.2.7",
4
4
  "description": "Shared tooling presets for AntelopeJS repositories: oxlint (with the vendored anti-slop rules), oxfmt, ESLint for Nuxt layers, Knip, and an interface range check",
5
5
  "keywords": [
6
6
  "antelopejs",
@@ -27,6 +27,7 @@
27
27
  "antelopejs-checks": "./dist/bin/checks.mjs",
28
28
  "antelopejs-comment-proof": "./dist/bin/comment-proof.mjs",
29
29
  "antelopejs-ratchet": "./dist/bin/ratchet.mjs",
30
+ "antelopejs-suppressions": "./dist/bin/suppressions.mjs",
30
31
  "antelopejs-sync": "./dist/bin/sync.mjs"
31
32
  },
32
33
  "files": [
@@ -60,11 +61,14 @@
60
61
  "prepare": "if git rev-parse --is-inside-work-tree >/dev/null 2>&1 && command -v lefthook >/dev/null 2>&1; then lefthook install; fi",
61
62
  "sync": "node src/bin/sync.ts",
62
63
  "sync:check": "node src/bin/sync.ts --check",
63
- "knip": "knip"
64
+ "knip": "knip",
65
+ "suppressions": "node src/bin/suppressions.ts",
66
+ "suppressions:update": "node src/bin/suppressions.ts --update"
64
67
  },
65
68
  "dependencies": {
66
69
  "@oxlint/plugins": "1.81.0",
67
70
  "dts-bundle-generator": "^9.5.1",
71
+ "typescript": "^5.9.3",
68
72
  "yaml": "^2.9.1"
69
73
  },
70
74
  "devDependencies": {
@@ -78,8 +82,7 @@
78
82
  "oxlint-tsgolint": "^7.0.2001",
79
83
  "release-it": "^19.2.4",
80
84
  "release-it-changelogen": "^0.1.0",
81
- "tsdown": "^0.22.14",
82
- "typescript": "^5.9.3"
85
+ "tsdown": "^0.22.14"
83
86
  },
84
87
  "peerDependencies": {
85
88
  "@nuxt/eslint-config": ">=1.2.0",