@leitwerk-dev/github 0.3.1 → 0.4.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/dist/index.js CHANGED
@@ -2,10 +2,15 @@ import {
2
2
  GitHubClient,
3
3
  assertGitHubRepository,
4
4
  parseGitHubProfiles
5
- } from "./chunk-PNHJ5QZ6.js";
5
+ } from "./chunk-FDDQQGXI.js";
6
6
 
7
7
  // src/index.ts
8
- import { coreHostCapabilities } from "@leitwerk-dev/process-sdk";
8
+ import {
9
+ coreHostCapabilities,
10
+ parseTicketCreationConfig,
11
+ repositorySettingsIdentity,
12
+ scopedSettingsCapability
13
+ } from "@leitwerk-dev/process-sdk";
9
14
 
10
15
  // src/capability.ts
11
16
  import { createCapabilityToken } from "@leitwerk-dev/process-sdk";
@@ -491,14 +496,156 @@ function createGitHubProvider(deps, integration, options = {}) {
491
496
  });
492
497
  }
493
498
 
499
+ // src/ticket-creation.ts
500
+ import {
501
+ listTicketDestinations,
502
+ markdownTicketCreationDefinition,
503
+ numberArg,
504
+ objectArg,
505
+ parseTicketDestinationId,
506
+ stringArg,
507
+ ticketDestinationId,
508
+ ticketLabelNames
509
+ } from "@leitwerk-dev/process-sdk";
510
+ function destinationData(snapshot) {
511
+ const data = objectArg(snapshot.data);
512
+ return {
513
+ profile: stringArg(data, "profile"),
514
+ baseUrl: stringArg(data, "baseUrl"),
515
+ repositoryId: numberArg(data, "repositoryId"),
516
+ owner: stringArg(data, "owner"),
517
+ repo: stringArg(data, "repo"),
518
+ defaultLabels: ticketLabelNames(data.defaultLabels)
519
+ };
520
+ }
521
+ function available(repository) {
522
+ return !!repository.id && !repository.archived && repository.has_issues;
523
+ }
524
+ function registerGitHubTicketCreation(api, integration, config) {
525
+ if (!config.enabled) return;
526
+ const summary = (profile, repository) => ({
527
+ id: ticketDestinationId(profile, repository.id ?? 0),
528
+ displayName: repository.full_name,
529
+ group: `${profile} \xB7 ${new URL(integration.client(profile).profile.apiBaseUrl).hostname}`,
530
+ description: config.defaultLabels.length ? `Default labels: ${config.defaultLabels.join(", ")}` : "No default labels"
531
+ });
532
+ const validateDestination = async (snapshot, signal) => {
533
+ const data = destinationData(snapshot);
534
+ const client = integration.client(data.profile);
535
+ if (client.profile.apiBaseUrl !== data.baseUrl)
536
+ throw new Error("GitHub profile installation changed");
537
+ assertGitHubRepository(client.profile, data.owner, data.repo);
538
+ const repository = await client.getRepositoryById(data.repositoryId, signal);
539
+ if (!available(repository) || repository.owner.login !== data.owner || repository.name !== data.repo)
540
+ throw new Error("The selected GitHub repository changed; choose the destination again");
541
+ };
542
+ const destinations = {
543
+ list() {
544
+ return listTicketDestinations(
545
+ "GitHub",
546
+ integration.profiles?.() ?? [],
547
+ async (profile) => (await integration.client(profile).listRepositories()).filter(available).map((repository) => summary(profile, repository))
548
+ );
549
+ },
550
+ async resolve({ destinationId }) {
551
+ const { profile, resourceId } = parseTicketDestinationId(destinationId);
552
+ const client = integration.client(profile);
553
+ const repository = await client.getRepositoryById(Number(resourceId));
554
+ if (!available(repository))
555
+ throw new Error("The selected GitHub repository cannot accept issues");
556
+ const labels = await client.listLabels(repository.owner.login, repository.name);
557
+ return {
558
+ summary: summary(profile, repository),
559
+ data: {
560
+ profile,
561
+ baseUrl: client.profile.apiBaseUrl,
562
+ repositoryId: repository.id,
563
+ owner: repository.owner.login,
564
+ repo: repository.name,
565
+ defaultLabels: config.defaultLabels
566
+ },
567
+ agentContext: `Create an issue in ${repository.full_name}. Existing optional labels: ${labels.map((label) => label.name).join(", ") || "none"}.`
568
+ };
569
+ },
570
+ validate: validateDestination
571
+ };
572
+ api.tool({
573
+ name: "github_create_issue",
574
+ description: "Create one issue in the selected GitHub repository",
575
+ ...markdownTicketCreationDefinition("GitHub", destinations),
576
+ async execute(ctx, args) {
577
+ if (!ctx.ticketDestination) throw new Error("A GitHub ticket destination is required");
578
+ ctx.signal.throwIfAborted();
579
+ await validateDestination(ctx.ticketDestination, ctx.signal);
580
+ ctx.signal.throwIfAborted();
581
+ const target = destinationData(ctx.ticketDestination);
582
+ const client = integration.client(target.profile);
583
+ const title = stringArg(args, "title");
584
+ const body = stringArg(args, "body");
585
+ const requestedLabels = ticketLabelNames(args.labels);
586
+ const labels = await client.listLabels(target.owner, target.repo, ctx.signal);
587
+ const unknown = requestedLabels.filter(
588
+ (name) => !target.defaultLabels.includes(name) && !labels.some((label) => label.name === name)
589
+ );
590
+ if (unknown.length) throw new Error(`Unknown GitHub labels: ${unknown.join(", ")}`);
591
+ for (const name of target.defaultLabels) {
592
+ ctx.signal.throwIfAborted();
593
+ await ctx.externalWrites.ensure(
594
+ { writeType: "github.ensure_label", dedupKey: `${ctx.idempotencyKey}:label:${name}` },
595
+ {
596
+ reconcile: async () => (await client.listLabels(target.owner, target.repo, ctx.signal)).find(
597
+ (label) => label.name === name
598
+ ) ?? null,
599
+ execute: () => {
600
+ ctx.signal.throwIfAborted();
601
+ return client.createLabel(target.owner, target.repo, name, ctx.signal);
602
+ },
603
+ toMetadata: (label) => ({ id: label.id, name: label.name })
604
+ }
605
+ );
606
+ }
607
+ const marker = `<!-- leitwerk-ticket-write:${ctx.idempotencyKey} -->`;
608
+ const issue = await ctx.externalWrites.ensure(
609
+ { writeType: "github.create_issue", dedupKey: ctx.idempotencyKey },
610
+ {
611
+ reconcile: async () => (await client.listIssues(target.owner, target.repo, ctx.signal)).find(
612
+ (issue2) => issue2.body?.includes(marker)
613
+ ) ?? null,
614
+ execute: () => {
615
+ ctx.signal.throwIfAborted();
616
+ return client.createIssue(
617
+ target.owner,
618
+ target.repo,
619
+ {
620
+ title,
621
+ body: `${body}
622
+
623
+ ${marker}`,
624
+ labels: [.../* @__PURE__ */ new Set([...target.defaultLabels, ...requestedLabels])]
625
+ },
626
+ ctx.signal
627
+ );
628
+ },
629
+ toMetadata: (issue2) => ({ number: issue2.number, url: issue2.html_url })
630
+ }
631
+ );
632
+ return {
633
+ externalId: `${target.owner}/${target.repo}#${issue.number}`,
634
+ url: issue.html_url,
635
+ result: issue
636
+ };
637
+ }
638
+ });
639
+ }
640
+
494
641
  // src/tools.ts
