@ryuugg/stanza 0.3.3 → 0.4.1

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.
Files changed (59) hide show
  1. package/README.md +15 -13
  2. package/package.json +19 -11
  3. package/src/launcher +102 -8
  4. package/src/cli.ts +0 -684
  5. package/src/compile/darwin-arm64.ts +0 -3
  6. package/src/compile/darwin-x64.ts +0 -3
  7. package/src/compile/linux-arm64-musl.ts +0 -3
  8. package/src/compile/linux-arm64.ts +0 -3
  9. package/src/compile/linux-x64-musl.ts +0 -3
  10. package/src/compile/linux-x64.ts +0 -3
  11. package/src/compiled.ts +0 -9
  12. package/src/depth.ts +0 -372
  13. package/src/directories.ts +0 -77
  14. package/src/engine/attach.ts +0 -62
  15. package/src/engine/directives.ts +0 -157
  16. package/src/engine/doc.ts +0 -93
  17. package/src/engine/edits.ts +0 -79
  18. package/src/engine/explain.ts +0 -337
  19. package/src/engine/gaps.ts +0 -361
  20. package/src/engine/hunks.ts +0 -319
  21. package/src/engine/index.ts +0 -273
  22. package/src/engine/model.ts +0 -103
  23. package/src/engine/rules.ts +0 -104
  24. package/src/engine/types.ts +0 -38
  25. package/src/files.ts +0 -1186
  26. package/src/format.ts +0 -159
  27. package/src/gitignore.ts +0 -280
  28. package/src/hook.ts +0 -380
  29. package/src/languages/index.ts +0 -34
  30. package/src/languages/javascript/ast.ts +0 -261
  31. package/src/languages/javascript/braces.ts +0 -374
  32. package/src/languages/javascript/config/biome.ts +0 -112
  33. package/src/languages/javascript/config/eslint.ts +0 -128
  34. package/src/languages/javascript/config/evaluate.ts +0 -278
  35. package/src/languages/javascript/config/find.ts +0 -105
  36. package/src/languages/javascript/config/glob.ts +0 -149
  37. package/src/languages/javascript/config/index.ts +0 -48
  38. package/src/languages/javascript/config/layers.ts +0 -468
  39. package/src/languages/javascript/config/module.ts +0 -327
  40. package/src/languages/javascript/config/oxlint.ts +0 -170
  41. package/src/languages/javascript/config/width.ts +0 -723
  42. package/src/languages/javascript/deserializers.ts +0 -17
  43. package/src/languages/javascript/embedded.ts +0 -7
  44. package/src/languages/javascript/entry.ts +0 -42
  45. package/src/languages/javascript/facts.ts +0 -294
  46. package/src/languages/javascript/index.ts +0 -20
  47. package/src/languages/javascript/lists.ts +0 -64
  48. package/src/languages/javascript/oracle.ts +0 -191
  49. package/src/languages/javascript/oxc-raw.d.ts +0 -31
  50. package/src/languages/javascript/parse.ts +0 -131
  51. package/src/languages/javascript/raw.ts +0 -95
  52. package/src/languages/javascript/scan.ts +0 -68
  53. package/src/languages/language.ts +0 -109
  54. package/src/native-file.d.ts +0 -4
  55. package/src/pool.ts +0 -473
  56. package/src/start.ts +0 -49
  57. package/src/step.ts +0 -113
  58. package/src/usage.ts +0 -35
  59. package/src/worker.ts +0 -5
