@ryuugg/stanza 0.2.0 → 0.3.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ryuugg/stanza",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "description": "An opinionated code formatter for TypeScript.",
5
5
  "keywords": [
6
6
  "formatter",
package/src/cli.ts CHANGED
@@ -32,12 +32,15 @@ import {
32
32
  } from "./files.ts";
33
33
  import { explain } from "./engine/explain.ts";
34
34
  import { languageOf } from "./languages/index.ts";
35
- import { blockReason, claudeCodeHooks, hookInput, rereadLine, writtenFiles } from "./hook.ts";
35
+ import { blockReason, claudeCodeHooks, hookCall, rereadLine, type HookCall } from "./hook.ts";
36
+ import { systemIo, type Io } from "./start.ts";
36
37
  import type { Changed } from "./engine/model.ts";
37
38
  import { RULES } from "./engine/rules.ts";
38
39
  import { decode, type Decoded, formatText, withoutMark } from "./step.ts";
39
40
  import { compareFindings, type Braces, type Finding, type Mode } from "./engine/types.ts";
40
- import { columns, flags, usage } from "./usage.ts";
41
+ import { bothBraces, columns, flags, usage } from "./usage.ts";
42
+
43
+ export type { Io } from "./start.ts";
41
44
 
42
45
  declare const STANZA_COMMIT: string | undefined;
43
46
 
@@ -58,16 +61,6 @@ interface ExplainArguments {
58
61
  noBraces: boolean;
59
62
  }
60
63
 
61
- type Writer = (chunk: string | Uint8Array) => void;
62
-
63
- export interface Io {
64
- cwd: string;
65
- env: Readonly<Record<string, string | undefined>>;
66
- stdin: () => Uint8Array;
67
- stdout: Writer;
68
- stderr: Writer;
69
- }
70
-
71
64
  interface Input {
72
65
  path: string;
73
66
  read: () => Decoded;
@@ -91,32 +84,8 @@ interface Formatted {
91
84
  unreadWidth: Set<string>;
92
85
  }
93
86
 
94
- function ignoreBrokenPipe(error: NodeJS.ErrnoException): void {
95
- if (error.code !== "EPIPE") throw error;
96
- }
97
-
98
- export function systemIo(): Io {
99
- // Under Bun a stream write throws EPIPE into a stack trace and exit 1, where console.log swallowed it.
100
- process.stdout.on("error", ignoreBrokenPipe);
101
- process.stderr.on("error", ignoreBrokenPipe);
102
-
103
- return {
104
- cwd: process.cwd(),
105
- env: process.env,
106
- stdin: () => readFileSync(0),
107
- stdout: (chunk) => {
108
- process.stdout.write(chunk);
109
- },
110
- stderr: (chunk) => {
111
- process.stderr.write(chunk);
112
- },
113
- };
114
- }
115
-
116
87
  const switches = new Set(["--braces", "--changed", "--hunks", "--json", "--no-braces", "--staged"]);
117
88
  const standalone = new Set(["--help", "-h", "--version"]);
118
- const hookSwitches = new Set(["--braces", "--hunks", "--no-braces"]);
119
- const bothBraces = "use one of --braces or --no-braces";
120
89
 
121
90
  function help(): string {
122
91
  const rules = Object.entries(RULES).map(([id, rule]) => [
@@ -725,16 +694,11 @@ function fixChanged(
725
694
  }
726
695
 
727
696
  function runStopHook(
728
- input: { cwd: string; stopHookActive: boolean; transcriptPath: string | undefined },
697
+ input: { cwd: string; written: Set<string> | undefined },
729
698
  args: string[],
730
699
  io: Io,
731
700
  ): number {
732
- if (input.stopHookActive) return 0;
733
-
734
- const written =
735
- input.transcriptPath === undefined ? undefined : writtenFiles(input.transcriptPath);
736
-
737
- const result = fixChanged(input.cwd, written, args, io);
701
+ const result = fixChanged(input.cwd, input.written, args, io);
738
702
  if (typeof result === "number") return result;
739
703
 
740
704
  const reason = blockReason(result.findings, result.rewritten);
@@ -761,32 +725,14 @@ function runEditHook(input: { cwd: string; paths: string[] }, args: string[], io
761
725
  }
762
726
 
763
727
  function runHook(args: string[], io: Io): number {
764
- if (io.env.AGENT_HOOKS === "0") return 0;
765
-
766
- const unexpected = args.find(
767
- (arg, index) => !hookSwitches.has(arg) || args.indexOf(arg) !== index,
768
- );
769
-
770
- if (unexpected !== undefined) {
771
- warn(io, `stanza hook: unexpected argument ${unexpected}\n${usage}`);
772
- return 1;
773
- }
774
-
775
- if (args.includes("--braces") && args.includes("--no-braces")) {
776
- warn(io, `stanza hook: ${bothBraces}\n${usage}`);
777
- return 1;
778
- }
779
-
780
- const input = hookInput(Buffer.from(io.stdin()).toString("utf8"), io.cwd);
781
- if ("error" in input) {
782
- warn(io, `stanza hook: ${input.error}`);
783
- return 1;
784
- }
728
+ const call = hookCall(args, io);
729
+ return typeof call === "number" ? call : runHookCall(call, args, io);
730
+ }
785
731
 
786
- if (input.event === "ignored") return 0;
787
- if (input.event === "write") return runWriteHook(input.cwd, input.toolInput, args, io);
788
- if (input.event === "edit") return runEditHook(input, args, io);
789
- return runStopHook(input, args, io);
732
+ export function runHookCall(call: HookCall, args: string[], io: Io): number {
733
+ if (call.event === "write") return runWriteHook(call.cwd, call.toolInput, args, io);
734
+ if (call.event === "edit") return runEditHook(call, args, io);
735
+ return runStopHook(call, args, io);
790
736
  }
791
737
 
792
738
  export function main(argv: string[], io: Io): number {
package/src/compiled.ts CHANGED
@@ -1,6 +1,9 @@
1
+ import { embedCompiledDeserializers } from "./languages/javascript/embedded.ts";
2
+
1
3
  export async function start(addon: string): Promise<void> {
2
4
  // Must precede any oxc-parser import (its loader cannot find the binding in a compiled binary), hence the dynamic import.
3
5
  process.env.NAPI_RS_NATIVE_LIBRARY_PATH = addon;
4
- const { main, systemIo } = await import("./cli.ts");
5
- process.exitCode = main(process.argv.slice(2), systemIo());
6
+ embedCompiledDeserializers();
7
+ const { start } = await import("./start.ts");
8
+ process.exitCode = await start(process.argv.slice(2));
6
9
  }
@@ -1,5 +1,12 @@
1
1
  import { languageOf } from "../languages/index.ts";
2
- import type { BracePass, Language, Parsed, Scan, Touches } from "../languages/language.ts";
2
+ import type {
3
+ BracePass,
4
+ Language,
5
+ Parsed,
6
+ Rejection,
7
+ Scan,
8
+ Touches,
9
+ } from "../languages/language.ts";
3
10
  import { blankLines, document, lineAt, parseFinding, position } from "./doc.ts";
4
11
  import { applyLines, applyOffsets, offsetMap, type OffsetEdit } from "./edits.ts";
5
12
  import { spacing } from "./gaps.ts";
@@ -109,19 +116,25 @@ function netGaps(trail: Trail, first: Scan, final: Doc, finalScan: Scan): Findin
109
116
  });
110
117
  }
111
118
 
119
+ interface Parse {
120
+ doc: Doc;
121
+ scanned: Scan;
122
+ error: Rejection | undefined;
123
+ }
124
+
112
125
  function unbrace(
113
126
  language: Language,
114
- doc: Doc,
115
- scanned: Scan,
127
+ last: Parse,
116
128
  pass: BracePass,
117
129
  lines: Changed | undefined,
118
130
  trail: Trail,
119
131
  collapseChains: boolean,
120
132
  width: Options["width"],
121
133
  passes?: OffsetEdit[][],
122
- ): { doc: Doc; scanned: Scan; lines: Changed | undefined } {
134
+ ): Parse & { lines: Changed | undefined } {
123
135
  let touches = touching(lines);
124
- for (; pass.edits.length > 0; pass = bracePass(doc, scanned, touches, collapseChains)) {
136
+ for (; pass.edits.length > 0; pass = bracePass(last.doc, last.scanned, touches, collapseChains)) {
137
+ const { doc } = last;
125
138
  passes?.push(pass.edits);
126
139
  record(trail, doc, pass.findings);
127
140
  retrace(trail, offsetMap(pass.edits).back);
@@ -132,11 +145,10 @@ function unbrace(
132
145
 
133
146
  lines = afterOffsets(doc, lines, pass.edits, next);
134
147
  touches = touching(lines);
135
- doc = next;
136
- scanned = parsed.scan(doc, width);
148
+ last = { doc: next, scanned: parsed.scan(next, width), error: parsed.error };
137
149
  }
138
150
 
139
- return { doc, scanned, lines };
151
+ return { ...last, lines };
140
152
  }
141
153
 
142
154
  export interface Trace {
@@ -160,8 +172,7 @@ export function traceFix(
160
172
  const passes: OffsetEdit[][] = [];
161
173
  const { doc, scanned } = unbrace(
162
174
  language,
163
- original,
164
- first,
175
+ { doc: original, scanned: first, error: parsed.error },
165
176
  pass,
166
177
  undefined,
167
178
  startTrail(original),
@@ -181,6 +192,7 @@ export function processFile(path: string, text: string, mode: Mode, options: Opt
181
192
  if (rejected)
182
193
  return {
183
194
  text,
195
+ lastParse: { text, error: parsed.error },
184
196
  findings: [parseFinding(doc, rejected.start, rejected.message)],
185
197
  parseError: true,
186
198
  };
@@ -190,15 +202,13 @@ export function processFile(path: string, text: string, mode: Mode, options: Opt
190
202
  let touches = touching(lines);
191
203
  const trail = startTrail(doc);
192
204
 
193
- let last = doc;
194
- let lastScan = scanned;
205
+ let last: Parse = { doc, scanned, error: parsed.error };
195
206
  let settled: Finding[] | undefined;
196
207
  let pass = options.keepBraces ? NO_BRACES : bracePass(doc, scanned, touches, lines === undefined);
197
208
  while (true) {
198
209
  const unbraced = unbrace(
199
210
  language,
200
211
  last,
201
- lastScan,
202
212
  pass,
203
213
  lines,
204
214
  trail,
@@ -221,33 +231,43 @@ export function processFile(path: string, text: string, mode: Mode, options: Opt
221
231
  touches = touching(lines);
222
232
 
223
233
  if (spacedText === unbraced.doc.text || (mode === "check" && lines === undefined)) {
224
- last = unbraced.doc;
225
- lastScan = unbraced.scanned;
234
+ last = unbraced;
226
235
  settled = spaced.findings;
227
236
  break;
228
237
  }
229
238
 
230
239
  const spacedParse = language.parse(path, spacedText);
231
- last = document(path, spacedText, spacedParse.comments);
232
- lastScan = spacedParse.scan(last, options.width);
233
- retrace(trail, lineBack(unbraced.doc, last, spaced.edits));
240
+ const spacedDoc = document(path, spacedText, spacedParse.comments);
241
+ last = {
242
+ doc: spacedDoc,
243
+ scanned: spacedParse.scan(spacedDoc, options.width),
244
+ error: spacedParse.error,
245
+ };
246
+
247
+ retrace(trail, lineBack(unbraced.doc, last.doc, spaced.edits));
234
248
  if (lines === undefined || options.keepBraces) break;
235
249
 
236
- pass = bracePass(last, lastScan, touches, false);
250
+ pass = bracePass(last.doc, last.scanned, touches, false);
237
251
  if (pass.edits.length === 0) break;
238
252
  }
239
253
 
240
254
  const remaining = (
241
- settled ?? spacing(last, lastScan.lists, lastScan.frozen, touches).findings
255
+ settled ?? spacing(last.doc, last.scanned.lists, last.scanned.frozen, touches).findings
242
256
  ).filter((item) => !item.fixable);
243
257
 
244
258
  if (mode === "fix")
245
- return { text: last.text, findings: remaining.sort(compareFindings), parseError: false };
259
+ return {
260
+ text: last.doc.text,
261
+ lastParse: { text: last.doc.text, error: last.error },
262
+ findings: remaining.sort(compareFindings),
263
+ parseError: false,
264
+ };
246
265
 
247
- record(trail, last, remaining);
266
+ record(trail, last.doc, remaining);
248
267
  return {
249
268
  text,
250
- findings: netGaps(trail, scanned, last, lastScan).sort(compareFindings),
269
+ lastParse: { text: last.doc.text, error: last.error },
270
+ findings: netGaps(trail, scanned, last.doc, last.scanned).sort(compareFindings),
251
271
  parseError: false,
252
272
  };
253
273
  }
@@ -1,4 +1,4 @@
1
- import type { Layout } from "../languages/language.ts";
1
+ import type { Layout, Rejection } from "../languages/language.ts";
2
2
  import type { Changed } from "./model.ts";
3
3
  import type { RuleId } from "./rules.ts";
4
4
 
@@ -32,6 +32,7 @@ export function compareFindings(left: Finding, right: Finding): number {
32
32
 
33
33
  export interface FileResult {
34
34
  text: string;
35
+ lastParse: { text: string; error: Rejection | undefined };
35
36
  findings: Finding[];
36
37
  parseError: boolean;
37
38
  }
package/src/hook.ts CHANGED
@@ -1,7 +1,64 @@
1
- import { readFileSync, readdirSync } from "node:fs";
1
+ import { readFileSync, readdirSync, realpathSync } from "node:fs";
2
2
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
3
- import { RULES } from "./engine/rules.ts";
4
3
  import type { Finding } from "./engine/types.ts";
4
+ import { isCandidate } from "./languages/index.ts";
5
+ import type { Io } from "./start.ts";
6
+ import { bothBraces, usage } from "./usage.ts";
7
+
8
+ export type HookCall =
9
+ | {
10
+ event: "write";
11
+ cwd: string;
12
+ toolInput: { file_path: string; content: string } & Record<string, unknown>;
13
+ }
14
+ | { event: "edit"; cwd: string; paths: string[] }
15
+ | { event: "stop"; cwd: string; written: Set<string> | undefined };
16
+
17
+ const hookSwitches = new Set(["--braces", "--hunks", "--no-braces"]);
18
+
19
+ function isCandidateFile(path: string): boolean {
20
+ try {
21
+ return isCandidate(basename(realpathSync(path)));
22
+ } catch {
23
+ return false;
24
+ }
25
+ }
26
+
27
+ export function hookCall(args: string[], io: Io): HookCall | number {
28
+ if (io.env.AGENT_HOOKS === "0") return 0;
29
+
30
+ const unexpected = args.find(
31
+ (arg, index) => !hookSwitches.has(arg) || args.indexOf(arg) !== index,
32
+ );
33
+
34
+ if (unexpected !== undefined) {
35
+ io.stderr(`stanza hook: unexpected argument ${unexpected}\n${usage}\n`);
36
+ return 1;
37
+ }
38
+
39
+ if (args.includes("--braces") && args.includes("--no-braces")) {
40
+ io.stderr(`stanza hook: ${bothBraces}\n${usage}\n`);
41
+ return 1;
42
+ }
43
+
44
+ const input = hookInput(Buffer.from(io.stdin()).toString("utf8"), io.cwd);
45
+ if ("error" in input) {
46
+ io.stderr(`stanza hook: ${input.error}\n`);
47
+ return 1;
48
+ }
49
+
50
+ if (input.event === "ignored") return 0;
51
+ if (input.event === "write") return isCandidate(basename(input.toolInput.file_path)) ? input : 0;
52
+ if (input.event === "edit") return input.paths.some(isCandidateFile) ? input : 0;
53
+ if (input.stopHookActive) return 0;
54
+
55
+ const written =
56
+ input.transcriptPath === undefined ? undefined : writtenFiles(input.transcriptPath);
57
+
58
+ if (written !== undefined && ![...written].some(isCandidateFile)) return 0;
59
+
60
+ return { event: "stop", cwd: input.cwd, written };
61
+ }
5
62
 
6
63
  export const claudeCodeHooks =
7
64
  '{ "hooks": { "PreToolUse": [{ "matcher": "Write", "hooks": [{ "type": "command", "command": "stanza hook" }] }], "PostToolUse": [{ "matcher": "Edit|MultiEdit", "hooks": [{ "type": "command", "command": "stanza hook" }] }], "Stop": [{ "hooks": [{ "type": "command", "command": "stanza hook" }] }] } }';
@@ -242,6 +299,8 @@ const failures: Partial<Record<Finding["rule"], string>> = {
242
299
  export function blockReason(findings: Finding[], rewritten: string[]): string | undefined {
243
300
  if (findings.length === 0) return undefined;
244
301
 
302
+ const { RULES } = require("./engine/rules.ts") as typeof import("./engine/rules.ts");
303
+
245
304
  const shown = findings.slice(0, 12);
246
305
  const lines = shown.map((finding) => {
247
306
  const failure = failures[finding.rule];
@@ -36,11 +36,39 @@ export function children(node: Node): [string, Node][] {
36
36
  return result;
37
37
  }
38
38
 
39
- function reverseFrom(stack: unknown[], first: number): void {
40
- for (let left = first, right = stack.length - 1; left < right; left++, right--) {
41
- const swapped = stack[left];
42
- stack[left] = stack[right];
43
- stack[right] = swapped;
39
+ function pushValueReverse(
40
+ value: unknown,
41
+ parent: Node,
42
+ nodes: Node[],
43
+ parents: (Node | null)[],
44
+ ): void {
45
+ if (Array.isArray(value)) {
46
+ for (let index = value.length - 1; index >= 0; index--) {
47
+ const child: unknown = value[index];
48
+ if (!isNode(child)) continue;
49
+
50
+ nodes.push(child);
51
+ parents.push(parent);
52
+ }
53
+ } else if (isNode(value)) {
54
+ nodes.push(value);
55
+ parents.push(parent);
56
+ }
57
+ }
58
+
59
+ function pushChildrenReverse(node: Node, nodes: Node[], parents: (Node | null)[]): void {
60
+ const keys = visitorKeys[node.type];
61
+ if (keys) {
62
+ const fields = node as unknown as Record<string, unknown>;
63
+ for (let index = keys.length - 1; index >= 0; index--)
64
+ pushValueReverse(fields[keys[index]!], node, nodes, parents);
65
+ } else {
66
+ const entries = Object.entries(node);
67
+ for (let index = entries.length - 1; index >= 0; index--) {
68
+ const [key, value] = entries[index]!;
69
+ if (key === "parent") continue;
70
+ pushValueReverse(value, node, nodes, parents);
71
+ }
44
72
  }
45
73
  }
46
74
 
@@ -49,22 +77,35 @@ export function walk(
49
77
  enter: (node: Node, parent: Node | null) => void,
50
78
  leave?: (node: Node, parent: Node | null) => void,
51
79
  ): void {
52
- const stack = [{ node: root, parent: null as Node | null, leaving: false }];
53
- while (stack.length > 0) {
54
- const frame = stack.pop()!;
55
- const { node, parent } = frame;
56
- if (frame.leaving) {
57
- leave?.(node, parent);
80
+ const nodes: Node[] = [root];
81
+ const parents: (Node | null)[] = [null];
82
+ if (!leave) {
83
+ while (nodes.length > 0) {
84
+ const node = nodes.pop()!;
85
+ const parent = parents.pop()!;
86
+ enter(node, parent);
87
+ pushChildrenReverse(node, nodes, parents);
88
+ }
89
+
90
+ return;
91
+ }
92
+
93
+ const leaveIndexes: number[] = [];
94
+ while (nodes.length > 0) {
95
+ const node = nodes.pop()!;
96
+ const parent = parents.pop()!;
97
+ if (leaveIndexes.at(-1) === nodes.length) {
98
+ leaveIndexes.pop();
99
+ leave(node, parent);
58
100
  continue;
59
101
  }
60
102
 
61
103
  enter(node, parent);
62
- frame.leaving = true;
63
- stack.push(frame);
104
+ leaveIndexes.push(nodes.length);
105
+ nodes.push(node);
106
+ parents.push(parent);
64
107
 
65
- const first = stack.length;
66
- eachChild(node, (_key, child) => stack.push({ node: child, parent: node, leaving: false }));
67
- reverseFrom(stack, first);
108
+ pushChildrenReverse(node, nodes, parents);
68
109
  }
69
110
  }
70
111
 
@@ -70,13 +70,16 @@ export interface Context {
70
70
  exceeded: boolean;
71
71
  cycles: number;
72
72
  memo: Map<Value, Map<string, Layer[]>>;
73
+ charged: Set<string>;
74
+ reaching: Set<string>[];
73
75
  };
74
76
  }
75
77
 
76
78
  export const UNKNOWN_LAYER: Layer = { reach: "all", setting: "unknown" };
77
79
  const EXPANSION_BUDGET = 100000;
78
80
 
79
- const layerCache = new Map<string, { layers: Layer[]; root: Value }>();
81
+ const layerCache = new Map<string, { layers: Layer[]; root: Value; reached: Set<string> }>();
82
+ const exclusiveCost = new Map<string, number>();
80
83
 
81
84
  export function lastLayers(layers: Layer[]): Layer[] {
82
85
  const seen = new Set<Layer>();
@@ -311,6 +314,19 @@ function backstop(module: ConfigModule, context: Context, result: Layer[]): void
311
314
  });
312
315
  }
313
316
 
317
+ function charge(keys: Iterable<string>, work: Context["work"]): void {
318
+ for (const key of keys) {
319
+ for (const reached of work.reaching) reached.add(key);
320
+
321
+ if (work.charged.has(key)) continue;
322
+
323
+ work.charged.add(key);
324
+ work.count += exclusiveCost.get(key)!;
325
+ }
326
+
327
+ if (work.count > EXPANSION_BUDGET) work.exceeded = true;
328
+ }
329
+
314
330
  export function fileLayers(file: string, context: Context): { layers: Layer[]; root: Value } {
315
331
  const module = moduleAt(file);
316
332
  if (!module || context.chain.includes(module.file) || context.chain.length >= 32)
@@ -318,11 +334,37 @@ export function fileLayers(file: string, context: Context): { layers: Layer[]; r
318
334
 
319
335
  const key = JSON.stringify([file, dirname(file), context.reader.family, context.shared]);
320
336
  const cached = layerCache.get(key);
321
- if (cached) return cached;
337
+ if (cached) {
338
+ charge(cached.reached, context.work);
339
+ return cached;
340
+ }
341
+
342
+ const work = context.work;
343
+ for (const reached of work.reaching) reached.add(key);
344
+
345
+ const reached = new Set([key]);
346
+ work.reaching.push(reached);
347
+ const cycles = work.cycles;
348
+ const count = work.count;
349
+ const charged = new Set(work.charged);
350
+
351
+ let result: { layers: Layer[]; root: Value };
352
+ try {
353
+ result = readFileLayers(file, module, context);
354
+ } finally {
355
+ work.reaching.pop();
356
+ }
357
+
358
+ if (!work.exceeded && work.cycles === cycles) {
359
+ let cost = work.count - count;
360
+ for (const entry of work.charged)
361
+ if (entry !== key && !charged.has(entry)) cost -= exclusiveCost.get(entry)!;
362
+
363
+ layerCache.set(key, { ...result, reached });
364
+ exclusiveCost.set(key, cost);
365
+ work.charged.add(key);
366
+ }
322
367
 
323
- const cycles = context.work.cycles;
324
- const result = readFileLayers(file, module, context);
325
- if (!context.work.exceeded && context.work.cycles === cycles) layerCache.set(key, result);
326
368
  return result;
327
369
  }
328
370
 
@@ -378,11 +420,13 @@ export function configAt(
378
420
  extension: string | undefined,
379
421
  reader: Reader,
380
422
  ): Found {
381
- const work = {
423
+ const work: Context["work"] = {
382
424
  count: 0,
383
425
  exceeded: false,
384
426
  cycles: 0,
385
427
  memo: new Map<Value, Map<string, Layer[]>>(),
428
+ charged: new Set<string>(),
429
+ reaching: [],
386
430
  };
387
431
 
388
432
  const result = fileLayers(file, {
@@ -0,0 +1,17 @@
1
+ import { dirname, join } from "node:path";
2
+
3
+ export interface DeserializerFiles {
4
+ js: string;
5
+ ts: string;
6
+ }
7
+
8
+ let embedded: DeserializerFiles | undefined;
9
+ export function embedDeserializers(files: DeserializerFiles): void {
10
+ embedded = files;
11
+ }
12
+
13
+ export function deserializerFiles(): DeserializerFiles {
14
+ if (embedded) return embedded;
15
+ const generated = join(dirname(require.resolve("oxc-parser")), "generated", "deserialize");
16
+ return { js: join(generated, "js.js"), ts: join(generated, "ts.js") };
17
+ }
@@ -0,0 +1,7 @@
1
+ import js from "oxc-parser/src-js/generated/deserialize/js.js" with { type: "file" };
2
+ import ts from "oxc-parser/src-js/generated/deserialize/ts.js" with { type: "file" };
3
+ import { embedDeserializers } from "./deserializers.ts";
4
+
5
+ export function embedCompiledDeserializers(): void {
6
+ embedDeserializers({ js, ts });
7
+ }
@@ -0,0 +1,31 @@
1
+ declare module "oxc-parser/src-js/bindings.js" {
2
+ import type { ParserOptions } from "oxc-parser";
3
+
4
+ export function getBufferOffset(buffer: Uint8Array): number;
5
+ export function rawTransferSupported(): boolean;
6
+ export function parseRawSync(
7
+ path: string,
8
+ block: Uint8Array,
9
+ sourceStartPos: number,
10
+ sourceByteLen: number,
11
+ options: ParserOptions,
12
+ ): void;
13
+ }
14
+
15
+ declare module "oxc-parser/src-js/generated/constants.js" {
16
+ export const ACTIVE_SIZE: number;
17
+ export const BLOCK_ALIGN: number;
18
+ export const BLOCK_SIZE: number;
19
+ export const BUFFER_SIZE: number;
20
+ export const IS_TS_FLAG_POS: number;
21
+ }
22
+
23
+ declare module "oxc-parser/src-js/generated/deserialize/js.js" {
24
+ const path: string;
25
+ export default path;
26
+ }
27
+
28
+ declare module "oxc-parser/src-js/generated/deserialize/ts.js" {
29
+ const path: string;
30
+ export default path;
31
+ }
@@ -24,11 +24,84 @@ const javascript: Record<string, ParserOptions> = {
24
24
 
25
25
  const loneCr = /\r(?!\n)/g;
26
26
 
27
+ const RAW_AFTER_LENGTH = 500_000;
28
+ const RAW_MAX_LENGTH = 1_000_000;
29
+ const RAW_COLLECT_EVERY = 1_000_000;
30
+
31
+ let parsedSinceCollect = 0;
32
+
33
+ type Handoff =
34
+ | { kind: "pending"; remaining: number; required: boolean }
35
+ | { kind: "raw"; parseRaw: typeof import("./raw.ts").parseRaw }
36
+ | { kind: "json" }
37
+ | { kind: "unavailable"; error: Error };
38
+
39
+ let handoff: Handoff | undefined;
40
+
27
41
  export function parse(path: string, text: string): Parsed {
28
- const result = parseSync(path, text, javascript[extname(path)]);
42
+ const options = javascript[extname(path)];
43
+ const current = currentHandoff(text.length <= RAW_MAX_LENGTH ? text.length : 0);
44
+ if (current.kind === "unavailable") throw current.error;
45
+
46
+ if (current.kind === "raw") {
47
+ collectWhileRaw(text.length);
48
+
49
+ if (text.length <= RAW_MAX_LENGTH)
50
+ try {
51
+ return current.parseRaw(path, text, options);
52
+ } catch {
53
+ // The raw deserializer recurses and overflows the stack on deep or long inputs that JSON.parse handles.
54
+ }
55
+ }
56
+
57
+ const result = parseSync(path, text, options);
29
58
  return { program: result.program, comments: result.comments, errors: result.errors };
30
59
  }
31
60
 
61
+ function collectWhileRaw(length: number): void {
62
+ parsedSinceCollect += length;
63
+ if (parsedSinceCollect < RAW_COLLECT_EVERY) return;
64
+
65
+ parsedSinceCollect = 0;
66
+ // JSC counts the 4 GiB raw transfer buffer as live heap, so on its own it never collects the ASTs a whole repo run leaves behind.
67
+ Bun.gc(true);
68
+ }
69
+
70
+ function currentHandoff(length: number): Handoff {
71
+ handoff ??= initialHandoff();
72
+ if (handoff.kind === "pending" && (handoff.remaining -= length) <= 0)
73
+ handoff = loadRaw(handoff.required);
74
+
75
+ return handoff;
76
+ }
77
+
78
+ function initialHandoff(): Handoff {
79
+ const mode = process.env.STANZA_RAW_TRANSFER;
80
+ if (mode === "0") return { kind: "json" };
81
+ return {
82
+ kind: "pending",
83
+ remaining: mode === "1" ? 0 : RAW_AFTER_LENGTH,
84
+ required: mode === "1",
85
+ };
86
+ }
87
+
88
+ function loadRaw(required: boolean): Handoff {
89
+ try {
90
+ // A bare require is the one lazy load bun build --compile embeds; createRequire and import.meta.require fail at runtime in the binary.
91
+ const { parseRaw } = require("./raw.ts") as typeof import("./raw.ts");
92
+ parseRaw("probe.js", "", javascript[".js"]);
93
+ return { kind: "raw", parseRaw };
94
+ } catch (cause) {
95
+ if (!required) return { kind: "json" };
96
+
97
+ const error = new Error(`STANZA_RAW_TRANSFER=1 but raw transfer is unavailable: ${cause}`, {
98
+ cause,
99
+ });
100
+
101
+ return { kind: "unavailable", error };
102
+ }
103
+ }
104
+
32
105
  function crLineEnding(text: string, program: Program): number | undefined {
33
106
  if (text.search(loneCr) < 0) return undefined;
34
107
 
@@ -0,0 +1,95 @@
1
+ import type { Comment, OxcError, ParserOptions, Program } from "oxc-parser";
2
+ import { getBufferOffset, parseRawSync, rawTransferSupported } from "oxc-parser/src-js/bindings.js";
3
+ import {
4
+ ACTIVE_SIZE,
5
+ BLOCK_ALIGN,
6
+ BLOCK_SIZE,
7
+ BUFFER_SIZE,
8
+ IS_TS_FLAG_POS,
9
+ } from "oxc-parser/src-js/generated/constants.js";
10
+ import { deserializerFiles } from "./deserializers.ts";
11
+ import type { Parsed } from "./parse.ts";
12
+
13
+ interface RawBuffer extends Uint8Array {
14
+ block: Uint8Array;
15
+ int32: Int32Array;
16
+ float64: Float64Array;
17
+ }
18
+
19
+ interface Deserializer {
20
+ deserialize(
21
+ buffer: RawBuffer,
22
+ text: string,
23
+ sourceStartPos: number,
24
+ sourceByteLen: number,
25
+ ): { program: Program; comments: Comment[]; errors: OxcError[] };
26
+ }
27
+
28
+ const ALLOCATION_ATTEMPTS = 8;
29
+ const MAX_SOURCE_BYTES = 1 << 30;
30
+
31
+ if (!rawTransferSupported()) throw new Error("raw transfer needs a 64-bit little-endian platform");
32
+
33
+ // Required by path, not by literal, so a compiled binary does not parse 330 KB of deserializers on every start.
34
+ const files = deserializerFiles();
35
+ const deserializeJs = (require(files.js) as Deserializer).deserialize;
36
+ const deserializeTs = (require(files.ts) as Deserializer).deserialize;
37
+
38
+ const encoder = new TextEncoder();
39
+
40
+ let shared: RawBuffer | undefined;
41
+ export function parseRaw(path: string, text: string, options?: ParserOptions): Parsed {
42
+ shared ??= createBuffer();
43
+
44
+ const { sourceStartPos, sourceByteLen } = writeSource(shared, text);
45
+ parseRawSync(path, shared.block, sourceStartPos, sourceByteLen, options ?? {});
46
+
47
+ const isJs = shared[IS_TS_FLAG_POS] === 0;
48
+ const deserialize = isJs ? deserializeJs : deserializeTs;
49
+ const { program, comments, errors } = deserialize(shared, text, sourceStartPos, sourceByteLen);
50
+ if (isJs && program.hashbang !== null) {
51
+ const { value, start, end } = program.hashbang;
52
+ comments.unshift({ type: "Line", value, start, end });
53
+ }
54
+
55
+ return { program, comments, errors };
56
+ }
57
+
58
+ function writeSource(
59
+ buffer: RawBuffer,
60
+ text: string,
61
+ ): { sourceStartPos: number; sourceByteLen: number } {
62
+ const maxBytes = text.length * 3;
63
+ if (maxBytes > MAX_SOURCE_BYTES) throw new Error("Source text is too long for raw transfer");
64
+
65
+ const sourceStartPos = ACTIVE_SIZE - maxBytes;
66
+ const target = new Uint8Array(buffer.buffer, buffer.byteOffset + sourceStartPos, maxBytes);
67
+ const { read, written } = encoder.encodeInto(text, target);
68
+ if (read !== text.length) throw new Error("Failed to write source text into the raw buffer");
69
+
70
+ return { sourceStartPos, sourceByteLen: written };
71
+ }
72
+
73
+ function createBuffer(): RawBuffer {
74
+ const { arrayBuffer, offset } = allocate();
75
+
76
+ const buffer = new Uint8Array(arrayBuffer, offset, BUFFER_SIZE) as RawBuffer;
77
+ buffer.int32 = new Int32Array(arrayBuffer, offset, BUFFER_SIZE / 4);
78
+ buffer.float64 = new Float64Array(arrayBuffer, offset, BUFFER_SIZE / 8);
79
+ buffer.block = new Uint8Array(arrayBuffer, offset, BLOCK_SIZE);
80
+ return buffer;
81
+ }
82
+
83
+ // Bun caps an ArrayBuffer at 4 GiB, so the aligned block only fits some starts; the live spacer shifts each retry by 2 GiB.
84
+ function allocate(): { arrayBuffer: ArrayBuffer; offset: number } {
85
+ const spacers: ArrayBuffer[] = [];
86
+ for (let attempt = 0; attempt < ALLOCATION_ATTEMPTS; attempt++) {
87
+ const arrayBuffer = new ArrayBuffer(BLOCK_ALIGN);
88
+ const offset = getBufferOffset(new Uint8Array(arrayBuffer));
89
+ if (offset + BLOCK_SIZE <= BLOCK_ALIGN) return { arrayBuffer, offset };
90
+
91
+ spacers.push(new ArrayBuffer(BLOCK_ALIGN / 2));
92
+ }
93
+
94
+ throw new Error("Failed to allocate a raw transfer buffer aligned on 4 GiB");
95
+ }
package/src/launcher CHANGED
@@ -17,5 +17,5 @@ if (!Bun.semver.satisfies(Bun.version, ">=1.4.0")) {
17
17
  process.exit(process.argv[2] === "hook" ? 1 : 2);
18
18
  }
19
19
 
20
- const { main, systemIo } = await import("./cli.ts");
21
- process.exitCode = main(process.argv.slice(2), systemIo());
20
+ const { start } = await import("./start.ts");
21
+ process.exitCode = await start(process.argv.slice(2));
package/src/start.ts ADDED
@@ -0,0 +1,49 @@
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 CHANGED
@@ -88,7 +88,12 @@ export function formatText(path: string, text: Decoded, options: StepOptions): S
88
88
 
89
89
  const changed = options.mode === "fix" && !result.parseError && result.text !== text;
90
90
  if (changed) {
91
- const error = languageOf(path).parse(path, withoutMark(result.text)).error;
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
+
92
97
  if (error)
93
98
  return failure(
94
99
  path,
package/src/usage.ts CHANGED
@@ -1,3 +1,5 @@
1
+ export const bothBraces = "use one of --braces or --no-braces";
2
+
1
3
  export const usage =
2
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 <file>:<line> [--no-braces]\n stanza hook [--braces | --no-braces] [--hunks]";
3
5