495
642
  import {
496
643
  existingObject,
497
644
  matchesPatch,
498
- numberArg,
499
- objectArg,
645
+ numberArg as numberArg2,
646
+ objectArg as objectArg2,
500
647
  projectParameters,
501
- stringArg
648
+ stringArg as stringArg2
502
649
  } from "@leitwerk-dev/process-sdk";
503
650
 
504
651
  // src/binding.ts
@@ -506,7 +653,7 @@ import { resolveRepositoryProjectBinding } from "@leitwerk-dev/process-sdk";
506
653
  var resolveGitHubProjectBinding = (ctx) => resolveRepositoryProjectBinding(ctx, "github");
507
654
 
508
655
  // src/tools.ts
509
- var object = (value) => objectArg(value, "Expected an object");
656
+ var object = (value) => objectArg2(value, "Expected an object");
510
657
  function registerGitHubTools(api, integration) {
511
658
  const target = (ctx) => {
512
659
  const binding = resolveGitHubProjectBinding(ctx);
@@ -565,10 +712,10 @@ function registerGitHubTools(api, integration) {
565
712
  const input = object(args);
566
713
  const t = target(ctx);
567
714
  const client = integration.client(t.profile);
568
- const key = !(pullRequest && update) && typeof input.writeKey === "string" ? stringArg(input, "writeKey") : ctx.idempotencyKey;
715
+ const key = !(pullRequest && update) && typeof input.writeKey === "string" ? stringArg2(input, "writeKey") : ctx.idempotencyKey;
569
716
  const signal = pullRequest ? ctx.signal : void 0;
570
717
  const marker = `<!-- leitwerk-write:${ctx.process.id}:${key} -->`;
571
- const issueNumber = () => numberArg(
718
+ const issueNumber = () => numberArg2(
572
719
  input,
573
720
  pullRequest || input.issueNumber == null ? "pullRequestNumber" : "issueNumber"
574
721
  );
@@ -577,10 +724,10 @@ function registerGitHubTools(api, integration) {
577
724
  t.owner,
578
725
  t.repo,
579
726
  issueNumber(),
580
- stringArg(input, "feedbackKind")
727
+ stringArg2(input, "feedbackKind")
581
728
  ) : await client.listIssueComments(t.owner, t.repo, issueNumber(), signal);
582
729
  return replies.find(
583
- (comment) => String(comment.body).includes(marker) && (name !== "github_reply_to_pull_request_feedback" || input.feedbackKind !== "inline" || object(comment).in_reply_to_id === numberArg(input, "feedbackId"))
730
+ (comment) => String(comment.body).includes(marker) && (name !== "github_reply_to_pull_request_feedback" || input.feedbackKind !== "inline" || object(comment).in_reply_to_id === numberArg2(input, "feedbackId"))
584
731
  ) ?? null;
585
732
  };
586
733
  const result = await ctx.externalWrites.ensure(
@@ -592,7 +739,7 @@ function registerGitHubTools(api, integration) {
592
739
  reconcile: async (phase) => existingObject(async () => {
593
740
  if (name === "github_ensure_label")
594
741
  return (await client.listLabels(t.owner, t.repo)).find(
595
- (label) => label.name === stringArg(input, "name")
742
+ (label) => label.name === stringArg2(input, "name")
596
743
  ) ?? null;
597
744
  if (update) {
598
745
  const current = await client[pullRequest ? "getPullRequest" : "getIssue"](
@@ -607,8 +754,8 @@ function registerGitHubTools(api, integration) {
607
754
  return (await client.listFeedbackReactions(
608
755
  t.owner,
609
756
  t.repo,
610
- stringArg(input, "feedbackKind"),
611
- numberArg(input, "feedbackId")
757
+ stringArg2(input, "feedbackKind"),
758
+ numberArg2(input, "feedbackId")
612
759
  )).find(
613
760
  (reaction) => reaction.content === "eyes" && reaction.user.login.toLowerCase() === client.profile.botLogin.toLowerCase()
614
761
  ) ?? null;
@@ -616,7 +763,7 @@ function registerGitHubTools(api, integration) {
616
763
  }),
617
764
  execute: async () => {
618
765
  if (name === "github_ensure_label")
619
- return client.createLabel(t.owner, t.repo, stringArg(input, "name"));
766
+ return client.createLabel(t.owner, t.repo, stringArg2(input, "name"));
620
767
  if (update)
621
768
  return pullRequest ? object(
622
769
  await client.updatePullRequest(
@@ -632,11 +779,11 @@ function registerGitHubTools(api, integration) {
632
779
  await client.addFeedbackReaction(
633
780
  t.owner,
634
781
  t.repo,
635
- stringArg(input, "feedbackKind"),
636
- numberArg(input, "feedbackId")
782
+ stringArg2(input, "feedbackKind"),
783
+ numberArg2(input, "feedbackId")
637
784
  )
638
785
  );
639
- const body = `${stringArg(input, "body")}
786
+ const body = `${stringArg2(input, "body")}
640
787
 
641
788
  ${marker}`;
642
789
  return object(
@@ -644,8 +791,8 @@ ${marker}`;
644
791
  t.owner,
645
792
  t.repo,
646
793
  issueNumber(),
647
- stringArg(input, "feedbackKind"),
648
- numberArg(input, "feedbackId"),
794
+ stringArg2(input, "feedbackKind"),
795
+ numberArg2(input, "feedbackId"),
649
796
  body
650
797
  ))
651
798
  );
@@ -653,7 +800,7 @@ ${marker}`;
653
800
  toMetadata: (value) => pullRequest ? { owner: t.owner, repo: t.repo, pullRequestNumber: issueNumber() } : { value }
654
801
  }
655
802
  );
656
- if (name === "github_ensure_label") return { name: stringArg(input, "name") };
803
+ if (name === "github_ensure_label") return { name: stringArg2(input, "name") };
657
804
  return result;
658
805
  }
659
806
  });
@@ -670,8 +817,8 @@ ${marker}`;
670
817
  async execute(ctx, input) {
671
818
  const t = target(ctx);
672
819
  const client = integration.client(t.profile);
673
- const head = stringArg(input, "head");
674
- const base = stringArg(input, "base");
820
+ const head = stringArg2(input, "head");
821
+ const base = stringArg2(input, "base");
675
822
  if (head !== ctx.project?.workBranch || base !== ctx.project?.baseBranch)
676
823
  throw new Error("Pull request branches must match the process project");
677
824
  const find = async () => (await client.listPullRequests(t.owner, t.repo, "all")).find(
@@ -682,8 +829,8 @@ ${marker}`;
682
829
  {
683
830
  reconcile: () => existingObject(find),
684
831
  execute: () => client.createPullRequest(t.owner, t.repo, {
685
- title: stringArg(input, "title"),
686
- body: stringArg(input, "body"),
832
+ title: stringArg2(input, "title"),
833
+ body: stringArg2(input, "body"),
687
834
  head,
688
835
  base
689
836
  }),
@@ -718,7 +865,7 @@ ${marker}`;
718
865
  parameters: projectParameters({ [numberName]: { type: "integer" } }),
719
866
  async execute(ctx, input) {
720
867
  const t = target(ctx);
721
- return integration.client(t.profile)[method](t.owner, t.repo, numberArg(input, numberName), ctx.signal);
868
+ return integration.client(t.profile)[method](t.owner, t.repo, numberArg2(input, numberName), ctx.signal);
722
869
  }
723
870
  });
724
871
  }
@@ -732,7 +879,7 @@ ${marker}`;
732
879
  async execute(ctx, input) {
733
880
  const t = target(ctx);
734
881
  const client = integration.client(t.profile);
735
- const number = numberArg(input, "pullRequestNumber");
882
+ const number = numberArg2(input, "pullRequestNumber");
736
883
  const pr = await client.getPullRequest(t.owner, t.repo, number, ctx.signal);
737
884
  if (pr.head.ref !== ctx.project?.workBranch || pr.base.ref !== ctx.project.baseBranch)
738
885
  throw new Error("Pull request does not belong to the process branches");
@@ -740,7 +887,7 @@ ${marker}`;
740
887
  t.owner,
741
888
  t.repo,
742
889
  number,
743
- stringArg(input, "headSha"),
890
+ stringArg2(input, "headSha"),
744
891
  ctx.signal
745
892
  );
746
893
  }
@@ -751,7 +898,7 @@ ${marker}`;
751
898
  parameters: projectParameters({ headSha: { type: "string" } }),
752
899
  async execute(ctx, input) {
753
900
  const t = target(ctx);
754
- return integration.client(t.profile).getCheckSummary(t.owner, t.repo, stringArg(input, "headSha"));
901
+ return integration.client(t.profile).getCheckSummary(t.owner, t.repo, stringArg2(input, "headSha"));
755
902
  }
756
903
  });
757
904
  }
@@ -766,6 +913,23 @@ var extension = {
766
913
  manifest,
767
914
  setupServer(api, config) {
768
915
  const profiles = parseGitHubProfiles(config);
916
+ const settings = api.get(scopedSettingsCapability);
917
+ if (settings && !Array.isArray(settings))
918
+ settings.registerDiscovery("repository", async () => {
919
+ const subjects = [];
920
+ for (const profile of profiles.values()) {
921
+ for (const repo of await new GitHubClient(profile).listRepositories()) {
922
+ if (repo.id === void 0) continue;
923
+ subjects.push({
924
+ scopeType: "repository",
925
+ identity: repositorySettingsIdentity(repo.html_url, repo.id),
926
+ label: repo.full_name,
927
+ aliases: [repo.ssh_url, ...repo.clone_url ? [repo.clone_url] : []]
928
+ });
929
+ }
930
+ }
931
+ return subjects;
932
+ });
769
933
  const integration = {
770
934
  profiles: () => [...profiles.keys()],
771
935
  client(profile) {
@@ -774,7 +938,9 @@ var extension = {
774
938
  return new GitHubClient(value);
775
939
  }
776
940
  };
777
- setupGitHubIntegration(api, integration);
941
+ setupGitHubIntegration(api, integration, {
942
+ ticketCreation: parseTicketCreationConfig(config, "GitHub")
943
+ });
778
944
  }
779
945
  };
780
946
  var index_default = extension;
@@ -783,6 +949,11 @@ function setupGitHubIntegration(api, integration, options = {}) {
783
949
  const deps = api.get(coreHostCapabilities.serverSetup);
784
950
  if (!deps || Array.isArray(deps)) return;
785
951
  registerGitHubTools(api, integration);
952
+ registerGitHubTicketCreation(
953
+ api,
954
+ integration,
955
+ options.ticketCreation ?? { enabled: false, defaultLabels: [] }
956
+ );
786
957
  return createGitHubProvider(deps, integration, options);
787
958
  }
788
959
  export {