walkdiff 0.12.0 → 0.14.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
@@ -7,10 +7,11 @@ import { parseArgs, promisify } from "node:util";
7
7
  import { z } from "zod";
8
8
  import { createHash, randomBytes } from "node:crypto";
9
9
  import { Language, Parser } from "web-tree-sitter";
10
- import { LineCounter, isMap, isPair, isScalar, isSeq, parse, parseAllDocuments } from "yaml";
10
+ import { LineCounter, isMap, isPair, isScalar, isSeq, parse, parseAllDocuments, parseDocument } from "yaml";
11
+ import { Kind, parse as parse$1, print } from "graphql";
11
12
  import { homedir, tmpdir } from "node:os";
12
- import { existsSync, readFileSync } from "node:fs";
13
- import { parse as parse$1 } from "smol-toml";
13
+ import { existsSync, readFileSync, rmSync } from "node:fs";
14
+ import { parse as parse$2 } from "smol-toml";
14
15
  import Anthropic from "@anthropic-ai/sdk";
15
16
  import { betaZodOutputFormat } from "@anthropic-ai/sdk/helpers/beta/zod";
16
17
  import { inflateRawSync } from "node:zlib";
@@ -1090,6 +1091,7 @@ const CheckId = {
1090
1091
  OsvDatabase: "osvDatabase",
1091
1092
  DependencyTrust: "dependencyTrust",
1092
1093
  NpmReleases: "npmReleases",
1094
+ Hotspots: "hotspots",
1093
1095
  Zizmor: "zizmor",
1094
1096
  Poutine: "poutine",
1095
1097
  Ruff: "ruff",
@@ -1425,6 +1427,23 @@ const LogLevel = {
1425
1427
  Warn: "warn",
1426
1428
  Error: "error"
1427
1429
  };
1430
+ // packages/review-model/src/fileHistory.ts
1431
+ var HistoryUnavailableError = class extends Error {
1432
+ name = "HistoryUnavailableError";
1433
+ };
1434
+ z.object({
1435
+ url: z.url(),
1436
+ host: z.enum(GitHostKind),
1437
+ /** `owner/repo#12` or `group/project!12`. */
1438
+ displayName: z.string(),
1439
+ /** `owner/repo` or `group/subgroup/project`. */
1440
+ repository: z.string(),
1441
+ number: z.number().int().positive(),
1442
+ title: z.string(),
1443
+ author: z.string(),
1444
+ draft: z.boolean(),
1445
+ updatedAt: z.iso.datetime({ offset: true })
1446
+ });
1428
1447
  // packages/engine/src/blobs.ts
1429
1448
  const NEWLINE = 10;
1430
1449
  /**
@@ -5442,6 +5461,955 @@ function isCodeFinding(finding) {
5442
5461
  function lineKey(finding) {
5443
5462
  return finding.location === null || finding.location.line === null ? void 0 : `${finding.location.path}\0${finding.location.line}`;
5444
5463
  }
5464
+ // packages/engine/src/risk/breaking/apiSchemas/apiChange.ts
5465
+ /** What changed in an API's contract, in terms every schema format shares. */
5466
+ const ApiChangeKind = {
5467
+ /** An HTTP operation or an RPC is gone. */
5468
+ OperationRemoved: "operation-removed",
5469
+ /** A type, message or enum is gone. */
5470
+ TypeRemoved: "type-removed",
5471
+ /** A field clients read or send is gone. */
5472
+ FieldRemoved: "field-removed",
5473
+ EnumValueRemoved: "enum-value-removed",
5474
+ TypeChanged: "type-changed",
5475
+ /** A new input that clients must now send. */
5476
+ RequiredAdded: "required-added",
5477
+ /** An input that was optional must now be sent. */
5478
+ BecameRequired: "became-required",
5479
+ /** An output field that was always there can now be missing or null. */
5480
+ BecameOptional: "became-optional",
5481
+ /** A protobuf field or enum value keeps its name but changes its number, which the wire format uses. */
5482
+ NumberChanged: "number-changed"
5483
+ };
5484
+ /** Reads one schema file, naming it in any error so the report can say which file it couldn't read. */
5485
+ function readFile$1(file, read) {
5486
+ try {
5487
+ return read(file.text);
5488
+ } catch (error) {
5489
+ throw new Error(`${file.path}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
5490
+ }
5491
+ }
5492
+ const WORDING$1 = {
5493
+ [ApiChangeKind.OperationRemoved]: {
5494
+ title: (subject) => `${subject} removed from the API`,
5495
+ breaks: "Clients that call it will get errors."
5496
+ },
5497
+ [ApiChangeKind.TypeRemoved]: {
5498
+ title: (subject) => `Type ${subject} removed`,
5499
+ breaks: "Clients that use it will no longer build or validate."
5500
+ },
5501
+ [ApiChangeKind.FieldRemoved]: {
5502
+ title: (subject) => `${subject} removed`,
5503
+ breaks: "Clients that read or send it will break."
5504
+ },
5505
+ [ApiChangeKind.EnumValueRemoved]: {
5506
+ title: (subject) => `Enum value ${subject} removed`,
5507
+ breaks: "Clients that send it will be rejected, and those that match on it will miss it."
5508
+ },
5509
+ [ApiChangeKind.TypeChanged]: {
5510
+ title: (subject, change) => `${subject} changed type${change === void 0 ? "" : ` from ${change}`}`,
5511
+ breaks: "Clients that send or read the old type will break."
5512
+ },
5513
+ [ApiChangeKind.RequiredAdded]: {
5514
+ title: (subject) => `${subject} is new and required`,
5515
+ breaks: "Clients that don't send it yet will be rejected."
5516
+ },
5517
+ [ApiChangeKind.BecameRequired]: {
5518
+ title: (subject) => `${subject} is now required`,
5519
+ breaks: "Clients that leave it out will be rejected."
5520
+ },
5521
+ [ApiChangeKind.BecameOptional]: {
5522
+ title: (subject) => `${subject} can now be missing`,
5523
+ breaks: "Clients that assume it's always there can fail on responses without it."
5524
+ },
5525
+ [ApiChangeKind.NumberChanged]: {
5526
+ title: (subject, change) => `${subject} changed number${change === void 0 ? "" : ` from ${change}`}`,
5527
+ breaks: "Data written with the old number is read as a different field, or lost, by every client and service still using the old schema."
5528
+ }
5529
+ };
5530
+ const ACTION = "Keep the old form alongside the new one until clients have moved, or release it as a new API version.";
5531
+ /** A finding for one API change in `path`, rated higher when it breaks clients already running. */
5532
+ function apiChangeFinding(format, change) {
5533
+ const wording = WORDING$1[change.kind];
5534
+ const subject = codeSpan(change.subject);
5535
+ return findingAt({
5536
+ id: `breaking.api-${change.kind}`,
5537
+ category: RiskCategory.BreakingChange,
5538
+ severity: change.breaksDeployedClients === true ? RiskSeverity.High : RiskSeverity.Medium,
5539
+ title: `${format.name}: ${wording.title(subject, change.change)}`,
5540
+ detail: `${wording.breaks} ${ACTION}`
5541
+ }, change.path, change.line, change.subject);
5542
+ }
5543
+ // packages/engine/src/risk/breaking/apiSchemas/graphql.ts
5544
+ /**
5545
+ * GraphQL schema files (SDL). Types are compared by name, with `extend type` merged into the type
5546
+ * it extends: removed types, fields, arguments and enum values, retyped fields, output fields that
5547
+ * can now be null, and inputs that became required. A schema is often split across files, so all
5548
+ * the PR's GraphQL files are read as one: a type that moves to another file is compared with
5549
+ * itself there, and each change is placed in the file the type is in now.
5550
+ */
5551
+ const SCHEMA_EXTENSIONS = /* @__PURE__ */ new Set([
5552
+ ".graphql",
5553
+ ".graphqls",
5554
+ ".gql"
5555
+ ]);
5556
+ const NON_NULL = "!";
5557
+ const TypeKind = {
5558
+ Object: "object",
5559
+ Input: "input",
5560
+ Enum: "enum",
5561
+ Other: "other"
5562
+ };
5563
+ const GRAPHQL = {
5564
+ name: "GraphQL",
5565
+ matches: (path) => SCHEMA_EXTENSIONS.has(extname(path).toLowerCase()),
5566
+ compare: (before, after) => compareSchemas$1(readSchemas(before), readSchemas(after))
5567
+ };
5568
+ function compareSchemas$1(old, now) {
5569
+ return [...old].flatMap(([name, previous]) => {
5570
+ const current = now.get(name);
5571
+ if (current === void 0) return [{
5572
+ kind: ApiChangeKind.TypeRemoved,
5573
+ subject: name,
5574
+ path: previous.path,
5575
+ line: null,
5576
+ breaksDeployedClients: true
5577
+ }];
5578
+ if (current.kind !== previous.kind) return [{
5579
+ kind: ApiChangeKind.TypeChanged,
5580
+ subject: name,
5581
+ change: `${previous.kind} to ${current.kind}`,
5582
+ path: current.path,
5583
+ line: current.line,
5584
+ breaksDeployedClients: true
5585
+ }];
5586
+ switch (current.kind) {
5587
+ case TypeKind.Object: return outputMemberChanges(name, previous, current);
5588
+ case TypeKind.Input: return inputMemberChanges(name, previous, current);
5589
+ case TypeKind.Enum: return [...previous.values].filter((value) => !current.values.has(value)).map((value) => ({
5590
+ kind: ApiChangeKind.EnumValueRemoved,
5591
+ subject: `${name}.${value}`,
5592
+ path: current.path,
5593
+ line: current.line,
5594
+ breaksDeployedClients: true
5595
+ }));
5596
+ case TypeKind.Other: return [];
5597
+ }
5598
+ });
5599
+ }
5600
+ /** Fields of object types and interfaces, which clients select and read. */
5601
+ function outputMemberChanges(typeName, previous, current) {
5602
+ return [...previous.members].flatMap(([name, member]) => {
5603
+ const subject = `${typeName}.${name}`;
5604
+ const now = current.members.get(name);
5605
+ if (now === void 0) return [{
5606
+ kind: ApiChangeKind.FieldRemoved,
5607
+ subject,
5608
+ path: current.path,
5609
+ line: current.line,
5610
+ breaksDeployedClients: true
5611
+ }];
5612
+ return [...outputTypeChange(subject, member.type, now), ...argumentChanges(subject, member.arguments, now)];
5613
+ });
5614
+ }
5615
+ function outputTypeChange(subject, before, now) {
5616
+ const { type: after, path, line } = now;
5617
+ if (withoutNonNull(before) !== withoutNonNull(after)) return [{
5618
+ kind: ApiChangeKind.TypeChanged,
5619
+ subject,
5620
+ change: `${before} to ${after}`,
5621
+ path,
5622
+ line,
5623
+ breaksDeployedClients: true
5624
+ }];
5625
+ return nonNullCount(after) < nonNullCount(before) ? [{
5626
+ kind: ApiChangeKind.BecameOptional,
5627
+ subject,
5628
+ path,
5629
+ line
5630
+ }] : [];
5631
+ }
5632
+ function inputTypeChange(subject, before, after, path, line) {
5633
+ if (withoutNonNull(before) !== withoutNonNull(after)) return [{
5634
+ kind: ApiChangeKind.TypeChanged,
5635
+ subject,
5636
+ change: `${before} to ${after}`,
5637
+ path,
5638
+ line,
5639
+ breaksDeployedClients: true
5640
+ }];
5641
+ return nonNullCount(after) > nonNullCount(before) ? [{
5642
+ kind: ApiChangeKind.BecameRequired,
5643
+ subject,
5644
+ path,
5645
+ line,
5646
+ breaksDeployedClients: true
5647
+ }] : [];
5648
+ }
5649
+ function argumentChanges(fieldName, before, now) {
5650
+ const { arguments: after, path, line } = now;
5651
+ const removed = [...before.keys()].filter((name) => !after.has(name)).map((name) => ({
5652
+ kind: ApiChangeKind.FieldRemoved,
5653
+ subject: `${fieldName}(${name}:)`,
5654
+ path,
5655
+ line,
5656
+ breaksDeployedClients: true
5657
+ }));
5658
+ const changed = [...after].flatMap(([name, argument]) => {
5659
+ const subject = `${fieldName}(${name}:)`;
5660
+ const previous = before.get(name);
5661
+ if (previous === void 0) return isRequired(argument) ? [{
5662
+ kind: ApiChangeKind.RequiredAdded,
5663
+ subject,
5664
+ path,
5665
+ line,
5666
+ breaksDeployedClients: true
5667
+ }] : [];
5668
+ return inputTypeChange(subject, previous.type, argument.type, path, line);
5669
+ });
5670
+ return [...removed, ...changed];
5671
+ }
5672
+ /** Fields of input types, which clients send. */
5673
+ function inputMemberChanges(typeName, before, after) {
5674
+ const removed = [...before.members.keys()].filter((name) => !after.members.has(name)).map((name) => ({
5675
+ kind: ApiChangeKind.FieldRemoved,
5676
+ subject: `${typeName}.${name}`,
5677
+ path: after.path,
5678
+ line: after.line,
5679
+ breaksDeployedClients: true
5680
+ }));
5681
+ const changed = [...after.members].flatMap(([name, member]) => {
5682
+ const subject = `${typeName}.${name}`;
5683
+ const previous = before.members.get(name);
5684
+ if (previous === void 0) return isRequired(member) ? [{
5685
+ kind: ApiChangeKind.RequiredAdded,
5686
+ subject,
5687
+ path: member.path,
5688
+ line: member.line,
5689
+ breaksDeployedClients: true
5690
+ }] : [];
5691
+ return inputTypeChange(subject, previous.type, member.type, member.path, member.line);
5692
+ });
5693
+ return [...removed, ...changed];
5694
+ }
5695
+ function isRequired(input) {
5696
+ return input.type.endsWith(NON_NULL) && !input.hasDefault;
5697
+ }
5698
+ function withoutNonNull(type) {
5699
+ return type.replaceAll(NON_NULL, "");
5700
+ }
5701
+ function nonNullCount(type) {
5702
+ return type.split(NON_NULL).length - 1;
5703
+ }
5704
+ /** Every type the files define, with `extend` merged in, wherever in the files it is. */
5705
+ function readSchemas(files) {
5706
+ const types = /* @__PURE__ */ new Map();
5707
+ for (const file of files) readFile$1(file, (text) => addTypes(types, file.path, text));
5708
+ return types;
5709
+ }
5710
+ function addTypes(types, path, text) {
5711
+ if (text.trim() === "") return;
5712
+ const lineStarts = [0, ...[...text.matchAll(/\n/g)].map((match) => match.index + 1)];
5713
+ const lineAt = (offset) => offset === void 0 ? 1 : lineStarts.findLastIndex((start) => start <= offset) + 1;
5714
+ for (const definition of parse$1(text).definitions) {
5715
+ const read = typeParts(definition);
5716
+ if (read === void 0) continue;
5717
+ const type = types.get(read.name) ?? {
5718
+ path,
5719
+ kind: read.kind,
5720
+ line: lineAt(definition.loc?.start),
5721
+ members: /* @__PURE__ */ new Map(),
5722
+ values: /* @__PURE__ */ new Set()
5723
+ };
5724
+ for (const member of read.fields) type.members.set(member.name.value, memberOf(member, path, lineAt));
5725
+ for (const value of read.values) type.values.add(value);
5726
+ types.set(read.name, type);
5727
+ }
5728
+ }
5729
+ function typeParts(definition) {
5730
+ switch (definition.kind) {
5731
+ case Kind.OBJECT_TYPE_DEFINITION:
5732
+ case Kind.OBJECT_TYPE_EXTENSION:
5733
+ case Kind.INTERFACE_TYPE_DEFINITION:
5734
+ case Kind.INTERFACE_TYPE_EXTENSION: return {
5735
+ name: definition.name.value,
5736
+ kind: TypeKind.Object,
5737
+ fields: definition.fields ?? [],
5738
+ values: []
5739
+ };
5740
+ case Kind.INPUT_OBJECT_TYPE_DEFINITION:
5741
+ case Kind.INPUT_OBJECT_TYPE_EXTENSION: return {
5742
+ name: definition.name.value,
5743
+ kind: TypeKind.Input,
5744
+ fields: definition.fields ?? [],
5745
+ values: []
5746
+ };
5747
+ case Kind.ENUM_TYPE_DEFINITION:
5748
+ case Kind.ENUM_TYPE_EXTENSION: return {
5749
+ name: definition.name.value,
5750
+ kind: TypeKind.Enum,
5751
+ fields: [],
5752
+ values: (definition.values ?? []).map((value) => value.name.value)
5753
+ };
5754
+ case Kind.UNION_TYPE_DEFINITION:
5755
+ case Kind.UNION_TYPE_EXTENSION:
5756
+ case Kind.SCALAR_TYPE_DEFINITION:
5757
+ case Kind.SCALAR_TYPE_EXTENSION: return {
5758
+ name: definition.name.value,
5759
+ kind: TypeKind.Other,
5760
+ fields: [],
5761
+ values: []
5762
+ };
5763
+ default: return;
5764
+ }
5765
+ }
5766
+ function memberOf(member, path, lineAt) {
5767
+ const argumentNodes = member.kind === Kind.FIELD_DEFINITION ? member.arguments ?? [] : [];
5768
+ return {
5769
+ path,
5770
+ type: print(member.type),
5771
+ line: lineAt(member.loc?.start),
5772
+ arguments: new Map(argumentNodes.map((argument) => [argument.name.value, {
5773
+ type: print(argument.type),
5774
+ hasDefault: argument.defaultValue !== void 0
5775
+ }])),
5776
+ hasDefault: member.kind === Kind.INPUT_VALUE_DEFINITION && member.defaultValue !== void 0
5777
+ };
5778
+ }
5779
+ // packages/engine/src/risk/dependencies/fields.ts
5780
+ function isRecord(value) {
5781
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5782
+ }
5783
+ function field(value, key) {
5784
+ return isRecord(value) ? value[key] : void 0;
5785
+ }
5786
+ function stringField(value, key) {
5787
+ const found = field(value, key);
5788
+ return typeof found === "string" ? found : void 0;
5789
+ }
5790
+ function recordOrEmpty(value) {
5791
+ return isRecord(value) ? value : {};
5792
+ }
5793
+ // packages/engine/src/risk/breaking/apiSchemas/openApi.ts
5794
+ /**
5795
+ * OpenAPI 3 and Swagger 2 specs, in YAML or JSON. Each operation is compared with its earlier
5796
+ * version: removed operations, new or newly required parameters and request fields, removed or
5797
+ * retyped response fields, and enum values clients can no longer send. Only the top level of a
5798
+ * request or response body is compared, after following `$ref`s and `allOf` within the file.
5799
+ */
5800
+ const SPEC_EXTENSIONS = /* @__PURE__ */ new Set([
5801
+ ".yaml",
5802
+ ".yml",
5803
+ ".json"
5804
+ ]);
5805
+ const SPEC_MARKER = /^\s*\{?\s*["']?(?:openapi|swagger)["']?\s*:/m;
5806
+ const HTTP_METHODS = /* @__PURE__ */ new Set([
5807
+ "get",
5808
+ "put",
5809
+ "post",
5810
+ "delete",
5811
+ "options",
5812
+ "head",
5813
+ "patch",
5814
+ "trace"
5815
+ ]);
5816
+ const SUCCESS_STATUS = /^2(?:\d\d|XX)$/;
5817
+ const JSON_MEDIA_TYPE = "application/json";
5818
+ const LOCAL_REF = "#/";
5819
+ const MAX_REF_DEPTH = 32;
5820
+ const OPEN_API = {
5821
+ name: "OpenAPI",
5822
+ matches: (path, text) => SPEC_EXTENSIONS.has(extname(path).toLowerCase()) && SPEC_MARKER.test(text),
5823
+ compare: (before, after) => before.flatMap((old) => {
5824
+ const now = after.find((file) => file.path === old.path) ?? {
5825
+ path: old.path,
5826
+ text: ""
5827
+ };
5828
+ return compareSpecs(readFile$1(old, readSpec), readFile$1(now, readSpec)).map((change) => ({
5829
+ ...change,
5830
+ path: old.path
5831
+ }));
5832
+ })
5833
+ };
5834
+ function compareSpecs(old, now) {
5835
+ return [...old.operations.values()].flatMap((previous) => {
5836
+ const current = now.operations.get(previous.name);
5837
+ if (current === void 0) return [{
5838
+ kind: ApiChangeKind.OperationRemoved,
5839
+ subject: previous.name,
5840
+ line: now.lineOf(["paths", previous.path]),
5841
+ breaksDeployedClients: true
5842
+ }];
5843
+ const line = now.lineOf([
5844
+ "paths",
5845
+ current.path,
5846
+ current.method
5847
+ ]);
5848
+ return [
5849
+ ...inputChanges(previous.parameters, current.parameters, (key) => `${current.name} ${key} parameter`, line),
5850
+ ...!previous.bodyRequired && current.bodyRequired ? [{
5851
+ kind: ApiChangeKind.BecameRequired,
5852
+ subject: `${current.name} request body`,
5853
+ line
5854
+ }] : [],
5855
+ ...inputChanges(previous.requestFields, current.requestFields, (name) => `${current.name} request: ${name}`, line),
5856
+ ...outputChanges(previous.responseFields, current.responseFields, (name) => `${current.name} response: ${name}`, line)
5857
+ ];
5858
+ });
5859
+ }
5860
+ /** What clients send: they break when something new is required, or a value they send stops being accepted. */
5861
+ function inputChanges(old, now, subjectOf, line) {
5862
+ return [...now].flatMap(([key, current]) => {
5863
+ const subject = subjectOf(key);
5864
+ const previous = old.get(key);
5865
+ if (previous === void 0) return current.required ? [{
5866
+ kind: ApiChangeKind.RequiredAdded,
5867
+ subject,
5868
+ line
5869
+ }] : [];
5870
+ const removedValues = previous.enumValues.filter((value) => current.enumValues.length > 0 && !current.enumValues.includes(value));
5871
+ return [
5872
+ ...!previous.required && current.required ? [{
5873
+ kind: ApiChangeKind.BecameRequired,
5874
+ subject,
5875
+ line
5876
+ }] : [],
5877
+ ...typeChange(previous, current, subject, line),
5878
+ ...removedValues.map((value) => ({
5879
+ kind: ApiChangeKind.EnumValueRemoved,
5880
+ subject: `${subject} = ${value}`,
5881
+ line
5882
+ }))
5883
+ ];
5884
+ });
5885
+ }
5886
+ /** What clients read: they break when a field they read is gone, retyped or no longer always there. */
5887
+ function outputChanges(old, now, subjectOf, line) {
5888
+ return [...old].flatMap(([key, previous]) => {
5889
+ const subject = subjectOf(key);
5890
+ const current = now.get(key);
5891
+ if (current === void 0) return [{
5892
+ kind: ApiChangeKind.FieldRemoved,
5893
+ subject,
5894
+ line,
5895
+ breaksDeployedClients: true
5896
+ }];
5897
+ return [...previous.required && !current.required ? [{
5898
+ kind: ApiChangeKind.BecameOptional,
5899
+ subject,
5900
+ line
5901
+ }] : [], ...typeChange(previous, current, subject, line)];
5902
+ });
5903
+ }
5904
+ function typeChange(previous, current, subject, line) {
5905
+ if (previous.type === void 0 || current.type === void 0 || previous.type === current.type) return [];
5906
+ return [{
5907
+ kind: ApiChangeKind.TypeChanged,
5908
+ subject,
5909
+ change: `${previous.type} to ${current.type}`,
5910
+ line
5911
+ }];
5912
+ }
5913
+ function readSpec(text) {
5914
+ const lineCounter = new LineCounter();
5915
+ const document = parseDocument(text, { lineCounter });
5916
+ const [error] = document.errors;
5917
+ if (error !== void 0) throw error;
5918
+ const spec = document.toJS();
5919
+ const operations = /* @__PURE__ */ new Map();
5920
+ for (const [path, item] of Object.entries(recordOrEmpty(field(spec, "paths")))) {
5921
+ const shared = arrayOf$1(field(item, "parameters"));
5922
+ for (const [method, operation] of Object.entries(recordOrEmpty(item))) {
5923
+ if (!HTTP_METHODS.has(method)) continue;
5924
+ const read = readOperation(spec, path, method, operation, shared);
5925
+ operations.set(read.name, read);
5926
+ }
5927
+ }
5928
+ return {
5929
+ operations,
5930
+ lineOf: (keys) => lineOfKeys(document, lineCounter, keys)
5931
+ };
5932
+ }
5933
+ function readOperation(spec, path, method, operation, shared) {
5934
+ const parameters = /* @__PURE__ */ new Map();
5935
+ let bodyRequired = false;
5936
+ let bodySchema;
5937
+ for (const raw of [...shared, ...arrayOf$1(field(operation, "parameters"))]) {
5938
+ const parameter = resolve$1(spec, raw);
5939
+ const name = stringField(parameter, "name");
5940
+ const place = stringField(parameter, "in");
5941
+ if (name === void 0 || place === void 0) continue;
5942
+ if (place === "body") {
5943
+ bodySchema = field(parameter, "schema");
5944
+ bodyRequired = field(parameter, "required") === true;
5945
+ continue;
5946
+ }
5947
+ const schema = field(parameter, "schema") ?? parameter;
5948
+ parameters.set(`${place} ${name}`, {
5949
+ required: field(parameter, "required") === true || place === "path",
5950
+ type: typeOf(spec, schema),
5951
+ enumValues: enumOf(spec, schema)
5952
+ });
5953
+ }
5954
+ const requestBody = resolve$1(spec, field(operation, "requestBody"));
5955
+ if (requestBody !== void 0) {
5956
+ bodySchema = mediaSchema(field(requestBody, "content"));
5957
+ bodyRequired = field(requestBody, "required") === true;
5958
+ }
5959
+ return {
5960
+ name: `${method.toUpperCase()} ${path}`,
5961
+ path,
5962
+ method,
5963
+ parameters,
5964
+ bodyRequired,
5965
+ requestFields: fieldsOf(spec, bodySchema),
5966
+ responseFields: fieldsOf(spec, successSchema(spec, field(operation, "responses")))
5967
+ };
5968
+ }
5969
+ function successSchema(spec, responses) {
5970
+ const status = Object.keys(recordOrEmpty(responses)).filter((code) => SUCCESS_STATUS.test(code)).sort().at(0);
5971
+ if (status === void 0) return void 0;
5972
+ const response = resolve$1(spec, field(responses, status));
5973
+ return field(response, "schema") ?? mediaSchema(field(response, "content"));
5974
+ }
5975
+ function mediaSchema(content) {
5976
+ const media = recordOrEmpty(content);
5977
+ return field(media[JSON_MEDIA_TYPE] ?? Object.values(media).at(0), "schema");
5978
+ }
5979
+ /** The top-level fields of a body schema, through `$ref`, `allOf` and, for a list, its items. */
5980
+ function fieldsOf(spec, schema) {
5981
+ const fields = /* @__PURE__ */ new Map();
5982
+ const resolved = resolve$1(spec, schema);
5983
+ if (field(resolved, "type") === "array") return fieldsOf(spec, field(resolved, "items"));
5984
+ const parts = [resolved, ...arrayOf$1(field(resolved, "allOf")).map((part) => resolve$1(spec, part))];
5985
+ const required = new Set(parts.flatMap((part) => arrayOf$1(field(part, "required")).filter((name) => typeof name === "string")));
5986
+ for (const part of parts) for (const [name, property] of Object.entries(recordOrEmpty(field(part, "properties")))) fields.set(name, {
5987
+ required: required.has(name),
5988
+ type: typeOf(spec, property),
5989
+ enumValues: enumOf(spec, property)
5990
+ });
5991
+ return fields;
5992
+ }
5993
+ function typeOf(spec, schema, depth = 0) {
5994
+ const reference = stringField(schema, "$ref");
5995
+ const resolved = resolve$1(spec, schema);
5996
+ const type = field(resolved, "type");
5997
+ if (type === "array" && depth < MAX_REF_DEPTH) return `array of ${typeOf(spec, field(resolved, "items"), depth + 1) ?? "anything"}`;
5998
+ if (typeof type === "string") return type;
5999
+ if (Array.isArray(type)) return type.join(" or ");
6000
+ return reference?.split("/").at(-1);
6001
+ }
6002
+ function enumOf(spec, schema) {
6003
+ return arrayOf$1(field(resolve$1(spec, schema), "enum")).map(String);
6004
+ }
6005
+ /** Follows a local `$ref` such as `#/components/schemas/User`; other references are left as they are. */
6006
+ function resolve$1(spec, value) {
6007
+ let current = value;
6008
+ for (let depth = 0; depth < MAX_REF_DEPTH; depth++) {
6009
+ const reference = stringField(current, "$ref");
6010
+ if (reference?.startsWith(LOCAL_REF) !== true) return current;
6011
+ current = reference.slice(2).split("/").map((segment) => segment.replaceAll("~1", "/").replaceAll("~0", "~")).reduce((node, segment) => isRecord(node) ? node[segment] : void 0, spec);
6012
+ }
6013
+ return current;
6014
+ }
6015
+ function arrayOf$1(value) {
6016
+ return Array.isArray(value) ? value : [];
6017
+ }
6018
+ /** The line of the deepest of `keys` the document still has, so a removed item points at what holds it. */
6019
+ function lineOfKeys(document, lineCounter, keys) {
6020
+ let node = document.contents;
6021
+ let line = null;
6022
+ for (const key of keys) {
6023
+ if (!isMap(node)) break;
6024
+ const pair = node.items.find((item) => isScalar(item.key) && String(item.key.value) === key);
6025
+ if (pair === void 0 || !isScalar(pair.key) || pair.key.range === void 0 || pair.key.range === null) break;
6026
+ line = lineCounter.linePos(pair.key.range[0]).line;
6027
+ node = pair.value;
6028
+ }
6029
+ return line;
6030
+ }
6031
+ // packages/engine/src/risk/breaking/apiSchemas/protobuf.ts
6032
+ /**
6033
+ * Protocol Buffers schemas (`.proto`). Messages, enums and services are compared by their full
6034
+ * name, with the package: removed or retyped RPCs, fields and enum values whose number changed,
6035
+ * retyped fields, and fields or values removed without reserving their number. The wire format
6036
+ * identifies a field by its number, so a changed number breaks every client and service already
6037
+ * deployed, while a removed name breaks code built against the schema.
6038
+ *
6039
+ * All the PR's `.proto` files are read as one, so a message moved to another file is compared with
6040
+ * itself there. This reads only what a contract consists of; options, extensions and groups are
6041
+ * skipped.
6042
+ */
6043
+ const PROTO_EXTENSION = ".proto";
6044
+ const MAX_FIELD_NUMBER = 536870911;
6045
+ const FIELD_LABELS = /* @__PURE__ */ new Set([
6046
+ "optional",
6047
+ "repeated",
6048
+ "required"
6049
+ ]);
6050
+ const PROTOBUF = {
6051
+ name: "Protobuf",
6052
+ matches: (path) => extname(path).toLowerCase() === PROTO_EXTENSION,
6053
+ compare: (before, after) => compareSchemas(readProtos(before), readProtos(after))
6054
+ };
6055
+ function compareSchemas(old, now) {
6056
+ return [
6057
+ ...rpcChanges(old.rpcs, now.rpcs),
6058
+ ...definitionChanges(old.messages, now.messages, "field"),
6059
+ ...definitionChanges(old.enums, now.enums, "value")
6060
+ ];
6061
+ }
6062
+ function rpcChanges(old, now) {
6063
+ return [...old].flatMap(([name, previous]) => {
6064
+ const current = now.get(name);
6065
+ if (current === void 0) return [{
6066
+ kind: ApiChangeKind.OperationRemoved,
6067
+ subject: name,
6068
+ path: previous.path,
6069
+ line: null,
6070
+ breaksDeployedClients: true
6071
+ }];
6072
+ const before = `${previous.request} → ${previous.response}`;
6073
+ const after = `${current.request} → ${current.response}`;
6074
+ return before === after ? [] : [{
6075
+ kind: ApiChangeKind.TypeChanged,
6076
+ subject: name,
6077
+ change: `${before} to ${after}`,
6078
+ path: current.path,
6079
+ line: current.line,
6080
+ breaksDeployedClients: true
6081
+ }];
6082
+ });
6083
+ }
6084
+ function definitionChanges(old, now, member) {
6085
+ return [...old].flatMap(([name, previous]) => {
6086
+ const current = now.get(name);
6087
+ if (current === void 0) return [{
6088
+ kind: ApiChangeKind.TypeRemoved,
6089
+ subject: name,
6090
+ path: previous.path,
6091
+ line: null
6092
+ }];
6093
+ return [...previous.fields].flatMap(([fieldName, field]) => memberChanges(`${name}.${fieldName}`, field, current, fieldName, member));
6094
+ });
6095
+ }
6096
+ function memberChanges(subject, previous, current, name, member) {
6097
+ const now = current.fields.get(name);
6098
+ if (now === void 0) {
6099
+ if (![...current.fields.values()].some((field) => field.number === previous.number) && isReserved(current.reserved, previous.number)) return [];
6100
+ return [{
6101
+ kind: member === "field" ? ApiChangeKind.FieldRemoved : ApiChangeKind.EnumValueRemoved,
6102
+ subject,
6103
+ path: current.path,
6104
+ line: current.line
6105
+ }];
6106
+ }
6107
+ const path = current.path;
6108
+ const line = now.line;
6109
+ return [...now.number === previous.number ? [] : [{
6110
+ kind: ApiChangeKind.NumberChanged,
6111
+ subject,
6112
+ change: `${previous.number} to ${now.number}`,
6113
+ path,
6114
+ line,
6115
+ breaksDeployedClients: true
6116
+ }], ...now.type === previous.type ? [] : [{
6117
+ kind: ApiChangeKind.TypeChanged,
6118
+ subject,
6119
+ change: `${previous.type} to ${now.type}`,
6120
+ path,
6121
+ line,
6122
+ breaksDeployedClients: true
6123
+ }]];
6124
+ }
6125
+ function isReserved(reserved, number) {
6126
+ return reserved.ranges.some(([low, high]) => number >= low && number <= high);
6127
+ }
6128
+ const TOKEN = /\/\/[^\n]*|\/\*[\s\S]*?\*\/|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[A-Za-z_.][\w.]*|-?\d+|\S/g;
6129
+ function tokenize(text) {
6130
+ const tokens = [];
6131
+ let line = 1;
6132
+ let lastIndex = 0;
6133
+ for (const match of text.matchAll(TOKEN)) {
6134
+ line += countNewlines(text, lastIndex, match.index);
6135
+ lastIndex = match.index;
6136
+ if (!match[0].startsWith("//") && !match[0].startsWith("/*")) tokens.push({
6137
+ text: match[0],
6138
+ line
6139
+ });
6140
+ }
6141
+ return tokens;
6142
+ }
6143
+ function countNewlines(text, from, to) {
6144
+ let count = 0;
6145
+ for (let index = text.indexOf("\n", from); index !== -1 && index < to; index = text.indexOf("\n", index + 1)) count++;
6146
+ return count;
6147
+ }
6148
+ /** Reads tokens front to back; each read method consumes what it reads. */
6149
+ var ProtoReader = class {
6150
+ position = 0;
6151
+ tokens;
6152
+ path;
6153
+ schema;
6154
+ /** Adds what one file defines to `schema`, which the PR's other files add to as well. */
6155
+ constructor(schema, path, text) {
6156
+ this.schema = schema;
6157
+ this.path = path;
6158
+ this.tokens = tokenize(text);
6159
+ }
6160
+ readFile() {
6161
+ let scope = "";
6162
+ while (!this.atEnd()) {
6163
+ const word = this.next().text;
6164
+ if (word === "package") {
6165
+ scope = `${this.next().text}.`;
6166
+ this.expect(";");
6167
+ } else if (word === "message") this.readMessage(scope);
6168
+ else if (word === "enum") this.readEnum(scope);
6169
+ else if (word === "service") this.readService(scope);
6170
+ else if (this.peek() === "{") this.skipBlock();
6171
+ else this.skipStatement();
6172
+ }
6173
+ }
6174
+ readMessage(scope) {
6175
+ const { text: name, line } = this.next();
6176
+ const fullName = `${scope}${name}`;
6177
+ const message = {
6178
+ path: this.path,
6179
+ line,
6180
+ fields: /* @__PURE__ */ new Map(),
6181
+ reserved: { ranges: [] }
6182
+ };
6183
+ this.schema.messages.set(fullName, message);
6184
+ this.expect("{");
6185
+ this.readMembers(message, `${fullName}.`);
6186
+ }
6187
+ readMembers(message, scope) {
6188
+ while (!this.atEnd() && this.peek() !== "}") {
6189
+ const word = this.peek();
6190
+ if (word === "option" || word === "extensions" || word === "extend" || word === "group") {
6191
+ this.skipStatementOrBlock();
6192
+ continue;
6193
+ }
6194
+ if (word !== "message" && word !== "enum" && word !== "oneof" && word !== "reserved") {
6195
+ this.readField(message);
6196
+ continue;
6197
+ }
6198
+ this.next();
6199
+ if (word === "message") this.readMessage(scope);
6200
+ else if (word === "enum") this.readEnum(scope);
6201
+ else if (word === "reserved") this.readReserved(message.reserved);
6202
+ else {
6203
+ this.next();
6204
+ this.expect("{");
6205
+ this.readMembers(message, scope);
6206
+ }
6207
+ }
6208
+ this.next();
6209
+ }
6210
+ readField(message) {
6211
+ const first = this.next();
6212
+ const label = FIELD_LABELS.has(first.text) ? `${first.text} ` : "";
6213
+ const type = label === "" ? this.readType(first.text) : this.readType(this.next().text);
6214
+ const name = this.next().text;
6215
+ if (this.peek() === "=") {
6216
+ this.next();
6217
+ message.fields.set(name, {
6218
+ type: `${label}${type}`,
6219
+ number: Number(this.next().text),
6220
+ line: first.line
6221
+ });
6222
+ }
6223
+ this.skipStatement();
6224
+ }
6225
+ readType(first) {
6226
+ if (first !== "map" || this.peek() !== "<") return first;
6227
+ const parts = [];
6228
+ while (!this.atEnd() && this.peek() !== ">") parts.push(this.next().text);
6229
+ this.next();
6230
+ return `map${parts.join("").replace(",", ", ")}>`;
6231
+ }
6232
+ readEnum(scope) {
6233
+ const { text: name, line } = this.next();
6234
+ const values = {
6235
+ path: this.path,
6236
+ line,
6237
+ fields: /* @__PURE__ */ new Map(),
6238
+ reserved: { ranges: [] }
6239
+ };
6240
+ this.schema.enums.set(`${scope}${name}`, values);
6241
+ this.expect("{");
6242
+ while (!this.atEnd() && this.peek() !== "}") {
6243
+ const token = this.next();
6244
+ if (token.text === "reserved") this.readReserved(values.reserved);
6245
+ else if (token.text === "option") this.skipStatement();
6246
+ else if (this.peek() === "=") {
6247
+ this.next();
6248
+ values.fields.set(token.text, {
6249
+ type: "",
6250
+ number: Number(this.next().text),
6251
+ line: token.line
6252
+ });
6253
+ this.skipStatement();
6254
+ } else this.skipStatement();
6255
+ }
6256
+ this.next();
6257
+ }
6258
+ readReserved(reserved) {
6259
+ while (!this.atEnd() && this.peek() !== ";") {
6260
+ const token = this.next().text;
6261
+ if (token === "," || /^["']/.test(token)) continue;
6262
+ const low = Number(token);
6263
+ if (this.peek() === "to") {
6264
+ this.next();
6265
+ const end = this.next().text;
6266
+ reserved.ranges.push([low, end === "max" ? MAX_FIELD_NUMBER : Number(end)]);
6267
+ } else reserved.ranges.push([low, low]);
6268
+ }
6269
+ this.next();
6270
+ }
6271
+ readService(scope) {
6272
+ const service = `${scope}${this.next().text}`;
6273
+ this.expect("{");
6274
+ while (!this.atEnd() && this.peek() !== "}") {
6275
+ const token = this.next();
6276
+ if (token.text !== "rpc") {
6277
+ this.skipStatementOrBlock();
6278
+ continue;
6279
+ }
6280
+ const name = this.next().text;
6281
+ const request = this.readRpcType();
6282
+ this.next();
6283
+ const response = this.readRpcType();
6284
+ this.schema.rpcs.set(`${service}.${name}`, {
6285
+ path: this.path,
6286
+ request,
6287
+ response,
6288
+ line: token.line
6289
+ });
6290
+ this.skipStatementOrBlock();
6291
+ }
6292
+ this.next();
6293
+ }
6294
+ readRpcType() {
6295
+ this.expect("(");
6296
+ const parts = [];
6297
+ while (!this.atEnd() && this.peek() !== ")") parts.push(this.next().text);
6298
+ this.next();
6299
+ return parts.join(" ");
6300
+ }
6301
+ skipStatementOrBlock() {
6302
+ while (!this.atEnd() && this.peek() !== ";" && this.peek() !== "{") this.next();
6303
+ if (this.peek() === "{") this.skipBlock();
6304
+ if (this.peek() === ";") this.next();
6305
+ }
6306
+ skipStatement() {
6307
+ let depth = 0;
6308
+ while (!this.atEnd()) {
6309
+ const text = this.next().text;
6310
+ if (text === "[" || text === "(") depth++;
6311
+ else if (text === "]" || text === ")") depth--;
6312
+ else if (text === ";" && depth <= 0) return;
6313
+ }
6314
+ }
6315
+ skipBlock() {
6316
+ let depth = 0;
6317
+ while (!this.atEnd()) {
6318
+ const text = this.next().text;
6319
+ if (text === "{") depth++;
6320
+ else if (text === "}" && --depth === 0) return;
6321
+ }
6322
+ }
6323
+ expect(text) {
6324
+ const token = this.next();
6325
+ if (token.text !== text) throw new SyntaxError(`expected "${text}" on line ${token.line}, found "${token.text}"`);
6326
+ }
6327
+ peek() {
6328
+ return this.tokens[this.position]?.text;
6329
+ }
6330
+ next() {
6331
+ const token = this.tokens[this.position];
6332
+ if (token === void 0) throw new SyntaxError("the file ends in the middle of a definition");
6333
+ this.position++;
6334
+ return token;
6335
+ }
6336
+ atEnd() {
6337
+ return this.position >= this.tokens.length;
6338
+ }
6339
+ };
6340
+ function readProtos(files) {
6341
+ const schema = {
6342
+ messages: /* @__PURE__ */ new Map(),
6343
+ enums: /* @__PURE__ */ new Map(),
6344
+ rpcs: /* @__PURE__ */ new Map()
6345
+ };
6346
+ for (const file of files) readFile$1(file, (text) => new ProtoReader(schema, file.path, text).readFile());
6347
+ return schema;
6348
+ }
6349
+ // packages/engine/src/risk/breaking/apiSchemas/scanApiSchemas.ts
6350
+ const FORMATS$2 = [
6351
+ OPEN_API,
6352
+ GRAPHQL,
6353
+ PROTOBUF
6354
+ ];
6355
+ /**
6356
+ * Compares the API schemas a PR touches with their versions at the merge base. A format is only
6357
+ * compared when the PR changes or deletes one of its files: a new schema file can't break anyone.
6358
+ */
6359
+ async function scanApiSchemas(repoDir, base, files) {
6360
+ const scan = {
6361
+ findings: [],
6362
+ notChecked: []
6363
+ };
6364
+ for (const [format, { before, after }] of await filesByFormat(repoDir, base, files)) {
6365
+ if (before.length === 0) continue;
6366
+ try {
6367
+ scan.findings.push(...format.compare(before, after).map((change) => apiChangeFinding(format, change)));
6368
+ } catch (error) {
6369
+ scan.notChecked.push({
6370
+ check: `${format.name} breaking changes`,
6371
+ reason: `couldn't read ${error instanceof Error ? error.message : String(error)}`
6372
+ });
6373
+ }
6374
+ }
6375
+ return scan;
6376
+ }
6377
+ async function filesByFormat(repoDir, base, files) {
6378
+ const relevant = files.filter((file) => !isThirdParty(file) && !isTestPath(file.diff.path));
6379
+ const earlier = relevant.filter((file) => file.diff.status !== FileChangeStatus.Added);
6380
+ const blobs = await readBlobs(repoDir, earlier.map((file) => ({
6381
+ commit: base,
6382
+ path: previousPathOf$3(file.diff)
6383
+ })));
6384
+ const before = new Map(earlier.flatMap((file, index) => {
6385
+ const text = blobs.at(index)?.toString("utf8");
6386
+ return text === void 0 ? [] : [[file, text]];
6387
+ }));
6388
+ const byFormat = /* @__PURE__ */ new Map();
6389
+ for (const file of relevant) {
6390
+ const earlierText = before.get(file);
6391
+ const after = file.diff.status === FileChangeStatus.Deleted ? "" : file.after;
6392
+ const format = FORMATS$2.find((candidate) => candidate.matches(file.diff.path, after === void 0 || after === "" ? earlierText ?? "" : after));
6393
+ if (format === void 0 || after === void 0) continue;
6394
+ const entry = byFormat.get(format) ?? {
6395
+ before: [],
6396
+ after: []
6397
+ };
6398
+ if (earlierText !== void 0) entry.before.push({
6399
+ path: file.diff.path,
6400
+ text: earlierText
6401
+ });
6402
+ entry.after.push({
6403
+ path: file.diff.path,
6404
+ text: after
6405
+ });
6406
+ byFormat.set(format, entry);
6407
+ }
6408
+ return byFormat;
6409
+ }
6410
+ function previousPathOf$3(diff) {
6411
+ return diff.status === FileChangeStatus.Renamed || diff.status === FileChangeStatus.Copied ? diff.previousPath : diff.path;
6412
+ }
5445
6413
  // packages/engine/src/risk/breaking/codeMentions.ts
5446
6414
  const MAX_FILES_FOR_A_COMMON_WORD = 25;
5447
6415
  const MAX_FILES_FOR_A_SPECIFIC_NAME = 200;
@@ -6476,16 +7444,21 @@ async function scanBreakingChanges(scan) {
6476
7444
  const mentions = await mentionsInCode(scan.repoDir, scan.head, names);
6477
7445
  const renamesInEnvFiles = new Set(configChanges.filter((change) => change.kind === ConfigChangeKind.RenamedVariable).map((change) => change.name));
6478
7446
  const config = configChanges.filter((change) => change.kind !== ConfigChangeKind.ReplacedRead || !renamesInEnvFiles.has(change.name)).flatMap((change) => configChangeFinding(change, mentions.get(change.name)) ?? []);
6479
- return [
6480
- ...scanPublicApi({
6481
- files: scan.files,
6482
- versions: scan.versions,
6483
- headTexts,
6484
- surface
6485
- }),
6486
- ...schemaChanges.map((change) => schemaChangeFinding(change, mentions.get(change.name))),
6487
- ...config
6488
- ];
7447
+ const apiSchemas = await scanApiSchemas(scan.repoDir, scan.base, scan.scanned);
7448
+ return {
7449
+ findings: [
7450
+ ...scanPublicApi({
7451
+ files: scan.files,
7452
+ versions: scan.versions,
7453
+ headTexts,
7454
+ surface
7455
+ }),
7456
+ ...apiSchemas.findings,
7457
+ ...schemaChanges.map((change) => schemaChangeFinding(change, mentions.get(change.name))),
7458
+ ...config
7459
+ ],
7460
+ notChecked: apiSchemas.notChecked
7461
+ };
6489
7462
  }
6490
7463
  // packages/engine/src/risk/dependencies/osv.ts
6491
7464
  const OSV_API = "https://api.osv.dev/v1";
@@ -6776,20 +7749,6 @@ function addReplacement(replacements, words) {
6776
7749
  function unquote(word) {
6777
7750
  return word.replace(/^["`]|["`]$/g, "");
6778
7751
  }
6779
- // packages/engine/src/risk/dependencies/fields.ts
6780
- function isRecord(value) {
6781
- return typeof value === "object" && value !== null && !Array.isArray(value);
6782
- }
6783
- function field(value, key) {
6784
- return isRecord(value) ? value[key] : void 0;
6785
- }
6786
- function stringField(value, key) {
6787
- const found = field(value, key);
6788
- return typeof found === "string" ? found : void 0;
6789
- }
6790
- function recordOrEmpty(value) {
6791
- return isRecord(value) ? value : {};
6792
- }
6793
7752
  // packages/engine/src/risk/dependencies/maven.ts
6794
7753
  const COMMENT_OPEN = "<!--";
6795
7754
  const COMMENT_CLOSE = "-->";
@@ -6931,7 +7890,7 @@ function buildCoordinates(text) {
6931
7890
  return [...fromStrings, ...fromMaps];
6932
7891
  }
6933
7892
  function catalogCoordinates(text) {
6934
- const catalog = parse$1(text);
7893
+ const catalog = parse$2(text);
6935
7894
  const versions = recordOrEmpty(field(catalog, "versions"));
6936
7895
  return Object.values(recordOrEmpty(field(catalog, "libraries"))).flatMap((library) => {
6937
7896
  if (typeof library === "string") {
@@ -7087,7 +8046,7 @@ function parsePackageJson(text) {
7087
8046
  return declared;
7088
8047
  }
7089
8048
  function parseCargoToml(text) {
7090
- const manifest = parse$1(text);
8049
+ const manifest = parse$2(text);
7091
8050
  const declared = /* @__PURE__ */ new Map();
7092
8051
  const sections = [
7093
8052
  field(manifest, "dependencies"),
@@ -7109,7 +8068,7 @@ function cargoSource(value) {
7109
8068
  return field(value, "workspace") === true ? "workspace:" : void 0;
7110
8069
  }
7111
8070
  function parsePyproject(text) {
7112
- const manifest = parse$1(text);
8071
+ const manifest = parse$2(text);
7113
8072
  const declared = /* @__PURE__ */ new Map();
7114
8073
  const project = field(manifest, "project");
7115
8074
  const requirementLists = [field(project, "dependencies"), ...Object.values(recordOrEmpty(field(project, "optional-dependencies")))];
@@ -7148,7 +8107,7 @@ function parsePackageLock(text) {
7148
8107
  });
7149
8108
  }
7150
8109
  function tomlPackages$1(text, ecosystem) {
7151
- const packages = field(parse$1(text), "package");
8110
+ const packages = field(parse$2(text), "package");
7152
8111
  return (Array.isArray(packages) ? packages : []).flatMap((entry) => {
7153
8112
  const name = stringField(entry, "name");
7154
8113
  const version = stringField(entry, "version");
@@ -7637,7 +8596,7 @@ const RegistryStatus = {
7637
8596
  Missing: "missing"
7638
8597
  };
7639
8598
  const NEW_PACKAGE_DAYS = 30;
7640
- const MS_PER_DAY = 864e5;
8599
+ const MS_PER_DAY$1 = 864e5;
7641
8600
  const MIN_NAME_LENGTH_TO_COMPARE = 5;
7642
8601
  const MAX_LOOKUPS = 100;
7643
8602
  const CONCURRENT_LOOKUPS = 8;
@@ -7703,7 +8662,7 @@ async function inBatches(items, size, work) {
7703
8662
  }
7704
8663
  function registryFindings(entry, found, now, allowedLicenses) {
7705
8664
  if (found.status === RegistryStatus.Missing) return [missingFinding(entry)];
7706
- const days = Math.floor((now.getTime() - found.firstPublished.getTime()) / MS_PER_DAY);
8665
+ const days = Math.floor((now.getTime() - found.firstPublished.getTime()) / MS_PER_DAY$1);
7707
8666
  const isPopular = POPULAR_PACKAGES[entry.ecosystem].has(entry.name);
7708
8667
  return [...days < NEW_PACKAGE_DAYS && !isPopular ? [newPackageFinding(entry, days)] : [], ...licenseFindings(entry, found.license, allowedLicenses)];
7709
8668
  }
@@ -9302,7 +10261,7 @@ const FROM_PYPI = {
9302
10261
  };
9303
10262
  const LOCAL = { kind: OriginKind.Local };
9304
10263
  function tomlPackages(text, read, normalizeName = (name) => name) {
9305
- const packages = field(parse$1(text), "package");
10264
+ const packages = field(parse$2(text), "package");
9306
10265
  return (Array.isArray(packages) ? packages : []).flatMap((entry) => {
9307
10266
  const name = stringField(entry, "name");
9308
10267
  const version = stringField(entry, "version");
@@ -9388,18 +10347,7 @@ function readGoSum(text) {
9388
10347
  }];
9389
10348
  });
9390
10349
  }
9391
- // packages/engine/src/risk/supplyChain/scanSupplyChain.ts
9392
- const SUPPLY_CHAIN_CHECK$1 = {
9393
- name: "Supply chain",
9394
- detail: "lockfile sources, content hashes and install scripts, and package-manager settings",
9395
- security: true
9396
- };
9397
- const NPM_RELEASES_CHECK = "npm release history";
9398
- const NPM_RELEASES_RUN = {
9399
- name: NPM_RELEASES_CHECK,
9400
- detail: "who published upgraded npm packages, and whether they kept provenance",
9401
- security: true
9402
- };
10350
+ // packages/engine/src/risk/supplyChain/lockfileReaders.ts
9403
10351
  const LOCKFILE_READERS = [
9404
10352
  PACKAGE_LOCK,
9405
10353
  YARN_LOCK,
@@ -9409,6 +10357,22 @@ const LOCKFILE_READERS = [
9409
10357
  POETRY_LOCK,
9410
10358
  GO_SUM
9411
10359
  ];
10360
+ /** The reader for a lockfile at `path`, by its file name; undefined for anything else. */
10361
+ function lockfileReaderFor(path) {
10362
+ return LOCKFILE_READERS.find((reader) => reader.matches(basename(path)));
10363
+ }
10364
+ // packages/engine/src/risk/supplyChain/scanSupplyChain.ts
10365
+ const SUPPLY_CHAIN_CHECK$1 = {
10366
+ name: "Supply chain",
10367
+ detail: "lockfile sources, content hashes and install scripts, and package-manager settings",
10368
+ security: true
10369
+ };
10370
+ const NPM_RELEASES_CHECK = "npm release history";
10371
+ const NPM_RELEASES_RUN = {
10372
+ name: NPM_RELEASES_CHECK,
10373
+ detail: "who published upgraded npm packages, and whether they kept provenance",
10374
+ security: true
10375
+ };
9412
10376
  /**
9413
10377
  * How the packages a PR depends on reach the build, separately from whether they're vulnerable:
9414
10378
  * lockfile entries that change source or content, gain install scripts or move a private name to a
@@ -9465,7 +10429,7 @@ async function readLockfiles(request, outcome) {
9465
10429
  return lockfiles.flatMap(({ diff }, index) => {
9466
10430
  const before = blobs.at(2 * index)?.toString("utf8");
9467
10431
  const after = blobs.at(2 * index + 1)?.toString("utf8");
9468
- const reader = readerFor(diff.path);
10432
+ const reader = lockfileReaderFor(diff.path);
9469
10433
  if (after === void 0 || reader === void 0) return [];
9470
10434
  try {
9471
10435
  return [{
@@ -9486,10 +10450,7 @@ async function readLockfiles(request, outcome) {
9486
10450
  }
9487
10451
  function isReadableLockfile(file) {
9488
10452
  if (file.diff.status === FileChangeStatus.Deleted || file.noise?.kind === NoiseKind.Vendored || isTestPath(file.diff.path)) return false;
9489
- return readerFor(file.diff.path) !== void 0;
9490
- }
9491
- function readerFor(path) {
9492
- return LOCKFILE_READERS.find((reader) => reader.matches(basename(path)));
10453
+ return lockfileReaderFor(file.diff.path) !== void 0;
9493
10454
  }
9494
10455
  function previousPathOf$1(diff) {
9495
10456
  return diff.status === FileChangeStatus.Renamed || diff.status === FileChangeStatus.Copied ? diff.previousPath : diff.path;
@@ -10033,6 +10994,760 @@ const BUILT_IN_RULES_CHECK = {
10033
10994
  function inWords(items) {
10034
10995
  return items.length <= 1 ? items[0] ?? "" : `${items.slice(0, -1).join(", ")} and ${items.at(-1) ?? ""}`;
10035
10996
  }
10997
+ // packages/engine/src/risk/docsDrift/docMentions.ts
10998
+ const DOC_EXTENSIONS = /* @__PURE__ */ new Set([
10999
+ ".md",
11000
+ ".mdx",
11001
+ ".markdown",
11002
+ ".rst",
11003
+ ".adoc",
11004
+ ".asciidoc"
11005
+ ]);
11006
+ const HISTORY_FILE = /change|history|release|news|migrat|upgrad|deprecat|breaking/i;
11007
+ const MAX_DOC_FILES = 2e3;
11008
+ const MAX_DOC_BYTES = 1e6;
11009
+ /**
11010
+ * Finds where the docs at `head` still use each retired name. A line naming both the old name and
11011
+ * its replacement is describing the rename, so it doesn't count.
11012
+ */
11013
+ async function staleMentions(repoDir, head, retired) {
11014
+ if (retired.length === 0) return [];
11015
+ const docs = (await docFiles(repoDir, head)).slice(0, MAX_DOC_FILES);
11016
+ const blobs = await readBlobs(repoDir, docs.map((path) => ({
11017
+ commit: head,
11018
+ path
11019
+ })));
11020
+ const matchers = retired.map((name) => ({
11021
+ retired: name,
11022
+ uses: wordPattern(name.name),
11023
+ describesRename: name.replacement === void 0 ? void 0 : wordPattern(name.replacement)
11024
+ }));
11025
+ return docs.flatMap((path, index) => {
11026
+ const blob = blobs.at(index);
11027
+ if (blob === void 0 || blob.length > MAX_DOC_BYTES) return [];
11028
+ const lines = blob.toString("utf8").split("\n");
11029
+ return matchers.flatMap(({ retired: name, uses, describesRename }) => {
11030
+ const hits = lines.flatMap((text, row) => uses.test(text) && describesRename?.test(text) !== true ? [{
11031
+ line: row + 1,
11032
+ text: text.trim()
11033
+ }] : []);
11034
+ const first = hits.at(0);
11035
+ return first === void 0 ? [] : [{
11036
+ retired: name,
11037
+ path,
11038
+ line: first.line,
11039
+ text: first.text,
11040
+ count: hits.length
11041
+ }];
11042
+ });
11043
+ });
11044
+ }
11045
+ async function docFiles(repoDir, head) {
11046
+ return (await runGit([
11047
+ "ls-tree",
11048
+ "-r",
11049
+ "-z",
11050
+ "--name-only",
11051
+ head
11052
+ ], {
11053
+ cwd: repoDir,
11054
+ env: ISOLATED_CONFIG_ENV
11055
+ })).split("\0").filter((path) => DOC_EXTENSIONS.has(extname(path).toLowerCase()) && !HISTORY_FILE.test(basename(path)) && !isNoiseByPath(path) && !isTestPath(path));
11056
+ }
11057
+ function wordPattern(name) {
11058
+ return new RegExp(`(?<![\\p{L}\\p{N}_$-])${escapeRegExp$1(name)}(?![\\p{L}\\p{N}_$-])`, "u");
11059
+ }
11060
+ // packages/engine/src/risk/docsDrift/parameterDocs.ts
11061
+ const AT_PARAM = /@param\s+(?:\{[^}]*\}\s+)?\[?\$?([A-Za-z_$][\w$]*)/g;
11062
+ const REST_PARAM = /:param\s+(?:[\w[\], .]+\s+)?([A-Za-z_]\w*)\s*:/g;
11063
+ const SECTION_HEADER = /^(\s*)(#+\s*)?(?:Args|Arguments|Parameters|Keyword Args|Keyword Arguments)\s*:?\s*$/;
11064
+ const LINE_DOC_PREFIX = /^\s*\/\/[/!] ?/;
11065
+ const UNDERLINE = /^\s*-{3,}\s*$/;
11066
+ const SECTION_ENTRY = /^\s*(?:[*-]\s+`)?\*{0,2}([A-Za-z_]\w*)`?\s*(?:\([^)]*\))?\s*[:-]/;
11067
+ const NAME_MARKERS = /^[*&$.]+/;
11068
+ const RECEIVERS = /* @__PURE__ */ new Set([
11069
+ "self",
11070
+ "cls",
11071
+ "this"
11072
+ ]);
11073
+ /**
11074
+ * Doc comments that no longer match their function's parameters, in functions the PR changed.
11075
+ * Only parameters the PR added or removed are compared: a doc comment that was already out of
11076
+ * date isn't this PR's doing.
11077
+ */
11078
+ function parameterDrift(files) {
11079
+ return files.filter((file) => !isTestPath(file.diff.path)).flatMap((file) => changedUnitsOf(file).flatMap((unit) => driftIn(file.diff.path, unit)));
11080
+ }
11081
+ function driftIn(path, unit) {
11082
+ const after = snapshotAfter(unit);
11083
+ const facts = unit.facts;
11084
+ if (after === void 0 || facts === null || isTestUnit(unit)) return [];
11085
+ const documented = documentedParameters(after.text);
11086
+ if (documented.size === 0) return [];
11087
+ const stale = facts.parametersRemoved.map(plainName).filter((name) => documented.has(name));
11088
+ const missing = facts.parametersAdded.map(plainName).filter((name) => !documented.has(name) && !RECEIVERS.has(name));
11089
+ return stale.length === 0 && missing.length === 0 ? [] : [{
11090
+ path,
11091
+ line: after.startLine,
11092
+ unit: unit.qualifiedName,
11093
+ stale,
11094
+ missing
11095
+ }];
11096
+ }
11097
+ function snapshotAfter(unit) {
11098
+ switch (unit.change.kind) {
11099
+ case UnitChangeKind.Modified:
11100
+ case UnitChangeKind.Renamed:
11101
+ case UnitChangeKind.MovedIn: return unit.change.after;
11102
+ case UnitChangeKind.Added:
11103
+ case UnitChangeKind.Removed:
11104
+ case UnitChangeKind.MovedOut: return;
11105
+ }
11106
+ }
11107
+ function plainName(name) {
11108
+ return name.replace(NAME_MARKERS, "");
11109
+ }
11110
+ /** The parameter names a function's doc comment describes, in any of the common styles. */
11111
+ function documentedParameters(text) {
11112
+ const names = new Set([...text.matchAll(AT_PARAM), ...text.matchAll(REST_PARAM)].map((match) => match[1] ?? ""));
11113
+ const lines = text.split("\n").map((line) => line.replace(LINE_DOC_PREFIX, ""));
11114
+ lines.forEach((line, index) => {
11115
+ const header = SECTION_HEADER.exec(line);
11116
+ if (header === null) return;
11117
+ const underlined = UNDERLINE.test(lines.at(index + 1) ?? "");
11118
+ const markdown = header[2] !== void 0;
11119
+ const body = lines.slice(index + (underlined ? 2 : 1));
11120
+ const start = markdown ? body.findIndex((entry) => entry.trim() !== "") : 0;
11121
+ for (const name of sectionEntries(body.slice(Math.max(start, 0)), (header[1] ?? "").length, underlined || markdown)) names.add(name);
11122
+ });
11123
+ names.delete("");
11124
+ return names;
11125
+ }
11126
+ /**
11127
+ * Entries of a section, which ends at a blank line, the next title, or a line less indented than
11128
+ * its header. Entries all share one indent: Google style indents them under the header and NumPy
11129
+ * style keeps them level with it. Their descriptions sit deeper, and can contain colons.
11130
+ */
11131
+ function sectionEntries(lines, headerIndent, entriesLevel) {
11132
+ const names = [];
11133
+ let entryIndent = entriesLevel ? headerIndent : void 0;
11134
+ for (const line of lines) {
11135
+ if (line.trim() === "" || SECTION_HEADER.test(line)) break;
11136
+ const indent = line.length - line.trimStart().length;
11137
+ if (indent < headerIndent || !entriesLevel && indent === headerIndent) break;
11138
+ entryIndent ??= indent;
11139
+ const name = indent === entryIndent ? SECTION_ENTRY.exec(line)?.[1] : void 0;
11140
+ if (name !== void 0) names.push(name);
11141
+ }
11142
+ return names;
11143
+ }
11144
+ // packages/engine/src/risk/docsDrift/retiredNames.ts
11145
+ /** What kind of name a PR retires, which says who notices when docs still use it. */
11146
+ const RetiredNameKind = {
11147
+ /** A command-line option: whoever copies it from the docs gets an error. */
11148
+ CliFlag: "cliFlag",
11149
+ /** An environment variable or config key: a deployment set up from the docs silently misses it. */
11150
+ Setting: "setting",
11151
+ /** A function, class or other unit: whoever reads the docs looks for code that isn't there. */
11152
+ Code: "code"
11153
+ };
11154
+ const FLAG_IN_CODE = /(?:["'`]|^\s*)(--[a-z][a-z0-9]*(?:-[a-z0-9]+)*)(?![\w-])/g;
11155
+ const DOCUMENTED_UNIT_CHANGES = /* @__PURE__ */ new Set([UnitChangeKind.Removed, UnitChangeKind.Renamed]);
11156
+ /**
11157
+ * Names the PR removes or renames: units, command-line options in code, environment variables and
11158
+ * config keys. A name only counts once nothing the PR adds still uses it; whether code elsewhere
11159
+ * still uses it is for the caller to rule out.
11160
+ */
11161
+ function retiredNames(files, scanned) {
11162
+ const kept = new Set(scanned.flatMap((file) => addedLines(file.diff).flatMap((line) => [...line.content.matchAll(FLAG_IN_CODE)].map((match) => match[1] ?? ""))));
11163
+ const names = [
11164
+ ...retiredUnits(files),
11165
+ ...retiredFlags(scanned, kept),
11166
+ ...retiredSettings(scanned)
11167
+ ];
11168
+ const seen = /* @__PURE__ */ new Set();
11169
+ return names.filter((retired) => {
11170
+ if (seen.has(retired.name)) return false;
11171
+ seen.add(retired.name);
11172
+ return true;
11173
+ });
11174
+ }
11175
+ function retiredUnits(files) {
11176
+ return files.filter((file) => !isTestPath(file.diff.path)).flatMap((file) => changedUnitsOf(file)).filter((unit) => DOCUMENTED_UNIT_CHANGES.has(unit.change.kind) && !isTestUnit(unit)).flatMap((unit) => {
11177
+ const before = unit.change.kind === UnitChangeKind.Renamed ? unit.change.previousName : unit.name;
11178
+ if (!isSpecificName(before)) return [];
11179
+ return [{
11180
+ name: before,
11181
+ kind: RetiredNameKind.Code,
11182
+ replacement: unit.change.kind === UnitChangeKind.Renamed ? unit.name : void 0
11183
+ }];
11184
+ });
11185
+ }
11186
+ function retiredFlags(scanned, kept) {
11187
+ return scanned.filter((file) => languageSpecFor(file.diff.path) !== void 0 && !isThirdParty(file) && !isTestPath(file.diff.path)).flatMap((file) => removedLines(file.diff).flatMap((line) => [...line.content.matchAll(FLAG_IN_CODE)].map((match) => match[1] ?? ""))).filter((flag) => flag !== "" && !kept.has(flag)).map((flag) => ({
11188
+ name: flag,
11189
+ kind: RetiredNameKind.CliFlag,
11190
+ replacement: void 0
11191
+ }));
11192
+ }
11193
+ const RETIRED_SETTINGS = /* @__PURE__ */ new Set([
11194
+ ConfigChangeKind.RemovedVariable,
11195
+ ConfigChangeKind.RenamedVariable,
11196
+ ConfigChangeKind.ReplacedRead,
11197
+ ConfigChangeKind.RemovedKey
11198
+ ]);
11199
+ function retiredSettings(scanned) {
11200
+ return findConfigChanges(scanned).filter((change) => RETIRED_SETTINGS.has(change.kind)).map((change) => ({
11201
+ name: change.name,
11202
+ kind: RetiredNameKind.Setting,
11203
+ replacement: change.newName
11204
+ }));
11205
+ }
11206
+ // packages/engine/src/risk/docsDrift/docsDriftCheck.ts
11207
+ const DOCS_DRIFT = "docsDrift";
11208
+ const DOCS_DRIFT_DIMENSION = {
11209
+ id: DOCS_DRIFT,
11210
+ label: "Docs drift",
11211
+ kind: DimensionKind.Review,
11212
+ advice: "Update the docs to match."
11213
+ };
11214
+ const DOCS_DRIFT_RUN = {
11215
+ name: "Docs drift",
11216
+ detail: "docs that still use names this PR removes or renames, and doc comments that no longer match their parameters"
11217
+ };
11218
+ const LEADING_DASHES = /^--/;
11219
+ const STALE_WORDING = {
11220
+ [RetiredNameKind.CliFlag]: {
11221
+ id: "docs.stale-flag",
11222
+ severity: RiskSeverity.Medium,
11223
+ consequence: "Whoever copies the command from the docs gets an error."
11224
+ },
11225
+ [RetiredNameKind.Setting]: {
11226
+ id: "docs.stale-setting",
11227
+ severity: RiskSeverity.Medium,
11228
+ consequence: "A deployment set up from the docs sets a name nothing reads, and the setting silently has no effect."
11229
+ },
11230
+ [RetiredNameKind.Code]: {
11231
+ id: "docs.stale-name",
11232
+ severity: RiskSeverity.Low,
11233
+ consequence: "Readers will look for code that isn't there."
11234
+ }
11235
+ };
11236
+ /**
11237
+ * Docs that this PR leaves out of date: prose that still uses a name it removes or renames, and
11238
+ * doc comments that describe parameters a changed function no longer takes. Reads only the
11239
+ * repository, so it runs offline.
11240
+ */
11241
+ const DOCS_DRIFT_CHECK = {
11242
+ step: AnalysisStep.CheckingBreakingChanges,
11243
+ dimensions: [DOCS_DRIFT_DIMENSION],
11244
+ run: async ({ request, scanned }) => {
11245
+ const retired = await stillRetiredAtHead(request.repoDir, request.head, retiredNames(request.files, scanned));
11246
+ const findings = [...(await staleMentions(request.repoDir, request.head, retired)).map(staleMentionFinding), ...parameterDrift(request.files).map(parameterFinding)];
11247
+ return {
11248
+ findings: creditedTo(DOCS_DRIFT_RUN.name, findings),
11249
+ checksRun: [DOCS_DRIFT_RUN],
11250
+ notChecked: []
11251
+ };
11252
+ }
11253
+ };
11254
+ /**
11255
+ * Docs only go stale for a name nothing uses any more: code at head that still names it, anywhere,
11256
+ * means it's still there, perhaps defined in another file.
11257
+ */
11258
+ async function stillRetiredAtHead(repoDir, head, retired) {
11259
+ if (retired.length === 0) return [];
11260
+ const searched = (name) => name.name.replace(LEADING_DASHES, "");
11261
+ const inCode = await filesMentioning(repoDir, head, [...new Set(retired.map(searched))]);
11262
+ return retired.filter((name) => (inCode.get(searched(name)) ?? []).every(isTestPath));
11263
+ }
11264
+ function staleMentionFinding(mention) {
11265
+ const { retired } = mention;
11266
+ const wording = STALE_WORDING[retired.kind];
11267
+ const change = retired.replacement === void 0 ? "removes it" : `renames it to ${codeSpan(retired.replacement)}`;
11268
+ const more = mention.count > 1 ? ` This file mentions it ${mention.count} times.` : "";
11269
+ return findingAt({
11270
+ id: wording.id,
11271
+ category: DOCS_DRIFT,
11272
+ severity: wording.severity,
11273
+ title: `Docs still mention ${codeSpan(retired.name)}`,
11274
+ detail: `This PR ${change}.${more} ${wording.consequence}`
11275
+ }, mention.path, mention.line, mention.text);
11276
+ }
11277
+ function parameterFinding(drift) {
11278
+ const stale = drift.stale.length === 0 ? "" : `still describes ${drift.stale.map(codeSpan).join(", ")}, which it no longer takes`;
11279
+ const missing = drift.missing.length === 0 ? "" : `doesn't describe ${drift.missing.map(codeSpan).join(", ")}`;
11280
+ return findingAt({
11281
+ id: "docs.parameters",
11282
+ category: DOCS_DRIFT,
11283
+ severity: RiskSeverity.Low,
11284
+ title: `Doc comment of ${codeSpan(drift.unit)} doesn't match its parameters`,
11285
+ detail: `It ${[stale, missing].filter((part) => part !== "").join(", and ")}. Editors and generated docs show this text to everyone who calls it.`
11286
+ }, drift.path, drift.line, null);
11287
+ }
11288
+ // packages/engine/src/risk/hotspots/hotspotsCheck.ts
11289
+ /**
11290
+ * Hotspots: changed files whose recent history says to look harder, because they keep needing
11291
+ * fixes, change far more often than most, or had a change reverted just before this PR. History
11292
+ * is read up to the merge base, so the PR's own commits never count.
11293
+ *
11294
+ * The limits below are judgement calls rather than measured values, chosen so a file has to stand
11295
+ * out: a busy project's ordinary files change a few times a month, and a fix now and then is normal.
11296
+ */
11297
+ const HISTORY_DAYS = 365;
11298
+ const RECENT_REVERT_DAYS = 90;
11299
+ const MIN_CHANGES_FOR_CHURN = 30;
11300
+ const MIN_FIXES = 5;
11301
+ const MIN_FIX_SHARE = .25;
11302
+ const MAX_FILES = 60;
11303
+ const MS_PER_DAY = 864e5;
11304
+ const FIX_SUBJECT = /\b(?:fix(?:e[sd]|ing)?|bug(?:fix)?|hotfix|regression|crash(?:es|ed)?|broken)\b/i;
11305
+ const NOT_A_BUG = /\b(?:typos?|lint(?:ing)?|format(?:ting)?|style|docs?|readme|tests?|ci|build|deps|dependenc(?:y|ies))\b/i;
11306
+ const REVERT_SUBJECT = /^revert\b/i;
11307
+ const HOTSPOT = "hotspot";
11308
+ const HOTSPOT_DIMENSION = {
11309
+ id: HOTSPOT,
11310
+ label: "Hotspot",
11311
+ kind: DimensionKind.Context,
11312
+ advice: ""
11313
+ };
11314
+ const HOTSPOTS_NAME = "Hotspots";
11315
+ const HOTSPOTS_RUN = {
11316
+ name: HOTSPOTS_NAME,
11317
+ detail: `each changed file's commits in the ${HISTORY_DAYS} days before this PR`
11318
+ };
11319
+ const CLOSER_LOOK = "Files like this tend to keep needing fixes, so this change deserves a closer look than its size suggests.";
11320
+ const HOTSPOTS_CHECK = {
11321
+ step: AnalysisStep.CheckingBreakingChanges,
11322
+ dimensions: [HOTSPOT_DIMENSION],
11323
+ run: async (context) => {
11324
+ if (context.request.disabledChecks.has(CheckId.Hotspots)) return {
11325
+ findings: [],
11326
+ checksRun: [],
11327
+ notChecked: [{
11328
+ check: HOTSPOTS_NAME,
11329
+ reason: TURNED_OFF_IN_SETTINGS
11330
+ }]
11331
+ };
11332
+ const candidates = historyCandidates(context).slice(0, MAX_FILES);
11333
+ if (candidates.length === 0) return {
11334
+ findings: [],
11335
+ checksRun: [],
11336
+ notChecked: []
11337
+ };
11338
+ const baseDate = await commitDate(context.request.repoDir, context.request.base);
11339
+ try {
11340
+ const since = /* @__PURE__ */ new Date(baseDate.getTime() - HISTORY_DAYS * MS_PER_DAY);
11341
+ const histories = await context.request.history({
11342
+ paths: candidates.map((candidate) => candidate.before),
11343
+ until: context.request.base,
11344
+ since
11345
+ });
11346
+ const findings = candidates.flatMap(({ before, path }) => {
11347
+ const history = histories.get(before);
11348
+ const found = history === void 0 ? void 0 : hotspotFinding(path, history, baseDate);
11349
+ return found === void 0 ? [] : [found];
11350
+ });
11351
+ return {
11352
+ findings: creditedTo(HOTSPOTS_NAME, findings),
11353
+ checksRun: [HOTSPOTS_RUN],
11354
+ notChecked: []
11355
+ };
11356
+ } catch (error) {
11357
+ if (!(error instanceof HistoryUnavailableError)) throw error;
11358
+ return {
11359
+ findings: [],
11360
+ checksRun: [],
11361
+ notChecked: [{
11362
+ check: HOTSPOTS_NAME,
11363
+ reason: `no history to read: ${error.message}`
11364
+ }]
11365
+ };
11366
+ }
11367
+ }
11368
+ };
11369
+ /** Code files the PR changes that existed before it: a new file has no history to speak of. */
11370
+ function historyCandidates({ scanned }) {
11371
+ return scanned.filter(({ diff }) => diff.status !== FileChangeStatus.Added && diff.status !== FileChangeStatus.Deleted).map(({ diff }) => ({
11372
+ before: diff.status === FileChangeStatus.Renamed ? diff.previousPath : diff.path,
11373
+ path: diff.path
11374
+ })).filter(({ path }) => languageFor(path) !== void 0 && !isTestPath(path) && !isNoiseByPath(path));
11375
+ }
11376
+ async function commitDate(repoDir, commit) {
11377
+ return new Date((await runGit([
11378
+ "show",
11379
+ "-s",
11380
+ "--format=%cI",
11381
+ commit
11382
+ ], {
11383
+ cwd: repoDir,
11384
+ env: ISOLATED_CONFIG_ENV
11385
+ })).trim());
11386
+ }
11387
+ function isFix(commit) {
11388
+ return FIX_SUBJECT.test(commit.subject) && !NOT_A_BUG.test(commit.subject) && !REVERT_SUBJECT.test(commit.subject);
11389
+ }
11390
+ /** A finding for a file whose history stands out, or undefined when it doesn't. */
11391
+ function hotspotFinding(path, history, baseDate) {
11392
+ const { commits, total } = history;
11393
+ const fixes = commits.filter(isFix).length;
11394
+ const authors = new Set(commits.map((commit) => commit.author)).size;
11395
+ const revert = commits.find((commit) => REVERT_SUBJECT.test(commit.subject) && daysBefore(baseDate, commit.committedAt) <= RECENT_REVERT_DAYS);
11396
+ const fixProne = fixes >= MIN_FIXES && fixes / Math.max(commits.length, 1) >= MIN_FIX_SHARE;
11397
+ if (revert === void 0 && !fixProne && !(total >= MIN_CHANGES_FOR_CHURN)) return void 0;
11398
+ const atLeast = commits.length < total ? "at least " : "";
11399
+ const facts = `In the year before this PR, ${total} commits by ${atLeast}${authors} ${authors === 1 ? "person" : "people"} changed it, and ${atLeast}${fixes} of them fixed something.`;
11400
+ const reverted = revert === void 0 ? "" : ` ${revert.sha.slice(0, 8)} reverted a change ${describeDaysAgo(daysBefore(baseDate, revert.committedAt))}: "${revert.subject}".`;
11401
+ return findingAt({
11402
+ id: revert !== void 0 ? "hotspot.recently-reverted" : fixProne ? "hotspot.fix-prone" : "hotspot.churn",
11403
+ category: HOTSPOT,
11404
+ severity: RiskSeverity.Low,
11405
+ title: revert !== void 0 ? "Had a change reverted recently" : fixProne ? `Often fixed: ${atLeast}${fixes} of ${total} changes in the past year` : `Changes often: ${total} commits in the past year`,
11406
+ detail: `${facts}${reverted} ${CLOSER_LOOK}`
11407
+ }, path, null, null);
11408
+ }
11409
+ function daysBefore(baseDate, timestamp) {
11410
+ return Math.floor((baseDate.getTime() - new Date(timestamp).getTime()) / MS_PER_DAY);
11411
+ }
11412
+ function describeDaysAgo(days) {
11413
+ if (days <= 1) return "the day before";
11414
+ if (days < 14) return `${days} days before`;
11415
+ return `${Math.round(days / 7)} weeks before`;
11416
+ }
11417
+ // packages/engine/src/risk/scope/areas.ts
11418
+ const PACKAGE_MANIFESTS = /* @__PURE__ */ new Set([
11419
+ "package.json",
11420
+ "Cargo.toml",
11421
+ "go.mod",
11422
+ "pyproject.toml",
11423
+ "setup.py",
11424
+ "pom.xml",
11425
+ "build.gradle",
11426
+ "build.gradle.kts",
11427
+ "composer.json",
11428
+ "Gemfile",
11429
+ "mix.exs",
11430
+ "pubspec.yaml"
11431
+ ]);
11432
+ const REPOSITORY_ROOT = "";
11433
+ /**
11434
+ * The workspace packages at `head`: every folder below the root with a package manifest, with
11435
+ * what `package.json`, `Cargo.toml` and `go.mod` say about their names and dependencies.
11436
+ */
11437
+ async function workspacePackages(repoDir, head) {
11438
+ const manifests = (await runGit([
11439
+ "ls-tree",
11440
+ "-r",
11441
+ "-z",
11442
+ "--name-only",
11443
+ head
11444
+ ], {
11445
+ cwd: repoDir,
11446
+ env: ISOLATED_CONFIG_ENV
11447
+ })).split("\0").filter((path) => PACKAGE_MANIFESTS.has(posix.basename(path)) && !path.includes("node_modules/") && dirname(path) !== ".");
11448
+ const blobs = await readBlobs(repoDir, manifests.map((path) => ({
11449
+ commit: head,
11450
+ path
11451
+ })));
11452
+ const byRoot = /* @__PURE__ */ new Map();
11453
+ manifests.forEach((path, index) => {
11454
+ const root = dirname(path);
11455
+ const read = readManifest(posix.basename(path), blobs.at(index)?.toString("utf8") ?? "");
11456
+ const known = byRoot.get(root);
11457
+ byRoot.set(root, {
11458
+ root,
11459
+ name: known?.name ?? read.name,
11460
+ dependsOn: /* @__PURE__ */ new Set([...known?.dependsOn ?? [], ...read.dependsOn])
11461
+ });
11462
+ });
11463
+ return [...byRoot.values()];
11464
+ }
11465
+ const NO_FACTS = {
11466
+ name: void 0,
11467
+ dependsOn: []
11468
+ };
11469
+ const NPM_DEPENDENCY_SECTIONS = [
11470
+ "dependencies",
11471
+ "devDependencies",
11472
+ "peerDependencies",
11473
+ "optionalDependencies"
11474
+ ];
11475
+ const CARGO_DEPENDENCY_SECTIONS = [
11476
+ "dependencies",
11477
+ "dev-dependencies",
11478
+ "build-dependencies"
11479
+ ];
11480
+ const GO_MODULE = /^module\s+(\S+)/m;
11481
+ const GO_REQUIREMENT = /^\s*(?:require\s+)?([\w.\-/]+\.[\w.\-/]+)\s+v\S+/gm;
11482
+ function readManifest(fileName, text) {
11483
+ try {
11484
+ if (fileName === "package.json") {
11485
+ const manifest = JSON.parse(text);
11486
+ return {
11487
+ name: stringField(manifest, "name"),
11488
+ dependsOn: NPM_DEPENDENCY_SECTIONS.flatMap((section) => Object.keys(recordOrEmpty(field(manifest, section))))
11489
+ };
11490
+ }
11491
+ if (fileName === "Cargo.toml") {
11492
+ const manifest = parse$2(text);
11493
+ return {
11494
+ name: stringField(field(manifest, "package"), "name"),
11495
+ dependsOn: CARGO_DEPENDENCY_SECTIONS.flatMap((section) => Object.keys(recordOrEmpty(field(manifest, section))))
11496
+ };
11497
+ }
11498
+ if (fileName === "go.mod") return {
11499
+ name: GO_MODULE.exec(text)?.[1],
11500
+ dependsOn: [...text.matchAll(GO_REQUIREMENT)].map((match) => match[1] ?? "")
11501
+ };
11502
+ } catch {}
11503
+ return NO_FACTS;
11504
+ }
11505
+ /** The behaviour changes of each package they fall in, by the deepest package folder holding them. */
11506
+ function areasOf(behaviour, packages) {
11507
+ const deepestFirst = packages.map((workspace) => workspace.root).sort((a, b) => b.length - a.length);
11508
+ const byRoot = /* @__PURE__ */ new Map();
11509
+ for (const file of behaviour) {
11510
+ const root = deepestFirst.find((candidate) => file.diff.path.startsWith(`${candidate}/`)) ?? REPOSITORY_ROOT;
11511
+ const files = byRoot.get(root);
11512
+ if (files === void 0) byRoot.set(root, [file]);
11513
+ else files.push(file);
11514
+ }
11515
+ return [...byRoot].map(([root, files]) => ({
11516
+ root,
11517
+ files,
11518
+ units: files.reduce((sum, file) => sum + changedUnitsOf(file).filter((unit) => isBehaviourChange(unit.change)).length, 0)
11519
+ }));
11520
+ }
11521
+ /**
11522
+ * Groups areas that belong together: one declares a dependency on the other, its added lines name
11523
+ * a unit the other changes, or a changed unit's traced callers are in the other. Layers of one
11524
+ * feature, such as a data format, the code writing it and the page reading it, usually depend on
11525
+ * each other without calling each other's new code. Two groups have nothing tying them together.
11526
+ */
11527
+ function connectedGroups(areas, packages) {
11528
+ const byRoot = new Map(packages.map((workspace) => [workspace.root, workspace]));
11529
+ const declares = (from, to) => {
11530
+ const target = byRoot.get(to.root)?.name;
11531
+ return target !== void 0 && byRoot.get(from.root)?.dependsOn.has(target) === true;
11532
+ };
11533
+ const parent = areas.map((_, index) => index);
11534
+ const find = (index) => {
11535
+ let root = index;
11536
+ while (parent[root] !== root) root = parent[root] ?? root;
11537
+ return root;
11538
+ };
11539
+ areas.forEach((from, fromIndex) => {
11540
+ const uses = mentionMatcher(from);
11541
+ areas.forEach((to, toIndex) => {
11542
+ const linked = declares(from, to) || uses !== void 0 && usesAny(to, uses) || isCalledFrom(from, to);
11543
+ if (fromIndex !== toIndex && linked) parent[find(toIndex)] = find(fromIndex);
11544
+ });
11545
+ });
11546
+ const groups = /* @__PURE__ */ new Map();
11547
+ areas.forEach((area, index) => {
11548
+ const group = groups.get(find(index));
11549
+ if (group === void 0) groups.set(find(index), [area]);
11550
+ else group.push(area);
11551
+ });
11552
+ return [...groups.values()];
11553
+ }
11554
+ function mentionMatcher(area) {
11555
+ const names = [...new Set(area.files.flatMap((file) => changedUnitsOf(file).map((unit) => unit.name)).filter(isSpecificName))];
11556
+ if (names.length === 0) return void 0;
11557
+ return new RegExp(`(?<![\\p{L}\\p{N}_$])(?:${names.map(escapeRegExp$1).join("|")})(?![\\p{L}\\p{N}_$])`, "u");
11558
+ }
11559
+ function usesAny(area, names) {
11560
+ return area.files.some((file) => addedLines(file.diff).some((line) => names.test(line.content)));
11561
+ }
11562
+ function isCalledFrom(from, to) {
11563
+ const paths = new Set(to.files.map((file) => file.diff.path));
11564
+ return from.files.some((file) => changedUnitsOf(file).some((unit) => unit.impact?.status === UnitImpactStatus.Traced && unit.impact.references.some((reference) => paths.has(reference.path))));
11565
+ }
11566
+ // packages/engine/src/risk/scope/concerns.ts
11567
+ /** What kind of work a changed file carries, as far as mixing concerns goes. */
11568
+ const Concern = {
11569
+ /** Code whose behaviour changes: units added, removed, or edited beyond formatting and comments. */
11570
+ Behaviour: "behaviour",
11571
+ /** Code that's only reformatted, re-commented, renamed or moved. */
11572
+ TidyUp: "tidyUp",
11573
+ /** A lockfile; how many packages it upgrades decides whether it's a concern of its own. */
11574
+ Dependencies: "dependencies",
11575
+ /** Tests, docs, CI and config, which normally travel with the change they belong to. */
11576
+ Neutral: "neutral",
11577
+ /** Generated or vendored files, which say nothing about what the author meant to change. */
11578
+ Ignored: "ignored"
11579
+ };
11580
+ const UNPARSED_CODE = /* @__PURE__ */ new Set([
11581
+ ".rb",
11582
+ ".php",
11583
+ ".swift",
11584
+ ".scala",
11585
+ ".sh",
11586
+ ".sql",
11587
+ ".lua",
11588
+ ".ex",
11589
+ ".exs",
11590
+ ".erl",
11591
+ ".clj",
11592
+ ".dart",
11593
+ ".r",
11594
+ ".pl"
11595
+ ]);
11596
+ const IDENTICAL_MOVE = 100;
11597
+ function concernOf(file) {
11598
+ const { diff, noise, syntax } = file;
11599
+ if (noise?.kind === NoiseKind.Lockfile) return Concern.Dependencies;
11600
+ if (noise !== null) return Concern.Ignored;
11601
+ if (isTestPath(diff.path)) return Concern.Neutral;
11602
+ if ((diff.status === FileChangeStatus.Renamed || diff.status === FileChangeStatus.Copied) && diff.similarity === IDENTICAL_MOVE) return Concern.TidyUp;
11603
+ if (syntax.status !== SyntaxAnalysisStatus.Analyzed) return UNPARSED_CODE.has(extname(diff.path).toLowerCase()) ? Concern.Behaviour : Concern.Neutral;
11604
+ const units = changedUnitsOf(file);
11605
+ if (units.some((unit) => isBehaviourChange(unit.change))) return Concern.Behaviour;
11606
+ return units.length > 0 ? Concern.TidyUp : Concern.Neutral;
11607
+ }
11608
+ // packages/engine/src/risk/scope/scopeCheck.ts
11609
+ /**
11610
+ * PRs that mix concerns: a tidy-up or a bulk dependency upgrade riding along with behaviour
11611
+ * changes, or behaviour changes in packages that have nothing to do with each other. Each half
11612
+ * would be easier to review, and to revert, on its own.
11613
+ *
11614
+ * The limits are judgement calls: a few formatted files or upgraded packages come with ordinary
11615
+ * work, so it takes enough of them to bury the change that matters.
11616
+ */
11617
+ const MIN_TIDY_FILES = 5;
11618
+ const MIN_UPGRADED_PACKAGES = 10;
11619
+ const MIN_UNITS_PER_AREA = 3;
11620
+ const FILES_NAMED = 3;
11621
+ const SCOPE = "scope";
11622
+ const SCOPE_DIMENSION = {
11623
+ id: SCOPE,
11624
+ label: "Scope",
11625
+ kind: DimensionKind.Review,
11626
+ advice: "Ask whether it should be split."
11627
+ };
11628
+ const SCOPE_RUN = {
11629
+ name: "Scope",
11630
+ detail: "tidy-ups, bulk dependency upgrades and unrelated packages mixed in with behaviour changes"
11631
+ };
11632
+ const SCOPE_CHECK = {
11633
+ step: AnalysisStep.ScanningCode,
11634
+ dimensions: [SCOPE_DIMENSION],
11635
+ run: async ({ request }) => {
11636
+ const byConcern = groupByConcern(request.files);
11637
+ const behaviour = byConcern.get(Concern.Behaviour) ?? [];
11638
+ if (behaviour.length === 0) return {
11639
+ findings: [],
11640
+ checksRun: [SCOPE_RUN],
11641
+ notChecked: []
11642
+ };
11643
+ const tidy = byConcern.get(Concern.TidyUp) ?? [];
11644
+ const upgrades = await upgradedPackages(request.repoDir, request.base, request.head, byConcern.get(Concern.Dependencies) ?? []);
11645
+ const packages = await workspacePackages(request.repoDir, request.head);
11646
+ const groups = connectedGroups(areasOf(behaviour, packages), packages).filter((group) => unitsIn(group) >= MIN_UNITS_PER_AREA);
11647
+ const findings = [...mixedConcernsFinding(behaviour, tidy, upgrades), ...unrelatedAreasFinding(groups)];
11648
+ return {
11649
+ findings: creditedTo(SCOPE_RUN.name, findings),
11650
+ checksRun: [SCOPE_RUN],
11651
+ notChecked: []
11652
+ };
11653
+ }
11654
+ };
11655
+ function groupByConcern(files) {
11656
+ const groups = /* @__PURE__ */ new Map();
11657
+ for (const file of files) {
11658
+ const concern = concernOf(file);
11659
+ const group = groups.get(concern);
11660
+ if (group === void 0) groups.set(concern, [file]);
11661
+ else group.push(file);
11662
+ }
11663
+ return groups;
11664
+ }
11665
+ /**
11666
+ * Packages a lockfile already had that the PR moves to other versions. A package new to the
11667
+ * lockfile comes with the code that uses it, so it doesn't count; neither does a lockfile that
11668
+ * can't be read, which the supply-chain check reports.
11669
+ */
11670
+ async function upgradedPackages(repoDir, base, head, lockfiles) {
11671
+ const readable = lockfiles.filter((file) => file.diff.status === FileChangeStatus.Modified && lockfileReaderFor(file.diff.path) !== void 0);
11672
+ const blobs = await readBlobs(repoDir, readable.flatMap((file) => [{
11673
+ commit: base,
11674
+ path: file.diff.path
11675
+ }, {
11676
+ commit: head,
11677
+ path: file.diff.path
11678
+ }]));
11679
+ const counted = readable.map((file, index) => {
11680
+ const reader = lockfileReaderFor(file.diff.path);
11681
+ const before = blobs.at(2 * index)?.toString("utf8");
11682
+ const after = blobs.at(2 * index + 1)?.toString("utf8");
11683
+ if (reader === void 0 || before === void 0 || after === void 0) return 0;
11684
+ try {
11685
+ return countUpgrades(versionsByName(reader.read(before)), versionsByName(reader.read(after)));
11686
+ } catch {
11687
+ return 0;
11688
+ }
11689
+ });
11690
+ return {
11691
+ packages: counted.reduce((sum, count) => sum + count, 0),
11692
+ lockfiles: readable.filter((_, index) => (counted[index] ?? 0) > 0).map((file) => file.diff.path)
11693
+ };
11694
+ }
11695
+ function versionsByName(packages) {
11696
+ const versions = /* @__PURE__ */ new Map();
11697
+ for (const { name, version } of packages) {
11698
+ const known = versions.get(name);
11699
+ if (known === void 0) versions.set(name, /* @__PURE__ */ new Set([version]));
11700
+ else known.add(version);
11701
+ }
11702
+ return versions;
11703
+ }
11704
+ function countUpgrades(before, after) {
11705
+ return [...after].filter(([name, versions]) => {
11706
+ const earlier = before.get(name);
11707
+ return earlier !== void 0 && [...versions].some((version) => !earlier.has(version));
11708
+ }).length;
11709
+ }
11710
+ function unitsIn(group) {
11711
+ return group.reduce((sum, area) => sum + area.units, 0);
11712
+ }
11713
+ function mixedConcernsFinding(behaviour, tidy, upgrades) {
11714
+ const parts = [...tidy.length >= MIN_TIDY_FILES ? [`${tidy.length} files that are only reformatted, re-commented, renamed or moved (${named(tidy)})`] : [], ...upgrades.packages >= MIN_UPGRADED_PACKAGES ? [`${upgrades.packages} package upgrades in ${upgrades.lockfiles.map(codeSpan).join(" and ")}`] : []];
11715
+ if (parts.length === 0) return [];
11716
+ const rule = {
11717
+ id: "scope.mixed-concerns",
11718
+ category: SCOPE,
11719
+ severity: RiskSeverity.Low,
11720
+ title: tidy.length >= MIN_TIDY_FILES && upgrades.packages >= MIN_UPGRADED_PACKAGES ? "Mixes a tidy-up and upgrades with behaviour changes" : tidy.length >= MIN_TIDY_FILES ? "Mixes a tidy-up with behaviour changes" : "Mixes dependency upgrades with behaviour changes",
11721
+ detail: `Besides behaviour changes in ${behaviour.length} ${behaviour.length === 1 ? "file" : "files"}, it has ${parts.join(", and ")}. Reviewers have to find the change that matters among the rest. Landing them separately makes each easier to review, and to revert.`
11722
+ };
11723
+ return [{
11724
+ ruleId: rule.id,
11725
+ category: rule.category,
11726
+ severity: rule.severity,
11727
+ title: rule.title,
11728
+ detail: rule.detail,
11729
+ location: null,
11730
+ evidence: null
11731
+ }];
11732
+ }
11733
+ function unrelatedAreasFinding(groups) {
11734
+ if (groups.length < 2) return [];
11735
+ const described = groups.map((group) => group.map((area) => area.root === "" ? "the repository root" : codeSpan(area.root)).join(" with ")).join("; ");
11736
+ return [{
11737
+ ruleId: "scope.unrelated-areas",
11738
+ category: SCOPE,
11739
+ severity: RiskSeverity.Low,
11740
+ title: `Changes ${groups.length} packages that don't use each other`,
11741
+ detail: `Behaviour changes in ${described}, with nothing in this PR tying them together. Each could be reviewed, released and reverted on its own.`,
11742
+ location: null,
11743
+ evidence: null
11744
+ }];
11745
+ }
11746
+ function named(files) {
11747
+ const shown = files.slice(0, FILES_NAMED).map((file) => codeSpan(file.diff.path));
11748
+ const rest = files.length - shown.length;
11749
+ return rest > 0 ? `${shown.join(", ")} and ${rest} more` : shown.join(" and ");
11750
+ }
10036
11751
  // packages/engine/src/risk/errorHandling.ts
10037
11752
  /**
10038
11753
  * Error handling that hides failures, in the code a PR adds: handlers that do nothing, handlers that
@@ -10465,7 +12180,7 @@ async function assessQuality({ request, scanned, config }) {
10465
12180
  // packages/engine/src/risk/checks/registry.ts
10466
12181
  const BREAKING_CHANGES_RUN = {
10467
12182
  name: "Breaking changes",
10468
- detail: "public APIs, database migrations, environment variables and config keys"
12183
+ detail: "public APIs, OpenAPI, GraphQL and protobuf schemas, database migrations, environment variables and config keys"
10469
12184
  };
10470
12185
  /**
10471
12186
  * Every check a review runs. Their findings, runs and gaps are reported in this order, which is
@@ -10521,19 +12236,25 @@ const CHECKS$1 = [
10521
12236
  },
10522
12237
  {
10523
12238
  step: AnalysisStep.CheckingBreakingChanges,
10524
- run: async ({ request, scanned, config }) => ({
10525
- findings: creditedTo(BREAKING_CHANGES_RUN.name, await scanBreakingChanges({
12239
+ run: async ({ request, scanned, config }) => {
12240
+ const breaking = await scanBreakingChanges({
10526
12241
  repoDir: request.repoDir,
10527
12242
  base: request.base,
10528
12243
  head: request.head,
10529
12244
  files: request.files.filter((file) => !isIgnored(config, file.diff.path)),
10530
12245
  scanned,
10531
12246
  versions: request.versions
10532
- })),
10533
- checksRun: [BREAKING_CHANGES_RUN],
10534
- notChecked: []
10535
- })
12247
+ });
12248
+ return {
12249
+ findings: creditedTo(BREAKING_CHANGES_RUN.name, breaking.findings),
12250
+ checksRun: [BREAKING_CHANGES_RUN],
12251
+ notChecked: breaking.notChecked
12252
+ };
12253
+ }
10536
12254
  },
12255
+ DOCS_DRIFT_CHECK,
12256
+ HOTSPOTS_CHECK,
12257
+ SCOPE_CHECK,
10537
12258
  QUALITY_CHECK
10538
12259
  ];
10539
12260
  /** The order checks run in, which the progress display follows. */
@@ -10622,6 +12343,60 @@ function coverageGaps(files, ignoredCount) {
10622
12343
  function byImportance(dimensions) {
10623
12344
  return (a, b) => SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity] || Number(isSecurityFinding(b, dimensions)) - Number(isSecurityFinding(a, dimensions)) || (a.location?.path ?? "").localeCompare(b.location?.path ?? "") || (a.location?.line ?? 0) - (b.location?.line ?? 0);
10624
12345
  }
12346
+ // packages/engine/src/risk/hotspots/gitHistory.ts
12347
+ const RECORD = "";
12348
+ const FIELD = "";
12349
+ const LOG_FORMAT = `${RECORD}%H${FIELD}%s${FIELD}%ae${FIELD}%cI`;
12350
+ const PATHS_PER_COMMAND = 200;
12351
+ /**
12352
+ * Reads file history from the repository itself, for local reviews and checkouts with history.
12353
+ * A shallow repository, such as the depth-1 cache a hosted review fetches, has none to give.
12354
+ */
12355
+ function gitHistoryReader(repoDir) {
12356
+ return async ({ paths, until, since }) => {
12357
+ if ((await runGit(["rev-parse", "--is-shallow-repository"], {
12358
+ cwd: repoDir,
12359
+ env: ISOLATED_CONFIG_ENV
12360
+ })).trim() === "true") throw new HistoryUnavailableError("the repository was fetched without its history");
12361
+ const histories = new Map(paths.map((path) => [path, []]));
12362
+ for (let start = 0; start < paths.length; start += PATHS_PER_COMMAND) {
12363
+ const batch = paths.slice(start, start + PATHS_PER_COMMAND);
12364
+ const output = await runGit([
12365
+ "log",
12366
+ until,
12367
+ `--since=${since.toISOString()}`,
12368
+ `--format=${LOG_FORMAT}`,
12369
+ "--name-only",
12370
+ "--",
12371
+ ...batch.map((path) => `:(literal)${path}`)
12372
+ ], {
12373
+ cwd: repoDir,
12374
+ env: ISOLATED_CONFIG_ENV
12375
+ });
12376
+ for (const { commit, paths: touched } of parseLog(output)) for (const path of touched) histories.get(path)?.push(commit);
12377
+ }
12378
+ return new Map([...histories].map(([path, commits]) => [path, {
12379
+ commits,
12380
+ total: commits.length
12381
+ }]));
12382
+ };
12383
+ }
12384
+ function parseLog(output) {
12385
+ return output.split(RECORD).filter((record) => record.trim() !== "").flatMap((record) => {
12386
+ const [header = "", ...files] = record.split("\n");
12387
+ const [sha, subject, author, committedAt] = header.split(FIELD);
12388
+ if (sha === void 0 || subject === void 0 || author === void 0 || committedAt === void 0) return [];
12389
+ return [{
12390
+ commit: {
12391
+ sha,
12392
+ subject,
12393
+ author,
12394
+ committedAt
12395
+ },
12396
+ paths: files.filter((file) => file !== "")
12397
+ }];
12398
+ });
12399
+ }
10625
12400
  // packages/engine/src/syntax/similarity.ts
10626
12401
  /**
10627
12402
  * How alike two token sequences are, from 0 (nothing shared) to 1 (the same).
@@ -11096,7 +12871,8 @@ async function analyzeChangedFiles(repoDir, from, to, options) {
11096
12871
  network: options.network,
11097
12872
  runScanner: options.runScanner ?? runScannerProcess,
11098
12873
  disabledChecks: new Set(options.disabledChecks),
11099
- reportStep
12874
+ reportStep,
12875
+ history: options.history ?? gitHistoryReader(repoDir)
11100
12876
  })
11101
12877
  };
11102
12878
  }
@@ -12152,6 +13928,18 @@ const CHECKS = [
12152
13928
  when: "When a PR upgrades npm packages"
12153
13929
  }
12154
13930
  },
13931
+ {
13932
+ id: CheckId.Hotspots,
13933
+ name: "Hotspots",
13934
+ purpose: "Flags changed files that keep needing fixes, change very often, or had a change reverted recently",
13935
+ binary: null,
13936
+ install: null,
13937
+ sends: {
13938
+ where: "The PR's host",
13939
+ what: "Paths of the files a PR changes, to read their commits from the past year",
13940
+ when: "Reviews of a pull or merge request"
13941
+ }
13942
+ },
12155
13943
  {
12156
13944
  id: CheckId.FunctionMetrics,
12157
13945
  name: "Function measures",
@@ -12726,6 +14514,114 @@ function displayName(ref) {
12726
14514
  const separator = ref.host === GitHostKind.GitHub ? "#" : "!";
12727
14515
  return `${repositoryPath(ref)}${separator}${ref.number}`;
12728
14516
  }
14517
+ // packages/providers/src/trustedHosts.ts
14518
+ const TRUSTED_GITHUB_HOSTS_VARIABLE = "WALKDIFF_TRUSTED_GITHUB_HOSTS";
14519
+ const TRUSTED_GITLAB_HOSTS_VARIABLE = "WALKDIFF_TRUSTED_GITLAB_HOSTS";
14520
+ const GITHUB_DOT_COM_ORIGIN$1 = "https://github.com";
14521
+ const GITLAB_DOT_COM_ORIGIN = "https://gitlab.com";
14522
+ /**
14523
+ * Whether this link's host may receive the token for its kind of host. Links are pasted by
14524
+ * hand and their kind is read from the path, so neither the host name nor the kind can be
14525
+ * taken on trust: `https://evil.example/a/b/pull/1` would otherwise receive a GitHub token,
14526
+ * and `https://gitlab.com/a/b/pull/1` would receive a GitHub token at GitLab. Comparing
14527
+ * whole origins also keeps a token off plain http and off look-alikes such as
14528
+ * `github.com.evil.example`.
14529
+ */
14530
+ function isTrustedHost(ref, trusted) {
14531
+ return ref.host === GitHostKind.GitHub ? ref.webOrigin === GITHUB_DOT_COM_ORIGIN$1 || trusted.github.includes(ref.webOrigin) : ref.webOrigin === GITLAB_DOT_COM_ORIGIN || trusted.gitlab.includes(ref.webOrigin);
14532
+ }
14533
+ /**
14534
+ * The kind of host at a trusted origin, or undefined for any other origin. A git remote's URL
14535
+ * doesn't show the kind the way a PR link's path does, so only the hosts the user trusts can be
14536
+ * told apart, and those are the only ones that get a token anyway.
14537
+ */
14538
+ function trustedHostKind(origin, trusted) {
14539
+ if (origin === GITHUB_DOT_COM_ORIGIN$1 || trusted.github.includes(origin)) return GitHostKind.GitHub;
14540
+ if (origin === GITLAB_DOT_COM_ORIGIN || trusted.gitlab.includes(origin)) return GitHostKind.GitLab;
14541
+ }
14542
+ // packages/providers/src/remoteUrl.ts
14543
+ /**
14544
+ * A git remote Walkdiff can't use. The message never repeats the remote itself, which can carry a
14545
+ * token, as in `https://user:token@github.com/acme/app.git`.
14546
+ */
14547
+ var InvalidRemoteUrlError = class extends Error {
14548
+ name = "InvalidRemoteUrlError";
14549
+ };
14550
+ const REMOTE_PROTOCOLS = /* @__PURE__ */ new Set([
14551
+ "https:",
14552
+ "http:",
14553
+ "ssh:",
14554
+ "git+ssh:"
14555
+ ]);
14556
+ const SSH_PROTOCOLS = /* @__PURE__ */ new Set(["ssh:", "git+ssh:"]);
14557
+ const SCP_LIKE_REMOTE = /^(?:[^@/]+@)?(?<host>[^:/]+):(?<path>[^/].*)$/;
14558
+ const GIT_SUFFIX = /\.git$/;
14559
+ const GITHUB_PATH_SEGMENTS = 2;
14560
+ const MIN_GITLAB_PATH_SEGMENTS = 2;
14561
+ /**
14562
+ * The repository a git remote points at, such as `git@github.com:acme/app.git` or
14563
+ * `https://gitlab.example.com/group/sub/app.git`. A remote over SSH is taken to have its web pages
14564
+ * over HTTPS on the same host name.
14565
+ *
14566
+ * # Errors
14567
+ *
14568
+ * Throws an `InvalidRemoteUrlError` when the remote can't be read, or its host isn't github.com,
14569
+ * gitlab.com or a host the user trusts, since only those can be told apart.
14570
+ */
14571
+ function parseRemoteUrl(remote, trusted) {
14572
+ const { webOrigin, segments } = remoteLocation(remote.trim());
14573
+ switch (trustedHostKind(webOrigin, trusted)) {
14574
+ case GitHostKind.GitHub: {
14575
+ const [owner, repo] = segments;
14576
+ if (segments.length !== GITHUB_PATH_SEGMENTS || owner === void 0 || repo === void 0) throw new InvalidRemoteUrlError(`A GitHub remote should end in owner/repo, at ${webOrigin}.`);
14577
+ return {
14578
+ host: GitHostKind.GitHub,
14579
+ webOrigin,
14580
+ owner,
14581
+ repo
14582
+ };
14583
+ }
14584
+ case GitHostKind.GitLab:
14585
+ if (segments.length < MIN_GITLAB_PATH_SEGMENTS) throw new InvalidRemoteUrlError(`A GitLab remote should end in group/project, at ${webOrigin}.`);
14586
+ return {
14587
+ host: GitHostKind.GitLab,
14588
+ webOrigin,
14589
+ projectPath: segments.join("/")
14590
+ };
14591
+ case void 0: throw new InvalidRemoteUrlError(`Walkdiff can't tell whether ${webOrigin} is GitHub or GitLab. If you trust it, add it to ${TRUSTED_GITHUB_HOSTS_VARIABLE} or ${TRUSTED_GITLAB_HOSTS_VARIABLE}.`);
14592
+ }
14593
+ }
14594
+ function remoteLocation(remote) {
14595
+ const url = URL.canParse(remote) ? new URL(remote) : void 0;
14596
+ if (url !== void 0 && REMOTE_PROTOCOLS.has(url.protocol)) return {
14597
+ webOrigin: SSH_PROTOCOLS.has(url.protocol) ? `https://${url.hostname}` : url.origin,
14598
+ segments: pathSegments(decodeURIComponent(url.pathname))
14599
+ };
14600
+ const scpLike = SCP_LIKE_REMOTE.exec(remote)?.groups;
14601
+ if (scpLike?.host !== void 0 && scpLike.path !== void 0) return {
14602
+ webOrigin: `https://${scpLike.host.toLowerCase()}`,
14603
+ segments: pathSegments(scpLike.path)
14604
+ };
14605
+ throw new InvalidRemoteUrlError("Walkdiff reads remotes over HTTPS or SSH, such as git@github.com:owner/repo.git.");
14606
+ }
14607
+ function pathSegments(path) {
14608
+ return path.replace(GIT_SUFFIX, "").split("/").filter((segment) => segment !== "");
14609
+ }
14610
+ // packages/providers/src/pullRequestDirectory.ts
14611
+ var NotSignedInError = class extends Error {
14612
+ name = "NotSignedInError";
14613
+ };
14614
+ /** A listing named and numbered from its own link, which every host gives. */
14615
+ function listingFrom(details) {
14616
+ const ref = parsePullRequestUrl(details.url);
14617
+ return {
14618
+ ...details,
14619
+ host: ref.host,
14620
+ displayName: displayName(ref),
14621
+ repository: repositoryPath(ref),
14622
+ number: ref.number
14623
+ };
14624
+ }
12729
14625
  // packages/providers/src/gitHost.ts
12730
14626
  const COVERAGE_ARCHIVE_NAME = /cov|lcov|cobertura/i;
12731
14627
  const MAX_COVERAGE_ARCHIVE_BYTES = 209715200;
@@ -12873,6 +14769,111 @@ async function findMarked(api, marker) {
12873
14769
  if (comments.length < 100) return void 0;
12874
14770
  }
12875
14771
  }
14772
+ // packages/providers/src/fileHistory.ts
14773
+ /**
14774
+ * Reads changed files' recent commits from a host's API, for reviews whose local repository has
14775
+ * only the PR's own commits. Every failure becomes a `HistoryUnavailableError`, which the review
14776
+ * reports as a check it couldn't run instead of failing.
14777
+ */
14778
+ const COMMITS_PER_FILE = 100;
14779
+ const GITHUB_PATHS_PER_QUERY = 20;
14780
+ const GITLAB_CONCURRENT_REQUESTS = 6;
14781
+ const githubHistorySchema = z.object({
14782
+ totalCount: z.number(),
14783
+ nodes: z.array(z.object({
14784
+ oid: z.string(),
14785
+ messageHeadline: z.string(),
14786
+ committedDate: z.string(),
14787
+ author: z.object({
14788
+ email: z.string().nullable(),
14789
+ user: z.object({ login: z.string() }).nullable()
14790
+ }).nullable()
14791
+ }))
14792
+ });
14793
+ const githubResponseSchema = z.object({ repository: z.object({ object: z.record(z.string(), githubHistorySchema).nullable() }).nullable() });
14794
+ /** GitHub's GraphQL API answers for many files in one query; its REST API would need a request each. */
14795
+ async function githubFileHistory(graphql, owner, name, request) {
14796
+ if (graphql === void 0) throw new HistoryUnavailableError("GitHub's API for commit history needs a token");
14797
+ const histories = /* @__PURE__ */ new Map();
14798
+ for (let start = 0; start < request.paths.length; start += GITHUB_PATHS_PER_QUERY) {
14799
+ const paths = request.paths.slice(start, start + GITHUB_PATHS_PER_QUERY);
14800
+ const variables = {
14801
+ owner,
14802
+ name,
14803
+ oid: request.until,
14804
+ since: request.since.toISOString()
14805
+ };
14806
+ paths.forEach((path, index) => {
14807
+ variables[`p${index}`] = path;
14808
+ });
14809
+ const byAlias = (await asHistoryUnavailable(() => graphql(githubHistoryQuery(paths.length), variables, githubResponseSchema))).repository?.object;
14810
+ if (byAlias === null || byAlias === void 0) throw new HistoryUnavailableError("GitHub didn't find the merge base commit");
14811
+ paths.forEach((path, index) => {
14812
+ const history = byAlias[`f${index}`];
14813
+ if (history === void 0) return;
14814
+ histories.set(path, {
14815
+ total: history.totalCount,
14816
+ commits: history.nodes.map((node) => ({
14817
+ sha: node.oid,
14818
+ subject: node.messageHeadline,
14819
+ committedAt: node.committedDate,
14820
+ author: node.author?.user?.login ?? node.author?.email ?? ""
14821
+ }))
14822
+ });
14823
+ });
14824
+ }
14825
+ return histories;
14826
+ }
14827
+ function githubHistoryQuery(count) {
14828
+ const indexes = Array.from({ length: count }, (_, index) => index);
14829
+ return `query($owner: String!, $name: String!, $oid: GitObjectID!, $since: GitTimestamp!, ${indexes.map((index) => `$p${index}: String!`).join(", ")}) {
14830
+ repository(owner: $owner, name: $name) { object(oid: $oid) { ... on Commit { ${indexes.map((index) => `f${index}: history(path: $p${index}, since: $since, first: ${COMMITS_PER_FILE}) { totalCount nodes { oid messageHeadline committedDate author { email user { login } } } }`).join("\n")} } } }
14831
+ }`;
14832
+ }
14833
+ const gitlabCommitsSchema = z.array(z.object({
14834
+ id: z.string(),
14835
+ title: z.string(),
14836
+ committed_date: z.string(),
14837
+ author_email: z.string().nullable().optional(),
14838
+ author_name: z.string().nullable().optional()
14839
+ }));
14840
+ /** GitLab lists a file's commits one file at a time. */
14841
+ async function gitlabFileHistory(get, projectApi, request) {
14842
+ const histories = /* @__PURE__ */ new Map();
14843
+ for (let start = 0; start < request.paths.length; start += GITLAB_CONCURRENT_REQUESTS) {
14844
+ const batch = request.paths.slice(start, start + GITLAB_CONCURRENT_REQUESTS);
14845
+ const results = await Promise.all(batch.map((path) => {
14846
+ const query = new URLSearchParams({
14847
+ ref_name: request.until,
14848
+ path,
14849
+ since: request.since.toISOString(),
14850
+ per_page: String(COMMITS_PER_FILE)
14851
+ });
14852
+ return asHistoryUnavailable(() => get(`${projectApi}/repository/commits?${query.toString()}`, gitlabCommitsSchema));
14853
+ }));
14854
+ batch.forEach((path, index) => {
14855
+ const commits = (results[index] ?? []).map((commit) => ({
14856
+ sha: commit.id,
14857
+ subject: commit.title,
14858
+ committedAt: commit.committed_date,
14859
+ author: commit.author_email ?? commit.author_name ?? ""
14860
+ }));
14861
+ histories.set(path, {
14862
+ commits,
14863
+ total: commits.length
14864
+ });
14865
+ });
14866
+ }
14867
+ return histories;
14868
+ }
14869
+ async function asHistoryUnavailable(request) {
14870
+ try {
14871
+ return await request();
14872
+ } catch (error) {
14873
+ if (error instanceof HostApiError || error instanceof TypeError || error instanceof z.ZodError) throw new HistoryUnavailableError(error.message, { cause: error });
14874
+ throw error;
14875
+ }
14876
+ }
12876
14877
  // packages/providers/src/stack.ts
12877
14878
  /**
12878
14879
  * Finds a stack by following branches, for hosts or repositories without stacks of their own.
@@ -12970,13 +14971,13 @@ function inStackOrder(members) {
12970
14971
  return ordered;
12971
14972
  }
12972
14973
  // packages/providers/src/github.ts
12973
- const GITHUB_DOT_COM_ORIGIN$1 = "https://github.com";
14974
+ const GITHUB_DOT_COM_ORIGIN = "https://github.com";
12974
14975
  const GITHUB_DOT_COM_API = "https://api.github.com";
12975
14976
  const GITHUB_API_VERSION = "2022-11-28";
12976
14977
  const GITHUB_GIT_USERNAME = "x-access-token";
12977
14978
  const USER_AGENT = "walkdiff-review";
12978
- const AUTH_HINT$1 = "Set GITHUB_TOKEN (or GH_TOKEN) to a token that can read this repository; posting comments also needs pull-requests: write.";
12979
- const DELETED_USER_LOGIN = "ghost";
14979
+ const AUTH_HINT$3 = "Set GITHUB_TOKEN (or GH_TOKEN) to a token that can read this repository; posting comments also needs pull-requests: write.";
14980
+ const DELETED_USER_LOGIN$1 = "ghost";
12980
14981
  const branchTipSchema = z.object({
12981
14982
  ref: z.string(),
12982
14983
  sha: commitShaSchema
@@ -13025,8 +15026,8 @@ pull_requests: z.array(z.object({
13025
15026
  state: z.string(),
13026
15027
  merged_at: z.string().nullable()
13027
15028
  })) });
13028
- const OPEN_STATE$1 = "open";
13029
- const PULLS_PER_PAGE = 100;
15029
+ const OPEN_STATE$2 = "open";
15030
+ const PULLS_PER_PAGE$1 = 100;
13030
15031
  const issueCommentSchema = z.object({
13031
15032
  id: z.number().int(),
13032
15033
  body: z.string().nullable()
@@ -13098,7 +15099,7 @@ var GitHubHost = class {
13098
15099
  #ref;
13099
15100
  #token;
13100
15101
  #authHint;
13101
- constructor(ref, token, authHint = AUTH_HINT$1) {
15102
+ constructor(ref, token, authHint = AUTH_HINT$3) {
13102
15103
  this.#ref = ref;
13103
15104
  this.#token = token;
13104
15105
  this.#authHint = authHint;
@@ -13116,7 +15117,7 @@ var GitHubHost = class {
13116
15117
  number: pull.number,
13117
15118
  title: pull.title,
13118
15119
  description: pull.body ?? "",
13119
- author: pull.user?.login ?? DELETED_USER_LOGIN,
15120
+ author: pull.user?.login ?? DELETED_USER_LOGIN$1,
13120
15121
  baseRef: pull.base.ref,
13121
15122
  headRef: pull.head.ref,
13122
15123
  baseSha: pull.base.sha,
@@ -13153,7 +15154,7 @@ var GitHubHost = class {
13153
15154
  }, conversationResponseSchema)).repository.pullRequest;
13154
15155
  return {
13155
15156
  reviewers: latestReviews.nodes.map((review) => ({
13156
- name: review.author?.login ?? DELETED_USER_LOGIN,
15157
+ name: review.author?.login ?? DELETED_USER_LOGIN$1,
13157
15158
  state: REVIEWER_STATES$1.get(review.state) ?? ReviewerState.Other
13158
15159
  })),
13159
15160
  threads: reviewThreads.nodes.map((thread) => ({
@@ -13164,7 +15165,7 @@ var GitHubHost = class {
13164
15165
  isResolved: thread.isResolved,
13165
15166
  isOutdated: thread.isOutdated,
13166
15167
  comments: thread.comments.nodes.map((comment) => ({
13167
- author: comment.author?.login ?? DELETED_USER_LOGIN,
15168
+ author: comment.author?.login ?? DELETED_USER_LOGIN$1,
13168
15169
  body: comment.bodyText,
13169
15170
  createdAt: comment.createdAt,
13170
15171
  url: comment.url
@@ -13229,17 +15230,20 @@ var GitHubHost = class {
13229
15230
  }, this.#openPullRequests(repoApi));
13230
15231
  }
13231
15232
  async #hostStack(repoApi, stackNumber) {
13232
- const open = (await this.#get(`${repoApi}/stacks/${stackNumber}`, stackSchema)).pull_requests.filter((pull) => pull.state === OPEN_STATE$1 && pull.merged_at === null).map((pull) => pull.number);
15233
+ const open = (await this.#get(`${repoApi}/stacks/${stackNumber}`, stackSchema)).pull_requests.filter((pull) => pull.state === OPEN_STATE$2 && pull.merged_at === null).map((pull) => pull.number);
13233
15234
  const kept = keptAround(open, open.indexOf(this.#ref.number));
13234
15235
  return stackFromHost((await Promise.all(kept.map((number) => this.#get(`${repoApi}/pulls/${number}`, listedPullSchema)))).map((pull) => stackCandidate$1(pull).member), this.#ref.number);
13235
15236
  }
13236
15237
  #openPullRequests(repoApi) {
13237
- const list = async (filter) => (await this.#get(`${repoApi}/pulls?state=${OPEN_STATE$1}&per_page=${PULLS_PER_PAGE}&${filter}`, z.array(listedPullSchema))).map(stackCandidate$1);
15238
+ const list = async (filter) => (await this.#get(`${repoApi}/pulls?state=${OPEN_STATE$2}&per_page=${PULLS_PER_PAGE$1}&${filter}`, z.array(listedPullSchema))).map(stackCandidate$1);
13238
15239
  return {
13239
15240
  withHead: (branch) => list(`head=${encodeURIComponent(`${this.#ref.owner}:${branch}`)}`),
13240
15241
  withBase: (branch) => list(`base=${encodeURIComponent(branch)}`)
13241
15242
  };
13242
15243
  }
15244
+ fetchFileHistory(request) {
15245
+ return githubFileHistory(this.#token === void 0 ? void 0 : (query, variables, schema) => this.#graphql(query, variables, schema), this.#ref.owner, this.#ref.repo, request);
15246
+ }
13243
15247
  async #graphql(query, variables, schema) {
13244
15248
  const url = graphqlUrl(this.#ref.webOrigin);
13245
15249
  const response = await writeJson({
@@ -13258,7 +15262,7 @@ var GitHubHost = class {
13258
15262
  }
13259
15263
  #repoApi() {
13260
15264
  const { owner, repo, webOrigin } = this.#ref;
13261
- return `${apiBase(webOrigin)}/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`;
15265
+ return `${githubApiBase(webOrigin)}/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`;
13262
15266
  }
13263
15267
  async #mergeBase(repoApi, base, head) {
13264
15268
  return (await this.#get(`${repoApi}/compare/${base}...${head}`, compareSchema)).merge_base_commit.sha;
@@ -13281,13 +15285,7 @@ var GitHubHost = class {
13281
15285
  });
13282
15286
  }
13283
15287
  #headers() {
13284
- const headers = {
13285
- Accept: "application/vnd.github+json",
13286
- "X-GitHub-Api-Version": GITHUB_API_VERSION,
13287
- "User-Agent": USER_AGENT
13288
- };
13289
- if (this.#token !== void 0) headers.Authorization = `Bearer ${this.#token}`;
13290
- return headers;
15288
+ return githubHeaders(this.#token);
13291
15289
  }
13292
15290
  #gitAuth() {
13293
15291
  return this.#token === void 0 ? void 0 : {
@@ -13310,14 +15308,14 @@ function withUnplacedComments$1(review) {
13310
15308
  /** GitHub calls a merged PR closed, telling them apart only by `merged_at`. */
13311
15309
  function githubState(pull) {
13312
15310
  if (pull.merged_at !== null) return PullRequestState.Merged;
13313
- return pull.state === OPEN_STATE$1 ? PullRequestState.Open : PullRequestState.Closed;
15311
+ return pull.state === OPEN_STATE$2 ? PullRequestState.Open : PullRequestState.Closed;
13314
15312
  }
13315
15313
  function stackCandidate$1(pull) {
13316
15314
  return {
13317
15315
  member: {
13318
15316
  number: pull.number,
13319
15317
  title: pull.title,
13320
- author: pull.user?.login ?? DELETED_USER_LOGIN,
15318
+ author: pull.user?.login ?? DELETED_USER_LOGIN$1,
13321
15319
  headRef: pull.head.ref,
13322
15320
  baseRef: pull.base.ref
13323
15321
  },
@@ -13325,10 +15323,18 @@ function stackCandidate$1(pull) {
13325
15323
  };
13326
15324
  }
13327
15325
  function graphqlUrl(webOrigin) {
13328
- return webOrigin === GITHUB_DOT_COM_ORIGIN$1 ? `${GITHUB_DOT_COM_API}/graphql` : `${webOrigin}/api/graphql`;
15326
+ return webOrigin === GITHUB_DOT_COM_ORIGIN ? `${GITHUB_DOT_COM_API}/graphql` : `${webOrigin}/api/graphql`;
15327
+ }
15328
+ function githubHeaders(token) {
15329
+ return {
15330
+ Accept: "application/vnd.github+json",
15331
+ "X-GitHub-Api-Version": GITHUB_API_VERSION,
15332
+ "User-Agent": USER_AGENT,
15333
+ ...token === void 0 ? {} : { Authorization: `Bearer ${token}` }
15334
+ };
13329
15335
  }
13330
- function apiBase(webOrigin) {
13331
- return webOrigin === GITHUB_DOT_COM_ORIGIN$1 ? GITHUB_DOT_COM_API : `${webOrigin}/api/v3`;
15336
+ function githubApiBase(webOrigin) {
15337
+ return webOrigin === GITHUB_DOT_COM_ORIGIN ? GITHUB_DOT_COM_API : `${webOrigin}/api/v3`;
13332
15338
  }
13333
15339
  function githubReviewComment(comment) {
13334
15340
  if (comment.range === null) return {
@@ -13353,10 +15359,60 @@ function githubReviewComment(comment) {
13353
15359
  body: comment.body
13354
15360
  };
13355
15361
  }
15362
+ // packages/providers/src/githubDirectory.ts
15363
+ const AUTH_HINT$2 = "Set GITHUB_TOKEN (or GH_TOKEN) to a token that can read this repository, or sign in with the GitHub CLI.";
15364
+ const DELETED_USER_LOGIN = "ghost";
15365
+ const PULLS_PER_PAGE = 100;
15366
+ const AWAITING_MY_REVIEW_QUERY = "is:open is:pr review-requested:@me archived:false";
15367
+ /** A PR as both the pulls list and search results give it. */
15368
+ const listedSchema$1 = z.object({
15369
+ html_url: z.url(),
15370
+ title: z.string(),
15371
+ user: z.object({ login: z.string() }).nullable(),
15372
+ draft: z.boolean().default(false),
15373
+ updated_at: z.string()
15374
+ });
15375
+ const searchSchema = z.object({ items: z.array(listedSchema$1) });
15376
+ var GitHubDirectory = class {
15377
+ #repository;
15378
+ #token;
15379
+ constructor(repository, token) {
15380
+ this.#repository = repository;
15381
+ this.#token = token;
15382
+ }
15383
+ async openFromBranch(branch) {
15384
+ const { owner, repo, webOrigin } = this.#repository;
15385
+ const head = encodeURIComponent(`${owner}:${branch}`);
15386
+ const url = `${githubApiBase(webOrigin)}/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/pulls?state=open&head=${head}&per_page=${PULLS_PER_PAGE}`;
15387
+ return (await this.#get(url, z.array(listedSchema$1))).map(toListing$1);
15388
+ }
15389
+ async awaitingMyReview() {
15390
+ if (this.#token === void 0) throw new NotSignedInError(`Walkdiff needs your GitHub login to find PRs waiting for your review. ${AUTH_HINT$2}`);
15391
+ const url = `${githubApiBase(this.#repository.webOrigin)}/search/issues?q=${encodeURIComponent(AWAITING_MY_REVIEW_QUERY)}&sort=updated&order=desc&per_page=50`;
15392
+ return (await this.#get(url, searchSchema)).items.map(toListing$1);
15393
+ }
15394
+ #get(url, schema) {
15395
+ return getJson({
15396
+ url,
15397
+ headers: githubHeaders(this.#token),
15398
+ schema,
15399
+ authHint: AUTH_HINT$2
15400
+ });
15401
+ }
15402
+ };
15403
+ function toListing$1(pull) {
15404
+ return listingFrom({
15405
+ url: pull.html_url,
15406
+ title: pull.title,
15407
+ author: pull.user?.login ?? DELETED_USER_LOGIN,
15408
+ draft: pull.draft,
15409
+ updatedAt: pull.updated_at
15410
+ });
15411
+ }
13356
15412
  // packages/providers/src/gitlab.ts
13357
15413
  const GITLAB_GIT_USERNAME = "oauth2";
13358
15414
  const APPROVAL_REFUSED_STATUS = 401;
13359
- const AUTH_HINT = "Set GITLAB_TOKEN to a token with the read_api and read_repository scopes; posting comments needs the api scope.";
15415
+ const AUTH_HINT$1 = "Set GITLAB_TOKEN to a token with the read_api and read_repository scopes; posting comments needs the api scope.";
13360
15416
  const mergeRequestSchema = z.object({
13361
15417
  web_url: z.url(),
13362
15418
  iid: z.number().int().positive(),
@@ -13390,8 +15446,8 @@ const listedMergeRequestSchema = z.object({
13390
15446
  target_project_id: z.number().int()
13391
15447
  });
13392
15448
  const projectSchema = z.object({ default_branch: z.string() });
13393
- const OPEN_STATE = "opened";
13394
- const MERGE_REQUESTS_PER_PAGE = 100;
15449
+ const OPEN_STATE$1 = "opened";
15450
+ const MERGE_REQUESTS_PER_PAGE$1 = 100;
13395
15451
  const STACK_MEMBER_FIELDS = "iid title author { username } sourceBranch targetBranch";
13396
15452
  const STACK_QUERY = `query($project: ID!, $iid: String!) {
13397
15453
  project(fullPath: $project) { mergeRequest(iid: $iid) { ${STACK_MEMBER_FIELDS} stack { ${STACK_MEMBER_FIELDS} } } }
@@ -13419,7 +15475,7 @@ const noteSchema = z.object({
13419
15475
  body: z.string().nullable()
13420
15476
  });
13421
15477
  const DISCUSSIONS_PER_PAGE = 100;
13422
- const userSchema = z.object({ username: z.string() });
15478
+ const userSchema$1 = z.object({ username: z.string() });
13423
15479
  const discussionSchema = z.object({
13424
15480
  id: z.string(),
13425
15481
  individual_note: z.boolean(),
@@ -13428,7 +15484,7 @@ const discussionSchema = z.object({
13428
15484
  body: z.string(),
13429
15485
  created_at: z.string(),
13430
15486
  system: z.boolean(),
13431
- author: userSchema,
15487
+ author: userSchema$1,
13432
15488
  resolvable: z.boolean().optional(),
13433
15489
  resolved: z.boolean().optional(),
13434
15490
  position: z.object({
@@ -13439,11 +15495,11 @@ const discussionSchema = z.object({
13439
15495
  }).nullable().optional()
13440
15496
  }))
13441
15497
  });
13442
- const approvalsSchema = z.object({ approved_by: z.array(z.object({ user: userSchema })) });
15498
+ const approvalsSchema = z.object({ approved_by: z.array(z.object({ user: userSchema$1 })) });
13443
15499
  /** Only `user_has_approved`: on GitLab Free, `user_can_approve` reads false for merge requests the user can approve. */
13444
15500
  const ownApprovalSchema = z.object({ user_has_approved: z.boolean() });
13445
15501
  const reviewersSchema = z.array(z.object({
13446
- user: userSchema,
15502
+ user: userSchema$1,
13447
15503
  state: z.string().nullable().optional()
13448
15504
  }));
13449
15505
  const REVIEWER_STATES = /* @__PURE__ */ new Map([
@@ -13481,7 +15537,7 @@ var GitLabHost = class {
13481
15537
  #ref;
13482
15538
  #token;
13483
15539
  #authHint;
13484
- constructor(ref, token, authHint = AUTH_HINT) {
15540
+ constructor(ref, token, authHint = AUTH_HINT$1) {
13485
15541
  this.#ref = ref;
13486
15542
  this.#token = token;
13487
15543
  this.#authHint = authHint;
@@ -13679,8 +15735,11 @@ var GitLabHost = class {
13679
15735
  defaultBranch: project.default_branch
13680
15736
  }, this.#openMergeRequests(projectApi));
13681
15737
  }
15738
+ fetchFileHistory(request) {
15739
+ return gitlabFileHistory((url, schema) => this.#get(url, schema), this.#projectApi(), request);
15740
+ }
13682
15741
  #openMergeRequests(projectApi) {
13683
- const list = async (filter) => (await this.#get(`${projectApi}/merge_requests?state=${OPEN_STATE}&per_page=${MERGE_REQUESTS_PER_PAGE}&${filter}`, z.array(listedMergeRequestSchema))).map(stackCandidate);
15742
+ const list = async (filter) => (await this.#get(`${projectApi}/merge_requests?state=${OPEN_STATE$1}&per_page=${MERGE_REQUESTS_PER_PAGE$1}&${filter}`, z.array(listedMergeRequestSchema))).map(stackCandidate);
13684
15743
  return {
13685
15744
  withHead: (branch) => list(`source_branch=${encodeURIComponent(branch)}`),
13686
15745
  withBase: (branch) => list(`target_branch=${encodeURIComponent(branch)}`)
@@ -13716,8 +15775,7 @@ var GitLabHost = class {
13716
15775
  }]);
13717
15776
  }
13718
15777
  #projectApi() {
13719
- const { webOrigin, projectPath } = this.#ref;
13720
- return `${webOrigin}/api/v4/projects/${encodeURIComponent(projectPath)}`;
15778
+ return gitlabProjectApi(this.#ref);
13721
15779
  }
13722
15780
  #mergeRequestApi() {
13723
15781
  return `${this.#projectApi()}/merge_requests/${this.#ref.number}`;
@@ -13732,7 +15790,7 @@ var GitLabHost = class {
13732
15790
  });
13733
15791
  }
13734
15792
  #headers() {
13735
- return this.#token === void 0 ? {} : { "PRIVATE-TOKEN": this.#token };
15793
+ return gitlabHeaders(this.#token);
13736
15794
  }
13737
15795
  #gitAuth() {
13738
15796
  return this.#token === void 0 ? void 0 : {
@@ -13742,6 +15800,15 @@ var GitLabHost = class {
13742
15800
  }
13743
15801
  };
13744
15802
  /** GitLab's "locked" is an open merge request in the middle of being merged. */
15803
+ function gitlabHeaders(token) {
15804
+ return token === void 0 ? {} : { "PRIVATE-TOKEN": token };
15805
+ }
15806
+ function gitlabApiBase(webOrigin) {
15807
+ return `${webOrigin}/api/v4`;
15808
+ }
15809
+ function gitlabProjectApi({ webOrigin, projectPath }) {
15810
+ return `${gitlabApiBase(webOrigin)}/projects/${encodeURIComponent(projectPath)}`;
15811
+ }
13745
15812
  function gitlabState(state) {
13746
15813
  if (state === MERGED_STATE) return PullRequestState.Merged;
13747
15814
  return state === CLOSED_STATE ? PullRequestState.Closed : PullRequestState.Open;
@@ -13784,21 +15851,68 @@ function gitlabNote(comment) {
13784
15851
  const last = number(range.end);
13785
15852
  return first === last ? comment.body : `Lines ${first}–${last}${range.side === LineSide.Old ? " (before)" : ""}:\n\n${comment.body}`;
13786
15853
  }
13787
- // packages/providers/src/trustedHosts.ts
13788
- const TRUSTED_GITHUB_HOSTS_VARIABLE = "WALKDIFF_TRUSTED_GITHUB_HOSTS";
13789
- const TRUSTED_GITLAB_HOSTS_VARIABLE = "WALKDIFF_TRUSTED_GITLAB_HOSTS";
13790
- const GITHUB_DOT_COM_ORIGIN = "https://github.com";
13791
- const GITLAB_DOT_COM_ORIGIN = "https://gitlab.com";
13792
- /**
13793
- * Whether this link's host may receive the token for its kind of host. Links are pasted by
13794
- * hand and their kind is read from the path, so neither the host name nor the kind can be
13795
- * taken on trust: `https://evil.example/a/b/pull/1` would otherwise receive a GitHub token,
13796
- * and `https://gitlab.com/a/b/pull/1` would receive a GitHub token at GitLab. Comparing
13797
- * whole origins also keeps a token off plain http and off look-alikes such as
13798
- * `github.com.evil.example`.
13799
- */
13800
- function isTrustedHost(ref, trusted) {
13801
- return ref.host === GitHostKind.GitHub ? ref.webOrigin === GITHUB_DOT_COM_ORIGIN || trusted.github.includes(ref.webOrigin) : ref.webOrigin === GITLAB_DOT_COM_ORIGIN || trusted.gitlab.includes(ref.webOrigin);
15854
+ // packages/providers/src/gitlabDirectory.ts
15855
+ const AUTH_HINT = "Set GITLAB_TOKEN to a token with the read_api scope.";
15856
+ const OPEN_STATE = "opened";
15857
+ const MERGE_REQUESTS_PER_PAGE = 100;
15858
+ const listedSchema = z.object({
15859
+ web_url: z.url(),
15860
+ title: z.string(),
15861
+ author: z.object({ username: z.string() }),
15862
+ draft: z.boolean().default(false),
15863
+ updated_at: z.string(),
15864
+ source_project_id: z.number().int(),
15865
+ target_project_id: z.number().int()
15866
+ });
15867
+ const userSchema = z.object({ username: z.string() });
15868
+ var GitLabDirectory = class {
15869
+ #project;
15870
+ #token;
15871
+ constructor(project, token) {
15872
+ this.#project = project;
15873
+ this.#token = token;
15874
+ }
15875
+ async openFromBranch(branch) {
15876
+ const url = `${gitlabProjectApi(this.#project)}/merge_requests?state=${OPEN_STATE}&source_branch=${encodeURIComponent(branch)}&per_page=${MERGE_REQUESTS_PER_PAGE}`;
15877
+ return (await this.#get(url, z.array(listedSchema))).filter((mergeRequest) => mergeRequest.source_project_id === mergeRequest.target_project_id).map(toListing);
15878
+ }
15879
+ /**
15880
+ * GitLab keeps a reviewer on a merge request after they review it, so unlike GitHub this also
15881
+ * lists merge requests the user has already reviewed and that are still open.
15882
+ */
15883
+ async awaitingMyReview() {
15884
+ if (this.#token === void 0) throw new NotSignedInError(`Walkdiff needs your GitLab login to find merge requests waiting for your review. ${AUTH_HINT}`);
15885
+ const api = gitlabApiBase(this.#project.webOrigin);
15886
+ const { username } = await this.#get(`${api}/user`, userSchema);
15887
+ const url = `${api}/merge_requests?state=${OPEN_STATE}&scope=all&reviewer_username=${encodeURIComponent(username)}&order_by=updated_at&sort=desc&per_page=50`;
15888
+ return (await this.#get(url, z.array(listedSchema))).map(toListing);
15889
+ }
15890
+ #get(url, schema) {
15891
+ return getJson({
15892
+ url,
15893
+ headers: gitlabHeaders(this.#token),
15894
+ schema,
15895
+ authHint: AUTH_HINT
15896
+ });
15897
+ }
15898
+ };
15899
+ function toListing(mergeRequest) {
15900
+ return listingFrom({
15901
+ url: mergeRequest.web_url,
15902
+ title: mergeRequest.title,
15903
+ author: mergeRequest.author.username,
15904
+ draft: mergeRequest.draft,
15905
+ updatedAt: mergeRequest.updated_at
15906
+ });
15907
+ }
15908
+ // packages/providers/src/pullRequestDirectoryFor.ts
15909
+ /** Like `gitHostFor`, the token only goes to a host the user trusts for it. */
15910
+ function pullRequestDirectoryFor(repository, tokens) {
15911
+ const trusted = isTrustedHost(repository, tokens.trustedOrigins);
15912
+ switch (repository.host) {
15913
+ case GitHostKind.GitHub: return new GitHubDirectory(repository, trusted ? tokens.github : void 0);
15914
+ case GitHostKind.GitLab: return new GitLabDirectory(repository, trusted ? tokens.gitlab : void 0);
15915
+ }
13802
15916
  }
13803
15917
  // packages/providers/src/gitHostFor.ts
13804
15918
  /**
@@ -14202,6 +16316,13 @@ async function isReadable(path) {
14202
16316
  return false;
14203
16317
  }
14204
16318
  }
16319
+ // packages/cli/src/version.ts
16320
+ const MANIFEST_PATH = firstExisting([resolve(import.meta.dirname, "package.json"), resolve(import.meta.dirname, "../../../package.json")]);
16321
+ const manifestSchema = z.object({ version: z.string().min(1) });
16322
+ /** The running Walkdiff's version, read from its package.json. */
16323
+ function walkdiffVersion(manifestPath = MANIFEST_PATH) {
16324
+ return manifestSchema.parse(JSON.parse(readFileSync(manifestPath, "utf8"))).version;
16325
+ }
14205
16326
  // packages/cli/src/server.ts
14206
16327
  const LOOPBACK_HOST = "127.0.0.1";
14207
16328
  const INDEX_FILE = "index.html";
@@ -14343,6 +16464,48 @@ async function attachCoverage(store, id, reports, write) {
14343
16464
  });
14344
16465
  return store.get(id);
14345
16466
  }
16467
+ // packages/cli/src/app/pullRequestLookup.ts
16468
+ const PullRequestLookup = {
16469
+ FromBranch: "fromBranch",
16470
+ AwaitingMyReview: "awaitingMyReview"
16471
+ };
16472
+ const BAD_REQUEST = 400;
16473
+ const FORBIDDEN = 403;
16474
+ const BAD_GATEWAY = 502;
16475
+ const OK = 200;
16476
+ /**
16477
+ * Answers a plugin asking which PRs it could review, from the git remote of the repository it has
16478
+ * open: the open PRs from a branch (`remote` and `branch`), or those waiting for the user's review
16479
+ * on that remote's host (`remote` alone).
16480
+ */
16481
+ async function lookUpPullRequests(lookup, query, context) {
16482
+ const remote = query.get("remote") ?? "";
16483
+ const branch = query.get("branch") ?? "";
16484
+ if (remote === "") return failure(BAD_REQUEST, "Ask with the repository's git remote, as remote=<url>.");
16485
+ if (lookup === PullRequestLookup.FromBranch && branch === "") return failure(BAD_REQUEST, "Ask with the branch, as branch=<name>.");
16486
+ try {
16487
+ const directory = await context.directoryFor(parseRemoteUrl(remote, context.trustedOrigins));
16488
+ const listed = lookup === PullRequestLookup.FromBranch ? await directory.openFromBranch(branch) : await directory.awaitingMyReview();
16489
+ return {
16490
+ status: OK,
16491
+ body: listed
16492
+ };
16493
+ } catch (error) {
16494
+ return failureFor(error);
16495
+ }
16496
+ }
16497
+ function failureFor(error) {
16498
+ if (error instanceof InvalidRemoteUrlError) return failure(BAD_REQUEST, error.message);
16499
+ if (error instanceof NotSignedInError) return failure(FORBIDDEN, error.message);
16500
+ if (error instanceof HostApiError) return failure(BAD_GATEWAY, error.message);
16501
+ throw error;
16502
+ }
16503
+ function failure(status, error) {
16504
+ return {
16505
+ status,
16506
+ body: { error }
16507
+ };
16508
+ }
14346
16509
  // packages/cli/src/app/stackStatus.ts
14347
16510
  /**
14348
16511
  * A grouped stack with each member's state read from its host now, bottom first. One member's
@@ -14504,6 +16667,7 @@ async function approve({ member, host, analyzed }, body) {
14504
16667
  };
14505
16668
  }
14506
16669
  }
16670
+ const PULL_REQUEST_LOOKUPS = /* @__PURE__ */ new Map([["/api/pull-requests", PullRequestLookup.FromBranch], ["/api/review-requests", PullRequestLookup.AwaitingMyReview]]);
14507
16671
  const API_KEY_META = "walkdiff-api-key";
14508
16672
  const HOME_META = "walkdiff-home";
14509
16673
  const REVIEW_ID_META = "walkdiff-review-id";
@@ -14524,6 +16688,8 @@ var AppPortInUseError = class extends Error {
14524
16688
  async function startAppServer(store, service, options) {
14525
16689
  const { port, log, apiKey = newApiKey(), env = {}, offline = false } = options;
14526
16690
  const hostFor = options.hostFor ?? ((ref) => Promise.resolve(gitHostFor(ref, readHostTokens(env))));
16691
+ const directoryFor = options.directoryFor ?? ((repository) => Promise.resolve(pullRequestDirectoryFor(repository, readHostTokens(env))));
16692
+ const { trustedOrigins } = readHostTokens(env);
14527
16693
  const allowedHosts = /* @__PURE__ */ new Set();
14528
16694
  const context = {
14529
16695
  store,
@@ -14533,6 +16699,8 @@ async function startAppServer(store, service, options) {
14533
16699
  env,
14534
16700
  offline,
14535
16701
  hostFor,
16702
+ directoryFor,
16703
+ trustedOrigins,
14536
16704
  writeReport: options.writeReport ?? writeReport,
14537
16705
  describeChecks: options.describeChecks ?? (() => describeChecks())
14538
16706
  };
@@ -14551,6 +16719,10 @@ async function startAppServer(store, service, options) {
14551
16719
  close: () => new Promise((done, fail) => server.close((error) => error ? fail(error) : done()))
14552
16720
  };
14553
16721
  }
16722
+ /**
16723
+ * A key for the API. Made fresh each run and kept only in memory and in the connection file, which
16724
+ * is removed when the app stops, so it lasts only as long as the process.
16725
+ */
14554
16726
  function newApiKey() {
14555
16727
  return randomBytes(API_KEY_BYTES).toString("hex");
14556
16728
  }
@@ -14585,6 +16757,30 @@ async function handleApi(request, response, pathname, context) {
14585
16757
  return;
14586
16758
  }
14587
16759
  const method = request.method ?? "GET";
16760
+ if (pathname === "/api/info" && method === "GET") {
16761
+ sendJson(response, 200, {
16762
+ apiVersion: 1,
16763
+ reportSchemaVersion: 11,
16764
+ version: walkdiffVersion()
16765
+ });
16766
+ return;
16767
+ }
16768
+ const reportData = /^\/api\/reviews\/(\d+)\/report$/.exec(pathname);
16769
+ if (reportData !== null && method === "GET") {
16770
+ await sendReportData(response, Number(reportData[1]), context);
16771
+ return;
16772
+ }
16773
+ const lookup = PULL_REQUEST_LOOKUPS.get(pathname);
16774
+ if (lookup !== void 0 && method === "GET") {
16775
+ const answer = await lookUpPullRequests(lookup, new URL(request.url ?? "/", "http://localhost").searchParams, context);
16776
+ sendJson(response, answer.status, answer.body);
16777
+ return;
16778
+ }
16779
+ const changedFile = /^\/api\/reviews\/(\d+)\/file$/.exec(pathname);
16780
+ if (changedFile !== null && method === "GET") {
16781
+ await sendChangedFile(request, response, Number(changedFile[1]), context);
16782
+ return;
16783
+ }
14588
16784
  if (pathname === "/api/reviews") {
14589
16785
  if (method === "GET") {
14590
16786
  sendJson(response, 200, context.service.list());
@@ -14896,6 +17092,72 @@ async function sendReportPage(response, id, context) {
14896
17092
  }
14897
17093
  sendHtml(response, withReviewId(withMeta(page.replace(REPORT_FILE_POLICY_TAG, ""), context.apiKey), id), REPORT_PAGE_POLICY);
14898
17094
  }
17095
+ /** A review's report as data, as its page shows it. */
17096
+ async function sendReportData(response, id, context) {
17097
+ const model = await readReviewModel(context.store.reportDirOf(id));
17098
+ if (model === void 0) {
17099
+ sendJson(response, 404, { error: "This review has no report. Refresh it to create one." });
17100
+ return;
17101
+ }
17102
+ sendJson(response, 200, model);
17103
+ }
17104
+ const FileSide = {
17105
+ Base: "base",
17106
+ Head: "head"
17107
+ };
17108
+ function isFileSide(value) {
17109
+ return value === FileSide.Base || value === FileSide.Head;
17110
+ }
17111
+ /**
17112
+ * One of a review's changed files at the PR's merge base or head, from the repository the app
17113
+ * fetched its commits into, for showing a diff of a PR that isn't checked out. Only the PR's
17114
+ * changed files can be read, so this never serves anything else from the repository.
17115
+ */
17116
+ async function sendChangedFile(request, response, id, context) {
17117
+ const query = new URL(request.url ?? "/", "http://localhost").searchParams;
17118
+ const side = query.get("side");
17119
+ const path = query.get("path");
17120
+ if (!isFileSide(side) || path === null || path === "") {
17121
+ sendJson(response, 400, { error: "Ask for side=base or side=head, and a path." });
17122
+ return;
17123
+ }
17124
+ const model = await readReviewModel(context.store.reportDirOf(id));
17125
+ const repoDir = context.store.repoDirOf(id);
17126
+ if (model === void 0 || repoDir === void 0) {
17127
+ sendJson(response, 404, { error: "This review's files aren't available. Refresh it to fetch them." });
17128
+ return;
17129
+ }
17130
+ if (!model.files.some(({ diff }) => diff.path === path || "previousPath" in diff && diff.previousPath === path)) {
17131
+ sendJson(response, 404, { error: "That file isn't one this PR changes." });
17132
+ return;
17133
+ }
17134
+ const commit = side === FileSide.Base ? model.pullRequest.mergeBaseSha : model.pullRequest.headSha;
17135
+ const [blob] = await readBlobs(repoDir, [{
17136
+ commit,
17137
+ path
17138
+ }]);
17139
+ if (blob === void 0) {
17140
+ sendJson(response, 404, { error: `That file doesn't exist at the PR's ${side}.` });
17141
+ return;
17142
+ }
17143
+ sendJson(response, 200, {
17144
+ path,
17145
+ side,
17146
+ commit,
17147
+ text: blob.toString("utf8")
17148
+ });
17149
+ }
17150
+ /** Undefined when there's no report, it's gone from disk, or it was written in an older format. */
17151
+ async function readReviewModel(reportDir) {
17152
+ if (reportDir === void 0) return void 0;
17153
+ try {
17154
+ const parsed = reviewModelSchema.safeParse(JSON.parse(await readFile(join(reportDir, REVIEW_MODEL_FILE), "utf8")));
17155
+ return parsed.success ? parsed.data : void 0;
17156
+ } catch (error) {
17157
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return void 0;
17158
+ throw error;
17159
+ }
17160
+ }
14899
17161
  /** Undefined when the file is gone, which happens after the cache folder is cleared. */
14900
17162
  async function readReportPage(reportDir) {
14901
17163
  try {
@@ -14954,6 +17216,32 @@ function sendText(response, status, body) {
14954
17216
  });
14955
17217
  response.end(body);
14956
17218
  }
17219
+ // packages/cli/src/app/connectionFile.ts
17220
+ /**
17221
+ * How editor plugins find a running app: its address and the key its API requires, in a file
17222
+ * only the user can read. The key is otherwise created fresh each run and never stored, so this
17223
+ * file is the one place it's written down; it's removed when the app stops. A file left by an app
17224
+ * that crashed points at nothing, which a plugin finds out from `GET /api/info`.
17225
+ */
17226
+ const CONNECTION_FILE = "app.json";
17227
+ const OWNER_ONLY = 384;
17228
+ async function writeConnectionFile(dataDir, connection) {
17229
+ const path = join(dataDir, CONNECTION_FILE);
17230
+ await rm(path, { force: true });
17231
+ await writeFile(path, `${JSON.stringify(connection, null, 2)}\n`, { mode: OWNER_ONLY });
17232
+ return path;
17233
+ }
17234
+ /** Removes the file when the process ends, including on Ctrl+C, which would otherwise skip `exit`. */
17235
+ function removeOnExit(path) {
17236
+ const remove = () => rmSync(path, { force: true });
17237
+ process.once("exit", remove);
17238
+ for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, () => {
17239
+ remove();
17240
+ process.exit(signal === "SIGINT" ? EXIT_ON_SIGINT : EXIT_ON_SIGTERM);
17241
+ });
17242
+ }
17243
+ const EXIT_ON_SIGINT = 130;
17244
+ const EXIT_ON_SIGTERM = 143;
14957
17245
  // packages/cli/src/app/stacks.ts
14958
17246
  /** One row per PR, however its URL was pasted (`/files`, trailing slash, and so on). */
14959
17247
  function canonicalUrl(ref) {
@@ -15186,10 +17474,11 @@ function urlsByStack(reviews) {
15186
17474
  }
15187
17475
  return grouped;
15188
17476
  }
15189
- function summarize({ model, reportDir }) {
17477
+ function summarize({ model, reportDir, repoDir }) {
15190
17478
  const units = model.files.flatMap(changedUnitsOf);
15191
17479
  return {
15192
17480
  reportDir,
17481
+ repoDir,
15193
17482
  title: model.pullRequest.title,
15194
17483
  author: model.pullRequest.author,
15195
17484
  securityLevel: model.risk.securityLevel,
@@ -15233,7 +17522,8 @@ const MIGRATIONS = [
15233
17522
  `ALTER TABLE reviews ADD COLUMN detected_stack TEXT`,
15234
17523
  `ALTER TABLE reviews ADD COLUMN dismissed_stack_members TEXT`,
15235
17524
  `ALTER TABLE reviews ADD COLUMN head_sha TEXT`,
15236
- `ALTER TABLE reviews ADD COLUMN base_ref TEXT`
17525
+ `ALTER TABLE reviews ADD COLUMN base_ref TEXT`,
17526
+ `ALTER TABLE reviews ADD COLUMN repo_dir TEXT`
15237
17527
  ];
15238
17528
  const attachedCoverageSchema = z.object({
15239
17529
  headSha: z.string(),
@@ -15258,6 +17548,7 @@ const reviewRowSchema = z.object({
15258
17548
  status: z.enum(ReviewStatus),
15259
17549
  error: z.string().nullable(),
15260
17550
  report_dir: z.string().nullable(),
17551
+ repo_dir: z.string().nullable(),
15261
17552
  ai: z.number(),
15262
17553
  title: z.string().nullable(),
15263
17554
  author: z.string().nullable(),
@@ -15305,6 +17596,10 @@ var ReviewStore = class {
15305
17596
  reportDirOf(id) {
15306
17597
  return this.#parsedRow(id)?.report_dir ?? void 0;
15307
17598
  }
17599
+ /** Undefined for reviews made before the app kept it, until they're refreshed. */
17600
+ repoDirOf(id) {
17601
+ return this.#parsedRow(id)?.repo_dir ?? void 0;
17602
+ }
15308
17603
  add(review) {
15309
17604
  const now = this.#timestamp();
15310
17605
  const { lastInsertRowid } = this.#db.prepare("INSERT INTO reviews (url, host, display_name, status, ai, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)").run(review.url, review.host, review.displayName, ReviewStatus.Queued, review.ai ? 1 : 0, now, now);
@@ -15320,8 +17615,8 @@ var ReviewStore = class {
15320
17615
  this.#db.prepare("UPDATE reviews SET status = ?, error = NULL, updated_at = ? WHERE id = ?").run(status, this.#timestamp(), id);
15321
17616
  }
15322
17617
  markReady(id, analysis) {
15323
- this.#db.prepare(`UPDATE reviews SET status = ?, error = NULL, report_dir = ?, title = ?, author = ?, security_level = ?,
15324
- units_to_review = ?, untouched_references = ?, findings = ?, coverage_source = ?, head_sha = ?, base_ref = ?, updated_at = ? WHERE id = ?`).run(ReviewStatus.Ready, analysis.reportDir, analysis.title, analysis.author, analysis.securityLevel, analysis.unitsToReview, analysis.untouchedReferences, analysis.findings, analysis.coverageSource, analysis.head.headSha, analysis.head.baseRef, this.#timestamp(), id);
17618
+ this.#db.prepare(`UPDATE reviews SET status = ?, error = NULL, report_dir = ?, repo_dir = ?, title = ?, author = ?, security_level = ?,
17619
+ units_to_review = ?, untouched_references = ?, findings = ?, coverage_source = ?, head_sha = ?, base_ref = ?, updated_at = ? WHERE id = ?`).run(ReviewStatus.Ready, analysis.reportDir, analysis.repoDir, analysis.title, analysis.author, analysis.securityLevel, analysis.unitsToReview, analysis.untouchedReferences, analysis.findings, analysis.coverageSource, analysis.head.headSha, analysis.head.baseRef, this.#timestamp(), id);
15325
17620
  }
15326
17621
  /** Records what the last detection found; undefined clears it, for a PR that now stands alone. */
15327
17622
  saveDetection(id, stack) {
@@ -15578,8 +17873,9 @@ async function serveReportOnPreferredPort(reportDir, port) {
15578
17873
  }
15579
17874
  async function reviewPullRequest(options, deps) {
15580
17875
  const ref = parsePullRequestUrl(options.url ?? await detectPullRequestUrl(deps.env));
17876
+ const { model } = await analyzePullRequest(ref, options, deps);
15581
17877
  return {
15582
- model: await analyzePullRequest(ref, options, deps),
17878
+ model,
15583
17879
  reportDir: options.outDir ?? defaultReportDir(deps.cacheDir, ref)
15584
17880
  };
15585
17881
  }
@@ -15608,22 +17904,33 @@ async function reviewLocalBranch(local, options, deps) {
15608
17904
  }
15609
17905
  async function analyzePullRequest(ref, options, deps) {
15610
17906
  deps.reportStep(AnalysisStep.FetchingPullRequest);
15611
- const snapshot = await gitHostFor(ref, deps.tokens).fetchPullRequest();
17907
+ const host = gitHostFor(ref, deps.tokens);
17908
+ const snapshot = await host.fetchPullRequest();
17909
+ const history = options.network ? (request) => host.fetchFileHistory(request) : offlineHistory;
15612
17910
  const { pullRequest } = snapshot;
15613
17911
  deps.reportStep(AnalysisStep.FetchingCommits);
15614
- return analyzeChange({
15615
- repoDir: await fetchCommits({
15616
- cacheDir: deps.cacheDir,
15617
- cloneUrl: snapshot.cloneUrl,
15618
- credentials: snapshot.gitAuth,
15619
- commits: [pullRequest.mergeBaseSha, pullRequest.headSha]
15620
- }),
15621
- pullRequest,
15622
- ref
15623
- }, options, deps);
17912
+ const repoDir = await fetchCommits({
17913
+ cacheDir: deps.cacheDir,
17914
+ cloneUrl: snapshot.cloneUrl,
17915
+ credentials: snapshot.gitAuth,
17916
+ commits: [pullRequest.mergeBaseSha, pullRequest.headSha]
17917
+ });
17918
+ return {
17919
+ model: await analyzeChange({
17920
+ repoDir,
17921
+ pullRequest,
17922
+ ref,
17923
+ history
17924
+ }, options, deps),
17925
+ repoDir
17926
+ };
17927
+ }
17928
+ async function offlineHistory() {
17929
+ throw new HistoryUnavailableError("offline mode: the host was not asked");
15624
17930
  }
15625
- async function analyzeChange({ repoDir, pullRequest, ref }, options, deps) {
17931
+ async function analyzeChange({ repoDir, pullRequest, ref, history }, options, deps) {
15626
17932
  const { files, risk } = await analyzeChangedFiles(repoDir, pullRequest.mergeBaseSha, pullRequest.headSha, {
17933
+ history,
15627
17934
  network: options.network,
15628
17935
  disabledChecks: options.disabledChecks ?? [],
15629
17936
  reportStep: deps.reportStep
@@ -15711,10 +18018,11 @@ async function runApp(options, deps) {
15711
18018
  const store = new ReviewStore(join(dataDir, DATABASE_FILE), deps.now);
15712
18019
  store.markInterrupted();
15713
18020
  const hostFor = async (ref) => gitHostFor(ref, await hostTokensFor(ref, deps.env, runCommand));
15714
- const server = await startAppServer(store, new ReviewService(store, {
18021
+ const directoryFor = async (repository) => pullRequestDirectoryFor(repository, await hostTokensFor(repository, deps.env, runCommand));
18022
+ const service = new ReviewService(store, {
15715
18023
  generate: async ({ ref, ai, attachedCoverage, reportStep }) => {
15716
18024
  const settings = store.getSettings();
15717
- const model = await analyzePullRequest(ref, {
18025
+ const { model, repoDir } = await analyzePullRequest(ref, {
15718
18026
  network: options.network,
15719
18027
  coveragePath: void 0,
15720
18028
  attachedCoverage,
@@ -15731,18 +18039,30 @@ async function runApp(options, deps) {
15731
18039
  await writeReport(model, reportDir);
15732
18040
  return {
15733
18041
  model,
15734
- reportDir
18042
+ reportDir,
18043
+ repoDir
15735
18044
  };
15736
18045
  },
15737
18046
  findStack: async (ref) => (await hostFor(ref)).fetchStack(),
15738
18047
  log: deps.log
15739
- }), {
18048
+ });
18049
+ const apiKey = newApiKey();
18050
+ const server = await startAppServer(store, service, {
15740
18051
  port: options.port,
15741
18052
  log: deps.log,
15742
18053
  env: deps.env,
15743
18054
  offline: !options.network,
15744
- hostFor
18055
+ hostFor,
18056
+ directoryFor,
18057
+ apiKey
15745
18058
  });
18059
+ removeOnExit(await writeConnectionFile(dataDir, {
18060
+ url: server.url,
18061
+ apiKey,
18062
+ apiVersion: 1,
18063
+ version: walkdiffVersion(),
18064
+ pid: process.pid
18065
+ }));
15746
18066
  deps.log(`Walkdiff is running at ${server.url} (Ctrl+C to stop)`, { fields: { url: server.url } });
15747
18067
  if (options.open && canOpenBrowser(process.platform, deps.env)) openBrowser(server.url, deps.log);
15748
18068
  const scanners = await findInstalledScanners();
@@ -15925,13 +18245,6 @@ async function runComment(options, deps) {
15925
18245
  deps.log(`Could not post the summary comment (this token may be read-only): ${error.message}`, { level: LogLevel.Warn });
15926
18246
  }
15927
18247
  }
15928
- // packages/cli/src/version.ts
15929
- const MANIFEST_PATH = firstExisting([resolve(import.meta.dirname, "package.json"), resolve(import.meta.dirname, "../../../package.json")]);
15930
- const manifestSchema = z.object({ version: z.string().min(1) });
15931
- /** The running Walkdiff's version, read from its package.json. */
15932
- function walkdiffVersion(manifestPath = MANIFEST_PATH) {
15933
- return manifestSchema.parse(JSON.parse(readFileSync(manifestPath, "utf8"))).version;
15934
- }
15935
18248
  // packages/cli/src/main.ts
15936
18249
  const EXIT_FAILURE = 1;
15937
18250
  const EXIT_USAGE = 2;