@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.
@@ -0,0 +1,282 @@
1
+ import { c as object, f as parseJson, i as isObject, l as optNum, p as str, s as num, t as child } from "./json-CG2L7YFl.mjs";
2
+ import { readFileSync, readdirSync, readlinkSync } from "node:fs";
3
+ import { isAbsolute, join } from "node:path";
4
+ import { execFileSync } from "node:child_process";
5
+ import { createHash } from "node:crypto";
6
+ import { homedir } from "node:os";
7
+ import { connect, createServer } from "node:net";
8
+ //#region src/lease/protocol.ts
9
+ /**
10
+ * The port every antelopejs-lease version listens on, on 127.0.0.1, while it holds the registry lock.
11
+ * Each repository pins its own tooling-configs version, so this port, {@link leaseHome} and the v1
12
+ * record are a protocol between versions: they may be extended, never changed.
13
+ */
14
+ const LOCK_PORT = 2e4;
15
+ const RECORD_VERSION = 1;
16
+ /** The offset of each role's port in its block of ten. Offsets 6 to 9 stay spare for later roles. */
17
+ const PORT_ROLES = {
18
+ api: 0,
19
+ web: 1,
20
+ mongo: 2,
21
+ smtp: 3,
22
+ inspect: 4,
23
+ hmr: 5
24
+ };
25
+ function isRole(value) {
26
+ return Object.hasOwn(PORT_ROLES, value);
27
+ }
28
+ /**
29
+ * `ANTELOPEJS_LEASE_HOME`, else `~/.antelopejs/leases`: one registry for every repository of the
30
+ * user. A relative `ANTELOPEJS_LEASE_HOME` throws, since each working directory would resolve it to
31
+ * another registry.
32
+ */
33
+ function leaseHome(env) {
34
+ const home = env.ANTELOPEJS_LEASE_HOME;
35
+ if (!home) return join(homedir(), ".antelopejs", "leases");
36
+ if (!isAbsolute(home)) throw new Error(`antelopejs-lease: ANTELOPEJS_LEASE_HOME must be an absolute path, not ${home}`);
37
+ return home;
38
+ }
39
+ function isLeaseId(value) {
40
+ return /^[0-9a-f]{10}$/u.test(value);
41
+ }
42
+ /** The lease id of the worktree whose real path is `worktree`. */
43
+ function leaseId(worktree) {
44
+ const id = createHash("sha256").update(worktree).digest("hex").slice(0, 10);
45
+ if (!isLeaseId(id)) throw new Error(`unexpected digest ${id}`);
46
+ return id;
47
+ }
48
+ /** Builds a value for every role, so a new role is a compile error until each table names it. */
49
+ function eachRole(value) {
50
+ return {
51
+ api: value("api"),
52
+ web: value("web"),
53
+ mongo: value("mongo"),
54
+ smtp: value("smtp"),
55
+ inspect: value("inspect"),
56
+ hmr: value("hmr")
57
+ };
58
+ }
59
+ function isMongoMode(value) {
60
+ return value === "owned" || value === "external";
61
+ }
62
+ function decodeRecord(value) {
63
+ const source = object(value, "lease.json");
64
+ if (num(source, "version") !== RECORD_VERSION) return void 0;
65
+ const id = str(source, "id");
66
+ const mongo = str(source, "mongo");
67
+ if (!isLeaseId(id) || !isMongoMode(mongo)) return void 0;
68
+ const ports = child(source, "ports");
69
+ return {
70
+ version: RECORD_VERSION,
71
+ id,
72
+ worktree: str(source, "worktree"),
73
+ gitInode: num(source, "gitInode"),
74
+ gitBirth: num(source, "gitBirth"),
75
+ ports: eachRole((role) => num(ports, role)),
76
+ createdAt: str(source, "createdAt"),
77
+ mongo
78
+ };
79
+ }
80
+ function reservedPorts(value) {
81
+ if (!isObject(value) || !Object.hasOwn(value, "ports")) return [];
82
+ const ports = value.ports;
83
+ if (!isObject(ports)) return [];
84
+ return Object.keys(ports).map((key) => optNum(ports, key)).filter((port) => port !== void 0);
85
+ }
86
+ function tryJson(text) {
87
+ try {
88
+ return parseJson(text);
89
+ } catch {
90
+ return;
91
+ }
92
+ }
93
+ function tryRecord(value) {
94
+ try {
95
+ return decodeRecord(value);
96
+ } catch {
97
+ return;
98
+ }
99
+ }
100
+ /** Reads a `lease.json` leniently: unknown fields are ignored, anything unreadable is `foreign`. */
101
+ function parseRecord(text) {
102
+ const value = tryJson(text);
103
+ if (value === void 0) return {
104
+ kind: "foreign",
105
+ reserved: []
106
+ };
107
+ const record = tryRecord(value);
108
+ if (record !== void 0) return {
109
+ kind: "current",
110
+ record
111
+ };
112
+ return {
113
+ kind: "foreign",
114
+ reserved: reservedPorts(value)
115
+ };
116
+ }
117
+ //#endregion
118
+ //#region src/lease/ports.ts
119
+ const BAND_START = 20010;
120
+ const BLOCK_SIZE = 10;
121
+ const BLOCK_COUNT = 9990 / BLOCK_SIZE;
122
+ const DENIED_PORTS = [
123
+ 24678,
124
+ 27017,
125
+ 27018,
126
+ 27019
127
+ ];
128
+ const CONNECT_TIMEOUT_MS = 1e3;
129
+ const LISTEN_STATE = "0A";
130
+ /**
131
+ * The block bases a lease tries, in order: from a block picked by a hash of the id and `uid`
132
+ * together, forward and around the band. Each user keeps a registry of its own, so mixing in the
133
+ * uid usually starts two users' worktrees at one path on different blocks. The band [20010, 30000)
134
+ * sits below the kernel's ephemeral range (32768 and up on Linux, 49152 and up on macOS), so no
135
+ * `bind(:0)` caller races for these ports. Blocks holding the Vite HMR default (24678) or a system
136
+ * mongod (27017 to 27019) are skipped.
137
+ */
138
+ function candidateBases(id, uid = process.getuid?.() ?? 0) {
139
+ const first = createHash("sha256").update(`${uid}:${id}`).digest().readUInt32BE(0) % BLOCK_COUNT;
140
+ return Array.from({ length: BLOCK_COUNT }, (_, step) => BAND_START + (first + step) % BLOCK_COUNT * BLOCK_SIZE).filter((base) => !DENIED_PORTS.some((port) => port >= base && port < base + BLOCK_SIZE));
141
+ }
142
+ function blockPorts(base) {
143
+ return Array.from({ length: BLOCK_SIZE }, (_, offset) => base + offset);
144
+ }
145
+ async function everyBindable(ports, bindable) {
146
+ for (const port of ports) if (!await bindable(port)) return false;
147
+ return true;
148
+ }
149
+ /**
150
+ * The first candidate block none of whose ten ports is in `taken` and all of whose ports bind.
151
+ * Throws when the band has no such block.
152
+ */
153
+ async function chooseBlock(id, taken, bindable) {
154
+ for (const base of candidateBases(id)) {
155
+ const ports = blockPorts(base);
156
+ if (ports.some((port) => taken.has(port))) continue;
157
+ if (await everyBindable(ports, bindable)) return eachRole((role) => base + PORT_ROLES[role]);
158
+ }
159
+ throw new Error(`antelopejs-lease: no free port block in ${BAND_START}-29999; run antelopejs-lease gc, then retry`);
160
+ }
161
+ /** Listens on `host:port`, Node's dual-stack default without `host`. `undefined` when the address is in use. */
162
+ function claimPort(port, host) {
163
+ return new Promise((resolve, reject) => {
164
+ const server = createServer();
165
+ server.once("error", (error) => {
166
+ if (error.code === "EADDRINUSE") resolve(void 0);
167
+ else reject(error);
168
+ });
169
+ server.listen({
170
+ port,
171
+ host
172
+ }, () => resolve(server));
173
+ });
174
+ }
175
+ function closeServer(server) {
176
+ return new Promise((resolve) => server.close(() => resolve()));
177
+ }
178
+ async function bindsOn(port, host) {
179
+ try {
180
+ const server = await claimPort(port, host);
181
+ if (server === void 0) return false;
182
+ await closeServer(server);
183
+ return true;
184
+ } catch {
185
+ return false;
186
+ }
187
+ }
188
+ /**
189
+ * True when nothing holds `port`. The dual-stack wildcard bind fails on Linux for a listener on any
190
+ * local address; the 127.0.0.1 bind covers systems that let a wildcard sit beside a specific address.
191
+ */
192
+ async function bindable(port) {
193
+ return await bindsOn(port, "127.0.0.1") && bindsOn(port);
194
+ }
195
+ function acceptsOn(port, host) {
196
+ return new Promise((resolve) => {
197
+ const socket = connect({
198
+ port,
199
+ host,
200
+ timeout: CONNECT_TIMEOUT_MS
201
+ });
202
+ const settle = (answer) => {
203
+ socket.destroy();
204
+ resolve(answer);
205
+ };
206
+ socket.once("connect", () => settle(true));
207
+ socket.once("timeout", () => settle(false));
208
+ socket.once("error", () => settle(false));
209
+ });
210
+ }
211
+ /** True when a server accepts connections on `port` on the IPv4 or the IPv6 loopback. */
212
+ async function accepting(port) {
213
+ return await acceptsOn(port, "127.0.0.1") || acceptsOn(port, "::1");
214
+ }
215
+ function listenInodes(table, port) {
216
+ let text;
217
+ try {
218
+ text = readFileSync(table, "utf8");
219
+ } catch {
220
+ return [];
221
+ }
222
+ return text.split("\n").slice(1).map((line) => line.trim().split(/\s+/u)).filter((columns) => columns[3] === LISTEN_STATE && Number.parseInt(columns[1]?.split(":")[1] ?? "", 16) === port).map((columns) => `socket:[${columns[9]}]`);
223
+ }
224
+ function holdsSocket(pid, sockets) {
225
+ let fds;
226
+ try {
227
+ fds = readdirSync(`/proc/${pid}/fd`);
228
+ } catch {
229
+ return false;
230
+ }
231
+ return fds.some((fd) => {
232
+ try {
233
+ return sockets.has(readlinkSync(`/proc/${pid}/fd/${fd}`));
234
+ } catch {
235
+ return false;
236
+ }
237
+ });
238
+ }
239
+ function listenSockets(port) {
240
+ return /* @__PURE__ */ new Set([...listenInodes("/proc/net/tcp", port), ...listenInodes("/proc/net/tcp6", port)]);
241
+ }
242
+ function linuxListenerPids(port) {
243
+ const sockets = listenSockets(port);
244
+ if (sockets.size === 0) return [];
245
+ return readdirSync("/proc").filter((name) => /^\d+$/u.test(name) && holdsSocket(name, sockets)).map(Number);
246
+ }
247
+ function lsofListenerPids(port) {
248
+ try {
249
+ return execFileSync("lsof", [
250
+ "-nP",
251
+ "-t",
252
+ `-iTCP:${port}`,
253
+ "-sTCP:LISTEN"
254
+ ], {
255
+ encoding: "utf8",
256
+ stdio: [
257
+ "ignore",
258
+ "pipe",
259
+ "ignore"
260
+ ]
261
+ }).split("\n").filter((line) => /^\d+$/u.test(line)).map(Number);
262
+ } catch {
263
+ return [];
264
+ }
265
+ }
266
+ /** The pids listening on `port` that this user may inspect; empty when none can be read. */
267
+ function listenerPids(port) {
268
+ if (process.platform === "linux") return linuxListenerPids(port);
269
+ if (process.platform === "darwin") return lsofListenerPids(port);
270
+ return [];
271
+ }
272
+ /**
273
+ * True when process `pid` listens on `port`. Where the platform gives no way to tell, true when
274
+ * anything accepts on `port`.
275
+ */
276
+ async function listensOn(pid, port) {
277
+ if (process.platform === "linux") return holdsSocket(String(pid), listenSockets(port));
278
+ if (process.platform === "darwin") return lsofListenerPids(port).includes(pid);
279
+ return accepting(port);
280
+ }
281
+ //#endregion
282
+ export { closeServer as a, LOCK_PORT as c, isRole as d, leaseHome as f, claimPort as i, PORT_ROLES as l, parseRecord as m, bindable as n, listenerPids as o, leaseId as p, chooseBlock as r, listensOn as s, accepting as t, isLeaseId as u };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@antelopejs/tooling-configs",
3
- "version": "0.3.1",
3
+ "version": "0.3.3",
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",
@@ -33,6 +33,7 @@
33
33
  "antelopejs-ratchet": "./dist/bin/ratchet.mjs",
34
34
  "antelopejs-suppressions": "./dist/bin/suppressions.mjs",
35
35
  "antelopejs-sync": "./dist/bin/sync.mjs",
36
+ "antelopejs-triage": "./dist/bin/triage.mjs",
36
37
  "antelopejs-verify": "./dist/bin/verify.mjs"
37
38
  },
38
39
  "files": [