@antelopejs/tooling-configs 0.3.1 → 0.3.3
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.
- package/README.md +26 -14
- package/dist/api-CCOiLN3w.mjs +185 -0
- package/dist/bin/checks.mjs +253 -27
- package/dist/bin/garden.mjs +6 -171
- package/dist/bin/lease.mjs +3 -279
- package/dist/bin/sync.mjs +8 -8
- package/dist/bin/triage.d.mts +1 -0
- package/dist/bin/triage.mjs +108 -0
- package/dist/bin/verify.mjs +155 -11
- package/dist/{ci-workflow-mc0vywUV.mjs → ci-workflow-CXcAZj6g.mjs} +55 -1
- package/dist/ports-DGP6bPJy.mjs +282 -0
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -27,7 +27,7 @@ The AntelopeJS guardrail pack: shared lint, format and dead-code presets, the co
|
|
|
27
27
|
| `./oxc/guardrails` | Loaded by the oxlint preset as a JS plugin | The `antelopejs` comment and test-quality rules |
|
|
28
28
|
| `./verify` | `import type { VerifyConfig } from "@antelopejs/tooling-configs/verify"` | Types and check helpers for a shared verification skill's `verify.config.ts` |
|
|
29
29
|
| bin | `antelopejs-sync` | Writes the guardrail pack into a repository; `--check` reports drift |
|
|
30
|
-
| bin | `antelopejs-checks`
|
|
30
|
+
| bin | `antelopejs-checks [--no-services]` | Runs every check and prints only the failures; starts `.github/compose.yml` services around them |
|
|
31
31
|
| bin | `antelopejs-ratchet` | Fails when recorded debt grows; `--update` lowers the record and adopts rules a pack release newly enabled |
|
|
32
32
|
| bin | `antelopejs-suppressions` | Fails when suppressions exceed their budget or an added one breaks policy; `--update` lowers the budget |
|
|
33
33
|
| bin | `antelopejs-check-size` | Fails on authored files over 20,000 bytes and on blanket disable directives |
|
|
@@ -36,6 +36,7 @@ The AntelopeJS guardrail pack: shared lint, format and dead-code presets, the co
|
|
|
36
36
|
| bin | `antelopejs-body-check <body.md \| -> [--head <sha>] [--base <sha>]` | Checks a PR body's proof and findings blocks against HEAD; `--findings` prints the findings block |
|
|
37
37
|
| bin | `antelopejs-check-interface-ranges` | Fails on interface ranges that break module startup |
|
|
38
38
|
| bin | `antelopejs-garden [--json] [--apply-pauses] [--apply] [--apply-prunes]` | The Gardener's scans of the organization through the GitHub API and npm |
|
|
39
|
+
| bin | `antelopejs-triage [--json]` | Community Triage's ranked shortlist of untriaged issues |
|
|
39
40
|
| bin | `antelopejs-verify <command>` | The harness of the shared `verify-interface`, `verify-module` and `verify-template` skills |
|
|
40
41
|
| bin | `antelopejs-lease run \| status \| down \| gc` | Ports, a mongod, logs and tmp per worktree; see [Run a DMS from a git worktree](./docs/agent-worktrees.md) |
|
|
41
42
|
|
|
@@ -51,6 +52,14 @@ The AntelopeJS guardrail pack: shared lint, format and dead-code presets, the co
|
|
|
51
52
|
|
|
52
53
|
Both profiles of `antelopejs-sync` keep the shared CI caller on the job id `ci`, so the check is reported as `ci / checks`. The `ci` job is read-only (`contents: read`) and passes `renovate-sync: false` and `test-job: true`, which runs the tests in their own job (sync adds `test-job: true` to a caller that does not set it and keeps a value the caller set); the `contents: write` and `actions: write` grants that let the Renovate sync push its commit and dispatch the caller live on a separate `renovate-sync` job calling `ci-renovate-sync.yml`, which sync adds when it is missing and never re-pins. Under the full profile it also sets the `docs-files` input of every ci-node caller to the existing `README.md` and `docs` of the root and of each workspace package that is not private, then keeps the caller's other listed paths that still exist. Renaming a caller to `ci` also rewrites `needs:` lists and `needs.<old-id>` reads in expressions, and sync (and `--check`) fails a caller in which a job needs a job that does not exist or reads `needs.<id>` of a job missing from its own `needs:`, since GitHub evaluates that read to null and a gate like `needs.checks.result == 'skipped'` then never fails.
|
|
53
54
|
|
|
55
|
+
## antelopejs-triage
|
|
56
|
+
|
|
57
|
+
`antelopejs-triage` lists the issues Community Triage has not looked at yet, ranked, through one GitHub GraphQL search authenticated with the token `gh` is logged in with. An issue is listed when it is open, labelled `needs-triage`, has no assignee, sits in a public, non-archived AntelopeJS repository, and no open pull request is linked to it. A linked pull request that was closed does not hide the issue.
|
|
58
|
+
|
|
59
|
+
- The ranking puts bugs first, then features, then the rest, then the most 👍 reactions first, then the oldest first. The `bug` label sets the kind `bug`, the `feature` or `enhancement` label sets `feature`, and the issue type does when none of them is there.
|
|
60
|
+
- `--json` prints `{ items, notShown }`. `items` holds at most 10 `{ ref, url, kind, title, firstLine, created }`, with `ref` as `AntelopeJS/<repo>#<number>`, `kind` as `bug`, `feature` or `other`, and `created` as the `YYYY-MM-DD` date. `firstLine` is the first line of the body that is not blank, a Markdown heading, an HTML comment or `_No response_`, cut at 200 characters. `notShown` counts the listed issues past the tenth.
|
|
61
|
+
- Without `--json` it prints one line per item and a last line with the count not shown, and nothing when no issue waits.
|
|
62
|
+
|
|
54
63
|
## Shared verification skills
|
|
55
64
|
|
|
56
65
|
`antelopejs-sync` writes one shared verification skill into a repository: `verify-interface` for an interface, `verify-module` for an implementation module (inferred from `antelopeJs.implements`) and `verify-template` in a template source repository, which keeps an `.agents/skills/verify-template/` folder (bootstrap one with `--verify template`). `--profile template` infers no kind, because a scaffold ships without `.agents`: it keeps the skill that exists or the one `--verify` names. Pass `--verify interface|module|template` to choose, or `--verify custom` for a repository that keeps its own `.agents/skills/verify-<repo>/`. Sync writes `SKILL.md`, `package.json` and `tsconfig.json` in `.agents/skills/verify-<kind>/` with a `.claude/skills/verify-<kind>` link, and `--check` reports them as drift. The `tsconfig.json` extends the root one with ES module resolution and loads the Node types, so type-aware lint sees the real types of the repository's files there, Node APIs included. It never touches the repository's own layer beside them: `verify.config.ts` and `features/`, which holds an index in `features/README.md` and one file per feature.
|
|
@@ -184,24 +193,27 @@ pnpm exec antelopejs-sync
|
|
|
184
193
|
pnpm install
|
|
185
194
|
```
|
|
186
195
|
|
|
187
|
-
| File | What `sync` does
|
|
188
|
-
| ------------------------------------------------------- |
|
|
189
|
-
| `oxlint.config.ts`, `oxfmt.config.ts`, `knip.config.ts` | Writes a config that extends the preset, unless the file already imports it
|
|
190
|
-
| `lefthook.yml` | Pre-commit on staged files: oxfmt, oxlint, size, suppressions. Pre-push: typecheck
|
|
191
|
-
| `package.json` | `prepare` installs lefthook. Sets `checks`, `size`, `ratchet`, `ratchet:update`, `suppressions`, `suppressions:update`, `sync`, `sync:check`; adds missing `typecheck`, `lint`, `format`, `format:check`, `knip`; adds `lefthook` and `knip`
|
|
192
|
-
|
|
|
193
|
-
| `.
|
|
194
|
-
| `
|
|
195
|
-
| `
|
|
196
|
-
| `
|
|
197
|
-
| `
|
|
198
|
-
| `guardrails.
|
|
199
|
-
|
|
|
196
|
+
| File | What `sync` does |
|
|
197
|
+
| ------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
198
|
+
| `oxlint.config.ts`, `oxfmt.config.ts`, `knip.config.ts` | Writes a config that extends the preset, unless the file already imports it |
|
|
199
|
+
| `lefthook.yml` | Pre-commit on staged files: oxfmt, oxlint, size, suppressions. Pre-push: typecheck |
|
|
200
|
+
| `package.json` | `prepare` installs lefthook. Sets `checks`, `size`, `ratchet`, `ratchet:update`, `suppressions`, `suppressions:update`, `sync`, `sync:check`; adds missing `typecheck`, `lint`, `format`, `format:check`, `knip`; adds `lefthook` and `knip` |
|
|
201
|
+
| `renovate.json` | Writes one extending `github>AntelopeJS/.github:renovate.json5` when the repository has no Renovate config at any path Renovate reads (including a `renovate` key in `package.json`). An existing config stays as it is; sync and `--check` fail one that does not extend the preset. Under `--profile template`, only in the template source, so a scaffold may keep, change or delete the copy it gets |
|
|
202
|
+
| `.nvmrc` | `24` |
|
|
203
|
+
| `.agents/setup` | Orb setup: switches to the `.nvmrc` Node, activates `packageManager` through corepack, installs with the frozen lockfile |
|
|
204
|
+
| `AGENTS.md` | Writes the managed block between `<!-- antelopejs-guardrails:start -->` and `:end -->`; text outside the markers stays |
|
|
205
|
+
| `README.md` of each `@antelopejs` package | Writes the generated compatibility block (see [Generated compatibility block](./docs/documentation-checks.md#generated-compatibility-block)); prose outside its markers stays |
|
|
206
|
+
| `CLAUDE.md` | `@AGENTS.md` |
|
|
207
|
+
| `guardrails.ratchet.json` | Records non-empty debt on first adoption, before `sync:check` exists |
|
|
208
|
+
| `guardrails.suppressions.json` | Records the current suppression counts when the file is missing; restores the committed file instead when HEAD has one; otherwise only adds `config` and `agentFiles` at today's counts when the file predates them |
|
|
209
|
+
| `<layer>/build/backend-boundary.ts` | Where a DMS frontend layer tracks one, restores the pack's backend boundary plugin for the package that holds the layer. A formatter's rewrite is not drift; any other edit is |
|
|
200
210
|
|
|
201
211
|
`--profile template` writes only the three preset configs, a user-facing `AGENTS.md` block and the `suppressions` package scripts (plus `ratchet` once `guardrails.ratchet.json` exists) that `antelopejs-checks` requires, for template repositories. The agent layer, `verify-template` and the writing skills under `.agents/skills/` with their `.claude/skills` links, is synced and checked only in the template source, marked by its `.agents/skills/verify-template/` folder; a project scaffolded from the template ships without it, so the template's `AGENTS.md` block links no skill under `.agents/` or `.claude/skills/`. `antelopejs-sync --check` writes nothing and exits 1 on any drift; `pnpm run checks` runs it.
|
|
202
212
|
|
|
203
213
|
`pnpm run checks` runs `typecheck`, `lint`, `format:check`, `knip`, `test`, `size`, `suppressions` and `sync:check`, plus `ratchet` when `guardrails.ratchet.json` exists. It prints only the output of the steps that failed. Sync adds the ratchet scripts and pre-commit hook only while that file exists.
|
|
204
214
|
|
|
215
|
+
When the repository has `.github/compose.yml`, the file the shared CI starts through its `services-compose-file` input, and the `test` step runs, `pnpm run checks` runs `docker compose -f .github/compose.yml up -d --wait` before the steps and `docker compose -f .github/compose.yml down -v` after them, also when a step fails or the run is interrupted (SIGINT, SIGTERM or SIGHUP stops the running step or `up`, removes the services and exits 130, 143 or 129; a repeated signal does not cut the teardown short). The compose project is `COMPOSE_PROJECT_NAME` when set, else the file's own `name:`, else one named after the repository root, so checkouts never share the `github` project compose would derive from the file's directory. Services are left alone when every port the file publishes already accepts connections, so a stack you started yourself is reused and kept. A run's project that already had containers before the run is started but not removed. When Docker Compose cannot run, the run fails before any step, naming the compose file, because the tests that need those services would wait for them forever. On GitHub Actions (`GITHUB_ACTIONS=true`) the workflow owns the services, and `--no-services` skips all of this anywhere.
|
|
216
|
+
|
|
205
217
|
### Ratchet
|
|
206
218
|
|
|
207
219
|
`guardrails.ratchet.json` holds the debt a repository had when it adopted the pack:
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import { a as isString, f as parseJson, i as isObject } from "./json-CG2L7YFl.mjs";
|
|
2
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { execFileSync, spawnSync } from "node:child_process";
|
|
5
|
+
import { homedir, tmpdir } from "node:os";
|
|
6
|
+
//#region src/garden/api.ts
|
|
7
|
+
/** A GitHub or npm answer that is not a success. */
|
|
8
|
+
var ApiError = class extends Error {
|
|
9
|
+
status;
|
|
10
|
+
constructor(status, message) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.status = status;
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
const GITHUB = "https://api.github.com";
|
|
16
|
+
const NPM = "https://registry.npmjs.org";
|
|
17
|
+
const CREDENTIAL_NAME = /TOKEN|SECRET|PASSW|CREDENTIAL|API_?KEY|PRIVATE_?KEY|ACCESS_?KEY/i;
|
|
18
|
+
const MINTED_TOKENS = /* @__PURE__ */ new Set(["GH_TOKEN", "GITHUB_TOKEN"]);
|
|
19
|
+
const CREDENTIAL_FILES = [
|
|
20
|
+
".aws/credentials",
|
|
21
|
+
".netrc",
|
|
22
|
+
".pypirc",
|
|
23
|
+
".config/gcloud/application_default_credentials.json",
|
|
24
|
+
".kube/config",
|
|
25
|
+
".ssh/id_rsa",
|
|
26
|
+
".ssh/id_ed25519",
|
|
27
|
+
".ssh/id_ecdsa"
|
|
28
|
+
];
|
|
29
|
+
const MAX_ATTEMPTS = 4;
|
|
30
|
+
function ghToken() {
|
|
31
|
+
return execFileSync("gh", ["auth", "token"], { encoding: "utf8" }).trim();
|
|
32
|
+
}
|
|
33
|
+
function pause(milliseconds) {
|
|
34
|
+
return new Promise((resolve) => setTimeout(resolve, milliseconds));
|
|
35
|
+
}
|
|
36
|
+
function nextLink(header) {
|
|
37
|
+
return header?.match(/<([^>]+)>;\s*rel="next"/)?.[1];
|
|
38
|
+
}
|
|
39
|
+
function withPaging(path) {
|
|
40
|
+
return path.includes("per_page=") ? path : `${path}${path.includes("?") ? "&" : "?"}per_page=100`;
|
|
41
|
+
}
|
|
42
|
+
function npmrcCarriesToken(home) {
|
|
43
|
+
const path = join(home, ".npmrc");
|
|
44
|
+
return existsSync(path) && /_auth(?:Token)?\s*=/.test(readFileSync(path, "utf8"));
|
|
45
|
+
}
|
|
46
|
+
/** Reads variable names only, never values. */
|
|
47
|
+
function readSecretSurface(names, home) {
|
|
48
|
+
const files = CREDENTIAL_FILES.filter((file) => existsSync(join(home, file)));
|
|
49
|
+
if (npmrcCarriesToken(home)) files.push(".npmrc");
|
|
50
|
+
return {
|
|
51
|
+
variables: names.filter((name) => CREDENTIAL_NAME.test(name) && !MINTED_TOKENS.has(name)).sort(),
|
|
52
|
+
files: files.sort()
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
/** Runs the released `antelopejs-registry --check` against committed manifests copied to a temporary directory. */
|
|
56
|
+
function registryCheck(files) {
|
|
57
|
+
const directory = mkdtempSync(join(tmpdir(), "garden-registry-"));
|
|
58
|
+
try {
|
|
59
|
+
for (const file of files) {
|
|
60
|
+
mkdirSync(dirname(join(directory, file.path)), { recursive: true });
|
|
61
|
+
writeFileSync(join(directory, file.path), file.content);
|
|
62
|
+
}
|
|
63
|
+
const result = spawnSync("npx", [
|
|
64
|
+
"--yes",
|
|
65
|
+
"--package",
|
|
66
|
+
"@antelopejs/tooling-configs@latest",
|
|
67
|
+
"antelopejs-registry",
|
|
68
|
+
"--check",
|
|
69
|
+
directory
|
|
70
|
+
], { encoding: "utf8" });
|
|
71
|
+
if (result.error) throw result.error;
|
|
72
|
+
return result.status !== 0;
|
|
73
|
+
} finally {
|
|
74
|
+
rmSync(directory, {
|
|
75
|
+
recursive: true,
|
|
76
|
+
force: true
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
function githubHeaders(token) {
|
|
81
|
+
return {
|
|
82
|
+
Authorization: `Bearer ${token}`,
|
|
83
|
+
Accept: "application/vnd.github+json",
|
|
84
|
+
"X-GitHub-Api-Version": "2022-11-28",
|
|
85
|
+
"User-Agent": "antelopejs-garden"
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
/** Retries a rate-limited or gateway answer up to four times and returns the last answer. */
|
|
89
|
+
async function request(headers, url, init) {
|
|
90
|
+
for (let attempt = 1;; attempt++) {
|
|
91
|
+
const response = await fetch(url, {
|
|
92
|
+
...init,
|
|
93
|
+
headers: {
|
|
94
|
+
...headers,
|
|
95
|
+
...init.headers
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
const retryAfter = Number(response.headers.get("retry-after") ?? 0);
|
|
99
|
+
if (!(response.status === 429 || response.status === 403 && retryAfter > 0 || response.status >= 502) || attempt === MAX_ATTEMPTS) return response;
|
|
100
|
+
await pause(Math.max(retryAfter, attempt) * 1e3);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/** A GraphQL client authenticated like {@link createApi}; an answer that carries `errors` throws. */
|
|
104
|
+
function createGraphql(token) {
|
|
105
|
+
const headers = githubHeaders(token);
|
|
106
|
+
return async (query, variables) => {
|
|
107
|
+
const response = await request(headers, `${GITHUB}/graphql`, {
|
|
108
|
+
method: "POST",
|
|
109
|
+
body: JSON.stringify({
|
|
110
|
+
query,
|
|
111
|
+
variables
|
|
112
|
+
}),
|
|
113
|
+
headers: { "Content-Type": "application/json" }
|
|
114
|
+
});
|
|
115
|
+
const text = await response.text();
|
|
116
|
+
if (!response.ok) throw new ApiError(response.status, `POST /graphql: HTTP ${response.status} ${text.slice(0, 200)}`);
|
|
117
|
+
const body = parseJson(text);
|
|
118
|
+
if (!isObject(body)) throw new ApiError(response.status, "POST /graphql: not an object");
|
|
119
|
+
const errors = Object.hasOwn(body, "errors") ? body.errors : null;
|
|
120
|
+
if (Array.isArray(errors) && errors.length > 0) throw new ApiError(response.status, `POST /graphql: ${JSON.stringify(errors).slice(0, 200)}`);
|
|
121
|
+
return Object.hasOwn(body, "data") ? body.data : null;
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
/** Authenticates with the token `gh` is logged in with and with no other credential. */
|
|
125
|
+
function createApi(token) {
|
|
126
|
+
const headers = githubHeaders(token);
|
|
127
|
+
async function get(path, accept) {
|
|
128
|
+
const url = path.startsWith("http") ? path : `${GITHUB}${path}`;
|
|
129
|
+
const response = await request(headers, url, { headers: accept ? { Accept: accept } : {} });
|
|
130
|
+
if (!response.ok) throw new ApiError(response.status, `GET ${path}: HTTP ${response.status} ${(await response.text()).slice(0, 200)}`);
|
|
131
|
+
return response;
|
|
132
|
+
}
|
|
133
|
+
return {
|
|
134
|
+
async json(path) {
|
|
135
|
+
return parseJson(await (await get(path)).text());
|
|
136
|
+
},
|
|
137
|
+
async pages(path, key) {
|
|
138
|
+
const items = [];
|
|
139
|
+
for (let url = `${GITHUB}${withPaging(path)}`; url;) {
|
|
140
|
+
const response = await get(url);
|
|
141
|
+
const body = parseJson(await response.text());
|
|
142
|
+
const page = key === void 0 || !isObject(body) ? body : body[key];
|
|
143
|
+
if (Array.isArray(page)) items.push(...page);
|
|
144
|
+
url = nextLink(response.headers.get("link"));
|
|
145
|
+
}
|
|
146
|
+
return items;
|
|
147
|
+
},
|
|
148
|
+
async text(path) {
|
|
149
|
+
return (await get(path, "application/vnd.github.raw+json")).text();
|
|
150
|
+
},
|
|
151
|
+
async bytes(path) {
|
|
152
|
+
return new Uint8Array(await (await get(path)).arrayBuffer());
|
|
153
|
+
},
|
|
154
|
+
async send(method, path, body) {
|
|
155
|
+
const response = await request(headers, `${GITHUB}${path}`, body === void 0 ? { method } : {
|
|
156
|
+
method,
|
|
157
|
+
body: JSON.stringify(body),
|
|
158
|
+
headers: { "Content-Type": "application/json" }
|
|
159
|
+
});
|
|
160
|
+
if (!response.ok) throw new ApiError(response.status, `${method} ${path}: HTTP ${response.status}`);
|
|
161
|
+
},
|
|
162
|
+
async npm(name) {
|
|
163
|
+
const response = await fetch(`${NPM}/${name.replace("/", "%2F")}`);
|
|
164
|
+
if (response.status === 404) return void 0;
|
|
165
|
+
if (!response.ok) throw new ApiError(response.status, `npm ${name}: HTTP ${response.status}`);
|
|
166
|
+
return parseJson(await response.text());
|
|
167
|
+
},
|
|
168
|
+
async contentLength(url) {
|
|
169
|
+
const response = await fetch(url, { method: "HEAD" });
|
|
170
|
+
const length = response.headers.get("content-length");
|
|
171
|
+
return response.ok && length !== null && isString(length) ? Number(length) : void 0;
|
|
172
|
+
},
|
|
173
|
+
async registryDiffers(files) {
|
|
174
|
+
return registryCheck(files);
|
|
175
|
+
},
|
|
176
|
+
secrets() {
|
|
177
|
+
return readSecretSurface(Object.keys(process.env), homedir());
|
|
178
|
+
},
|
|
179
|
+
now() {
|
|
180
|
+
return /* @__PURE__ */ new Date();
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
//#endregion
|
|
185
|
+
export { ghToken as i, createApi as n, createGraphql as r, ApiError as t };
|
package/dist/bin/checks.mjs
CHANGED
|
@@ -1,11 +1,189 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import "../ceilings-B7KayYIG.mjs";
|
|
3
3
|
import { i as parseManifest, r as packageManager } from "../package-BRTjkzt5.mjs";
|
|
4
|
-
import {
|
|
4
|
+
import { n as runCliAsync } from "../cli-4Tv71vYk.mjs";
|
|
5
5
|
import { c as repositoryRoot } from "../files-DJ0TeaTU.mjs";
|
|
6
|
+
import { t as accepting } from "../ports-DGP6bPJy.mjs";
|
|
6
7
|
import { existsSync, readFileSync } from "node:fs";
|
|
7
|
-
import { join } from "node:path";
|
|
8
|
-
import {
|
|
8
|
+
import { basename, join } from "node:path";
|
|
9
|
+
import { spawn } from "node:child_process";
|
|
10
|
+
import { isMap, isScalar, isSeq, parseDocument } from "yaml";
|
|
11
|
+
import { createHash } from "node:crypto";
|
|
12
|
+
import { parseArgs } from "node:util";
|
|
13
|
+
//#region src/guardrails/run-command.ts
|
|
14
|
+
const KILL_GRACE_MS = 5e3;
|
|
15
|
+
function stopGroup(child, signal) {
|
|
16
|
+
if (child.pid === void 0 || child.exitCode !== null) return;
|
|
17
|
+
try {
|
|
18
|
+
if (process.platform === "win32") child.kill(signal);
|
|
19
|
+
else process.kill(-child.pid, signal);
|
|
20
|
+
} catch {
|
|
21
|
+
child.kill(signal);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Runs `command` in its own process group and collects stdout and stderr together. When `signal` aborts, the group
|
|
26
|
+
* gets SIGTERM, then SIGKILL after a grace period, so a step's own children stop with it.
|
|
27
|
+
*/
|
|
28
|
+
function runCommand(command, args, options) {
|
|
29
|
+
const { cwd, env = process.env, signal } = options;
|
|
30
|
+
return new Promise((resolve) => {
|
|
31
|
+
const child = spawn(command, args, {
|
|
32
|
+
cwd,
|
|
33
|
+
env,
|
|
34
|
+
shell: process.platform === "win32",
|
|
35
|
+
detached: process.platform !== "win32",
|
|
36
|
+
stdio: [
|
|
37
|
+
"ignore",
|
|
38
|
+
"pipe",
|
|
39
|
+
"pipe"
|
|
40
|
+
]
|
|
41
|
+
});
|
|
42
|
+
const chunks = [];
|
|
43
|
+
const stdout = [];
|
|
44
|
+
child.stdout.on("data", (chunk) => {
|
|
45
|
+
chunks.push(chunk);
|
|
46
|
+
stdout.push(chunk);
|
|
47
|
+
});
|
|
48
|
+
child.stderr.on("data", (chunk) => chunks.push(chunk));
|
|
49
|
+
const interrupt = () => {
|
|
50
|
+
stopGroup(child, "SIGTERM");
|
|
51
|
+
setTimeout(() => stopGroup(child, "SIGKILL"), KILL_GRACE_MS).unref();
|
|
52
|
+
};
|
|
53
|
+
if (signal?.aborted) interrupt();
|
|
54
|
+
else signal?.addEventListener("abort", interrupt, { once: true });
|
|
55
|
+
child.once("error", (error) => {
|
|
56
|
+
signal?.removeEventListener("abort", interrupt);
|
|
57
|
+
resolve({
|
|
58
|
+
status: null,
|
|
59
|
+
stdout: "",
|
|
60
|
+
output: `${error.message}\n`
|
|
61
|
+
});
|
|
62
|
+
});
|
|
63
|
+
child.once("close", (code, killed) => {
|
|
64
|
+
signal?.removeEventListener("abort", interrupt);
|
|
65
|
+
const text = Buffer.concat(chunks).toString("utf8");
|
|
66
|
+
resolve({
|
|
67
|
+
status: code,
|
|
68
|
+
stdout: Buffer.concat(stdout).toString("utf8"),
|
|
69
|
+
output: `${text}${killed ? `Terminated by ${killed}\n` : ""}`
|
|
70
|
+
});
|
|
71
|
+
});
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
//#endregion
|
|
75
|
+
//#region src/guardrails/services.ts
|
|
76
|
+
/** The compose file the shared CI starts through its `services-compose-file` input, relative to the repository root. */
|
|
77
|
+
const COMPOSE_FILE = ".github/compose.yml";
|
|
78
|
+
function shortPort(text) {
|
|
79
|
+
const parts = text.replace(/\/\w+$/, "").split(":");
|
|
80
|
+
return parts.length < 2 ? void 0 : wholePort(parts.at(-2));
|
|
81
|
+
}
|
|
82
|
+
function wholePort(text) {
|
|
83
|
+
return text !== void 0 && /^\d+$/.test(text) ? Number(text) : void 0;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* The host ports the compose file publishes, or `undefined` when a service publishes none or one this cannot read
|
|
87
|
+
* (a range, an interpolation, a container-only port), since such a service cannot be probed.
|
|
88
|
+
*/
|
|
89
|
+
function publishedPorts(text) {
|
|
90
|
+
const services = parseDocument(text).get("services");
|
|
91
|
+
if (!isMap(services) || services.items.length === 0) return void 0;
|
|
92
|
+
const ports = [];
|
|
93
|
+
for (const { value } of services.items) {
|
|
94
|
+
const entries = isMap(value) ? value.get("ports") : void 0;
|
|
95
|
+
if (!isSeq(entries) || entries.items.length === 0) return void 0;
|
|
96
|
+
for (const entry of entries.items) {
|
|
97
|
+
const published = isMap(entry) ? entry.get("published") : void 0;
|
|
98
|
+
const port = isScalar(entry) ? shortPort(String(entry.value)) : wholePort(published === void 0 ? void 0 : String(published));
|
|
99
|
+
if (port === void 0) return void 0;
|
|
100
|
+
ports.push(port);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return ports;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* The environment compose runs in. A project named by `COMPOSE_PROJECT_NAME` or by the compose file's own `name:` is
|
|
107
|
+
* kept; otherwise the project is named after the repository root, since compose would name every repository's project
|
|
108
|
+
* `github` after the compose file's directory and a run could adopt or remove another checkout's containers.
|
|
109
|
+
*/
|
|
110
|
+
function composeEnv(root) {
|
|
111
|
+
if (process.env.COMPOSE_PROJECT_NAME) return process.env;
|
|
112
|
+
if (parseDocument(readFileSync(join(root, COMPOSE_FILE), "utf8")).has("name")) return process.env;
|
|
113
|
+
const slug = basename(root).toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^[^a-z0-9]+/, "");
|
|
114
|
+
const digest = createHash("sha256").update(root).digest("hex").slice(0, 8);
|
|
115
|
+
return {
|
|
116
|
+
...process.env,
|
|
117
|
+
COMPOSE_PROJECT_NAME: `${slug || "repo"}-${digest}`
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
async function compose(root, args, signal) {
|
|
121
|
+
const result = await runCommand("docker", [
|
|
122
|
+
"compose",
|
|
123
|
+
"-f",
|
|
124
|
+
COMPOSE_FILE,
|
|
125
|
+
...args
|
|
126
|
+
], {
|
|
127
|
+
cwd: root,
|
|
128
|
+
env: composeEnv(root),
|
|
129
|
+
signal
|
|
130
|
+
});
|
|
131
|
+
if (result.status === 0) return {
|
|
132
|
+
failure: "",
|
|
133
|
+
stdout: result.stdout
|
|
134
|
+
};
|
|
135
|
+
const outcome = result.status === null ? "did not finish" : `exited with status ${result.status}`;
|
|
136
|
+
return {
|
|
137
|
+
failure: `${result.output}docker compose -f ${COMPOSE_FILE} ${args.join(" ")}: ${outcome}\n`,
|
|
138
|
+
stdout: result.stdout
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Decides whether the checks start the services of `.github/compose.yml`: not when the file is absent or every port
|
|
143
|
+
* it publishes already accepts connections, and fail at once when Docker Compose cannot run, because the
|
|
144
|
+
* tests that need those services would wait for them forever.
|
|
145
|
+
*/
|
|
146
|
+
async function planServices(root) {
|
|
147
|
+
if (!existsSync(join(root, COMPOSE_FILE))) return { kind: "none" };
|
|
148
|
+
const ports = publishedPorts(readFileSync(join(root, COMPOSE_FILE), "utf8"));
|
|
149
|
+
if (ports && (await Promise.all(ports.map(accepting))).every(Boolean)) return { kind: "none" };
|
|
150
|
+
const probe = await compose(root, ["version"]);
|
|
151
|
+
if (!probe.failure) return { kind: "start" };
|
|
152
|
+
return {
|
|
153
|
+
kind: "unavailable",
|
|
154
|
+
output: `Docker Compose is not available, so the services in ${COMPOSE_FILE} cannot start and the tests that need them would hang. Start Docker, start the services yourself, or pass --no-services.\n${probe.failure}`
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Runs `docker compose up -d --wait` on the compose file, stopping it when `signal` aborts. `failure` is empty on
|
|
159
|
+
* success; `owned` is true when the project had no container before, so the run may remove it afterwards without
|
|
160
|
+
* taking a stack the developer started.
|
|
161
|
+
*/
|
|
162
|
+
async function startServices(root, signal) {
|
|
163
|
+
const before = await compose(root, [
|
|
164
|
+
"ps",
|
|
165
|
+
"--all",
|
|
166
|
+
"--quiet"
|
|
167
|
+
], signal);
|
|
168
|
+
if (before.failure) return {
|
|
169
|
+
failure: before.failure,
|
|
170
|
+
owned: false
|
|
171
|
+
};
|
|
172
|
+
const owned = before.stdout.trim() === "";
|
|
173
|
+
return {
|
|
174
|
+
failure: (await compose(root, [
|
|
175
|
+
"up",
|
|
176
|
+
"-d",
|
|
177
|
+
"--wait"
|
|
178
|
+
], signal)).failure,
|
|
179
|
+
owned
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
/** Runs `docker compose down -v` on the compose file; returns the failure output, empty on success. */
|
|
183
|
+
async function stopServices(root) {
|
|
184
|
+
return (await compose(root, ["down", "-v"])).failure;
|
|
185
|
+
}
|
|
186
|
+
//#endregion
|
|
9
187
|
//#region src/guardrails/checks.ts
|
|
10
188
|
const CHECK_STEPS = [
|
|
11
189
|
"typecheck",
|
|
@@ -23,51 +201,99 @@ const CHECKS_SKIP_ENV = "ANTELOPEJS_CHECKS_SKIP";
|
|
|
23
201
|
function skippedNames(setting) {
|
|
24
202
|
return setting.split(",").map((name) => name.trim()).filter(Boolean);
|
|
25
203
|
}
|
|
26
|
-
|
|
27
|
-
* Runs every check step and reports only what failed. `skipSetting` is the comma-separated value of
|
|
28
|
-
* `ANTELOPEJS_CHECKS_SKIP`: the steps it names are not run and are counted as skipped, never as passed, and a name that
|
|
29
|
-
* is not a step fails the run before any step starts so a typo cannot skip nothing.
|
|
30
|
-
*/
|
|
31
|
-
function runChecks(root, skipSetting = "") {
|
|
32
|
-
const requested = skippedNames(skipSetting);
|
|
33
|
-
const unknown = requested.filter((name) => !CHECK_STEPS.includes(name));
|
|
34
|
-
if (unknown.length) return {
|
|
35
|
-
failed: 1,
|
|
36
|
-
output: `[${CHECKS_SKIP_ENV}]\nUnknown step ${unknown.map((name) => `"${name}"`).join(", ")}. Valid steps: ${CHECK_STEPS.join(", ")}.\nChecks: 0 passed, 1 failed.\n`
|
|
37
|
-
};
|
|
38
|
-
const manifest = parseManifest(readFileSync(join(root, "package.json"), "utf8"));
|
|
204
|
+
async function runSteps(root, manifest, steps, signal) {
|
|
39
205
|
const manager = packageManager(manifest);
|
|
40
206
|
const failures = [];
|
|
41
|
-
const present = CHECK_STEPS.filter((step) => step !== "ratchet" || existsSync(join(root, "guardrails.ratchet.json")));
|
|
42
|
-
const steps = present.filter((step) => !requested.includes(step));
|
|
43
|
-
const skipped = present.length - steps.length;
|
|
44
207
|
for (const step of steps) {
|
|
208
|
+
if (signal?.aborted) break;
|
|
45
209
|
if (!manifest.scripts?.[step]) {
|
|
46
210
|
failures.push(`[${step}] Missing package.json script "${step}". Run antelopejs-sync.\n`);
|
|
47
211
|
continue;
|
|
48
212
|
}
|
|
49
|
-
const result =
|
|
213
|
+
const result = await runCommand(manager, ["run", step], {
|
|
50
214
|
cwd: root,
|
|
51
|
-
encoding: "utf8",
|
|
52
|
-
shell: process.platform === "win32",
|
|
53
215
|
env: {
|
|
54
216
|
...process.env,
|
|
55
217
|
CI: "1"
|
|
56
218
|
},
|
|
57
|
-
|
|
219
|
+
signal
|
|
58
220
|
});
|
|
59
|
-
if (result.status !== 0) failures.push(`[${step}]\n${result.
|
|
221
|
+
if (result.status !== 0) failures.push(`[${step}]\n${result.output}`);
|
|
222
|
+
}
|
|
223
|
+
return failures;
|
|
224
|
+
}
|
|
225
|
+
function summary(failures, passed, skipped) {
|
|
226
|
+
return `${failures.join("\n")}Checks: ${passed} passed, ${failures.length} failed${skipped ? `, ${skipped} skipped` : ""}.\n`;
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Runs every check step and reports only what failed. `skipSetting` is the comma-separated value of
|
|
230
|
+
* `ANTELOPEJS_CHECKS_SKIP`: the steps it names are not run and are counted as skipped, never as passed, and a name that
|
|
231
|
+
* is not a step fails the run before any step starts so a typo cannot skip nothing. Unless `services` is false, the
|
|
232
|
+
* services of `.github/compose.yml` are started before the steps when `test` runs, and removed after them if the run created them, also when a step fails or
|
|
233
|
+
* `signal` aborts the run; an aborted run stops the running step and reports `interrupted`.
|
|
234
|
+
*/
|
|
235
|
+
async function runChecks(root, options = {}) {
|
|
236
|
+
const { skipSetting = "", services = true, signal } = options;
|
|
237
|
+
const requested = skippedNames(skipSetting);
|
|
238
|
+
const unknown = requested.filter((name) => !CHECK_STEPS.includes(name));
|
|
239
|
+
if (unknown.length) return {
|
|
240
|
+
failed: 1,
|
|
241
|
+
interrupted: false,
|
|
242
|
+
output: `[${CHECKS_SKIP_ENV}]\nUnknown step ${unknown.map((name) => `"${name}"`).join(", ")}. Valid steps: ${CHECK_STEPS.join(", ")}.\nChecks: 0 passed, 1 failed.\n`
|
|
243
|
+
};
|
|
244
|
+
const present = CHECK_STEPS.filter((step) => step !== "ratchet" || existsSync(join(root, "guardrails.ratchet.json")));
|
|
245
|
+
const steps = present.filter((step) => !requested.includes(step));
|
|
246
|
+
const skipped = present.length - steps.length;
|
|
247
|
+
const manifest = parseManifest(readFileSync(join(root, "package.json"), "utf8"));
|
|
248
|
+
const plan = services && steps.includes("test") ? await planServices(root) : { kind: "none" };
|
|
249
|
+
if (plan.kind === "unavailable") return {
|
|
250
|
+
failed: 1,
|
|
251
|
+
interrupted: false,
|
|
252
|
+
output: `[services]\n${plan.output}Checks: 0 passed, 1 failed.\n`
|
|
253
|
+
};
|
|
254
|
+
const started = plan.kind === "start" ? await startServices(root, signal) : {
|
|
255
|
+
failure: "",
|
|
256
|
+
owned: false
|
|
257
|
+
};
|
|
258
|
+
let failures = [];
|
|
259
|
+
let stopped = "";
|
|
260
|
+
try {
|
|
261
|
+
failures = started.failure ? [`[services]\n${started.failure}`] : await runSteps(root, manifest, steps, signal);
|
|
262
|
+
} finally {
|
|
263
|
+
if (started.owned) stopped = await stopServices(root);
|
|
60
264
|
}
|
|
265
|
+
const passed = started.failure ? 0 : steps.length - failures.length;
|
|
266
|
+
if (stopped) failures.push(`[services]\n${stopped}`);
|
|
267
|
+
const interrupted = signal?.aborted ?? false;
|
|
61
268
|
return {
|
|
62
269
|
failed: failures.length,
|
|
63
|
-
|
|
270
|
+
interrupted,
|
|
271
|
+
output: interrupted ? `${failures.join("\n")}Checks interrupted by ${String(signal?.reason)}.\n` : summary(failures, passed, skipped)
|
|
64
272
|
};
|
|
65
273
|
}
|
|
66
274
|
//#endregion
|
|
67
275
|
//#region src/bin/checks.ts
|
|
68
|
-
|
|
69
|
-
|
|
276
|
+
const SIGNAL_EXIT = /* @__PURE__ */ new Map([
|
|
277
|
+
["SIGHUP", 129],
|
|
278
|
+
["SIGINT", 130],
|
|
279
|
+
["SIGTERM", 143]
|
|
280
|
+
]);
|
|
281
|
+
runCliAsync(async () => {
|
|
282
|
+
const { values } = parseArgs({ options: { "no-services": { type: "boolean" } } });
|
|
283
|
+
const controller = new AbortController();
|
|
284
|
+
let exitCode = 1;
|
|
285
|
+
for (const [name, code] of SIGNAL_EXIT) process.on(name, () => {
|
|
286
|
+
if (controller.signal.aborted) return;
|
|
287
|
+
exitCode = code;
|
|
288
|
+
controller.abort(name);
|
|
289
|
+
});
|
|
290
|
+
const result = await runChecks(repositoryRoot(), {
|
|
291
|
+
skipSetting: process.env[CHECKS_SKIP_ENV],
|
|
292
|
+
services: !values["no-services"] && process.env.GITHUB_ACTIONS !== "true",
|
|
293
|
+
signal: controller.signal
|
|
294
|
+
});
|
|
70
295
|
process.stdout.write(result.output);
|
|
296
|
+
if (result.interrupted) return exitCode;
|
|
71
297
|
return result.failed ? 1 : 0;
|
|
72
298
|
});
|
|
73
299
|
//#endregion
|