walkdiff 0.10.0 → 0.11.0

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/walkdiff.mjs CHANGED
@@ -253,12 +253,8 @@ const GitHostKind = {
253
253
  GitLab: "gitlab"
254
254
  };
255
255
  const commitShaSchema = z.string().regex(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/).brand();
256
- const pullRequestSchema = z.object({
257
- host: z.enum(GitHostKind),
258
- url: z.url(),
259
- /** The repository's web page, for linking to files at a commit. */
260
- repositoryWebUrl: z.url(),
261
- number: z.number().int().positive(),
256
+ /** The commits and branches every change under review has, hosted or not. */
257
+ const changeFields = {
262
258
  title: z.string(),
263
259
  description: z.string(),
264
260
  author: z.string(),
@@ -268,7 +264,32 @@ const pullRequestSchema = z.object({
268
264
  headSha: commitShaSchema,
269
265
  /** The diff is always computed from the merge base, matching what GitHub and GitLab show. */
270
266
  mergeBaseSha: commitShaSchema
267
+ };
268
+ /** A pull request or merge request on its host, where comments and approvals can be posted. */
269
+ const hostedPullRequestSchema = z.object({
270
+ host: z.enum(GitHostKind),
271
+ url: z.url(),
272
+ /** The repository's web page, for linking to files at a commit. */
273
+ repositoryWebUrl: z.url(),
274
+ number: z.number().int().positive(),
275
+ ...changeFields
271
276
  });
277
+ const LOCAL_CHANGE_HOST = "local";
278
+ /**
279
+ * A branch reviewed on its author's machine before it's pushed (`walkdiff review --local`). It
280
+ * has no host, so no link, number or web page to link files to, and nowhere to post a review.
281
+ */
282
+ const localChangeSchema = z.object({
283
+ host: z.literal(LOCAL_CHANGE_HOST),
284
+ /** The folder the repository is in, which names it in the report. */
285
+ repositoryName: z.string(),
286
+ ...changeFields
287
+ });
288
+ /** What's under review: still named for pull requests, which most reviews are. */
289
+ const pullRequestSchema = z.discriminatedUnion("host", [hostedPullRequestSchema, localChangeSchema]);
290
+ function isHostedPullRequest(pullRequest) {
291
+ return pullRequest.host !== LOCAL_CHANGE_HOST;
292
+ }
272
293
  const lineNumberSchema = z.number().int().positive();
273
294
  const DiffLineKind = {
274
295
  Context: "context",
@@ -325,7 +346,9 @@ const SourceLanguage = {
325
346
  Go: "go",
326
347
  Java: "java",
327
348
  C: "c",
328
- Cpp: "cpp"
349
+ Cpp: "cpp",
350
+ Kotlin: "kotlin",
351
+ CSharp: "csharp"
329
352
  };
330
353
  const UnitKind = {
331
354
  Function: "function",
@@ -747,6 +770,9 @@ const reviewModelSchema = z.object({
747
770
  /** Where to send feedback on the tool, from the repository's config. */
748
771
  feedbackUrl: z.url({ protocol: /^https?$/ }).nullable()
749
772
  });
773
+ function isHostedReview(model) {
774
+ return isHostedPullRequest(model.pullRequest);
775
+ }
750
776
  const ReviewStatus = {
751
777
  Queued: "queued",
752
778
  Analyzing: "analyzing",
@@ -889,7 +915,15 @@ function isBehaviourChange(change) {
889
915
  case UnitChangeKind.MovedOut: return false;
890
916
  }
891
917
  }
892
- UnitKind.TestSuite, UnitKind.Test, UnitKind.TestHook;
918
+ const TEST_KINDS = /* @__PURE__ */ new Set([
919
+ UnitKind.TestSuite,
920
+ UnitKind.Test,
921
+ UnitKind.TestHook
922
+ ]);
923
+ /** Suites, tests and their setup, recognised from the test framework's own calls. */
924
+ function isTestKind(kind) {
925
+ return TEST_KINDS.has(kind);
926
+ }
893
927
  /** Places using this unit that the PR did not change. */
894
928
  function untouchedReferences(unit) {
895
929
  if (unit.impact?.status !== UnitImpactStatus.Traced) return [];
@@ -931,6 +965,33 @@ const SECURITY_SCAN_LIMITS = "These checks look for known patterns and secrets o
931
965
  function codeSpan(text) {
932
966
  return `\`${text.replace(/[`\r\n]/g, "")}\``;
933
967
  }
968
+ // packages/review-model/src/testCode.ts
969
+ /**
970
+ * One rule, shared by the engine and the report, for what counts as test code. Checks that judge
971
+ * production code (function metrics, breaking changes, "no tests changed") leave it out, and the
972
+ * review path puts it last.
973
+ */
974
+ const TEST_PATHS = [
975
+ /(^|\/)(tests?|__tests__|specs?|testing)\//i,
976
+ /[._-](test|spec)\.[a-z0-9+]+$/i,
977
+ /(^|\/)test_[^/]+\.py$/,
978
+ /(^|\/)tests?\.rs$/,
979
+ /[a-z0-9]Tests?\.(java|kt|cs|scala|swift)$/
980
+ ];
981
+ const TEST_SCOPE = /(^|::|\.)tests?(::|\.)|(^|::|\.)test_/;
982
+ const TEST_FRAMEWORK_NAME = /^Test(?:[A-Z0-9_]|$)/;
983
+ const CODE_KINDS$1 = /* @__PURE__ */ new Set([
984
+ UnitKind.Function,
985
+ UnitKind.Method,
986
+ UnitKind.Class
987
+ ]);
988
+ function isTestPath(path) {
989
+ return TEST_PATHS.some((pattern) => pattern.test(path));
990
+ }
991
+ /** A test by its kind, from the framework's own calls, or by the names test frameworks collect. */
992
+ function isTestUnit(unit) {
993
+ return isTestKind(unit.kind) || TEST_SCOPE.test(unit.qualifiedName) || CODE_KINDS$1.has(unit.kind) && TEST_FRAMEWORK_NAME.test(unit.qualifiedName);
994
+ }
934
995
  // packages/review-model/src/settings.ts
935
996
  /** The optional checks a person can turn off. Built-in secret and risky API rules aren't among them. */
936
997
  const CheckId = {
@@ -1262,6 +1323,12 @@ z.object({
1262
1323
  /** The report these counts come from. After a refresh, the list can't trust them until the new report is opened. */
1263
1324
  head: reportHeadSchema
1264
1325
  }).refine((progress) => progress.reviewed <= progress.total);
1326
+ // packages/review-model/src/logging.ts
1327
+ const LogLevel = {
1328
+ Info: "info",
1329
+ Warn: "warn",
1330
+ Error: "error"
1331
+ };
1265
1332
  // packages/engine/src/blobs.ts
1266
1333
  const NEWLINE = 10;
1267
1334
  /**
@@ -1738,17 +1805,18 @@ const MAX_CALLEE_TEXT = 40;
1738
1805
  const LAST_SEGMENT = /[\p{L}\p{N}_$]+$/u;
1739
1806
  const RECEIVER_PARAMETER = /\b(self|cls)$|^this$/;
1740
1807
  const NO_PARAMETERS = "void";
1808
+ const UNNAMED_PARAMETER = "parameter";
1741
1809
  function extractShape(grammar, definition) {
1742
1810
  const fn = grammar.functionNode(definition);
1743
1811
  const calls = callNames(grammar, fn);
1744
1812
  const bailOuts = calls.list.filter((name) => grammar.errorCalls.has(name)).length;
1745
- const slots = parameterNodesOf(grammar.signatureNode(fn)).flatMap(parameterSlots);
1813
+ const slots = grammar.parameters(fn).flatMap(parameterSlots);
1746
1814
  const parameters = new Map(slots.map((slot) => [slot.name, slot.text]));
1747
1815
  const branches = fn.descendantsOfType([...grammar.branchTypes]).length;
1748
1816
  return {
1749
1817
  parameters,
1750
1818
  signature: slots.map((slot) => signatureParameter(grammar, slot)),
1751
- returnType: typeText(fn.childForFieldName(grammar.returnTypeField)),
1819
+ returnType: typeText(grammar.returnType(fn)),
1752
1820
  calls: new Set(calls.list),
1753
1821
  errorPaths: fn.descendantsOfType([...grammar.errorTypes]).length + bailOuts,
1754
1822
  branches,
@@ -1797,11 +1865,16 @@ function factsBetween(before, after) {
1797
1865
  };
1798
1866
  return facts.parametersAdded.length + facts.parametersRemoved.length + facts.parametersChanged.length + facts.callsAdded.length + facts.callsRemoved.length > 0 || facts.returnType !== null || facts.complexity !== null || facts.errorPathsDelta !== 0 || facts.branchesDelta !== 0 ? facts : null;
1799
1867
  }
1800
- function parameterNodesOf(fn) {
1868
+ /** The parameters in the function's `parameters` field, or the single `parameter` of `x => x + 1`. */
1869
+ function parametersByField(fn) {
1801
1870
  const list = fn.childForFieldName("parameters");
1802
1871
  const single = fn.childForFieldName("parameter");
1803
1872
  return (list === null ? single === null ? [] : [single] : list.namedChildren).filter((node) => node !== null && !node.type.includes("comment") && node.text !== NO_PARAMETERS);
1804
1873
  }
1874
+ /** Reads the return type from a field of the function's node. */
1875
+ function returnTypeByField(field) {
1876
+ return (fn) => fn.childForFieldName(field);
1877
+ }
1805
1878
  function parameterSlots(node) {
1806
1879
  const names = node.childrenForFieldName("name").filter((name) => name !== null);
1807
1880
  if (names.length < 2) return [{
@@ -1830,7 +1903,8 @@ function typeText(node) {
1830
1903
  function parameterName(node) {
1831
1904
  const named = node.childForFieldName("pattern") ?? node.childForFieldName("name") ?? declaratorName(node) ?? declaredName(node)?.nameNode ?? null;
1832
1905
  if (named !== null) return named.text;
1833
- return node.type.includes("typed") ? node.firstNamedChild?.text ?? node.text : node.text;
1906
+ if (!node.type.includes("typed") && node.type !== UNNAMED_PARAMETER) return node.text;
1907
+ return node.namedChildren.find((child) => child?.type === "identifier")?.text ?? node.firstNamedChild?.text ?? node.text;
1834
1908
  }
1835
1909
  function declaratorName(node) {
1836
1910
  return node.namedChildren.find((child) => child?.type === "variable_declarator")?.childForFieldName("name") ?? null;
@@ -1838,11 +1912,14 @@ function declaratorName(node) {
1838
1912
  function callNames(grammar, fn) {
1839
1913
  return { list: fn.descendantsOfType([...grammar.calls.keys()]).flatMap((call) => {
1840
1914
  const syntax = call === null ? void 0 : grammar.calls.get(call.type);
1841
- const callee = syntax === void 0 ? null : call?.childForFieldName(syntax.calleeField) ?? null;
1915
+ const callee = syntax === void 0 || call === null ? null : calleeOf(call, syntax);
1842
1916
  const name = callee === null ? void 0 : calleeName(callee);
1843
1917
  return syntax === void 0 || name === void 0 ? [] : [`${name}${syntax.suffix}`];
1844
1918
  }) };
1845
1919
  }
1920
+ function calleeOf(call, syntax) {
1921
+ return syntax.calleeField === void 0 ? call.firstNamedChild : call.childForFieldName(syntax.calleeField);
1922
+ }
1846
1923
  function calleeName(callee) {
1847
1924
  const text = callee.text.replace(/\s+/g, "");
1848
1925
  if (text.length <= MAX_CALLEE_TEXT && !text.includes("(")) return text;
@@ -2082,12 +2159,12 @@ const KIND_BY_SPECIFIER = /* @__PURE__ */ new Map([
2082
2159
  ["enum_specifier", UnitKind.Enum]
2083
2160
  ]);
2084
2161
  const CLASS_KINDS = /* @__PURE__ */ new Set([UnitKind.Class, UnitKind.Struct]);
2085
- const CONTAINERS$5 = /* @__PURE__ */ new Set([
2162
+ const CONTAINERS$7 = /* @__PURE__ */ new Set([
2086
2163
  UnitKind.Module,
2087
2164
  UnitKind.Class,
2088
2165
  UnitKind.Struct
2089
2166
  ]);
2090
- const OPAQUE_NODE_TYPES$2 = /* @__PURE__ */ new Set([
2167
+ const OPAQUE_NODE_TYPES$4 = /* @__PURE__ */ new Set([
2091
2168
  "compound_statement",
2092
2169
  "lambda_expression",
2093
2170
  "friend_declaration"
@@ -2121,8 +2198,8 @@ const TEST_MACROS = /* @__PURE__ */ new Set([
2121
2198
  const TEMPLATE_TYPE = "template_type";
2122
2199
  const MAX_SPECIALIZATION_NAME = 60;
2123
2200
  const ELLIPSIS = "…";
2124
- const IMPLICITLY_INVOKED$1 = /^(?:main$|operator\b|~)/;
2125
- const IDENTIFIER_GRAMMAR$5 = {
2201
+ const IMPLICITLY_INVOKED$3 = /^(?:main$|operator\b|~)/;
2202
+ const IDENTIFIER_GRAMMAR$7 = {
2126
2203
  member: /* @__PURE__ */ new Map([["field_expression", ["field", "argument"]]]),
2127
2204
  path: /* @__PURE__ */ new Map([["qualified_identifier", ["name", "scope"]]]),
2128
2205
  nameIsUse: /* @__PURE__ */ new Set(),
@@ -2139,7 +2216,7 @@ const IDENTIFIER_GRAMMAR$5 = {
2139
2216
  ["for_range_loop", "declarator"]
2140
2217
  ])
2141
2218
  };
2142
- function describe$4(node, container) {
2219
+ function describe$6(node, container) {
2143
2220
  switch (node.type) {
2144
2221
  case "function_definition": return describeFunctionDefinition(node, container);
2145
2222
  case "declaration":
@@ -2155,7 +2232,7 @@ function describe$4(node, container) {
2155
2232
  function describeFunctionDefinition(node, container) {
2156
2233
  const declared = declaredName(node);
2157
2234
  const call = declared?.functionDeclarator;
2158
- if (!(declared !== void 0 && call !== void 0 && node.childForFieldName("type") === null && MACRO_NAME.test(declared.name))) return describeFunction(declared, container);
2235
+ if (!(declared !== void 0 && call !== void 0 && node.childForFieldName("type") === null && MACRO_NAME.test(declared.name))) return describeFunction$1(declared, container);
2159
2236
  if (container !== void 0 && CLASS_KINDS.has(container.kind) && !isConstructorOf(container, declared.name)) return void 0;
2160
2237
  return {
2161
2238
  kind: TEST_MACROS.has(declared.name) ? UnitKind.Test : UnitKind.Function,
@@ -2166,7 +2243,7 @@ function describeFunctionDefinition(node, container) {
2166
2243
  function isConstructorOf(container, name) {
2167
2244
  return container.childPrefix === name || container.childPrefix.endsWith(`::${name}`);
2168
2245
  }
2169
- function describeFunction(declared, container) {
2246
+ function describeFunction$1(declared, container) {
2170
2247
  if (declared === void 0) return void 0;
2171
2248
  const header = {
2172
2249
  kind: declared.owner !== void 0 || container !== void 0 && CLASS_KINDS.has(container.kind) ? UnitKind.Method : UnitKind.Function,
@@ -2180,7 +2257,7 @@ function describeFunction(declared, container) {
2180
2257
  }
2181
2258
  function describeDeclaration(node, container) {
2182
2259
  const declared = declaredName(node);
2183
- if (declared?.functionDeclarator !== void 0) return describeFunction(declared, container);
2260
+ if (declared?.functionDeclarator !== void 0) return describeFunction$1(declared, container);
2184
2261
  const isFileScope = container === void 0 || container.kind === UnitKind.Module;
2185
2262
  const declaresOneVariable = node.type === "declaration" && node.childrenForFieldName("declarator").length === 1;
2186
2263
  return declared === void 0 || !isFileScope || !declaresOneVariable ? void 0 : {
@@ -2251,11 +2328,11 @@ function isInAnonymousNamespace(node) {
2251
2328
  for (let ancestor = node.parent; ancestor !== null; ancestor = ancestor.parent) if (ancestor.type === NAMESPACE && ancestor.childForFieldName("name") === null) return true;
2252
2329
  return false;
2253
2330
  }
2254
- function classifyIdentifier(leaf) {
2331
+ function classifyIdentifier$1(leaf) {
2255
2332
  if (declaresName(leaf)) return void 0;
2256
2333
  const parent = leaf.parent;
2257
2334
  if (parent !== null && KIND_BY_SPECIFIER.has(parent.type) && parent.childForFieldName("body") === null) return BARE_USE;
2258
- return classifyWithGrammar(leaf, IDENTIFIER_GRAMMAR$5);
2335
+ return classifyWithGrammar(leaf, IDENTIFIER_GRAMMAR$7);
2259
2336
  }
2260
2337
  function declaresName(leaf) {
2261
2338
  let name = leaf;
@@ -2263,7 +2340,7 @@ function declaresName(leaf) {
2263
2340
  const parent = name.parent;
2264
2341
  return parent !== null && DECLARING_PARENTS.has(parent.type) && parent.childForFieldName("declarator")?.id === name.id;
2265
2342
  }
2266
- function parameterKind$4(parameter) {
2343
+ function parameterKind$6(parameter) {
2267
2344
  if (parameter.type === "variadic_parameter" || parameter.type === "variadic_parameter_declaration") return ParameterKind.Rest;
2268
2345
  return parameter.type === "optional_parameter_declaration" ? ParameterKind.Optional : ParameterKind.Required;
2269
2346
  }
@@ -2272,11 +2349,11 @@ function makeSpec$1(language, grammar) {
2272
2349
  language,
2273
2350
  grammar,
2274
2351
  separator: "::",
2275
- describe: describe$4,
2352
+ describe: describe$6,
2276
2353
  outerNode: outerNode$2,
2277
2354
  isAttachedPrefix: () => false,
2278
- isContainer: (kind) => CONTAINERS$5.has(kind),
2279
- isOpaque: (node) => OPAQUE_NODE_TYPES$2.has(node.type),
2355
+ isContainer: (kind) => CONTAINERS$7.has(kind),
2356
+ isOpaque: (node) => OPAQUE_NODE_TYPES$4.has(node.type),
2280
2357
  childPrefix: (_header, _node, qualifiedName) => qualifiedName,
2281
2358
  normalizeLeaf: (leaf) => leaf.text,
2282
2359
  publicDefinitions: () => isPublicDefinition,
@@ -2286,17 +2363,17 @@ function makeSpec$1(language, grammar) {
2286
2363
  "type_identifier",
2287
2364
  "namespace_identifier"
2288
2365
  ]),
2289
- classifyIdentifier,
2366
+ classifyIdentifier: classifyIdentifier$1,
2290
2367
  selfReceivers: /* @__PURE__ */ new Set(["this"]),
2291
2368
  callsMembersByBareName: true,
2292
2369
  functionScopeTypes: /* @__PURE__ */ new Set(["function_definition", "lambda_expression"]),
2293
- isBindingSite: (leaf) => isBindingWithGrammar(leaf, IDENTIFIER_GRAMMAR$5),
2294
- isImplicitlyInvoked: (methodName) => IMPLICITLY_INVOKED$1.test(methodName),
2370
+ isBindingSite: (leaf) => isBindingWithGrammar(leaf, IDENTIFIER_GRAMMAR$7),
2371
+ isImplicitlyInvoked: (methodName) => IMPLICITLY_INVOKED$3.test(methodName),
2295
2372
  shape: {
2296
2373
  functionNode: (definition) => definition,
2297
- signatureNode: (fn) => declaredName(fn)?.functionDeclarator ?? fn,
2298
- returnTypeField: "type",
2299
- parameterKind: parameterKind$4,
2374
+ parameters: (fn) => parametersByField(declaredName(fn)?.functionDeclarator ?? fn),
2375
+ returnType: returnTypeByField("type"),
2376
+ parameterKind: parameterKind$6,
2300
2377
  calls: /* @__PURE__ */ new Map([["call_expression", {
2301
2378
  calleeField: "function",
2302
2379
  suffix: ""
@@ -2346,6 +2423,164 @@ function makeSpec$1(language, grammar) {
2346
2423
  }
2347
2424
  const cSpec = makeSpec$1(SourceLanguage.C, "tree-sitter-c/tree-sitter-c.wasm");
2348
2425
  const cppSpec = makeSpec$1(SourceLanguage.Cpp, "tree-sitter-cpp/tree-sitter-cpp.wasm");
2426
+ // packages/engine/src/syntax/csharp.ts
2427
+ const KIND_BY_NODE_TYPE$3 = /* @__PURE__ */ new Map([
2428
+ ["class_declaration", UnitKind.Class],
2429
+ ["record_declaration", UnitKind.Class],
2430
+ ["struct_declaration", UnitKind.Struct],
2431
+ ["interface_declaration", UnitKind.Interface],
2432
+ ["enum_declaration", UnitKind.Enum],
2433
+ ["method_declaration", UnitKind.Method],
2434
+ ["constructor_declaration", UnitKind.Method],
2435
+ ["delegate_declaration", UnitKind.TypeAlias],
2436
+ ["namespace_declaration", UnitKind.Module]
2437
+ ]);
2438
+ const CONTAINERS$6 = /* @__PURE__ */ new Set([
2439
+ UnitKind.Module,
2440
+ UnitKind.Class,
2441
+ UnitKind.Struct,
2442
+ UnitKind.Interface
2443
+ ]);
2444
+ const OPAQUE_NODE_TYPES$3 = /* @__PURE__ */ new Set([
2445
+ "lambda_expression",
2446
+ "anonymous_method_expression",
2447
+ "anonymous_object_creation_expression",
2448
+ "block",
2449
+ "arrow_expression_clause"
2450
+ ]);
2451
+ const FILE_SCOPED_NAMESPACE = "file_scoped_namespace_declaration";
2452
+ const DESTRUCTOR_PREFIX = "~";
2453
+ const PUBLIC_MODIFIER$1 = "public";
2454
+ const PRIVATE_MODIFIER$1 = "private";
2455
+ const IMPLICITLY_PUBLIC_CONTAINERS$1 = /* @__PURE__ */ new Set([UnitKind.Interface]);
2456
+ const RECEIVER_MODIFIER = "this";
2457
+ const IMPLICITLY_INVOKED$2 = /* @__PURE__ */ new Set([
2458
+ "ToString",
2459
+ "Equals",
2460
+ "GetHashCode",
2461
+ "Dispose",
2462
+ "DisposeAsync",
2463
+ "Main",
2464
+ "CompareTo",
2465
+ "GetEnumerator"
2466
+ ]);
2467
+ const IDENTIFIER_GRAMMAR$6 = {
2468
+ member: /* @__PURE__ */ new Map([["member_access_expression", ["name", "expression"]]]),
2469
+ path: /* @__PURE__ */ new Map([["qualified_name", ["name", "qualifier"]]]),
2470
+ nameIsUse: /* @__PURE__ */ new Set(),
2471
+ labels: /* @__PURE__ */ new Map(),
2472
+ bindings: /* @__PURE__ */ new Map([
2473
+ ["parameter", "name"],
2474
+ ["variable_declarator", "name"],
2475
+ ["foreach_statement", "left"],
2476
+ ["catch_declaration", "name"],
2477
+ ["lambda_expression", "parameters"]
2478
+ ])
2479
+ };
2480
+ function describe$5(node) {
2481
+ if (node.type === "destructor_declaration") {
2482
+ const nameNode = node.childForFieldName("name");
2483
+ return nameNode === null ? void 0 : {
2484
+ kind: UnitKind.Method,
2485
+ name: `${DESTRUCTOR_PREFIX}${nameNode.text}`,
2486
+ nameNode
2487
+ };
2488
+ }
2489
+ const kind = KIND_BY_NODE_TYPE$3.get(node.type);
2490
+ const header = kind === void 0 ? void 0 : namedDefinition(node, kind);
2491
+ const fileNamespace = fileScopedNamespaceOf(node);
2492
+ return header === void 0 || fileNamespace === void 0 ? header : {
2493
+ ...header,
2494
+ owner: fileNamespace
2495
+ };
2496
+ }
2497
+ function fileScopedNamespaceOf(node) {
2498
+ if (node.parent?.type !== "compilation_unit") return void 0;
2499
+ for (let sibling = node.previousNamedSibling; sibling !== null; sibling = sibling.previousNamedSibling) if (sibling.type === FILE_SCOPED_NAMESPACE) return sibling.childForFieldName("name")?.text;
2500
+ }
2501
+ function modifierWords$2(node) {
2502
+ return new Set(node.namedChildren.filter((child) => child?.type === "modifier").map((child) => child?.text ?? ""));
2503
+ }
2504
+ function isPublicMember$2(node, _name, container) {
2505
+ if (node.type === "namespace_declaration") return true;
2506
+ const words = modifierWords$2(node);
2507
+ if (container !== void 0 && IMPLICITLY_PUBLIC_CONTAINERS$1.has(container.kind)) return !words.has(PRIVATE_MODIFIER$1);
2508
+ return words.has(PUBLIC_MODIFIER$1);
2509
+ }
2510
+ function parametersOf$1(fn) {
2511
+ const list = fn.childForFieldName("parameters");
2512
+ if (list === null) return [];
2513
+ return list.namedChildren.filter((child) => child !== null && (child.type === "parameter" || list.childForFieldName("name")?.id === child.id));
2514
+ }
2515
+ function parameterKind$5(parameter) {
2516
+ if (parameter.type !== "parameter") return ParameterKind.Rest;
2517
+ if (parameter.namedChildren.some((child) => child?.type === "modifier" && child.text === RECEIVER_MODIFIER)) return ParameterKind.Receiver;
2518
+ return parameter.children.some((child) => child?.type === "=") ? ParameterKind.Optional : ParameterKind.Required;
2519
+ }
2520
+ const csharpSpec = {
2521
+ language: SourceLanguage.CSharp,
2522
+ grammar: "tree-sitter-c-sharp/tree-sitter-c_sharp.wasm",
2523
+ separator: ".",
2524
+ describe: describe$5,
2525
+ outerNode: (node) => node,
2526
+ isAttachedPrefix: () => false,
2527
+ isContainer: (kind) => CONTAINERS$6.has(kind),
2528
+ isOpaque: (node) => OPAQUE_NODE_TYPES$3.has(node.type),
2529
+ childPrefix: (_header, _node, qualifiedName) => qualifiedName,
2530
+ normalizeLeaf: (leaf) => leaf.text,
2531
+ publicDefinitions: () => isPublicMember$2,
2532
+ identifierTypes: /* @__PURE__ */ new Set(["identifier"]),
2533
+ classifyIdentifier: (leaf) => classifyWithGrammar(leaf, IDENTIFIER_GRAMMAR$6),
2534
+ selfReceivers: /* @__PURE__ */ new Set(["this"]),
2535
+ callsMembersByBareName: true,
2536
+ functionScopeTypes: /* @__PURE__ */ new Set([
2537
+ "method_declaration",
2538
+ "constructor_declaration",
2539
+ "local_function_statement",
2540
+ "lambda_expression",
2541
+ "anonymous_method_expression"
2542
+ ]),
2543
+ isBindingSite: (leaf) => isBindingWithGrammar(leaf, IDENTIFIER_GRAMMAR$6),
2544
+ isImplicitlyInvoked: (methodName) => IMPLICITLY_INVOKED$2.has(methodName),
2545
+ shape: {
2546
+ functionNode: (definition) => definition,
2547
+ parameters: parametersOf$1,
2548
+ returnType: returnTypeByField("returns"),
2549
+ parameterKind: parameterKind$5,
2550
+ calls: /* @__PURE__ */ new Map([["invocation_expression", {
2551
+ calleeField: "function",
2552
+ suffix: ""
2553
+ }], ["object_creation_expression", {
2554
+ calleeField: "type",
2555
+ suffix: ""
2556
+ }]]),
2557
+ errorCalls: /* @__PURE__ */ new Set(["Environment.Exit", "Environment.FailFast"]),
2558
+ errorTypes: ["throw_statement", "throw_expression"],
2559
+ branchTypes: [
2560
+ "if_statement",
2561
+ "for_statement",
2562
+ "foreach_statement",
2563
+ "while_statement",
2564
+ "do_statement",
2565
+ "switch_section",
2566
+ "switch_expression_arm",
2567
+ "catch_clause",
2568
+ "conditional_expression"
2569
+ ],
2570
+ nestingTypes: [
2571
+ "if_statement",
2572
+ "for_statement",
2573
+ "foreach_statement",
2574
+ "while_statement",
2575
+ "do_statement",
2576
+ "switch_statement",
2577
+ "switch_expression",
2578
+ "try_statement"
2579
+ ],
2580
+ logicalTypes: ["binary_expression"],
2581
+ logicalOperators: /* @__PURE__ */ new Set(["&&", "||"])
2582
+ }
2583
+ };
2349
2584
  // packages/engine/src/syntax/go.ts
2350
2585
  const KIND_BY_TYPE_NODE = /* @__PURE__ */ new Map([["struct_type", UnitKind.Struct], ["interface_type", UnitKind.Interface]]);
2351
2586
  const GROUPED_DECLARATIONS = /* @__PURE__ */ new Set([
@@ -2354,10 +2589,10 @@ const GROUPED_DECLARATIONS = /* @__PURE__ */ new Set([
2354
2589
  "var_declaration"
2355
2590
  ]);
2356
2591
  const VALUE_SPECS = /* @__PURE__ */ new Set(["const_spec", "var_spec"]);
2357
- const CONTAINERS$4 = /* @__PURE__ */ new Set([UnitKind.Interface]);
2592
+ const CONTAINERS$5 = /* @__PURE__ */ new Set([UnitKind.Interface]);
2358
2593
  const PROGRAM_PACKAGE = "main";
2359
2594
  const EXPORTED_NAME = /^\p{Lu}/u;
2360
- const IDENTIFIER_GRAMMAR$4 = {
2595
+ const IDENTIFIER_GRAMMAR$5 = {
2361
2596
  member: /* @__PURE__ */ new Map([["selector_expression", ["field", "operand"]]]),
2362
2597
  path: /* @__PURE__ */ new Map([["qualified_type", ["name", "package"]]]),
2363
2598
  nameIsUse: /* @__PURE__ */ new Set(),
@@ -2369,7 +2604,7 @@ const IDENTIFIER_GRAMMAR$4 = {
2369
2604
  ["const_spec", "name"]
2370
2605
  ])
2371
2606
  };
2372
- function describe$3(node, container) {
2607
+ function describe$4(node, container) {
2373
2608
  switch (node.type) {
2374
2609
  case "function_declaration": return namedDefinition(node, UnitKind.Function);
2375
2610
  case "method_declaration": return describeMethod(node);
@@ -2414,17 +2649,17 @@ function publicDefinitions$1(root) {
2414
2649
  return EXPORTED_NAME.test(name) && (owner === void 0 || EXPORTED_NAME.test(owner));
2415
2650
  };
2416
2651
  }
2417
- function parameterKind$3(parameter) {
2652
+ function parameterKind$4(parameter) {
2418
2653
  return parameter.type === "variadic_parameter_declaration" ? ParameterKind.Rest : ParameterKind.Required;
2419
2654
  }
2420
2655
  const goSpec = {
2421
2656
  language: SourceLanguage.Go,
2422
2657
  grammar: "tree-sitter-go/tree-sitter-go.wasm",
2423
2658
  separator: ".",
2424
- describe: describe$3,
2659
+ describe: describe$4,
2425
2660
  outerNode: outerNode$1,
2426
2661
  isAttachedPrefix: () => false,
2427
- isContainer: (kind) => CONTAINERS$4.has(kind),
2662
+ isContainer: (kind) => CONTAINERS$5.has(kind),
2428
2663
  isOpaque: (node) => node.type === "func_literal" || node.type === "block",
2429
2664
  childPrefix: (_header, _node, qualifiedName) => qualifiedName,
2430
2665
  normalizeLeaf: (leaf) => leaf.text,
@@ -2434,7 +2669,7 @@ const goSpec = {
2434
2669
  "field_identifier",
2435
2670
  "type_identifier"
2436
2671
  ]),
2437
- classifyIdentifier: (leaf) => classifyWithGrammar(leaf, IDENTIFIER_GRAMMAR$4),
2672
+ classifyIdentifier: (leaf) => classifyWithGrammar(leaf, IDENTIFIER_GRAMMAR$5),
2438
2673
  selfReceivers: /* @__PURE__ */ new Set(),
2439
2674
  callsMembersByBareName: false,
2440
2675
  functionScopeTypes: /* @__PURE__ */ new Set([
@@ -2442,13 +2677,13 @@ const goSpec = {
2442
2677
  "method_declaration",
2443
2678
  "func_literal"
2444
2679
  ]),
2445
- isBindingSite: (leaf) => isBindingWithGrammar(leaf, IDENTIFIER_GRAMMAR$4),
2680
+ isBindingSite: (leaf) => isBindingWithGrammar(leaf, IDENTIFIER_GRAMMAR$5),
2446
2681
  isImplicitlyInvoked: () => false,
2447
2682
  shape: {
2448
2683
  functionNode: (definition) => definition,
2449
- signatureNode: (fn) => fn,
2450
- returnTypeField: "result",
2451
- parameterKind: parameterKind$3,
2684
+ parameters: parametersByField,
2685
+ returnType: returnTypeByField("result"),
2686
+ parameterKind: parameterKind$4,
2452
2687
  calls: /* @__PURE__ */ new Map([["call_expression", {
2453
2688
  calleeField: "function",
2454
2689
  suffix: ""
@@ -2493,12 +2728,12 @@ const KIND_BY_NODE_TYPE$2 = /* @__PURE__ */ new Map([
2493
2728
  ["compact_constructor_declaration", UnitKind.Method],
2494
2729
  ["annotation_type_element_declaration", UnitKind.Method]
2495
2730
  ]);
2496
- const CONTAINERS$3 = /* @__PURE__ */ new Set([
2731
+ const CONTAINERS$4 = /* @__PURE__ */ new Set([
2497
2732
  UnitKind.Class,
2498
2733
  UnitKind.Interface,
2499
2734
  UnitKind.Enum
2500
2735
  ]);
2501
- const OPAQUE_NODE_TYPES$1 = /* @__PURE__ */ new Set([
2736
+ const OPAQUE_NODE_TYPES$2 = /* @__PURE__ */ new Set([
2502
2737
  "object_creation_expression",
2503
2738
  "lambda_expression",
2504
2739
  "enum_constant",
@@ -2507,7 +2742,7 @@ const OPAQUE_NODE_TYPES$1 = /* @__PURE__ */ new Set([
2507
2742
  const PUBLIC_MODIFIER = "public";
2508
2743
  const PRIVATE_MODIFIER = "private";
2509
2744
  const IMPLICITLY_PUBLIC_CONTAINERS = /* @__PURE__ */ new Set([UnitKind.Interface]);
2510
- const IMPLICITLY_INVOKED = /* @__PURE__ */ new Set([
2745
+ const IMPLICITLY_INVOKED$1 = /* @__PURE__ */ new Set([
2511
2746
  "toString",
2512
2747
  "equals",
2513
2748
  "hashCode",
@@ -2516,7 +2751,7 @@ const IMPLICITLY_INVOKED = /* @__PURE__ */ new Set([
2516
2751
  "main",
2517
2752
  "finalize"
2518
2753
  ]);
2519
- const IDENTIFIER_GRAMMAR$3 = {
2754
+ const IDENTIFIER_GRAMMAR$4 = {
2520
2755
  member: /* @__PURE__ */ new Map([
2521
2756
  ["method_invocation", ["name", "object"]],
2522
2757
  ["field_access", ["field", "object"]],
@@ -2534,20 +2769,20 @@ const IDENTIFIER_GRAMMAR$3 = {
2534
2769
  ["lambda_expression", "parameters"]
2535
2770
  ])
2536
2771
  };
2537
- function describe$2(node) {
2772
+ function describe$3(node) {
2538
2773
  const kind = KIND_BY_NODE_TYPE$2.get(node.type);
2539
2774
  return kind === void 0 ? void 0 : namedDefinition(node, kind);
2540
2775
  }
2541
- function modifierWords(node) {
2776
+ function modifierWords$1(node) {
2542
2777
  const modifiers = node.namedChildren.find((child) => child?.type === "modifiers");
2543
2778
  return new Set(modifiers?.children.filter((child) => child !== null && !child.isNamed).map((child) => child?.text ?? "") ?? []);
2544
2779
  }
2545
2780
  function isPublicMember$1(node, _name, container) {
2546
- const words = modifierWords(node);
2781
+ const words = modifierWords$1(node);
2547
2782
  if (container !== void 0 && IMPLICITLY_PUBLIC_CONTAINERS.has(container.kind)) return !words.has(PRIVATE_MODIFIER);
2548
2783
  return words.has(PUBLIC_MODIFIER);
2549
2784
  }
2550
- function parameterKind$2(parameter) {
2785
+ function parameterKind$3(parameter) {
2551
2786
  if (parameter.type === "spread_parameter") return ParameterKind.Rest;
2552
2787
  return parameter.type === "receiver_parameter" ? ParameterKind.Receiver : ParameterKind.Required;
2553
2788
  }
@@ -2555,16 +2790,16 @@ const javaSpec = {
2555
2790
  language: SourceLanguage.Java,
2556
2791
  grammar: "tree-sitter-java/tree-sitter-java.wasm",
2557
2792
  separator: ".",
2558
- describe: describe$2,
2793
+ describe: describe$3,
2559
2794
  outerNode: (node) => node,
2560
2795
  isAttachedPrefix: () => false,
2561
- isContainer: (kind) => CONTAINERS$3.has(kind),
2562
- isOpaque: (node) => OPAQUE_NODE_TYPES$1.has(node.type),
2796
+ isContainer: (kind) => CONTAINERS$4.has(kind),
2797
+ isOpaque: (node) => OPAQUE_NODE_TYPES$2.has(node.type),
2563
2798
  childPrefix: (_header, _node, qualifiedName) => qualifiedName,
2564
2799
  normalizeLeaf: (leaf) => leaf.text,
2565
2800
  publicDefinitions: () => isPublicMember$1,
2566
2801
  identifierTypes: /* @__PURE__ */ new Set(["identifier", "type_identifier"]),
2567
- classifyIdentifier: (leaf) => classifyWithGrammar(leaf, IDENTIFIER_GRAMMAR$3),
2802
+ classifyIdentifier: (leaf) => classifyWithGrammar(leaf, IDENTIFIER_GRAMMAR$4),
2568
2803
  selfReceivers: /* @__PURE__ */ new Set(["this"]),
2569
2804
  callsMembersByBareName: true,
2570
2805
  functionScopeTypes: /* @__PURE__ */ new Set([
@@ -2573,13 +2808,13 @@ const javaSpec = {
2573
2808
  "compact_constructor_declaration",
2574
2809
  "lambda_expression"
2575
2810
  ]),
2576
- isBindingSite: (leaf) => isBindingWithGrammar(leaf, IDENTIFIER_GRAMMAR$3),
2577
- isImplicitlyInvoked: (methodName) => IMPLICITLY_INVOKED.has(methodName),
2811
+ isBindingSite: (leaf) => isBindingWithGrammar(leaf, IDENTIFIER_GRAMMAR$4),
2812
+ isImplicitlyInvoked: (methodName) => IMPLICITLY_INVOKED$1.has(methodName),
2578
2813
  shape: {
2579
2814
  functionNode: (definition) => definition,
2580
- signatureNode: (fn) => fn,
2581
- returnTypeField: "type",
2582
- parameterKind: parameterKind$2,
2815
+ parameters: parametersByField,
2816
+ returnType: returnTypeByField("type"),
2817
+ parameterKind: parameterKind$3,
2583
2818
  calls: /* @__PURE__ */ new Map([["method_invocation", {
2584
2819
  calleeField: "name",
2585
2820
  suffix: ""
@@ -2613,6 +2848,190 @@ const javaSpec = {
2613
2848
  logicalOperators: /* @__PURE__ */ new Set(["&&", "||"])
2614
2849
  }
2615
2850
  };
2851
+ // packages/engine/src/syntax/kotlin.ts
2852
+ const CONTAINERS$3 = /* @__PURE__ */ new Set([
2853
+ UnitKind.Class,
2854
+ UnitKind.Interface,
2855
+ UnitKind.Enum
2856
+ ]);
2857
+ const OPAQUE_NODE_TYPES$1 = /* @__PURE__ */ new Set([
2858
+ "lambda_literal",
2859
+ "anonymous_function",
2860
+ "object_literal",
2861
+ "enum_entry",
2862
+ "function_body"
2863
+ ]);
2864
+ const INTERFACE_KEYWORD = "interface";
2865
+ const ENUM_MODIFIER = "enum";
2866
+ const HIDDEN_VISIBILITIES = /* @__PURE__ */ new Set([
2867
+ "private",
2868
+ "internal",
2869
+ "protected"
2870
+ ]);
2871
+ const COMPANION_NAME = "Companion";
2872
+ const PARAMETER_LIST = "function_value_parameters";
2873
+ const VARARG = "vararg";
2874
+ const TYPE_NODES = /* @__PURE__ */ new Set([
2875
+ "user_type",
2876
+ "nullable_type",
2877
+ "function_type",
2878
+ "parenthesized_type"
2879
+ ]);
2880
+ const IMPLICITLY_INVOKED = /* @__PURE__ */ new Set([
2881
+ "toString",
2882
+ "equals",
2883
+ "hashCode",
2884
+ "main",
2885
+ "compareTo",
2886
+ "close",
2887
+ "invoke"
2888
+ ]);
2889
+ const IDENTIFIER_GRAMMAR$3 = {
2890
+ member: /* @__PURE__ */ new Map(),
2891
+ path: /* @__PURE__ */ new Map(),
2892
+ nameIsUse: /* @__PURE__ */ new Set(),
2893
+ labels: /* @__PURE__ */ new Map([["type_alias", "type"]]),
2894
+ bindings: /* @__PURE__ */ new Map([
2895
+ ["parameter", null],
2896
+ ["class_parameter", null],
2897
+ ["variable_declaration", null],
2898
+ ["catch_block", null]
2899
+ ])
2900
+ };
2901
+ function describe$2(node, container) {
2902
+ switch (node.type) {
2903
+ case "class_declaration": return namedDefinition(node, classKind(node));
2904
+ case "object_declaration": return namedDefinition(node, UnitKind.Class);
2905
+ case "companion_object": return namedDefinition(node, UnitKind.Class) ?? {
2906
+ kind: UnitKind.Class,
2907
+ name: COMPANION_NAME,
2908
+ nameNode: null
2909
+ };
2910
+ case "function_declaration": return describeFunction(node, container);
2911
+ case "secondary_constructor": return {
2912
+ kind: UnitKind.Method,
2913
+ name: "constructor",
2914
+ nameNode: null
2915
+ };
2916
+ case "type_alias": {
2917
+ const nameNode = node.childForFieldName("type");
2918
+ return nameNode === null ? void 0 : {
2919
+ kind: UnitKind.TypeAlias,
2920
+ name: nameNode.text,
2921
+ nameNode
2922
+ };
2923
+ }
2924
+ case "property_declaration": return container === void 0 ? describeTopLevelProperty(node) : void 0;
2925
+ default: return;
2926
+ }
2927
+ }
2928
+ function classKind(node) {
2929
+ if (node.children.some((child) => child !== null && !child.isNamed && child.type === INTERFACE_KEYWORD)) return UnitKind.Interface;
2930
+ return modifierWords(node).has(ENUM_MODIFIER) ? UnitKind.Enum : UnitKind.Class;
2931
+ }
2932
+ function describeFunction(node, container) {
2933
+ const header = namedDefinition(node, container === void 0 ? UnitKind.Function : UnitKind.Method);
2934
+ const receiver = node.childForFieldName("name")?.previousNamedSibling;
2935
+ if (header === void 0 || container !== void 0 || receiver === null || receiver === void 0 || !TYPE_NODES.has(receiver.type)) return header;
2936
+ return {
2937
+ ...header,
2938
+ owner: receiver.text
2939
+ };
2940
+ }
2941
+ function describeTopLevelProperty(node) {
2942
+ const nameNode = node.namedChildren.find((child) => child?.type === "variable_declaration")?.namedChildren.find((child) => child?.type === "identifier");
2943
+ return nameNode === null || nameNode === void 0 ? void 0 : {
2944
+ kind: UnitKind.Constant,
2945
+ name: nameNode.text,
2946
+ nameNode
2947
+ };
2948
+ }
2949
+ function modifierWords(node) {
2950
+ const modifiers = node.namedChildren.find((child) => child?.type === "modifiers");
2951
+ return new Set(modifiers?.namedChildren.map((modifier) => modifier?.text ?? "") ?? []);
2952
+ }
2953
+ function isPublicDeclaration(node) {
2954
+ return ![...modifierWords(node)].some((word) => HIDDEN_VISIBILITIES.has(word));
2955
+ }
2956
+ function classifyIdentifier(leaf) {
2957
+ const parent = leaf.parent;
2958
+ if (parent?.type === "navigation_expression" && parent.firstNamedChild?.id !== leaf.id) return {
2959
+ kind: IdentifierUseKind.Member,
2960
+ receiver: parent.firstNamedChild?.text ?? ""
2961
+ };
2962
+ return classifyWithGrammar(leaf, IDENTIFIER_GRAMMAR$3);
2963
+ }
2964
+ function parametersOf(fn) {
2965
+ return (fn.namedChildren.find((child) => child?.type === PARAMETER_LIST)?.namedChildren ?? []).filter((child) => child?.type === "parameter");
2966
+ }
2967
+ function returnTypeOf(fn) {
2968
+ const next = fn.namedChildren.find((child) => child?.type === PARAMETER_LIST)?.nextNamedSibling ?? null;
2969
+ return next !== null && TYPE_NODES.has(next.type) ? next : null;
2970
+ }
2971
+ function parameterKind$2(parameter) {
2972
+ const before = parameter.previousNamedSibling;
2973
+ if (before?.type === "parameter_modifiers" && before.text.split(/\s+/).includes(VARARG)) return ParameterKind.Rest;
2974
+ return parameter.nextSibling?.type === "=" ? ParameterKind.Optional : ParameterKind.Required;
2975
+ }
2976
+ const kotlinSpec = {
2977
+ language: SourceLanguage.Kotlin,
2978
+ grammar: "@tree-sitter-grammars/tree-sitter-kotlin/tree-sitter-kotlin.wasm",
2979
+ separator: ".",
2980
+ describe: describe$2,
2981
+ outerNode: (node) => node,
2982
+ isAttachedPrefix: () => false,
2983
+ isContainer: (kind) => CONTAINERS$3.has(kind),
2984
+ isOpaque: (node) => OPAQUE_NODE_TYPES$1.has(node.type),
2985
+ childPrefix: (_header, _node, qualifiedName) => qualifiedName,
2986
+ normalizeLeaf: (leaf) => leaf.text,
2987
+ publicDefinitions: () => isPublicDeclaration,
2988
+ identifierTypes: /* @__PURE__ */ new Set(["identifier"]),
2989
+ classifyIdentifier,
2990
+ selfReceivers: /* @__PURE__ */ new Set(["this"]),
2991
+ callsMembersByBareName: true,
2992
+ functionScopeTypes: /* @__PURE__ */ new Set([
2993
+ "function_declaration",
2994
+ "secondary_constructor",
2995
+ "lambda_literal",
2996
+ "anonymous_function"
2997
+ ]),
2998
+ isBindingSite: (leaf) => isBindingWithGrammar(leaf, IDENTIFIER_GRAMMAR$3),
2999
+ isImplicitlyInvoked: (methodName) => IMPLICITLY_INVOKED.has(methodName),
3000
+ shape: {
3001
+ functionNode: (definition) => definition,
3002
+ parameters: parametersOf,
3003
+ returnType: returnTypeOf,
3004
+ parameterKind: parameterKind$2,
3005
+ calls: /* @__PURE__ */ new Map([["call_expression", {
3006
+ calleeField: void 0,
3007
+ suffix: ""
3008
+ }]]),
3009
+ errorCalls: /* @__PURE__ */ new Set([
3010
+ "error",
3011
+ "TODO",
3012
+ "exitProcess"
3013
+ ]),
3014
+ errorTypes: ["throw_expression"],
3015
+ branchTypes: [
3016
+ "if_expression",
3017
+ "when_entry",
3018
+ "for_statement",
3019
+ "while_statement",
3020
+ "do_while_statement",
3021
+ "catch_block"
3022
+ ],
3023
+ nestingTypes: [
3024
+ "if_expression",
3025
+ "when_expression",
3026
+ "for_statement",
3027
+ "while_statement",
3028
+ "do_while_statement",
3029
+ "try_expression"
3030
+ ],
3031
+ logicalTypes: ["binary_expression"],
3032
+ logicalOperators: /* @__PURE__ */ new Set(["&&", "||"])
3033
+ }
3034
+ };
2616
3035
  // packages/engine/src/syntax/python.ts
2617
3036
  const CONTAINERS$2 = /* @__PURE__ */ new Set([UnitKind.Class]);
2618
3037
  const IDENTIFIER_GRAMMAR$2 = {
@@ -2673,8 +3092,8 @@ const pythonSpec = {
2673
3092
  isImplicitlyInvoked: (methodName) => DUNDER_METHOD.test(methodName),
2674
3093
  shape: {
2675
3094
  functionNode: (definition) => definition,
2676
- signatureNode: (fn) => fn,
2677
- returnTypeField: "return_type",
3095
+ parameters: parametersByField,
3096
+ returnType: returnTypeByField("return_type"),
2678
3097
  parameterKind: parameterKind$1,
2679
3098
  calls: /* @__PURE__ */ new Map([["call", {
2680
3099
  calleeField: "function",
@@ -2768,8 +3187,8 @@ const rustSpec = {
2768
3187
  isImplicitlyInvoked: (methodName) => methodName === "drop",
2769
3188
  shape: {
2770
3189
  functionNode: (definition) => definition,
2771
- signatureNode: (fn) => fn,
2772
- returnTypeField: "return_type",
3190
+ parameters: parametersByField,
3191
+ returnType: returnTypeByField("return_type"),
2773
3192
  parameterKind: (parameter) => parameter.type === "self_parameter" ? ParameterKind.Receiver : parameter.type === "variadic_parameter" ? ParameterKind.Rest : ParameterKind.Required,
2774
3193
  calls: /* @__PURE__ */ new Map([["call_expression", {
2775
3194
  calleeField: "function",
@@ -3068,8 +3487,8 @@ function makeSpec(language, grammar) {
3068
3487
  isImplicitlyInvoked: (methodName) => methodName === "constructor",
3069
3488
  shape: {
3070
3489
  functionNode: (definition) => definition.childForFieldName("value") ?? definition,
3071
- signatureNode: (fn) => fn,
3072
- returnTypeField: "return_type",
3490
+ parameters: parametersByField,
3491
+ returnType: returnTypeByField("return_type"),
3073
3492
  parameterKind,
3074
3493
  calls: /* @__PURE__ */ new Map([["call_expression", {
3075
3494
  calleeField: "function",
@@ -3125,6 +3544,9 @@ const SPEC_BY_EXTENSION = /* @__PURE__ */ new Map([
3125
3544
  [".pyi", pythonSpec],
3126
3545
  [".go", goSpec],
3127
3546
  [".java", javaSpec],
3547
+ [".kt", kotlinSpec],
3548
+ [".kts", kotlinSpec],
3549
+ [".cs", csharpSpec],
3128
3550
  [".c", cSpec],
3129
3551
  [".h", cppSpec],
3130
3552
  [".cc", cppSpec],
@@ -3652,21 +4074,6 @@ function simpleTypeName(path) {
3652
4074
  const withoutGenerics = (/^<(.+?) as .+>$/.exec(path)?.at(1) ?? path).replace(/<.*>$/, "");
3653
4075
  return withoutGenerics.split(/::|\./).at(-1) ?? withoutGenerics;
3654
4076
  }
3655
- // packages/engine/src/risk/testCode.ts
3656
- const TEST_PATHS = [
3657
- /(^|\/)(tests?|__tests__|spec|specs)\//,
3658
- /\.(test|spec)\.[cm]?[jt]sx?$/,
3659
- /(^|\/)test_[^/]*\.py$/,
3660
- /_test\.(py|rs|go|c|cc|cpp|cxx)$/,
3661
- /(^|\/)tests?\.rs$/
3662
- ];
3663
- const TEST_UNIT = /(^|::|\.)tests?(::|\.)|(^|::|\.)test_|^Test/;
3664
- function isTestPath(path) {
3665
- return TEST_PATHS.some((pattern) => pattern.test(path));
3666
- }
3667
- function isTestUnit(qualifiedName) {
3668
- return TEST_UNIT.test(qualifiedName);
3669
- }
3670
4077
  // packages/engine/src/risk/breaking/codeMentions.ts
3671
4078
  const MAX_FILES_FOR_A_COMMON_WORD = 25;
3672
4079
  const MAX_FILES_FOR_A_SPECIFIC_NAME = 200;
@@ -4784,7 +5191,7 @@ function apiUnitsOf(file, versions, surface) {
4784
5191
  const bySnapshot = new Map(definitions.flatMap((definition) => [[definition.snapshot, definition], [definition.wholeSnapshot, definition]]));
4785
5192
  const beforePath = "previousPath" in file.diff ? file.diff.previousPath : file.diff.path;
4786
5193
  return changedUnitsOf(file).flatMap((unit) => {
4787
- if (!KIND_WORDS.has(unit.kind) || isTestUnit(unit.qualifiedName) || !("before" in unit.change)) return [];
5194
+ if (!KIND_WORDS.has(unit.kind) || isTestUnit(unit) || !("before" in unit.change)) return [];
4788
5195
  const before = bySnapshot.get(unit.change.before);
4789
5196
  const after = "after" in unit.change ? bySnapshot.get(unit.change.after) : void 0;
4790
5197
  if (before === void 0 || !isPublicApi(before, unit, versions, file.diff.path)) return [];
@@ -4970,6 +5377,8 @@ const GO = /* @__PURE__ */ new Set([SourceLanguage.Go]);
4970
5377
  const JAVA = /* @__PURE__ */ new Set([SourceLanguage.Java]);
4971
5378
  const C_FAMILY = /* @__PURE__ */ new Set([SourceLanguage.C, SourceLanguage.Cpp]);
4972
5379
  const CPP = /* @__PURE__ */ new Set([SourceLanguage.Cpp]);
5380
+ const KOTLIN = /* @__PURE__ */ new Set([SourceLanguage.Kotlin]);
5381
+ const CSHARP = /* @__PURE__ */ new Set([SourceLanguage.CSharp]);
4973
5382
  function rule(id, languages, severity, pattern, title, detail) {
4974
5383
  return {
4975
5384
  id,
@@ -4985,6 +5394,7 @@ const CODE_EXECUTION = "Runs a string as code. If any part of it can come from u
4985
5394
  const TLS_DISABLED = "Turns off certificate checks, so anyone on the network path can read or alter the traffic.";
4986
5395
  const SQL_INTERPOLATION = "SQL assembled from interpolated values is open to injection. Use bound parameters instead.";
4987
5396
  const SPAWNS_PROCESSES = "Check that no user input reaches the command or its arguments unchecked.";
5397
+ const DESERIALIZATION = "Reading objects from a stream can run code chosen by whoever wrote it; never deserialize untrusted data.";
4988
5398
  const API_RULES = [
4989
5399
  rule("js.eval", ECMASCRIPT, RiskSeverity.High, /\beval\s*\(/, "eval()", CODE_EXECUTION),
4990
5400
  rule("js.new-function", ECMASCRIPT, RiskSeverity.High, /\bnew\s+Function\s*\(/, "new Function()", CODE_EXECUTION),
@@ -5012,14 +5422,23 @@ const API_RULES = [
5012
5422
  rule("go.unescaped-template", GO, RiskSeverity.Medium, /\btemplate\.(?:HTML|HTMLAttr|JS|JSStr|CSS|URL)\s*\(/, "Marks text as safe for a template", "html/template won't escape it; if any of it comes from users, that's cross-site scripting."),
5013
5423
  rule("go.sql-format", GO, RiskSeverity.Medium, /\.(?:Query|QueryRow|Exec)(?:Context)?\s*\([^)]*\bfmt\.Sprintf\s*\(/, "SQL from fmt.Sprintf", SQL_INTERPOLATION),
5014
5424
  rule("java.exec", JAVA, RiskSeverity.Medium, /\bgetRuntime\(\)\s*\.exec\s*\(|\bnew\s+ProcessBuilder\s*\(/, "Spawns processes", SPAWNS_PROCESSES),
5015
- rule("java.deserialization", JAVA, RiskSeverity.Medium, /\bnew\s+ObjectInputStream\s*\(/, "Java deserialization", "Reading objects from a stream can run code chosen by whoever wrote it; never deserialize untrusted data."),
5425
+ rule("java.deserialization", JAVA, RiskSeverity.Medium, /\bnew\s+ObjectInputStream\s*\(/, "Java deserialization", DESERIALIZATION),
5016
5426
  rule("java.sql-concat", JAVA, RiskSeverity.Medium, /\.(?:executeQuery|executeUpdate|execute|prepareStatement|addBatch)\s*\(\s*"[^"]*"\s*\+/, "SQL built by concatenation", SQL_INTERPOLATION),
5017
5427
  rule("java.tls-disabled", JAVA, RiskSeverity.High, /\bNoopHostnameVerifier\b|\bALLOW_ALL_HOSTNAME_VERIFIER\b|\bsetHostnameVerifier\s*\(\s*\([^)]*\)\s*->\s*true\b/, "TLS verification disabled", TLS_DISABLED),
5018
5428
  rule("c.unbounded-copy", C_FAMILY, RiskSeverity.Medium, /\b(?:strcpy|strcat|stpcpy|wcscpy|wcscat|sprintf|vsprintf|gets)\s*\(/, "Unbounded string copy", "Writes with no length limit, so input longer than the buffer overflows it. Use a bounded form such as snprintf."),
5019
5429
  rule("c.format-string", C_FAMILY, RiskSeverity.Medium, /\b(?:printf\s*\(|fprintf\s*\(\s*[\w.>-]+\s*,)\s*[A-Za-z_][\w.>-]*\s*\)/, "Format string from a variable", "If the text can come from users, conversions such as %n and %s in it read or write memory. Print it through \"%s\" instead."),
5020
5430
  rule("c.exec", C_FAMILY, RiskSeverity.Medium, /\b(?:system|popen|exec(?:l|lp|le|v|vp|vpe|ve))\s*\(/, "Spawns processes", SPAWNS_PROCESSES),
5021
5431
  rule("c.tls-disabled", C_FAMILY, RiskSeverity.High, /\bSSL_(?:CTX_)?set_verify\s*\([^,]+,\s*SSL_VERIFY_NONE\b|\bCURLOPT_SSL_VERIFY(?:PEER|HOST)\s*,\s*0/, "TLS verification disabled", TLS_DISABLED),
5022
- rule("cpp.reinterpret-cast", CPP, RiskSeverity.Medium, /\breinterpret_cast\s*</, "reinterpret_cast", "Reinterprets memory with no checks; a wrong type or size is undefined behaviour.")
5432
+ rule("cpp.reinterpret-cast", CPP, RiskSeverity.Medium, /\breinterpret_cast\s*</, "reinterpret_cast", "Reinterprets memory with no checks; a wrong type or size is undefined behaviour."),
5433
+ rule("kotlin.exec", KOTLIN, RiskSeverity.Medium, /\bgetRuntime\(\)\s*\.exec\s*\(|\bProcessBuilder\s*\(/, "Spawns processes", SPAWNS_PROCESSES),
5434
+ rule("kotlin.deserialization", KOTLIN, RiskSeverity.Medium, /\bObjectInputStream\s*\(/, "Java deserialization", DESERIALIZATION),
5435
+ rule("kotlin.sql-template", KOTLIN, RiskSeverity.Medium, /\.(?:executeQuery|executeUpdate|execute|prepareStatement|rawQuery|execSQL)\s*\(\s*"[^"]*\$\{?\w/, "SQL built from a string template", SQL_INTERPOLATION),
5436
+ rule("kotlin.tls-disabled", KOTLIN, RiskSeverity.High, /\bNoopHostnameVerifier\b|\bhostnameVerifier\s*(?:=\s*HostnameVerifier\s*)?\{\s*_\s*,\s*_\s*->\s*true\b/, "TLS verification disabled", TLS_DISABLED),
5437
+ rule("csharp.exec", CSHARP, RiskSeverity.Medium, /\bProcess\.Start\s*\(|\bnew\s+ProcessStartInfo\s*\(/, "Spawns processes", SPAWNS_PROCESSES),
5438
+ rule("csharp.deserialization", CSHARP, RiskSeverity.High, /\bnew\s+(?:BinaryFormatter|NetDataContractSerializer|SoapFormatter|LosFormatter)\s*\(|\bTypeNameHandling\s*=\s*TypeNameHandling\.(?:All|Auto|Objects|Arrays)\b/, "Unsafe deserialization", "These serializers can create any type the data names, which lets whoever wrote it run code. Use System.Text.Json, or keep TypeNameHandling at None."),
5439
+ rule("csharp.sql-interpolation", CSHARP, RiskSeverity.Medium, /\b(?:new\s+SqlCommand|ExecuteSqlRaw(?:Async)?|FromSqlRaw|ExecuteSqlCommand)\s*\(\s*(?:\$"|"[^"]*"\s*\+)/, "SQL built from interpolation", SQL_INTERPOLATION),
5440
+ rule("csharp.tls-disabled", CSHARP, RiskSeverity.High, /\b(?:ServerCertificateCustomValidationCallback|ServerCertificateValidationCallback)\s*\+?=\s*(?:\([^)]*\)|\w+)\s*=>\s*true\b|\bDangerousAcceptAnyServerCertificateValidator\b/, "TLS verification disabled", TLS_DISABLED),
5441
+ rule("csharp.unsafe", CSHARP, RiskSeverity.Medium, /\bunsafe\s*(?:\{|\w)/, "unsafe code", "The runtime no longer checks memory safety here; review the pointer arithmetic and lifetimes the code relies on.")
5023
5442
  ];
5024
5443
  /**
5025
5444
  * Flags risky API uses on added lines of supported languages. A match only counts when it
@@ -6838,7 +7257,7 @@ const METRIC_RULES = [
6838
7257
  ];
6839
7258
  /** Flags functions this PR added over a limit or made meaningfully worse; test code is left out. */
6840
7259
  function scanFunctionMetrics(functions) {
6841
- return functions.filter((fn) => !isTestPath(fn.path) && !isTestUnit(fn.qualifiedName)).flatMap((fn) => METRIC_RULES.flatMap((rule) => {
7260
+ return functions.filter((fn) => !isTestPath(fn.path) && !isTestUnit(fn)).flatMap((fn) => METRIC_RULES.flatMap((rule) => {
6842
7261
  const before = fn.before?.[rule.metric];
6843
7262
  const after = fn.after[rule.metric];
6844
7263
  if (!isWorseThanLimit(before, after, rule.limit)) return [];
@@ -6852,16 +7271,16 @@ function isWorseThanLimit(before, after, limit) {
6852
7271
  }
6853
7272
  // packages/engine/src/risk/languageCoverage.ts
6854
7273
  const UNPARSED_CODE_EXTENSIONS = /* @__PURE__ */ new Set([
6855
- ".kt",
6856
7274
  ".rb",
6857
7275
  ".php",
6858
- ".cs",
6859
7276
  ".swift",
6860
7277
  ".scala",
6861
7278
  ".sh"
6862
7279
  ]);
6863
7280
  const WITHOUT_PUBLIC_API_RULES = /* @__PURE__ */ new Set([
6864
7281
  SourceLanguage.Java,
7282
+ SourceLanguage.Kotlin,
7283
+ SourceLanguage.CSharp,
6865
7284
  SourceLanguage.C,
6866
7285
  SourceLanguage.Cpp
6867
7286
  ]);
@@ -6872,7 +7291,7 @@ function languageGaps(paths) {
6872
7291
  const gaps = [];
6873
7292
  if (unparsed.length > 0) gaps.push({
6874
7293
  check: `Dangerous-API rules for ${unparsed.join(", ")} files`,
6875
- reason: "rules exist only for Rust, TypeScript/JavaScript, Python, Go, Java, C and C++"
7294
+ reason: "rules exist only for Rust, TypeScript/JavaScript, Python, Go, Java, Kotlin, C#, C and C++"
6876
7295
  });
6877
7296
  if (withoutApiRules.length > 0) gaps.push({
6878
7297
  check: `Public API checks for ${withoutApiRules.join(", ")} files`,
@@ -6914,8 +7333,8 @@ function sizeSignal(files) {
6914
7333
  }
6915
7334
  function missingTestsSignal(files) {
6916
7335
  const reviewable = files.filter((file) => file.noise === null);
6917
- const testsChanged = reviewable.some((file) => isTestPath(file.diff.path) || changedUnitsOf(file).some((unit) => isTestUnit(unit.qualifiedName)));
6918
- const codeChanges = reviewable.filter((file) => !isTestPath(file.diff.path)).flatMap(changedUnitsOf).filter((unit) => isBehaviourChange(unit.change) && !isTestUnit(unit.qualifiedName));
7336
+ const testsChanged = reviewable.some((file) => isTestPath(file.diff.path) || changedUnitsOf(file).some(isTestUnit));
7337
+ const codeChanges = reviewable.filter((file) => !isTestPath(file.diff.path)).flatMap(changedUnitsOf).filter((unit) => isBehaviourChange(unit.change) && !isTestUnit(unit));
6919
7338
  if (testsChanged || codeChanges.length === 0) return [];
6920
7339
  return [pullRequestFinding({
6921
7340
  id: "tests.none",
@@ -8759,6 +9178,7 @@ function functionQualities(files) {
8759
9178
  if (definition.shape === void 0) return [];
8760
9179
  return [{
8761
9180
  path: file.path,
9181
+ kind: definition.kind,
8762
9182
  qualifiedName: definition.qualifiedName,
8763
9183
  line: definition.snapshot.startLine,
8764
9184
  before: previousMetrics(definition, beforeByKey, beforeByBody),
@@ -10024,7 +10444,10 @@ async function downloadWithRetries(url, deps) {
10024
10444
  for (const delayMs of RETRY_DELAYS_MS) {
10025
10445
  const attempt = await downloadOnce(url, deps);
10026
10446
  if (attempt.outcome !== Outcome.TryAgain) return settled(attempt);
10027
- deps.log(`Downloading ${url} failed (${attempt.problem}). Trying again in ${delayMs / MS_PER_SECOND} seconds.`);
10447
+ deps.log(`Downloading ${url} failed (${attempt.problem}). Trying again in ${delayMs / MS_PER_SECOND} seconds.`, {
10448
+ level: LogLevel.Warn,
10449
+ fields: { url }
10450
+ });
10028
10451
  await deps.wait(delayMs);
10029
10452
  }
10030
10453
  const last = await downloadOnce(url, deps);
@@ -10237,19 +10660,31 @@ async function attempt(binary, bin, deps, install) {
10237
10660
  await rm(link, { force: true });
10238
10661
  await symlink(relative(bin, executable), link);
10239
10662
  } catch (error) {
10240
- deps.log(`Walkdiff couldn't install ${binary}: ${error instanceof Error ? error.message : String(error)}. Reports will list it as not run.`);
10663
+ deps.log(`Walkdiff couldn't install ${binary}: ${error instanceof Error ? error.message : String(error)}. Reports will list it as not run.`, {
10664
+ level: LogLevel.Warn,
10665
+ fields: { scanner: binary }
10666
+ });
10241
10667
  }
10242
10668
  }
10243
10669
  async function installBinary(pin, tools, deps) {
10244
10670
  const asset = pin.assets[deps.platform];
10245
10671
  if (asset === void 0) {
10246
- deps.log(`Walkdiff has no ${pin.binary} build for ${deps.platform}. Install it yourself to use it.`);
10672
+ deps.log(`Walkdiff has no ${pin.binary} build for ${deps.platform}. Install it yourself to use it.`, {
10673
+ level: LogLevel.Warn,
10674
+ fields: {
10675
+ scanner: pin.binary,
10676
+ platform: deps.platform
10677
+ }
10678
+ });
10247
10679
  return;
10248
10680
  }
10249
10681
  const target = join(tools, `${pin.binary}-${pin.version}`);
10250
10682
  const executable = join(target, pin.binary);
10251
10683
  if (existsSync(executable)) return executable;
10252
- deps.log(`Installing ${pin.binary} ${pin.version}…`);
10684
+ deps.log(`Installing ${pin.binary} ${pin.version}…`, { fields: {
10685
+ scanner: pin.binary,
10686
+ version: pin.version
10687
+ } });
10253
10688
  const bytes = await deps.download(`${pin.baseUrl}/${asset.file}`);
10254
10689
  const actual = createHash("sha256").update(bytes).digest("hex");
10255
10690
  if (actual !== asset.sha256) throw new Error(`${asset.file} doesn't match its pinned hash (expected ${asset.sha256}, got ${actual})`);
@@ -10292,12 +10727,20 @@ async function moveToTop(folder, member, binary) {
10292
10727
  /**
10293
10728
  * Semgrep is a Python application with no standalone build, so it gets a private environment
10294
10729
  * that nothing else on the machine shares. `--require-hashes` holds every package to the locked
10295
- * file, and `--only-binary` means no package's setup code runs. A virtual environment records its
10296
- * own path, so unlike the binaries it can't be built elsewhere and renamed; the marker says it's done.
10730
+ * file, and `--only-binary` means no package's setup code runs. `--no-deps` installs exactly that
10731
+ * file, which holds newer versions than Semgrep pins for some packages, to take their security fixes
10732
+ * (semgrep-overrides.txt lists them); pip would otherwise refuse them. A virtual environment records
10733
+ * its own path, so unlike the binaries it can't be built elsewhere and renamed; the marker says it's done.
10297
10734
  */
10298
10735
  async function installSemgrep(tools, deps) {
10299
10736
  if (SEMGREP_UNSUPPORTED_PLATFORMS.has(deps.platform.split("-").at(0) ?? "")) {
10300
- deps.log("Semgrep doesn't run natively here. Install it yourself, for example in WSL, to use it.");
10737
+ deps.log("Semgrep doesn't run natively here. Install it yourself, for example in WSL, to use it.", {
10738
+ level: LogLevel.Warn,
10739
+ fields: {
10740
+ scanner: SEMGREP_BINARY,
10741
+ platform: deps.platform
10742
+ }
10743
+ });
10301
10744
  return;
10302
10745
  }
10303
10746
  const requirements = await readFile(SEMGREP_REQUIREMENTS);
@@ -10305,7 +10748,10 @@ async function installSemgrep(tools, deps) {
10305
10748
  const executable = join(target, "bin", SEMGREP_BINARY);
10306
10749
  const marker = join(target, SEMGREP_COMPLETE_MARKER);
10307
10750
  if (existsSync(marker)) return executable;
10308
- deps.log(`Installing Semgrep ${SEMGREP_VERSION}…`);
10751
+ deps.log(`Installing Semgrep ${SEMGREP_VERSION}…`, { fields: {
10752
+ scanner: SEMGREP_BINARY,
10753
+ version: SEMGREP_VERSION
10754
+ } });
10309
10755
  await rm(target, {
10310
10756
  recursive: true,
10311
10757
  force: true
@@ -10329,6 +10775,7 @@ async function installSemgrep(tools, deps) {
10329
10775
  "pip",
10330
10776
  "install",
10331
10777
  "--require-hashes",
10778
+ "--no-deps",
10332
10779
  "--only-binary",
10333
10780
  ":all:",
10334
10781
  "--no-input",
@@ -10367,6 +10814,82 @@ function installScannersHere(log = console.log) {
10367
10814
  pins: BINARY_PINS
10368
10815
  });
10369
10816
  }
10817
+ // packages/engine/src/localChange.ts
10818
+ var LocalChangeError = class extends Error {
10819
+ name = "LocalChangeError";
10820
+ };
10821
+ const DEFAULT_BASE_REFS = ["main", "master"];
10822
+ const REMOTE_DEFAULT_BRANCH = "refs/remotes/origin/HEAD";
10823
+ const DETACHED_HEAD = "HEAD";
10824
+ /**
10825
+ * Reads the committed work on the current branch, from where it left its base, without changing
10826
+ * the repository: every command here only reads, and `status` takes no locks.
10827
+ *
10828
+ * # Errors
10829
+ *
10830
+ * Throws a `LocalChangeError` outside a git repository, when the base can't be found, or when the
10831
+ * branch has no commits of its own.
10832
+ */
10833
+ async function readLocalChange(request) {
10834
+ const repoDir = await topLevel(request.cwd);
10835
+ const git = (...args) => runGit(args, {
10836
+ cwd: repoDir,
10837
+ env: ISOLATED_CONFIG_ENV
10838
+ }).then((output) => output.trim());
10839
+ const headSha = await commitOf(git, DETACHED_HEAD);
10840
+ const branch = await git("rev-parse", "--abbrev-ref", DETACHED_HEAD);
10841
+ const headRef = branch === DETACHED_HEAD ? headSha.slice(0, 12) : branch;
10842
+ const baseRef = request.baseRef ?? await defaultBase(git);
10843
+ const baseSha = await commitOf(git, baseRef);
10844
+ const mergeBaseSha = commitShaSchema.parse(await git("merge-base", baseSha, headSha).catch(() => {
10845
+ throw new LocalChangeError(`${headRef} and ${baseRef} have no history in common.`);
10846
+ }));
10847
+ if (mergeBaseSha === headSha) throw new LocalChangeError(`${headRef} has no commits that aren't on ${baseRef} yet. Commit your changes, or name another base with --base.`);
10848
+ const subjects = (await git("log", "--format=%s", `${mergeBaseSha}..${headSha}`)).split("\n").filter((line) => line !== "");
10849
+ const change = {
10850
+ host: LOCAL_CHANGE_HOST,
10851
+ repositoryName: basename(repoDir),
10852
+ title: subjects.length === 1 ? subjects[0] ?? headRef : headRef,
10853
+ description: subjects.map((subject) => `- ${subject}`).join("\n"),
10854
+ author: await git("log", "-1", "--format=%an", headSha),
10855
+ baseRef,
10856
+ headRef,
10857
+ baseSha,
10858
+ headSha,
10859
+ mergeBaseSha
10860
+ };
10861
+ const status = await git("--no-optional-locks", "status", "--porcelain", "--untracked-files=no");
10862
+ return {
10863
+ repoDir,
10864
+ change,
10865
+ uncommittedFiles: status === "" ? 0 : status.split("\n").length
10866
+ };
10867
+ }
10868
+ async function topLevel(cwd) {
10869
+ try {
10870
+ return (await runGit(["rev-parse", "--show-toplevel"], {
10871
+ cwd,
10872
+ env: ISOLATED_CONFIG_ENV
10873
+ })).trim();
10874
+ } catch (error) {
10875
+ if (error instanceof GitCommandError) throw new LocalChangeError(`${cwd} isn't inside a git repository.`);
10876
+ throw error;
10877
+ }
10878
+ }
10879
+ async function commitOf(git, ref) {
10880
+ try {
10881
+ return commitShaSchema.parse(await git("rev-parse", "--verify", "--end-of-options", `${ref}^{commit}`));
10882
+ } catch (error) {
10883
+ if (error instanceof GitCommandError) throw new LocalChangeError(`${ref} isn't a commit, branch or tag in this repository.`);
10884
+ throw error;
10885
+ }
10886
+ }
10887
+ async function defaultBase(git) {
10888
+ const remoteDefault = await git("symbolic-ref", "--quiet", "--short", REMOTE_DEFAULT_BRANCH).catch(() => "");
10889
+ if (remoteDefault !== "") return remoteDefault;
10890
+ for (const candidate of DEFAULT_BASE_REFS) if (await git("rev-parse", "--verify", "--quiet", `${candidate}^{commit}`).then(() => true, () => false)) return candidate;
10891
+ throw new LocalChangeError(`Couldn't tell which branch this one will merge into. Name it with --base, such as --base main.`);
10892
+ }
10370
10893
  // packages/providers/src/pullRequestUrl.ts
10371
10894
  var InvalidPullRequestUrlError = class extends Error {
10372
10895
  name = "InvalidPullRequestUrlError";
@@ -11508,9 +12031,44 @@ function untrustedHostHint(origin, tokenVariable, trustVariable) {
11508
12031
  function assertNever(value) {
11509
12032
  throw new Error(`Unhandled git host: ${JSON.stringify(value)}`);
11510
12033
  }
12034
+ // packages/cli/src/logging.ts
12035
+ /** How log lines are printed: plain sentences for people, or JSON Lines for machines. */
12036
+ const LogFormat = {
12037
+ Text: "text",
12038
+ Json: "json"
12039
+ };
12040
+ const LOG_FORMAT_VARIABLE = "WALKDIFF_LOG_FORMAT";
12041
+ const LOG_FORMATS = new Set(Object.values(LogFormat));
12042
+ function isLogFormat(value) {
12043
+ return LOG_FORMATS.has(value);
12044
+ }
12045
+ const RESERVED_KEYS = /* @__PURE__ */ new Set([
12046
+ "time",
12047
+ "level",
12048
+ "msg"
12049
+ ]);
12050
+ /**
12051
+ * In JSON, each line is one object: `time` (ISO 8601, UTC), `level` (info, warn or error) and
12052
+ * `msg`, then the event's fields. These names follow common structured-logging practice, so
12053
+ * collectors read them without configuration. Text prints only the message, as Walkdiff always has.
12054
+ */
12055
+ function createLog(format, sink) {
12056
+ if (format === LogFormat.Text) return (message) => sink.write(message);
12057
+ return (message, details) => sink.write(jsonLine(message, details, sink.now()));
12058
+ }
12059
+ function jsonLine(message, details, time) {
12060
+ const fields = Object.entries(details?.fields ?? {}).filter(([key]) => !RESERVED_KEYS.has(key));
12061
+ return JSON.stringify({
12062
+ time: time.toISOString(),
12063
+ level: details?.level ?? LogLevel.Info,
12064
+ msg: message,
12065
+ ...Object.fromEntries(fields)
12066
+ });
12067
+ }
11511
12068
  // packages/cli/src/args.ts
11512
12069
  const USAGE = `Usage:
11513
12070
  walkdiff review [pull-request-url] [options]
12071
+ walkdiff review --local [--base <ref>] [options]
11514
12072
  walkdiff comment --report <dir> --report-url <url>
11515
12073
  walkdiff app [options]
11516
12074
  walkdiff setup
@@ -11526,6 +12084,10 @@ setup installs the pinned security scanners Walkdiff runs, checking each against
11526
12084
  and app do this on their first run anyway, unless --offline.
11527
12085
 
11528
12086
  Options:
12087
+ --local Review the committed work on this repository's current branch, before
12088
+ it has a pull request. Uncommitted changes are left out
12089
+ --base <ref> With --local: the branch it will merge into (default: the remote's
12090
+ default branch, else main or master)
11529
12091
  --out <dir> Write the report here instead of the cache directory
11530
12092
  --port <number> Port for the local server (review: 4318, or any free port; app: 4317)
11531
12093
  --no-serve Write the report and exit without serving it
@@ -11545,6 +12107,8 @@ Options:
11545
12107
  --data-dir <dir> With app: where the review list is stored (default: ~/.local/share/walkdiff)
11546
12108
  --report <dir> With comment: the directory review wrote (--out)
11547
12109
  --report-url <url> With comment: where reviewers can open the report
12110
+ --log-format <f> text (default), or json for one JSON object per line on stderr, with
12111
+ time, level and msg, for CI and log collectors
11548
12112
  -h, --help Show this help
11549
12113
  -v, --version Show which Walkdiff this is
11550
12114
 
@@ -11556,6 +12120,7 @@ Environment:
11556
12120
  may receive those tokens, such as git.acme.internal
11557
12121
  ANTHROPIC_API_KEY Key for --ai with Anthropic (or an \`ant auth login\` profile)
11558
12122
  WALKDIFF_AI_API_KEY Key for --ai with an OpenAI-compatible provider
12123
+ WALKDIFF_LOG_FORMAT text or json, as --log-format, which takes precedence
11559
12124
 
11560
12125
  Troubleshooting: https://github.com/navasvarela/walkdiff/blob/main/docs/troubleshooting.md`;
11561
12126
  const MAX_PORT = 65535;
@@ -11563,51 +12128,81 @@ const DEFAULT_APP_PORT = 4317;
11563
12128
  var UsageError = class extends Error {
11564
12129
  name = "UsageError";
11565
12130
  };
11566
- function parseCommand(argv) {
11567
- const { values, positionals } = parseArgs({
12131
+ function parseCommandLine(argv, env) {
12132
+ const { values, positionals } = parseOptions(argv);
12133
+ return {
12134
+ command: commandFrom(values, positionals),
12135
+ logFormat: parseLogFormat(values["log-format"], env)
12136
+ };
12137
+ }
12138
+ /**
12139
+ * The format for logs, from the option, else the environment, else text. Usable before the
12140
+ * command line has been read, so even an error in it can be logged as asked.
12141
+ */
12142
+ function logFormatFromEnvironment(env) {
12143
+ const fromEnvironment = env[LOG_FORMAT_VARIABLE];
12144
+ return fromEnvironment !== void 0 && isLogFormat(fromEnvironment) ? fromEnvironment : LogFormat.Text;
12145
+ }
12146
+ function parseLogFormat(flag, env) {
12147
+ const requested = flag ?? env["WALKDIFF_LOG_FORMAT"];
12148
+ if (requested === void 0) return LogFormat.Text;
12149
+ if (!isLogFormat(requested)) throw new UsageError(`${flag === void 0 ? LOG_FORMAT_VARIABLE : "--log-format"} must be text or json, got "${requested}"`);
12150
+ return requested;
12151
+ }
12152
+ const OPTIONS = {
12153
+ out: { type: "string" },
12154
+ port: { type: "string" },
12155
+ serve: {
12156
+ type: "boolean",
12157
+ default: true
12158
+ },
12159
+ open: {
12160
+ type: "boolean",
12161
+ default: true
12162
+ },
12163
+ offline: {
12164
+ type: "boolean",
12165
+ default: false
12166
+ },
12167
+ ai: {
12168
+ type: "boolean",
12169
+ default: false
12170
+ },
12171
+ "ai-model": { type: "string" },
12172
+ "ai-provider": { type: "string" },
12173
+ "ai-base-url": { type: "string" },
12174
+ "ai-max-input-tokens": { type: "string" },
12175
+ "data-dir": { type: "string" },
12176
+ report: { type: "string" },
12177
+ "report-url": { type: "string" },
12178
+ "cache-dir": { type: "string" },
12179
+ coverage: { type: "string" },
12180
+ local: {
12181
+ type: "boolean",
12182
+ default: false
12183
+ },
12184
+ base: { type: "string" },
12185
+ help: {
12186
+ type: "boolean",
12187
+ short: "h",
12188
+ default: false
12189
+ },
12190
+ version: {
12191
+ type: "boolean",
12192
+ short: "v",
12193
+ default: false
12194
+ },
12195
+ "log-format": { type: "string" }
12196
+ };
12197
+ function parseOptions(argv) {
12198
+ return parseArgs({
11568
12199
  args: [...argv],
11569
12200
  allowPositionals: true,
11570
12201
  allowNegative: true,
11571
- options: {
11572
- out: { type: "string" },
11573
- port: { type: "string" },
11574
- serve: {
11575
- type: "boolean",
11576
- default: true
11577
- },
11578
- open: {
11579
- type: "boolean",
11580
- default: true
11581
- },
11582
- offline: {
11583
- type: "boolean",
11584
- default: false
11585
- },
11586
- ai: {
11587
- type: "boolean",
11588
- default: false
11589
- },
11590
- "ai-model": { type: "string" },
11591
- "ai-provider": { type: "string" },
11592
- "ai-base-url": { type: "string" },
11593
- "ai-max-input-tokens": { type: "string" },
11594
- "data-dir": { type: "string" },
11595
- report: { type: "string" },
11596
- "report-url": { type: "string" },
11597
- "cache-dir": { type: "string" },
11598
- coverage: { type: "string" },
11599
- help: {
11600
- type: "boolean",
11601
- short: "h",
11602
- default: false
11603
- },
11604
- version: {
11605
- type: "boolean",
11606
- short: "v",
11607
- default: false
11608
- }
11609
- }
12202
+ options: OPTIONS
11610
12203
  });
12204
+ }
12205
+ function commandFrom(values, positionals) {
11611
12206
  const [command, url, ...extra] = positionals;
11612
12207
  if (values.version) return { kind: "version" };
11613
12208
  if (values.help || command === void 0) return { kind: "help" };
@@ -11631,10 +12226,13 @@ function parseCommand(argv) {
11631
12226
  };
11632
12227
  if (command !== "review") throw new UsageError(`Unknown command "${command}"`);
11633
12228
  if (extra.length > 0) throw new UsageError(`Unexpected arguments: ${extra.join(" ")}`);
12229
+ if (values.local && url !== void 0) throw new UsageError("--local reviews this repository's branch, so it takes no pull request URL");
12230
+ if (values.base !== void 0 && !values.local) throw new UsageError("--base only applies with --local");
11634
12231
  return {
11635
12232
  kind: "review",
11636
12233
  options: {
11637
12234
  url,
12235
+ local: values.local ? { baseRef: values.base } : void 0,
11638
12236
  outDir: values.out,
11639
12237
  port: values.port === void 0 ? void 0 : parsePort(values.port),
11640
12238
  serve: values.serve,
@@ -12152,7 +12750,7 @@ async function startAppServer(store, service, options) {
12152
12750
  };
12153
12751
  const server = createServer((request, response) => {
12154
12752
  handle(request, response, context).catch((error) => {
12155
- log(`The app could not answer ${request.method ?? ""} ${request.url ?? ""}: ${error instanceof Error ? error.message : String(error)}`);
12753
+ log(`The app could not answer ${request.method ?? ""} ${request.url ?? ""}: ${error instanceof Error ? error.message : String(error)}`, { level: LogLevel.Error });
12156
12754
  sendJson(response, 500, { error: UNEXPECTED_ERROR });
12157
12755
  });
12158
12756
  });
@@ -12758,7 +13356,10 @@ var ReviewService = class {
12758
13356
  if (this.#store.get(id) !== void 0) this.#store.markReady(id, summarize(report));
12759
13357
  } catch (error) {
12760
13358
  const message = error instanceof Error ? error.message : String(error);
12761
- this.#log(`${review.displayName}: ${message}`);
13359
+ this.#log(`${review.displayName}: ${message}`, {
13360
+ level: LogLevel.Error,
13361
+ fields: { review: review.displayName }
13362
+ });
12762
13363
  if (this.#store.get(id) !== void 0) this.#store.markFailed(id, message);
12763
13364
  } finally {
12764
13365
  this.#steps.delete(id);
@@ -12770,7 +13371,10 @@ var ReviewService = class {
12770
13371
  const stack = await this.#findStack(ref);
12771
13372
  if (this.#store.get(review.id) !== void 0) this.#store.saveDetection(review.id, stack);
12772
13373
  } catch (error) {
12773
- this.#log(`${review.displayName}: could not check whether it's part of a stack: ${error instanceof Error ? error.message : String(error)}`);
13374
+ this.#log(`${review.displayName}: could not check whether it's part of a stack: ${error instanceof Error ? error.message : String(error)}`, {
13375
+ level: LogLevel.Warn,
13376
+ fields: { review: review.displayName }
13377
+ });
12774
13378
  }
12775
13379
  }
12776
13380
  };
@@ -13160,14 +13764,16 @@ function gitLabMergeRequestUrl(env) {
13160
13764
  const PREFERRED_REPORT_PORT = 4318;
13161
13765
  const ANY_FREE_PORT = 0;
13162
13766
  async function runReview(options, deps) {
13163
- const ref = parsePullRequestUrl(options.url ?? await detectPullRequestUrl(deps.env));
13164
- const model = await analyzePullRequest(ref, options, deps);
13165
- const reportDir = options.outDir ?? defaultReportDir(deps.cacheDir, ref);
13767
+ const { model, reportDir } = options.local === void 0 ? await reviewPullRequest(options, deps) : await reviewLocalBranch(options.local, options, deps);
13166
13768
  await writeReport(model, reportDir);
13167
- deps.log(`${model.files.length} files changed, ${securitySummary(model.risk.findings).toLowerCase()}. Report written to ${reportDir}`);
13769
+ deps.log(`${model.files.length} files changed, ${securitySummary(model.risk.findings).toLowerCase()}. Report written to ${reportDir}`, { fields: {
13770
+ files: model.files.length,
13771
+ findings: model.risk.findings.length,
13772
+ reportDir
13773
+ } });
13168
13774
  if (!options.serve) return;
13169
13775
  const server = await serveReportOnPreferredPort(reportDir, options.port);
13170
- deps.log(`Serving the report at ${server.url} (Ctrl+C to stop)`);
13776
+ deps.log(`Serving the report at ${server.url} (Ctrl+C to stop)`, { fields: { url: server.url } });
13171
13777
  }
13172
13778
  /**
13173
13779
  * Prefers a fixed port because browsers keep saved data per origin, including the port: a new
@@ -13182,17 +13788,53 @@ async function serveReportOnPreferredPort(reportDir, port) {
13182
13788
  throw error;
13183
13789
  }
13184
13790
  }
13791
+ async function reviewPullRequest(options, deps) {
13792
+ const ref = parsePullRequestUrl(options.url ?? await detectPullRequestUrl(deps.env));
13793
+ return {
13794
+ model: await analyzePullRequest(ref, options, deps),
13795
+ reportDir: options.outDir ?? defaultReportDir(deps.cacheDir, ref)
13796
+ };
13797
+ }
13798
+ async function reviewLocalBranch(local, options, deps) {
13799
+ const { repoDir, change, uncommittedFiles } = await readLocalChange({
13800
+ cwd: deps.cwd,
13801
+ baseRef: local.baseRef
13802
+ });
13803
+ if (uncommittedFiles > 0) deps.log(`${uncommittedFiles} ${uncommittedFiles === 1 ? "file has" : "files have"} uncommitted changes, which this review leaves out. Commit them to include them.`, {
13804
+ level: LogLevel.Warn,
13805
+ fields: { uncommittedFiles }
13806
+ });
13807
+ deps.log(`Reviewing ${change.headRef} against ${change.baseRef} in ${repoDir}.`, { fields: {
13808
+ headRef: change.headRef,
13809
+ baseRef: change.baseRef,
13810
+ repoDir
13811
+ } });
13812
+ return {
13813
+ model: await analyzeChange({
13814
+ repoDir,
13815
+ pullRequest: change,
13816
+ ref: void 0
13817
+ }, options, deps),
13818
+ reportDir: options.outDir ?? localReportDir(deps.cacheDir, change)
13819
+ };
13820
+ }
13185
13821
  async function analyzePullRequest(ref, options, deps) {
13186
13822
  deps.reportStep(AnalysisStep.FetchingPullRequest);
13187
13823
  const snapshot = await gitHostFor(ref, deps.tokens).fetchPullRequest();
13188
13824
  const { pullRequest } = snapshot;
13189
13825
  deps.reportStep(AnalysisStep.FetchingCommits);
13190
- const repoDir = await fetchCommits({
13191
- cacheDir: deps.cacheDir,
13192
- cloneUrl: snapshot.cloneUrl,
13193
- credentials: snapshot.gitAuth,
13194
- commits: [pullRequest.mergeBaseSha, pullRequest.headSha]
13195
- });
13826
+ return analyzeChange({
13827
+ repoDir: await fetchCommits({
13828
+ cacheDir: deps.cacheDir,
13829
+ cloneUrl: snapshot.cloneUrl,
13830
+ credentials: snapshot.gitAuth,
13831
+ commits: [pullRequest.mergeBaseSha, pullRequest.headSha]
13832
+ }),
13833
+ pullRequest,
13834
+ ref
13835
+ }, options, deps);
13836
+ }
13837
+ async function analyzeChange({ repoDir, pullRequest, ref }, options, deps) {
13196
13838
  const { files, risk } = await analyzeChangedFiles(repoDir, pullRequest.mergeBaseSha, pullRequest.headSha, {
13197
13839
  network: options.network,
13198
13840
  disabledChecks: options.disabledChecks ?? [],
@@ -13242,10 +13884,11 @@ async function coverageFor(options, search, deps) {
13242
13884
  return found ?? null;
13243
13885
  }
13244
13886
  async function coverageFromCi(search, deps) {
13887
+ if (search.ref === void 0) return void 0;
13245
13888
  try {
13246
13889
  return coverageFromArchives(await gitHostFor(search.ref, deps.tokens).fetchCoverageArchives(search.headSha), search.diffs, search.patterns);
13247
13890
  } catch (error) {
13248
- deps.log(`Could not read CI artifacts: ${error instanceof Error ? error.message : String(error)}`);
13891
+ deps.log(`Could not read CI artifacts: ${error instanceof Error ? error.message : String(error)}`, { level: LogLevel.Warn });
13249
13892
  return;
13250
13893
  }
13251
13894
  }
@@ -13267,6 +13910,9 @@ function describeAiReview(ai) {
13267
13910
  function defaultReportDir(cacheDir, ref) {
13268
13911
  return join(cacheDir, "reports", new URL(ref.webOrigin).host, repositoryPath(ref), String(ref.number));
13269
13912
  }
13913
+ function localReportDir(cacheDir, change) {
13914
+ return join(cacheDir, "reports", LOCAL_CHANGE_HOST, change.repositoryName, ...change.headRef.split("/"));
13915
+ }
13270
13916
  // packages/cli/src/appCommand.ts
13271
13917
  const DATABASE_FILE = "walkdiff.db";
13272
13918
  /** Runs the local app until the process is stopped. */
@@ -13309,7 +13955,7 @@ async function runApp(options, deps) {
13309
13955
  offline: !options.network,
13310
13956
  hostFor
13311
13957
  });
13312
- deps.log(`Walkdiff is running at ${server.url} (Ctrl+C to stop)`);
13958
+ deps.log(`Walkdiff is running at ${server.url} (Ctrl+C to stop)`, { fields: { url: server.url } });
13313
13959
  if (options.open && canOpenBrowser(process.platform, deps.env)) openBrowser(server.url, deps.log);
13314
13960
  const scanners = await findInstalledScanners();
13315
13961
  deps.log(`Security scanners: ${scanners.installed.join(", ") || "none"} installed${scanners.missing.length > 0 ? `; not found: ${scanners.missing.join(", ")}` : ""}`);
@@ -13487,6 +14133,7 @@ function inlineCode(text) {
13487
14133
  async function runComment(options, deps) {
13488
14134
  const text = await readFile(join(options.reportDir, REVIEW_MODEL_FILE), "utf8");
13489
14135
  const model = reviewModelSchema.parse(JSON.parse(text));
14136
+ if (!isHostedReview(model)) throw new UsageError(`${options.reportDir} is a review of a local branch, which has no pull request to comment on.`);
13490
14137
  const body = renderSummaryComment(model, options.reportUrl);
13491
14138
  if (deps.stepSummaryPath !== void 0) await appendFile(deps.stepSummaryPath, `${body}\n`);
13492
14139
  const host = gitHostFor(parsePullRequestUrl(model.pullRequest.url), deps.tokens);
@@ -13498,7 +14145,7 @@ async function runComment(options, deps) {
13498
14145
  deps.log("Posted the summary comment.");
13499
14146
  } catch (error) {
13500
14147
  if (!(error instanceof HostApiError) || !error.isPermissionProblem) throw error;
13501
- deps.log(`Could not post the summary comment (this token may be read-only): ${error.message}`);
14148
+ deps.log(`Could not post the summary comment (this token may be read-only): ${error.message}`, { level: LogLevel.Warn });
13502
14149
  }
13503
14150
  }
13504
14151
  // packages/cli/src/version.ts
@@ -13512,10 +14159,10 @@ function walkdiffVersion(manifestPath = MANIFEST_PATH) {
13512
14159
  const EXIT_FAILURE = 1;
13513
14160
  const EXIT_USAGE = 2;
13514
14161
  const OWNER_ONLY_UMASK = 63;
13515
- async function main(argv) {
14162
+ async function main(argv, log) {
13516
14163
  process.umask(OWNER_ONLY_UMASK);
13517
14164
  await protectLocalData(process.env);
13518
- const command = parseCommand(argv);
14165
+ const { command } = parseCommandLine(argv, process.env);
13519
14166
  switch (command.kind) {
13520
14167
  case "help":
13521
14168
  console.log(USAGE);
@@ -13524,53 +14171,71 @@ async function main(argv) {
13524
14171
  console.log(`walkdiff ${walkdiffVersion()}`);
13525
14172
  return;
13526
14173
  case "setup":
13527
- await installScannersHere((message) => console.error(message));
13528
- console.error(`Scanners are ready in ${MANAGED_SCANNERS_ROOT}.`);
14174
+ await installScannersHere(log);
14175
+ log(`Scanners are ready in ${MANAGED_SCANNERS_ROOT}.`, { fields: { scannersDir: MANAGED_SCANNERS_ROOT } });
13529
14176
  return;
13530
14177
  case "review":
13531
- if (command.options.network) await installScannersHere((message) => console.error(message));
14178
+ if (command.options.network) await installScannersHere(log);
13532
14179
  await runReview(command.options, {
13533
14180
  tokens: readHostTokens(process.env),
13534
14181
  cacheDir: command.options.cacheDir ?? defaultCacheDir(process.env),
13535
14182
  env: process.env,
14183
+ cwd: process.cwd(),
13536
14184
  now: () => /* @__PURE__ */ new Date(),
13537
- log: (message) => console.error(message),
13538
- reportStep: (step) => console.error(`${stepLabel(step)}…`)
14185
+ log,
14186
+ reportStep: (step) => log(`${stepLabel(step)}…`, { fields: { step } })
13539
14187
  });
13540
14188
  return;
13541
14189
  case "app":
13542
- if (command.options.network) await installScannersHere((message) => console.error(message));
14190
+ if (command.options.network) await installScannersHere(log);
13543
14191
  await runApp(command.options, {
13544
14192
  env: process.env,
13545
14193
  now: () => /* @__PURE__ */ new Date(),
13546
- log: (message) => console.error(message)
14194
+ log
13547
14195
  });
13548
14196
  return;
13549
14197
  case "comment":
13550
14198
  await runComment(command.options, {
13551
14199
  tokens: readHostTokens(process.env),
13552
14200
  stepSummaryPath: process.env.GITHUB_STEP_SUMMARY,
13553
- log: (message) => console.error(message)
14201
+ log
13554
14202
  });
13555
14203
  return;
13556
14204
  }
13557
14205
  }
13558
- main(process.argv.slice(2)).catch((error) => {
14206
+ const logFormat = chosenLogFormat(process.argv.slice(2), process.env);
14207
+ const log = createLog(logFormat, {
14208
+ write: (line) => console.error(line),
14209
+ now: () => /* @__PURE__ */ new Date()
14210
+ });
14211
+ main(process.argv.slice(2), log).catch((error) => {
13559
14212
  if (error instanceof UsageError) {
13560
- console.error(`${error.message}\n\n${USAGE}`);
14213
+ log(error.message, { level: LogLevel.Error });
14214
+ if (logFormat === LogFormat.Text) console.error(`\n${USAGE}`);
13561
14215
  process.exitCode = EXIT_USAGE;
13562
14216
  return;
13563
14217
  }
13564
- console.error(error instanceof Error ? `${error.name}: ${error.message}` : String(error));
13565
- console.error(versionLine());
14218
+ const version = readableVersion();
14219
+ log(error instanceof Error ? `${error.name}: ${error.message}` : String(error), {
14220
+ level: LogLevel.Error,
14221
+ fields: { version: version ?? "unknown" }
14222
+ });
14223
+ if (logFormat === LogFormat.Text) console.error(version === void 0 ? "(walkdiff, version unknown)" : `(walkdiff ${version})`);
13566
14224
  process.exitCode = EXIT_FAILURE;
13567
14225
  });
13568
- /** Names the version in every failure, so a report of one says which Walkdiff it came from. */
13569
- function versionLine() {
14226
+ function chosenLogFormat(argv, env) {
13570
14227
  try {
13571
- return `(walkdiff ${walkdiffVersion()})`;
14228
+ return parseCommandLine(argv, env).logFormat;
13572
14229
  } catch {
13573
- return "(walkdiff, version unknown)";
14230
+ return logFormatFromEnvironment(env);
14231
+ }
14232
+ }
14233
+ /** Every failure names the version, so a report of one says which Walkdiff it came from. */
14234
+ function readableVersion() {
14235
+ try {
14236
+ return walkdiffVersion();
14237
+ } catch {
14238
+ return;
13574
14239
  }
13575
14240
  }
13576
14241
  export {};