package/src/pool.ts DELETED
@@ -1,473 +0,0 @@
1
- import { availableParallelism } from "node:os";
2
- import { statSync } from "node:fs";
3
- import 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 {
14
- deserializerFiles,
15
- embedDeserializers,
16
- type DeserializerFiles,
17
- } from "./languages/javascript/deserializers.ts";
18
-
19
- export const THRESHOLD = 256;
20
- export const DEFAULT_WORKERS = 3;
21
- export const CHUNK_SIZE = 64;
22
-
23
- export const LANE = { starting: 0, serving: 1, finished: 2, gone: 3 } as const;
24
- type LaneState = (typeof LANE)[keyof typeof LANE];
25
-
26
- export type Deferral = (path: string, text: string) => boolean;
27
-
28
- export interface FileInput extends Omit<Input, "read"> {
29
- output: string;
30
- }
31
-
32
- export interface PoolData<Input, Job> {
33
- id: number;
34
- inputs: Input[];
35
- job: Job;
36
- chunkSize: number;
37
- counter: SharedArrayBuffer;
38
- signal: SharedArrayBuffer;
39
- claims: SharedArrayBuffer;
40
- lanes: SharedArrayBuffer;
41
- posted: SharedArrayBuffer;
42
- port: MessagePort;
43
- addon: string | undefined;
44
- deserializers: DeserializerFiles;
45
- }
46
-
47
- export type ChunkMessage<Result> =
48
- | (Result & { chunk: number })
49
- | { chunk: number | undefined; error: string };
50
-
51
- export interface PoolTask<Input, Outcome, Result extends { outcomes: (Outcome | null)[] }, Job> {
52
- worker: string | URL;
53
- job: Job;
54
- chunkSize?: number;
55
- chunk(inputs: Input[]): Result;
56
- merge(result: Result): void;
57
- item(input: Input): Outcome;
58
- }
59
-
60
- interface Board {
61
- counter: Int32Array;
62
- signal: Int32Array;
63
- claims: Int32Array;
64
- lanes: Int32Array;
65
- posted: Int32Array;
66
- }
67
-
68
- interface Ledger<Outcome> {
69
- readonly inputCount: number;
70
- readonly chunkSize: number;
71
- readonly results: ((Outcome | null)[] | undefined)[];
72
- readonly errors: string[];
73
- pending: number;
74
- unowned: number;
75
- }
76
-
77
- interface Lane {
78
- readonly port: MessagePort;
79
- drained: number;
80
- started: boolean;
81
- fault: string | undefined;
82
- exitCode: number | undefined;
83
- recovered: number;
84
- }
85
-
86
- export function workerCount(
87
- fileCount: number,
88
- env: Readonly<Record<string, string | undefined>>,
89
- maximum = DEFAULT_WORKERS,
90
- cores = availableParallelism(),
91
- ): number {
92
- const override = env.STANZA_WORKERS;
93
- if (override !== undefined && /^\d+$/.test(override)) {
94
- const count = Number(override);
95
- if (count <= 64) return count;
96
- }
97
-
98
- if (fileCount < THRESHOLD) return 0;
99
-
100
- return Math.max(0, Math.min(maximum, cores - 1));
101
- }
102
-
103
- export function hardLinked(input: FileInput, run: FormatRun): boolean {
104
- if (run.mode !== "fix" || !run.write) return false;
105
-
106
- try {
107
- return statSync(input.path).nlink > 1;
108
- } catch {
109
- return false;
110
- }
111
- }
112
-
113
- export function formatChunk(inputs: FileInput[], run: FormatRun, defer?: Deferral) {
114
- const warnings = { unread: new Set<string>(), unreadWidth: new Set<string>() };
115
- const outcomes = inputs.map((input) => {
116
- if (hardLinked(input, run)) return null;
117
-
118
- const text = readText(input.path);
119
- if (defer !== undefined && typeof text === "string" && defer(input.path, text)) return null;
120
-
121
- return formatFile({ ...input, read: () => text }, run, input.output, warnings);
122
- });
123
-
124
- return { outcomes, unread: [...warnings.unread], unreadWidth: [...warnings.unreadWidth] };
125
- }
126
-
127
- function wake(signal: Int32Array): void {
128
- Atomics.add(signal, 0, 1);
129
- Atomics.notify(signal, 0);
130
- }
131
-
132
- function errorText(error: unknown): string {
133
- return error instanceof Error ? error.message : String(error);
134
- }
135
-
136
- function chunkLength(ledger: Ledger<unknown>, chunk: number): number {
137
- return Math.min(ledger.chunkSize, ledger.inputCount - chunk * ledger.chunkSize);
138
- }
139
-
140
- function settle<Outcome>(
141
- ledger: Ledger<Outcome>,
142
- chunk: number,
143
- outcomes: (Outcome | null)[],
144
- ): boolean {
145
- if (ledger.results[chunk] !== undefined) return false;
146
-
147
- ledger.results[chunk] = outcomes;
148
- ledger.pending--;
149
- return true;
150
- }
151
-
152
- function settleOnMain(ledger: Ledger<unknown>, chunk: number): boolean {
153
- return settle(ledger, chunk, Array<null>(chunkLength(ledger, chunk)).fill(null));
154
- }
155
-
156
- function accept<Input, Outcome, Result extends { outcomes: (Outcome | null)[] }, Job>(
157
- ledger: Ledger<Outcome>,
158
- message: ChunkMessage<Result>,
159
- task: PoolTask<Input, Outcome, Result, Job>,
160
- ): void {
161
- if ("error" in message) {
162
- if (message.chunk === undefined || settleOnMain(ledger, message.chunk))
163
- ledger.errors.push(message.error);
164
-
165
- return;
166
- }
167
-
168
- if (settle(ledger, message.chunk, message.outcomes)) task.merge(message);
169
- }
170
-
171
- function stopped(states: LaneState[]): boolean {
172
- return states.every((state) => state >= LANE.finished);
173
- }
174
-
175
- function quiet(
176
- index: number,
177
- states: LaneState[],
178
- posted: number[],
179
- lanes: Map<number, Lane>,
180
- ): boolean {
181
- return states[index]! >= LANE.finished && (lanes.get(index)?.drained ?? 0) >= posted[index]!;
182
- }
183
-
184
- function recoverStopped(
185
- ledger: Ledger<unknown>,
186
- claims: Int32Array,
187
- states: LaneState[],
188
- posted: number[],
189
- lanes: Map<number, Lane>,
190
- ): void {
191
- const everyLaneQuiet = states.every((_, index) => quiet(index, states, posted, lanes));
192
- for (let chunk = 0; chunk < claims.length; chunk++) {
193
- const owner = Atomics.load(claims, chunk);
194
- const ownerQuiet = owner !== 0 && quiet(owner - 1, states, posted, lanes);
195
- if (!ownerQuiet && !everyLaneQuiet) continue;
196
- if (!settleOnMain(ledger, chunk)) continue;
197
-
198
- const lane = lanes.get(owner - 1);
199
- if (lane === undefined) ledger.unowned += chunkLength(ledger, chunk);
200
- else lane.recovered += chunkLength(ledger, chunk);
201
- }
202
- }
203
-
204
- function fileCount(count: number): string {
205
- return `${count} ${count === 1 ? "file" : "files"}`;
206
- }
207
-
208
- function laneLoss(lane: Lane): string | undefined {
209
- const exit = `exited with code ${lane.exitCode}`;
210
- if (!lane.started)
211
- return `a worker thread failed to start, so main did its share: ${lane.fault ?? exit}`;
212
-
213
- if (lane.recovered === 0 && lane.fault === undefined && (lane.exitCode ?? 0) !== 0)
214
- return `a worker thread ${exit}, so main did its share`;
215
-
216
- if (lane.recovered === 0) return lane.fault;
217
-
218
- const files = fileCount(lane.recovered);
219
- if (lane.fault !== undefined)
220
- return `a worker thread failed before reporting ${files}, so main took them over: ${lane.fault}`;
221
-
222
- const ending = lane.exitCode === undefined ? "stopped" : exit;
223
- return `a worker thread ${ending} before reporting ${files}, so main took them over`;
224
- }
225
-
226
- function recoveredAny(ledger: Ledger<unknown>, lanes: Map<number, Lane>): boolean {
227
- return ledger.unowned > 0 || [...lanes.values()].some((lane) => lane.recovered > 0);
228
- }
229
-
230
- function losses(ledger: Ledger<unknown>, lanes: Map<number, Lane>): string[] {
231
- const laneLosses = [...lanes.values()].flatMap((lane) => laneLoss(lane) ?? []);
232
- const unowned =
233
- ledger.unowned === 0
234
- ? []
235
- : [
236
- `a worker thread stopped before reporting ${fileCount(ledger.unowned)}, so main took them over`,
237
- ];
238
-
239
- return [...ledger.errors, ...laneLosses, ...unowned];
240
- }
241
-
242
- export async function runPooled<
243
- Input,
244
- Outcome,
245
- Result extends { outcomes: (Outcome | null)[] },
246
- Job,
247
- >(
248
- inputs: Input[],
249
- task: PoolTask<Input, Outcome, Result, Job>,
250
- count: number,
251
- ): Promise<{ outcomes: Outcome[]; errors: string[] }> {
252
- const { Worker, MessageChannel, receiveMessageOnPort } =
253
- require("node:worker_threads") as typeof import("node:worker_threads");
254
-
255
- const chunkSize = task.chunkSize ?? CHUNK_SIZE;
256
- const chunkCount = Math.ceil(inputs.length / chunkSize);
257
- const board: Board = {
258
- counter: new Int32Array(new SharedArrayBuffer(4)),
259
- signal: new Int32Array(new SharedArrayBuffer(4)),
260
- claims: new Int32Array(new SharedArrayBuffer(4 * chunkCount)),
261
- lanes: new Int32Array(new SharedArrayBuffer(4 * count)),
262
- posted: new Int32Array(new SharedArrayBuffer(4 * count)),
263
- };
264
-
265
- const ledger: Ledger<Outcome> = {
266
- inputCount: inputs.length,
267
- chunkSize,
268
- results: Array.from({ length: chunkCount }, () => undefined),
269
- errors: [],
270
- pending: chunkCount,
271
- unowned: 0,
272
- };
273
-
274
- const lanes = new Map<number, Lane>();
275
- const deserializers = deserializerFiles();
276
- let open = true;
277
-
278
- for (let id = 0; id < count; id++) {
279
- const { port1, port2 } = new MessageChannel();
280
- try {
281
- const workerData: PoolData<Input, Job> = {
282
- id,
283
- inputs,
284
- job: task.job,
285
- chunkSize,
286
- counter: board.counter.buffer as SharedArrayBuffer,
287
- signal: board.signal.buffer as SharedArrayBuffer,
288
- claims: board.claims.buffer as SharedArrayBuffer,
289
- lanes: board.lanes.buffer as SharedArrayBuffer,
290
- posted: board.posted.buffer as SharedArrayBuffer,
291
- port: port2,
292
- addon: process.env.NAPI_RS_NATIVE_LIBRARY_PATH,
293
- deserializers,
294
- };
295
-
296
- const worker = new Worker(task.worker, { workerData, transferList: [port2] });
297
- const lane: Lane = {
298
- port: port1,
299
- drained: 0,
300
- started: true,
301
- fault: undefined,
302
- exitCode: undefined,
303
- recovered: 0,
304
- };
305
-
306
- worker.on("error", (error: Error) => {
307
- if (!open) return;
308
- lane.fault ??= error.message;
309
- wake(board.signal);
310
- });
311
-
312
- worker.on("exit", (code: number) => {
313
- if (!open) return;
314
-
315
- lane.started = Atomics.load(board.lanes, id) !== LANE.starting;
316
- lane.exitCode = code;
317
- Atomics.store(board.lanes, id, LANE.gone);
318
- wake(board.signal);
319
- });
320
-
321
- worker.unref();
322
- lanes.set(id, lane);
323
- } catch (error: unknown) {
324
- Atomics.store(board.lanes, id, LANE.gone);
325
- ledger.errors.push(errorText(error));
326
- port1.close();
327
- port2.close();
328
- }
329
- }
330
-
331
- try {
332
- for (;;) {
333
- const observed = Atomics.load(board.signal, 0);
334
- const states = Array.from(
335
- board.lanes,
336
- (_, index) => Atomics.load(board.lanes, index) as LaneState,
337
- );
338
-
339
- const posted = Array.from(board.posted, (_, index) => Atomics.load(board.posted, index));
340
-
341
- for (const lane of lanes.values()) {
342
- let received: ReturnType<typeof receiveMessageOnPort>;
343
- while ((received = receiveMessageOnPort(lane.port)) !== undefined) {
344
- lane.drained++;
345
- accept(ledger, received.message as ChunkMessage<Result>, task);
346
- }
347
- }
348
-
349
- const chunk =
350
- Atomics.load(board.counter, 0) < chunkCount ? Atomics.add(board.counter, 0, 1) : chunkCount;
351
-
352
- if (chunk < chunkCount) {
353
- try {
354
- const result = task.chunk(inputs.slice(chunk * chunkSize, (chunk + 1) * chunkSize));
355
- accept(ledger, { chunk, ...result }, task);
356
- } catch (error: unknown) {
357
- accept(ledger, { chunk, error: errorText(error) }, task);
358
- }
359
-
360
- continue;
361
- }
362
-
363
- recoverStopped(ledger, board.claims, states, posted, lanes);
364
-
365
- const undelivered = [...lanes].some(([index, lane]) => lane.drained < posted[index]!);
366
- const exited = [...lanes.values()].every((lane) => lane.exitCode !== undefined);
367
- const settled = ledger.pending === 0 && stopped(states) && !undelivered;
368
- if (settled && (exited || !recoveredAny(ledger, lanes))) break;
369
-
370
- if (undelivered && stopped(states)) {
371
- await new Promise((resolve) => setImmediate(resolve));
372
- continue;
373
- }
374
-
375
- // Bun releases a waitAsync's hold on the event loop when another thread notifies, before main resumes.
376
- const holdLoop = setInterval(() => {}, 2 ** 30);
377
- try {
378
- await Atomics.waitAsync(board.signal, 0, observed).value;
379
- } finally {
380
- clearInterval(holdLoop);
381
- }
382
- }
383
- } finally {
384
- open = false;
385
- for (const lane of lanes.values()) lane.port.close();
386
- }
387
-
388
- const outcomes: Outcome[] = [];
389
- for (const [chunk, results] of ledger.results.entries())
390
- for (const [offset, outcome] of results!.entries())
391
- outcomes.push(outcome ?? task.item(inputs[chunk * chunkSize + offset]!));
392
-
393
- return { outcomes, errors: losses(ledger, lanes) };
394
- }
395
-
396
- export function serveChunks<Input, Job, Result>(work: (inputs: Input[], job: Job) => Result): void {
397
- const { workerData } = require("node:worker_threads") as typeof import("node:worker_threads");
398
- const data = workerData as PoolData<Input, Job>;
399
-
400
- const counter = new Int32Array(data.counter);
401
- const signal = new Int32Array(data.signal);
402
- const claims = new Int32Array(data.claims);
403
- const lanes = new Int32Array(data.lanes);
404
- const posted = new Int32Array(data.posted);
405
- function post(message: ChunkMessage<Result>): void {
406
- data.port.postMessage(message);
407
- Atomics.add(posted, data.id, 1);
408
- wake(signal);
409
- }
410
-
411
- Atomics.store(lanes, data.id, LANE.serving);
412
- wake(signal);
413
-
414
- try {
415
- if (data.addon !== undefined) process.env.NAPI_RS_NATIVE_LIBRARY_PATH = data.addon;
416
- embedDeserializers(data.deserializers);
417
-
418
- const chunkCount = Math.ceil(data.inputs.length / data.chunkSize);
419
- for (
420
- let chunk = Atomics.add(counter, 0, 1);
421
- chunk < chunkCount;
422
- chunk = Atomics.add(counter, 0, 1)
423
- ) {
424
- Atomics.store(claims, chunk, data.id + 1);
425
-
426
- try {
427
- const result = work(
428
- data.inputs.slice(chunk * data.chunkSize, (chunk + 1) * data.chunkSize),
429
- data.job,
430
- );
431
-
432
- post({ chunk, ...result });
433
- } catch (error: unknown) {
434
- post({ chunk, error: errorText(error) });
435
- }
436
- }
437
- } catch (error: unknown) {
438
- post({ chunk: undefined, error: errorText(error) });
439
- } finally {
440
- Atomics.store(lanes, data.id, LANE.finished);
441
- wake(signal);
442
- }
443
- }
444
-
445
- export async function formatPooled(
446
- inputs: FileInput[],
447
- run: FormatRun,
448
- count: number,
449
- ): Promise<{ formatted: Formatted; errors: string[] }> {
450
- const warnings = { unread: new Set<string>(), unreadWidth: new Set<string>() };
451
- // A compiled Bun worker resolves a bare specifier inside bunfs, not a file URL.
452
- const specifier = Bun.main.includes("/$bunfs/")
453
- ? "./worker.ts"
454
- : new URL("./worker.ts", import.meta.url);
455
-
456
- const { outcomes, errors } = await runPooled(
457
- inputs,
458
- {
459
- worker: specifier,
460
- job: run,
461
- chunk: (inputs) => formatChunk(inputs, run),
462
- merge(result) {
463
- for (const path of result.unread) warnings.unread.add(path);
464
- for (const path of result.unreadWidth) warnings.unreadWidth.add(path);
465
- },
466
- item: (input): FileOutcome =>
467
- formatFile({ ...input, read: () => readText(input.path) }, run, input.output, warnings),
468
- },
469
- count,
470
- );
471
-
472
- return { formatted: mergeOutcomes(outcomes, warnings), errors };
473
- }
package/src/start.ts DELETED
@@ -1,49 +0,0 @@
1
- import { readFileSync } from "node:fs";
2
- import { hookCall } from "./hook.ts";
3
-
4
- type Writer = (chunk: string | Uint8Array) => void;
5
-
6
- export interface Io {
7
- cwd: string;
8
- env: Readonly<Record<string, string | undefined>>;
9
- stdin: () => Uint8Array;
10
- stdout: Writer;
11
- stderr: Writer;
12
- }
13
-
14
- function ignoreBrokenPipe(error: NodeJS.ErrnoException): void {
15
- if (error.code !== "EPIPE") throw error;
16
- }
17
-
18
- export function systemIo(): Io {
19
- // Under Bun a stream write throws EPIPE into a stack trace and exit 1, where console.log swallowed it.
20
- process.stdout.on("error", ignoreBrokenPipe);
21
- process.stderr.on("error", ignoreBrokenPipe);
22
-
23
- return {
24
- cwd: process.cwd(),
25
- env: process.env,
26
- stdin: () => readFileSync(0),
27
- stdout: (chunk) => {
28
- process.stdout.write(chunk);
29
- },
30
- stderr: (chunk) => {
31
- process.stderr.write(chunk);
32
- },
33
- };
34
- }
35
-
36
- export async function start(argv: string[]): Promise<number> {
37
- const io = systemIo();
38
- if (argv[0] === "hook") {
39
- const args = argv.slice(1);
40
- const call = hookCall(args, io);
41
- if (typeof call === "number") return call;
42
-
43
- const { runHookCall } = await import("./cli.ts");
44
- return runHookCall(call, args, io);
45
- }
46
-
47
- const { main } = await import("./cli.ts");
48
- return main(argv, io);
49
- }
package/src/step.ts DELETED
@@ -1,113 +0,0 @@
1
- import { dirname, extname } from "node:path";
2
- import { isGeneratedHeader } from "./files.ts";
3
- import { processFile } from "./engine/index.ts";
4
- import type { Changed } from "./engine/model.ts";
5
- import { languageOf } from "./languages/index.ts";
6
- import { FALLBACK_WIDTH, type Width } from "./languages/language.ts";
7
- import type { Braces, FileResult, Finding, Mode, Options } from "./engine/types.ts";
8
-
9
- export type Decoded = string | { message: string };
10
-
11
- export interface StepOptions {
12
- mode: Mode;
13
- braces?: Braces | undefined;
14
- changedLines?: Changed | undefined;
15
- unread?: Set<string>;
16
- unreadWidth?: Set<string>;
17
- }
18
-
19
- export interface StepResult {
20
- findings: Finding[];
21
- fixed: string | undefined;
22
- parseError: boolean;
23
- }
24
-
25
- const utf8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
26
- const bom = "";
27
-
28
- export function decode(bytes: Uint8Array): Decoded {
29
- try {
30
- return utf8.decode(bytes);
31
- } catch {
32
- return { message: "not valid UTF-8, left untouched" };
33
- }
34
- }
35
-
36
- export function withoutMark(text: string): string {
37
- return text.startsWith(bom) ? text.slice(bom.length) : text;
38
- }
39
-
40
- export function keepBraces(path: string, braces?: Braces, unread?: Set<string>): boolean {
41
- if (braces !== undefined) return braces === "off";
42
-
43
- const setting = languageOf(path).config?.setting(dirname(path), extname(path)) ?? {
44
- enforced: false,
45
- unread: [],
46
- };
47
-
48
- for (const file of setting.unread) unread?.add(file);
49
- return setting.enforced;
50
- }
51
-
52
- export function stepSettings(
53
- path: string,
54
- options: { braces?: Braces; unread?: Set<string>; unreadWidth?: Set<string> } = {},
55
- ): { keepBraces: boolean; width: Width } {
56
- const language = languageOf(path);
57
- const width = language.config?.width(path) ?? FALLBACK_WIDTH;
58
- for (const file of width.unread) options.unreadWidth?.add(file);
59
-
60
- return { keepBraces: keepBraces(path, options.braces, options.unread), width };
61
- }
62
-
63
- export function fixText(path: string, text: string, mode: Mode, options: Options): FileResult {
64
- const body = withoutMark(text);
65
- const mark = text.slice(0, text.length - body.length);
66
- const result = processFile(path, body, mode, options);
67
- return { ...result, text: mark + result.text };
68
- }
69
-
70
- function failure(path: string, rule: "parse" | "error", message: string): StepResult {
71
- return {
72
- findings: [{ path, line: 1, col: 1, rule, message, fixable: false }],
73
- fixed: undefined,
74
- parseError: true,
75
- };
76
- }
77
-
78
- export function formatText(path: string, text: Decoded, options: StepOptions): StepResult {
79
- if (typeof text !== "string") return failure(path, "parse", text.message);
80
-
81
- try {
82
- if (isGeneratedHeader(text)) return { findings: [], fixed: undefined, parseError: false };
83
-
84
- const result = fixText(path, text, options.mode, {
85
- ...stepSettings(path, options),
86
- ...(options.changedLines === undefined ? {} : { changedLines: options.changedLines }),
87
- });
88
-
89
- const changed = options.mode === "fix" && !result.parseError && result.text !== text;
90
- if (changed) {
91
- const body = withoutMark(result.text);
92
- const error =
93
- body === result.lastParse.text
94
- ? result.lastParse.error
95
- : languageOf(path).parse(path, body).error;
96
-
97
- if (error)
98
- return failure(
99
- path,
100
- "error",
101
- `fixed text does not parse (${error.message}), left untouched`,
102
- );
103
- }
104
-
105
- return {
106
- findings: result.findings,
107
- fixed: changed ? result.text : undefined,
108
- parseError: result.parseError,
109
- };
110
- } catch (error: unknown) {
111
- return failure(path, "error", String(error));
112
- }
113
- }
package/src/usage.ts DELETED
@@ -1,35 +0,0 @@
1
- export const bothBraces = "use one of --braces or --no-braces";
2
-
3
- export const usage =
4
- "Usage: stanza (--fix | --check) [--changed [--hunks] | --stdin <path> | [--] <paths...>] [--json] [--braces | --no-braces]\n stanza --check --staged [--hunks] [--json] [--braces | --no-braces]\n stanza explain [--no-braces] [--] <file>:<line>\n stanza hook [--braces | --no-braces] [--hunks]";
5
-
6
- export const flags: (readonly [string, string])[] = [
7
- ["--fix", "apply every deterministic rule in place"],
8
- ["--check", "report only, change nothing"],
9
- ["--changed", "files from `git diff --name-only HEAD` plus untracked files"],
10
- ["--hunks", "with --changed or --staged, only gaps and blocks touching changed lines"],
11
- ["--staged", "the staged content of staged files, for pre-commit"],
12
- [
13
- "--stdin <path>",
14
- "source on stdin; --fix: fixed text on stdout, findings on stderr; --check: findings on stdout",
15
- ],
16
- ["--json", "findings as a JSON array"],
17
- ["--braces", "turn on the braces rule even when lint config turns it off or cannot be read"],
18
- ["--no-braces", "turn off the braces rule, keep the blank line rules"],
19
- ["explain <file>:<line>", "which rule decides the gap or braced body at that line, and why"],
20
- [
21
- "hook",
22
- "Stop and SubagentStop; PostToolUse on Edit, MultiEdit and Codex `apply_patch`; PreToolUse on Write; reads JSON on stdin",
23
- ],
24
- ["--help", "usage, flags and the rule catalog"],
25
- ["--version", "the version, and for a built binary the commit it was built from"],
26
- ];
27
-
28
- export function columns(rows: readonly (readonly string[])[]): string[] {
29
- const widths = rows[0]!.map((_, index) => Math.max(...rows.map((row) => row[index]!.length)));
30
- return rows.map((row) =>
31
- row
32
- .map((cell, index) => (index < row.length - 1 ? cell.padEnd(widths[index]!) : cell))
33
- .join(" "),
34
- );
35
- }
package/src/worker.ts DELETED
@@ -1,5 +0,0 @@
1
- import { tooDeep } from "./depth.ts";
2
- import { formatChunk, serveChunks, type FileInput } from "./pool.ts";
3
- import type { FormatRun } from "./format.ts";
4
-
5
- serveChunks((inputs: FileInput[], run: FormatRun) => formatChunk(inputs, run, tooDeep));