@ryuugg/stanza 0.3.1 → 0.3.2

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.
@@ -2,7 +2,8 @@ import { existsSync, readFileSync } from "node:fs";
2
2
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
3
3
  import type { Width } from "../../language.ts";
4
4
  import { UNKNOWN, type Value, exported, object, property } from "./evaluate.ts";
5
- import { configDirectories, realDirectory } from "./find.ts";
5
+ import { holds, invocationMap, realDirectory } from "../../../directories.ts";
6
+ import { configDirectories } from "./find.ts";
6
7
  import { moduleAt } from "./module.ts";
7
8
 
8
9
  type Formatter = "oxfmt" | "prettier" | "biome";
@@ -72,7 +73,7 @@ const FILES = [
72
73
 
73
74
  const parsed = new Map<string, Read>();
74
75
  const directories = new Map<string, Directory>();
75
- const dependencies = new Map<string, Formatter[]>();
76
+ const dependencies = invocationMap<string, Formatter[]>();
76
77
  const globs = new Map<string, Bun.Glob>();
77
78
 
78
79
  const editorGlobs = new Map<string, { regex: RegExp; ranges: [bigint, bigint][] }>();
@@ -261,27 +262,32 @@ function directory(dir: string, files: string[]): Directory {
261
262
  }
262
263
 
263
264
  function dependent(dir: string): Formatter[] {
264
- const cached = dependencies.get(dir);
265
- if (cached) return cached;
265
+ const visited: string[] = [];
266
266
 
267
+ let found: Formatter[] = [];
267
268
  let current = dir;
268
269
  while (true) {
269
- try {
270
- const manifest = JSON.parse(readFileSync(join(current, "package.json"), "utf8")) as Record<
271
- string,
272
- Record<string, unknown>
273
- >;
274
-
275
- const names = { ...manifest.dependencies, ...manifest.devDependencies };
276
- const found: Formatter[] = [];
277
- if ("oxfmt" in names) found.push("oxfmt");
278
- if ("@biomejs/biome" in names) found.push("biome");
279
- if ("prettier" in names) found.push("prettier");
280
- if (found.length) {
281
- dependencies.set(dir, found);
282
- return found;
283
- }
284
- } catch {}
270
+ const cached = dependencies.get(current);
271
+ if (cached) {
272
+ found = cached;
273
+ break;
274
+ }
275
+
276
+ visited.push(current);
277
+
278
+ if (holds(current, "package.json"))
279
+ try {
280
+ const manifest = JSON.parse(readFileSync(join(current, "package.json"), "utf8")) as Record<
281
+ string,
282
+ Record<string, unknown>
283
+ >;
284
+
285
+ const names = { ...manifest.dependencies, ...manifest.devDependencies };
286
+ if ("oxfmt" in names) found.push("oxfmt");
287
+ if ("@biomejs/biome" in names) found.push("biome");
288
+ if ("prettier" in names) found.push("prettier");
289
+ if (found.length) break;
290
+ } catch {}
285
291
 
286
292
  const parent = dirname(current);
287
293
  if (parent === current) break;
@@ -289,8 +295,8 @@ function dependent(dir: string): Formatter[] {
289
295
  current = parent;
290
296
  }
291
297
 
292
- dependencies.set(dir, []);
293
- return [];
298
+ for (const directory of visited) dependencies.set(directory, found);
299
+ return found;
294
300
  }
295
301
 
296
302
  function number(value: Value): number | undefined {
@@ -586,7 +592,7 @@ function editorconfig(
586
592
  const file = join(dir, ".editorconfig");
587
593
 
588
594
  let root = false;
589
- if (existsSync(file)) {
595
+ if (holds(dir, ".editorconfig")) {
590
596
  const editor = parsedEditor(file);
591
597
  if (!editor) unread.push(file);
592
598
  else {
@@ -612,10 +618,10 @@ function editorconfig(
612
618
  // oxfmt 0.70 reads only the nearest .editorconfig file.
613
619
  if (
614
620
  biomeDir ||
615
- (nearest && existsSync(file)) ||
621
+ (nearest && holds(dir, ".editorconfig")) ||
616
622
  root ||
617
- existsSync(join(dir, ".git")) ||
618
- existsSync(join(dir, ".hg"))
623
+ holds(dir, ".git") ||
624
+ holds(dir, ".hg")
619
625
  )
620
626
  break;
621
627
 
package/src/pool.ts ADDED
@@ -0,0 +1,312 @@
1
+ import { availableParallelism } from "node:os";
2
+ import { statSync } from "node:fs";
3
+ import { workerData, type MessagePort } from "node:worker_threads";
4
+ import {
5
+ formatFile,
6
+ mergeOutcomes,
7
+ readText,
8
+ type FileOutcome,
9
+ type FormatRun,
10
+ type Formatted,
11
+ type Input,
12
+ } from "./format.ts";
13
+ import { deepRisk } from "./depth.ts";
14
+ import {
15
+ deserializerFiles,
16
+ embedDeserializers,
17
+ type DeserializerFiles,
18
+ } from "./languages/javascript/deserializers.ts";
19
+
20
+ export const THRESHOLD = 256;
21
+ export const DEFAULT_WORKERS = 3;
22
+ export const CHUNK_SIZE = 64;
23
+
24
+ export interface FileInput extends Omit<Input, "read"> {
25
+ output: string;
26
+ }
27
+
28
+ export interface PoolData<Input, Job> {
29
+ id: number;
30
+ inputs: Input[];
31
+ job: Job;
32
+ chunkSize: number;
33
+ counter: SharedArrayBuffer;
34
+ signal: SharedArrayBuffer;
35
+ claims: SharedArrayBuffer;
36
+ finished: SharedArrayBuffer;
37
+ port: MessagePort;
38
+ addon: string | undefined;
39
+ deserializers: DeserializerFiles;
40
+ }
41
+
42
+ export type ChunkMessage<Result> =
43
+ | (Result & { chunk: number })
44
+ | { chunk: number | undefined; error: string };
45
+
46
+ export interface PoolTask<Input, Outcome, Result extends { outcomes: (Outcome | null)[] }, Job> {
47
+ worker: string | URL;
48
+ job: Job;
49
+ chunkSize?: number;
50
+ chunk(inputs: Input[]): Result;
51
+ merge(result: Result): void;
52
+ item(input: Input): Outcome;
53
+ }
54
+
55
+ export function workerCount(
56
+ fileCount: number,
57
+ env: Readonly<Record<string, string | undefined>>,
58
+ maximum = DEFAULT_WORKERS,
59
+ ): number {
60
+ const override = env.STANZA_WORKERS;
61
+ if (override !== undefined && /^\d+$/.test(override)) {
62
+ const count = Number(override);
63
+ if (count <= 64) return count;
64
+ }
65
+
66
+ if (fileCount < THRESHOLD) return 0;
67
+
68
+ return Math.max(0, Math.min(maximum, availableParallelism() - 1));
69
+ }
70
+
71
+ export function hardLinked(input: FileInput, run: FormatRun): boolean {
72
+ if (run.mode !== "fix" || !run.write) return false;
73
+
74
+ try {
75
+ return statSync(input.path).nlink > 1;
76
+ } catch {
77
+ return false;
78
+ }
79
+ }
80
+
81
+ export function tooDeep(path: string, text: string): boolean {
82
+ return deepRisk(text, !/\.[cm]?ts$/.test(path));
83
+ }
84
+
85
+ export function formatChunk(inputs: FileInput[], run: FormatRun, inWorker: boolean) {
86
+ const warnings = { unread: new Set<string>(), unreadWidth: new Set<string>() };
87
+ const outcomes = inputs.map((input) => {
88
+ if (hardLinked(input, run)) return null;
89
+
90
+ const text = readText(input.path);
91
+ if (inWorker && typeof text === "string" && tooDeep(input.path, text)) return null;
92
+
93
+ return formatFile({ ...input, read: () => text }, run, input.output, warnings);
94
+ });
95
+
96
+ return { outcomes, unread: [...warnings.unread], unreadWidth: [...warnings.unreadWidth] };
97
+ }
98
+
99
+ function acceptChunk<Input, Outcome, Result extends { outcomes: (Outcome | null)[] }, Job>(
100
+ inputCount: number,
101
+ chunkSize: number,
102
+ message: ChunkMessage<Result>,
103
+ chunks: (Outcome | null)[][],
104
+ task: PoolTask<Input, Outcome, Result, Job>,
105
+ errors: string[],
106
+ ): void {
107
+ if ("error" in message) {
108
+ errors.push(message.error);
109
+ if (message.chunk === undefined) return;
110
+
111
+ const size = Math.min(chunkSize, inputCount - message.chunk * chunkSize);
112
+ chunks[message.chunk] = Array<null>(size).fill(null);
113
+ return;
114
+ }
115
+
116
+ chunks[message.chunk] = message.outcomes;
117
+ task.merge(message);
118
+ }
119
+
120
+ function recoverAbandoned<Outcome>(
121
+ inputCount: number,
122
+ chunkSize: number,
123
+ chunks: (Outcome | null)[][],
124
+ claims: Int32Array,
125
+ stopped: boolean[],
126
+ errors: string[],
127
+ ): number {
128
+ let recovered = 0;
129
+ for (let chunk = 0; chunk < claims.length; chunk++) {
130
+ const owner = Atomics.load(claims, chunk);
131
+ if (chunks[chunk] !== undefined || owner === 0 || !stopped[owner - 1]) continue;
132
+
133
+ const size = Math.min(chunkSize, inputCount - chunk * chunkSize);
134
+ chunks[chunk] = Array<null>(size).fill(null);
135
+ errors.push("a worker thread stopped before reporting its files, so main formatted them");
136
+ recovered++;
137
+ }
138
+
139
+ return recovered;
140
+ }
141
+
142
+ export function runPooled<Input, Outcome, Result extends { outcomes: (Outcome | null)[] }, Job>(
143
+ inputs: Input[],
144
+ task: PoolTask<Input, Outcome, Result, Job>,
145
+ count: number,
146
+ ): { outcomes: Outcome[]; errors: string[] } {
147
+ const { Worker, MessageChannel, receiveMessageOnPort } =
148
+ require("node:worker_threads") as typeof import("node:worker_threads");
149
+
150
+ const counter = new Int32Array(new SharedArrayBuffer(4));
151
+ const signal = new Int32Array(new SharedArrayBuffer(4));
152
+
153
+ const chunkSize = task.chunkSize ?? CHUNK_SIZE;
154
+ const chunkCount = Math.ceil(inputs.length / chunkSize);
155
+ const claims = new Int32Array(new SharedArrayBuffer(4 * chunkCount));
156
+ const finished = new Int32Array(new SharedArrayBuffer(4 * Math.max(count, 1)));
157
+ const chunks: (Outcome | null)[][] = Array(chunkCount);
158
+
159
+ const errors: string[] = [];
160
+ const ports: MessagePort[] = [];
161
+ const deserializers = deserializerFiles();
162
+ for (let index = 0; index < count; index++) {
163
+ const { port1, port2 } = new MessageChannel();
164
+ try {
165
+ const workerData: PoolData<Input, Job> = {
166
+ id: index,
167
+ inputs,
168
+ job: task.job,
169
+ chunkSize,
170
+ counter: counter.buffer as SharedArrayBuffer,
171
+ signal: signal.buffer as SharedArrayBuffer,
172
+ claims: claims.buffer as SharedArrayBuffer,
173
+ finished: finished.buffer as SharedArrayBuffer,
174
+ port: port2,
175
+ addon: process.env.NAPI_RS_NATIVE_LIBRARY_PATH,
176
+ deserializers,
177
+ };
178
+
179
+ const worker = new Worker(task.worker, { workerData, transferList: [port2] });
180
+ worker.on("error", (error: Error) => errors.push(error.message));
181
+ worker.unref();
182
+ ports.push(port1);
183
+ } catch (error: unknown) {
184
+ errors.push(error instanceof Error ? error.message : String(error));
185
+ port1.close();
186
+ port2.close();
187
+ }
188
+ }
189
+
190
+ let completed = 0;
191
+ while (completed < chunkCount) {
192
+ const observed = Atomics.load(signal, 0);
193
+ const stopped = Array.from(finished, (_, index) => Atomics.load(finished, index) === 1);
194
+
195
+ for (const port of ports) {
196
+ let received: ReturnType<typeof receiveMessageOnPort>;
197
+ while ((received = receiveMessageOnPort(port)) !== undefined) {
198
+ const message = received.message as ChunkMessage<Result>;
199
+ acceptChunk(inputs.length, chunkSize, message, chunks, task, errors);
200
+ if (message.chunk !== undefined) completed++;
201
+ }
202
+ }
203
+
204
+ const chunk = Atomics.add(counter, 0, 1);
205
+ if (chunk < chunkCount) {
206
+ try {
207
+ const result = task.chunk(inputs.slice(chunk * chunkSize, (chunk + 1) * chunkSize));
208
+ acceptChunk(inputs.length, chunkSize, { chunk, ...result }, chunks, task, errors);
209
+ } catch (error: unknown) {
210
+ acceptChunk(
211
+ inputs.length,
212
+ chunkSize,
213
+ { chunk, error: error instanceof Error ? error.message : String(error) },
214
+ chunks,
215
+ task,
216
+ errors,
217
+ );
218
+ }
219
+
220
+ completed++;
221
+ continue;
222
+ }
223
+
224
+ completed += recoverAbandoned(inputs.length, chunkSize, chunks, claims, stopped, errors);
225
+ if (completed < chunkCount) Atomics.wait(signal, 0, observed, 50);
226
+ }
227
+
228
+ const outcomes: Outcome[] = [];
229
+ for (let chunk = 0; chunk < chunks.length; chunk++)
230
+ for (const [offset, outcome] of chunks[chunk]!.entries()) {
231
+ const input = inputs[chunk * chunkSize + offset]!;
232
+ outcomes.push(outcome ?? task.item(input));
233
+ }
234
+
235
+ for (const port of ports) port.close();
236
+
237
+ return { outcomes, errors };
238
+ }
239
+
240
+ export function serveChunks<Input, Job, Result>(work: (inputs: Input[], job: Job) => Result): void {
241
+ const data = workerData as PoolData<Input, Job>;
242
+ const counter = new Int32Array(data.counter);
243
+ const signal = new Int32Array(data.signal);
244
+ const claims = new Int32Array(data.claims);
245
+ const finished = new Int32Array(data.finished);
246
+ function post(message: ChunkMessage<Result>): void {
247
+ data.port.postMessage(message);
248
+ Atomics.add(signal, 0, 1);
249
+ Atomics.notify(signal, 0);
250
+ }
251
+
252
+ try {
253
+ if (data.addon !== undefined) process.env.NAPI_RS_NATIVE_LIBRARY_PATH = data.addon;
254
+ embedDeserializers(data.deserializers);
255
+
256
+ const chunkCount = Math.ceil(data.inputs.length / data.chunkSize);
257
+ for (
258
+ let chunk = Atomics.add(counter, 0, 1);
259
+ chunk < chunkCount;
260
+ chunk = Atomics.add(counter, 0, 1)
261
+ ) {
262
+ Atomics.store(claims, chunk, data.id + 1);
263
+
264
+ try {
265
+ const result = work(
266
+ data.inputs.slice(chunk * data.chunkSize, (chunk + 1) * data.chunkSize),
267
+ data.job,
268
+ );
269
+
270
+ post({ chunk, ...result });
271
+ } catch (error: unknown) {
272
+ post({ chunk, error: error instanceof Error ? error.message : String(error) });
273
+ }
274
+ }
275
+ } catch (error: unknown) {
276
+ post({ chunk: undefined, error: error instanceof Error ? error.message : String(error) });
277
+ } finally {
278
+ Atomics.store(finished, data.id, 1);
279
+ Atomics.add(signal, 0, 1);
280
+ Atomics.notify(signal, 0);
281
+ }
282
+ }
283
+
284
+ export function formatPooled(
285
+ inputs: FileInput[],
286
+ run: FormatRun,
287
+ count: number,
288
+ ): { formatted: Formatted; errors: string[] } {
289
+ const warnings = { unread: new Set<string>(), unreadWidth: new Set<string>() };
290
+ // A compiled Bun worker resolves a bare specifier inside bunfs, not a file URL.
291
+ const specifier = Bun.main.includes("/$bunfs/")
292
+ ? "./worker.ts"
293
+ : new URL("./worker.ts", import.meta.url);
294
+
295
+ const { outcomes, errors } = runPooled(
296
+ inputs,
297
+ {
298
+ worker: specifier,
299
+ job: run,
300
+ chunk: (inputs) => formatChunk(inputs, run, false),
301
+ merge(result) {
302
+ for (const path of result.unread) warnings.unread.add(path);
303
+ for (const path of result.unreadWidth) warnings.unreadWidth.add(path);
304
+ },
305
+ item: (input): FileOutcome =>
306
+ formatFile({ ...input, read: () => readText(input.path) }, run, input.output, warnings),
307
+ },
308
+ count,
309
+ );
310
+
311
+ return { formatted: mergeOutcomes(outcomes, warnings), errors };
312
+ }
package/src/usage.ts CHANGED
@@ -13,11 +13,14 @@ export const flags: (readonly [string, string])[] = [
13
13
  "--stdin <path>",
14
14
  "source on stdin; --fix: fixed text on stdout, findings on stderr; --check: findings on stdout",
15
15
  ],
16
- ["--json", "findings as a JSON array, for hooks"],
16
+ ["--json", "findings as a JSON array"],
17
17
  ["--braces", "turn on the braces rule even when lint config turns it off or cannot be read"],
18
18
  ["--no-braces", "turn off the braces rule, keep the blank line rules"],
19
19
  ["explain <file>:<line>", "which rule decides the gap or braced body at that line, and why"],
20
- ["hook", "the Stop hook and PreToolUse hook on Write, reads JSON on stdin"],
20
+ [
21
+ "hook",
22
+ "Stop and SubagentStop; PostToolUse on Edit, MultiEdit and Codex apply_patch; PreToolUse on Write; reads JSON on stdin",
23
+ ],
21
24
  ["--help", "usage, flags and the rule catalog"],
22
25
  ["--version", "the version, and for a built binary the commit it was built from"],
23
26
  ];
package/src/worker.ts ADDED
@@ -0,0 +1,4 @@
1
+ import { formatChunk, serveChunks, type FileInput } from "./pool.ts";
2
+ import type { FormatRun } from "./format.ts";
3
+
4
+ serveChunks((inputs: FileInput[], run: FormatRun) => formatChunk(inputs, run, true));