spur-board 0.9.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/daemon.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { A as parseActorId, B as RESERVED_PROJECT, C as prFactsSchema, D as actorIdSchema, E as ticketFactsSchema, H as requiredSecretKeys, I as successEnvelopeSchema, M as taskKeySchema, N as ERRORS, O as encodeActorId, S as SESSION_STATUSES, T as sessionFactsSchema, U as SLACK_BOT_SCOPES, V as configSchema, _ as messageRefSchema, a as entityRefSchema, b as eventPayloadSchemas, c as roleCanUseOperation, g as interactionRefSchema, h as inboundEventSchema, i as batchSchema, j as parseRef$1, k as errorCodeOf, l as OPERATIONS, m as conversationRefSchema, o as sourceCursorSchema, p as SPACE_IDS, r as AdapterError, s as buildCatalogSnapshot, t as BOARD_TICK_MS, u as renderHttpProblem, v as userIdSchema, w as prRefSchema, x as SESSION_HEALTH_STATES, y as EVENT_KINDS, z as DEFAULT_SLACK_COMMAND } from "./src-DyDmiehC.mjs";
1
+ import { A as parseActorId, B as RESERVED_PROJECT, C as prFactsSchema, D as actorIdSchema, E as ticketFactsSchema, H as requiredSecretKeys, I as successEnvelopeSchema, M as taskKeySchema, N as ERRORS, O as encodeActorId, S as SESSION_STATUSES, T as sessionFactsSchema, U as SLACK_BOT_SCOPES, V as configSchema, _ as messageRefSchema, a as entityRefSchema, b as eventPayloadSchemas, c as roleCanUseOperation, g as interactionRefSchema, h as inboundEventSchema, i as batchSchema, j as parseRef$1, k as errorCodeOf, l as OPERATIONS, m as conversationRefSchema, o as sourceCursorSchema, p as SPACE_IDS, r as AdapterError, s as buildCatalogSnapshot, t as BOARD_TICK_MS, u as renderHttpProblem, v as userIdSchema, w as prRefSchema, x as SESSION_HEALTH_STATES, y as EVENT_KINDS, z as DEFAULT_SLACK_COMMAND } from "./src-Dl5c0sRb.mjs";
2
2
  import { createRequire } from "node:module";
3
3
  import { createHash, randomUUID } from "node:crypto";
4
4
  import { closeSync, existsSync, fstatSync, ftruncateSync, mkdirSync, openSync, readFileSync, readdirSync, writeSync } from "node:fs";
@@ -8075,7 +8075,7 @@ async function restartNotification(trx, sourceKey, at) {
8075
8075
  }
8076
8076
  /** Reconcile due semantic notifications in the sender's claim transaction. */
8077
8077
  async function reconcileDoorbells(trx, at, config) {
8078
- const due = await trx.selectFrom("notification").selectAll().where("acked_at", "is", null).where("exhausted_at", "is", null).where("next_at", "<=", at.toISOString()).orderBy("id").execute();
8078
+ const due = await trx.selectFrom("notification").innerJoin("task", "task.id", "notification.task_id").selectAll("notification").where("task.membership", "!=", "archived").where("notification.acked_at", "is", null).where("notification.exhausted_at", "is", null).where("notification.next_at", "<=", at.toISOString()).orderBy("notification.id").execute();
8079
8079
  for (const n of due) {
8080
8080
  const session = await selectNotificationRecipient(trx, n);
8081
8081
  if (session === void 0) {
@@ -8126,6 +8126,7 @@ async function reconcileDoorbells(trx, at, config) {
8126
8126
  continue;
8127
8127
  }
8128
8128
  const raised = await trx.selectFrom("operator_item").select((eb) => eb.fn.max("raise_no").as("series")).where("item_key", "=", itemKey).executeTakeFirst();
8129
+ const archived = await trx.selectFrom("event").select((eb) => eb.fn.countAll().as("count")).where("task_id", "=", n.task_id).where("kind", "=", "task_archived").executeTakeFirst();
8129
8130
  const ring = rings + 1;
8130
8131
  const text = `${task.key} block B${String(n.block_id)}: check board inbox (N${String(n.id)}-${String(ring)})`;
8131
8132
  const outboxId = await enqueueDoorbell(trx, {
@@ -8134,7 +8135,8 @@ async function reconcileDoorbells(trx, at, config) {
8134
8135
  session: session.id,
8135
8136
  text,
8136
8137
  at,
8137
- series: raised?.series ?? 0
8138
+ series: raised?.series ?? 0,
8139
+ archives: archived?.count ?? 0
8138
8140
  });
8139
8141
  await trx.updateTable("notification").set({ last_outbox_id: outboxId }).where("id", "=", n.id).execute();
8140
8142
  }
@@ -8166,6 +8168,17 @@ async function ringStillCurrent(trx, notificationId, sessionId) {
8166
8168
  if (session?.id !== sessionId) return "dead";
8167
8169
  return session.state === "working" ? "defer" : "send";
8168
8170
  }
8171
+ /**
8172
+ * The task of a ring: through its notification, or for an inbound author ring (no notification)
8173
+ * through the comment in its `doorbell:comment:<id>:` key. Archive kills only unclaimed rings;
8174
+ * the sender drops a claimed one of an archived task before its send starts.
8175
+ */
8176
+ async function ringTask(trx, notificationId, dedupeKey) {
8177
+ const commentId = /^doorbell:comment:(\d+):/.exec(dedupeKey)?.[1];
8178
+ if (notificationId === void 0 && commentId === void 0) return void 0;
8179
+ const owner = notificationId !== void 0 ? trx.selectFrom("notification").select("task_id").where("id", "=", notificationId) : trx.selectFrom("comment").select("task_id").where("id", "=", Number(commentId));
8180
+ return trx.selectFrom("task").selectAll().where("id", "in", owner).executeTakeFirst();
8181
+ }
8169
8182
  /** Stop notifications acknowledged by the addressed session. */
8170
8183
  async function acknowledgeNotification(trx, input) {
8171
8184
  let query = trx.selectFrom("notification").selectAll().where("acked_at", "is", null);
@@ -8315,13 +8328,15 @@ function renderBody(key, text) {
8315
8328
  }
8316
8329
  /**
8317
8330
  * A distinct semantic ring. Transport retries reuse this row and its text. A restarted series
8318
- * (`series` > 0) gets its own keys; the first series keeps the unsuffixed key.
8331
+ * (`series` > 0) and a ring after the task was archived (`archives` > 0) get their own keys, so a
8332
+ * ring cancelled by an archive does not block its replacement; unsuffixed keys stay as before.
8319
8333
  */
8320
8334
  async function enqueueDoorbell(trx, input) {
8321
8335
  const series = input.series ?? 0;
8336
+ const archives = input.archives ?? 0;
8322
8337
  const row = await insertOutbox(trx, {
8323
8338
  kind: "doorbell",
8324
- dedupeKey: `doorbell:${String(input.notificationId)}:${input.session}:${String(input.ring)}${series > 0 ? `:s${String(series)}` : ""}`,
8339
+ dedupeKey: `doorbell:${String(input.notificationId)}:${input.session}:${String(input.ring)}${series > 0 ? `:s${String(series)}` : ""}${archives > 0 ? `:a${String(archives)}` : ""}`,
8325
8340
  payload: {
8326
8341
  notificationId: input.notificationId,
8327
8342
  ring: input.ring,
@@ -8575,7 +8590,7 @@ async function enqueueConversationClose(trx, input) {
8575
8590
  const conversations = await trx.selectFrom("conversation").select("ref").where("block_id", "=", input.blockId).execute();
8576
8591
  const payload = {
8577
8592
  key: block.key,
8578
- text: `resolved: ${input.outcome} (${input.actor})`,
8593
+ text: `resolved: ${input.outcome === "archived" ? "task archived" : input.outcome} (${input.actor})`,
8579
8594
  persona: {
8580
8595
  name: "board",
8581
8596
  role: "board"
@@ -9394,7 +9409,8 @@ async function openBlock(trx, task, type, reason, ctx, config) {
9394
9409
  await registerBlockNotification(trx, row, new Date(ctx.at));
9395
9410
  return row;
9396
9411
  }
9397
- async function close(trx, task, block, ctx, outcome, outcomeReason) {
9412
+ /** Unblocks one block with its journal entry, thread close, doorbell close and item clears. */
9413
+ async function closeOpenBlock(trx, task, block, ctx, outcome, outcomeReason) {
9398
9414
  const updated = await trx.updateTable("block").set({
9399
9415
  state: "unblocked",
9400
9416
  outcome,
@@ -9438,7 +9454,7 @@ async function recordInboundBlockMessage(trx, input) {
9438
9454
  conversationRef: input.conversationRef,
9439
9455
  messageRef: input.messageRef
9440
9456
  }),
9441
- block: answered ? await close(trx, task, block, ctx, "done", null) : block,
9457
+ block: answered ? await closeOpenBlock(trx, task, block, ctx, "done", null) : block,
9442
9458
  task,
9443
9459
  answered,
9444
9460
  workerAuthor: authorRole(input.config, task, block.author) === "worker"
@@ -9562,7 +9578,7 @@ function createBlockMutations(config) {
9562
9578
  });
9563
9579
  const comment = await addComment(trx, task, block, input.text, ctx, authorRole(config, task, block.author), config);
9564
9580
  return {
9565
- block: blockView(await close(trx, task, block, ctx, "done", null), task),
9581
+ block: blockView(await closeOpenBlock(trx, task, block, ctx, "done", null), task),
9566
9582
  comment: commentView(comment, task)
9567
9583
  };
9568
9584
  }
@@ -9585,7 +9601,7 @@ function createBlockMutations(config) {
9585
9601
  actor: ctx.actor
9586
9602
  }));
9587
9603
  if (input.mode === "withdraw") await addComment(trx, task, block, input.answer, ctx, block.addressee_role, config);
9588
- return { block: blockView(await close(trx, task, block, ctx, decision.outcome, decision.outcomeReason), task) };
9604
+ return { block: blockView(await closeOpenBlock(trx, task, block, ctx, decision.outcome, decision.outcomeReason), task) };
9589
9605
  }
9590
9606
  },
9591
9607
  add: {
@@ -9662,31 +9678,39 @@ function createBlockMutations(config) {
9662
9678
  }
9663
9679
  return { acked: input.entries.map(({ id }) => id) };
9664
9680
  }
9665
- },
9666
- archive: {
9667
- id: "task.archive",
9668
- resolveTargets: (trx, input) => taskTarget(trx, input.task),
9669
- async run(trx, input, ctx) {
9670
- const task = found(await taskByKey$1(trx, input.task));
9671
- active(task);
9672
- const blocks = await trx.selectFrom("block").selectAll().where("task_id", "=", task.id).where("state", "=", "open").execute();
9673
- for (const block of blocks) await close(trx, task, block, ctx, "archived", null);
9674
- const updated = await trx.updateTable("task").set({
9675
- membership: "archived",
9676
- archive_reason: "manual"
9677
- }).where("id", "=", task.id).returningAll().executeTakeFirstOrThrow();
9678
- await journal$1(trx, task, ctx, "task_archived", { reason: "manual" });
9679
- return { task: {
9680
- key: updated.key,
9681
- project: updated.project,
9682
- column: updated.column,
9683
- membership: updated.membership
9684
- } };
9685
- }
9686
9681
  }
9687
9682
  };
9688
9683
  }
9689
9684
  //#endregion
9685
+ //#region ../core/src/app/archive.ts
9686
+ /**
9687
+ * Takes a task off the board in the caller's transaction: closes its open blocks with outcome
9688
+ * `archived`, clears its board-derived items, cancels its unsent doorbells and journals
9689
+ * `task_archived`. Callers set their own extra columns (manual flags, the Done slot).
9690
+ */
9691
+ async function archiveTask(trx, input) {
9692
+ const { task, reason, actor, at } = input;
9693
+ const ctx = {
9694
+ actor,
9695
+ at
9696
+ };
9697
+ const blocks = await trx.selectFrom("block").selectAll().where("task_id", "=", task.id).where("state", "=", "open").orderBy("id").execute();
9698
+ for (const block of blocks) await closeOpenBlock(trx, task, block, ctx, "archived", null);
9699
+ const items = await trx.selectFrom("operator_item").select("id").where("kind", "=", "board_observation").where("task_id", "=", task.id).where("cleared_at", "is", null).orderBy("id").execute();
9700
+ for (const item of items) await clearItem(trx, item.id, new Date(at), actor);
9701
+ const comments = await trx.selectFrom("comment").select("id").where("task_id", "=", task.id).execute();
9702
+ await trx.updateTable("outbox").set({
9703
+ state: "dead",
9704
+ last_error: "superseded"
9705
+ }).where("kind", "=", "doorbell").where("state", "in", ["pending", "post_failed"]).where("uncertain", "=", 0).where((eb) => eb.or([eb("id", "in", eb.selectFrom("notification").select("last_outbox_id").where("task_id", "=", task.id).where("last_outbox_id", "is not", null)), ...comments.map((comment) => eb("dedupe_key", "like", `doorbell:comment:${String(comment.id)}:%`))])).execute();
9706
+ await trx.updateTable("task").set({
9707
+ membership: "archived",
9708
+ archive_reason: reason,
9709
+ last_change_at: at
9710
+ }).where("id", "=", task.id).execute();
9711
+ await emit(trx, "task_archived", task.project, task.id, at, { reason }, actor);
9712
+ }
9713
+ //#endregion
9690
9714
  //#region ../core/src/app/membership.ts
9691
9715
  function canonicalKey(config, key) {
9692
9716
  const parsed = parseRef$1(key, "task");
@@ -9770,13 +9794,15 @@ function createMembershipMutations(config) {
9770
9794
  if (task === void 0) throw new CommandError("not_found", "Check the task key.");
9771
9795
  if (task.membership === "archived") throw new CommandError("task_archived", "Task is archived.");
9772
9796
  await trx.updateTable("task").set({
9773
- membership: "archived",
9774
- archive_reason: "manual",
9775
9797
  manual_include: 0,
9776
- manual_exclude: 1,
9777
- last_change_at: ctx.at
9798
+ manual_exclude: 1
9778
9799
  }).where("id", "=", task.id).execute();
9779
- await emit(trx, "task_archived", task.project, task.id, ctx.at, { reason: "manual" }, "operator");
9800
+ await archiveTask(trx, {
9801
+ task,
9802
+ reason: "manual",
9803
+ actor: ctx.actor,
9804
+ at: ctx.at
9805
+ });
9780
9806
  return { task: {
9781
9807
  ...taskView(task),
9782
9808
  membership: "archived"
@@ -10117,6 +10143,14 @@ function createSender(options) {
10117
10143
  };
10118
10144
  }
10119
10145
  }
10146
+ if (c.body.kind === "doorbell" && !c.maybeSent && (await ringTask(trx, c.body.payload.notificationId, c.key))?.membership === "archived") {
10147
+ await kill(trx, [c.id], "superseded");
10148
+ return {
10149
+ at,
10150
+ firstDeliveryAt: null,
10151
+ skip: true
10152
+ };
10153
+ }
10120
10154
  if (c.body.kind === "doorbell" && c.body.payload.notificationId !== void 0) {
10121
10155
  const status = await ringStillCurrent(trx, c.body.payload.notificationId, c.body.payload.session);
10122
10156
  if (status === "dead") {
@@ -10247,12 +10281,13 @@ function createSender(options) {
10247
10281
  }).execute();
10248
10282
  if (body.kind === "conversation.open" || body.kind === "feed.line") {
10249
10283
  const isBlock = body.kind === "conversation.open";
10250
- const taskId = isBlock ? body.payload.taskId : body.payload.taskId ?? null;
10251
10284
  const closedBlock = isBlock ? await trx.selectFrom("block").select([
10285
+ "task_id",
10252
10286
  "state",
10253
10287
  "unblocked_at",
10254
10288
  "created_at"
10255
10289
  ]).where("id", "=", body.payload.blockId).executeTakeFirstOrThrow() : void 0;
10290
+ const taskId = closedBlock?.task_id ?? body.payload.taskId ?? null;
10256
10291
  await trx.insertInto("conversation").values({
10257
10292
  ref: conversation,
10258
10293
  gateway: gatewayKind,
@@ -10411,6 +10446,20 @@ async function loadItem(trx, id) {
10411
10446
  task: item.task_id === null ? void 0 : await trx.selectFrom("task").selectAll().where("id", "=", item.task_id).executeTakeFirstOrThrow()
10412
10447
  };
10413
10448
  }
10449
+ /** The task a `delivery:<outbox id>` item's row belongs to; the item itself has no task. */
10450
+ async function deliveryTask(trx, item) {
10451
+ if (!item.item_key.startsWith("delivery:")) return void 0;
10452
+ const row = await trx.selectFrom("outbox").select([
10453
+ "kind",
10454
+ "dedupe_key",
10455
+ "payload"
10456
+ ]).where("id", "=", Number(item.item_key.slice(9))).executeTakeFirst();
10457
+ if (row === void 0) return void 0;
10458
+ const payload = JSON.parse(row.payload);
10459
+ if (typeof payload.taskId === "number") return trx.selectFrom("task").selectAll().where("id", "=", payload.taskId).executeTakeFirst();
10460
+ if (row.kind !== "doorbell") return void 0;
10461
+ return ringTask(trx, typeof payload.notificationId === "number" ? payload.notificationId : void 0, row.dedupe_key);
10462
+ }
10414
10463
  function view(item, task) {
10415
10464
  return { item: {
10416
10465
  id: `I${String(item.id)}`,
@@ -10453,7 +10502,7 @@ function createItemMutations(deps) {
10453
10502
  resolveTargets: () => Promise.resolve([]),
10454
10503
  async run(trx, input, ctx) {
10455
10504
  const { item, task } = await loadItem(trx, input.item);
10456
- if (task?.membership === "archived") throw new CommandError("task_archived", "Add the task again before retrying its item.");
10505
+ if ((task ?? await deliveryTask(trx, item))?.membership === "archived") throw new CommandError("task_archived", "Add the task again before retrying its item.");
10457
10506
  if (item.cleared_at !== null) throw notApplicable("The item is already cleared.");
10458
10507
  if (item.kind === "transport_health") {
10459
10508
  if (await retryTransport(trx, item.item_key.slice(10), ctx.at) === 0) throw notApplicable("No transport outage is recorded; the item clears on its own.");
@@ -11127,13 +11176,13 @@ async function reconcileMembership(trx, config, completeSince, at) {
11127
11176
  const complete = completeSince.get(source);
11128
11177
  return blind.has(source) || complete === void 0 || complete <= (task.last_change_at ?? task.created_at);
11129
11178
  })) continue;
11130
- await trx.updateTable("task").set({
11131
- membership: "archived",
11132
- archive_reason: "out_of_filter",
11133
- last_change_at: at
11134
- }).where("id", "=", task.id).execute();
11135
11179
  if (task.membership === "out_of_filter") await emit(trx, "flag_cleared", task.project, task.id, at, { flag: "out_of_filter" });
11136
- await emit(trx, "task_archived", task.project, task.id, at, { reason: "out_of_filter" });
11180
+ await archiveTask(trx, {
11181
+ task,
11182
+ reason: "out_of_filter",
11183
+ actor: "system",
11184
+ at
11185
+ });
11137
11186
  }
11138
11187
  }
11139
11188
  }
@@ -11454,6 +11503,27 @@ async function sourceState(trx, source, state, observedAt, cursor) {
11454
11503
  gone: toJson(z.array(entityRefSchema), [...state.gone])
11455
11504
  }))).execute();
11456
11505
  }
11506
+ /**
11507
+ * A merged pending key's open blocks were raised for the same ticket: they move to the surviving
11508
+ * task with what keeps them going (comments, threads, doorbells, items and undelivered rows).
11509
+ * Closed blocks and the journal stay with the archived row as its history.
11510
+ */
11511
+ async function moveOpenWork(trx, from, to) {
11512
+ const blocks = await trx.selectFrom("block").select("id").where("task_id", "=", from).where("state", "=", "open").execute();
11513
+ if (blocks.length === 0) return;
11514
+ const ids = blocks.map((block) => block.id);
11515
+ await trx.updateTable("block").set({ task_id: to }).where("id", "in", ids).execute();
11516
+ for (const table of [
11517
+ "comment",
11518
+ "conversation",
11519
+ "notification",
11520
+ "operator_item"
11521
+ ]) await trx.updateTable(table).set({ task_id: to }).where("block_id", "in", ids).execute();
11522
+ const keys = ids.flatMap((id) => [`operator-block:${String(id)}`, `block:${String(id)}`]);
11523
+ await trx.updateTable("operator_item").set({ task_id: to }).where("task_id", "=", from).where("item_key", "in", keys).execute();
11524
+ const itemKeys = (await trx.selectFrom("operator_item").select("item_key").where("task_id", "=", to).where((eb) => eb.or([eb("block_id", "in", ids), eb("item_key", "in", keys)])).execute()).map((item) => item.item_key);
11525
+ await trx.updateTable("outbox").set({ payload: sql`json_set(payload, '$.taskId', ${to})` }).where("state", "not in", ["done", "dead"]).where(sql`json_extract(payload, '$.taskId')`, "=", from).where((eb) => eb.or([eb(sql`json_extract(payload, '$.blockId')`, "in", ids), ...itemKeys.length === 0 ? [] : [eb(sql`json_extract(payload, '$.itemKey')`, "in", itemKeys)]])).execute();
11526
+ }
11457
11527
  async function ticket(trx, config, fact, at, source) {
11458
11528
  if (fact.trackerId !== source) throw new Error("Ticket from an unconfigured tracker");
11459
11529
  await trx.deleteFrom("source_miss").where("source", "=", source).where("ref_key", "=", `ticket:${source}:${fact.key}`).execute();
@@ -11472,6 +11542,7 @@ async function ticket(trx, config, fact, at, source) {
11472
11542
  archive_reason: "manual"
11473
11543
  }).where("id", "=", pending.id).execute();
11474
11544
  await emit(trx, "task_archived", pending.project, pending.id, at, { reason: "manual" });
11545
+ await moveOpenWork(trx, pending.id, task.id);
11475
11546
  await trx.updateTable("task").set({
11476
11547
  key: fact.key,
11477
11548
  manual_include: pending.manual_include,
@@ -11996,13 +12067,13 @@ async function tickBoard(deps) {
11996
12067
  const complete = completeSince.get(source);
11997
12068
  return blind.has(source) || complete === void 0 || complete <= (task.last_change_at ?? task.created_at);
11998
12069
  })) continue;
11999
- await trx.updateTable("task").set({
12000
- membership: "archived",
12001
- archive_reason: "done",
12002
- archive_slot_at: slot,
12003
- last_change_at: at
12004
- }).where("id", "=", task.id).execute();
12005
- await emit(trx, "task_archived", task.project, task.id, at, { reason: "done" });
12070
+ await trx.updateTable("task").set({ archive_slot_at: slot }).where("id", "=", task.id).execute();
12071
+ await archiveTask(trx, {
12072
+ task,
12073
+ reason: "done",
12074
+ actor: "system",
12075
+ at
12076
+ });
12006
12077
  }
12007
12078
  await reconcileItems(trx, config, now, completeSince.has("spur"));
12008
12079
  });
@@ -13119,6 +13190,18 @@ function acquireLock(file) {
13119
13190
  throw new Error(`flock failed to lock ${file} (status ${String(result.status)}): ${stderr || "no output"}`);
13120
13191
  }
13121
13192
  //#endregion
13193
+ //#region ../adapters/src/runner/wire.ts
13194
+ /**
13195
+ * Returns the parsed value or throws a transient `AdapterError` naming the first failing path
13196
+ * (`<label> at <dot.path>`). `at` prefixes the path when the value sits inside a larger
13197
+ * response. The error carries no cause, so no raw wire value reaches logs or smoke output.
13198
+ */
13199
+ function parseWire(schema, value, label, at = []) {
13200
+ const parsed = schema.safeParse(value);
13201
+ if (parsed.success) return parsed.data;
13202
+ throw new AdapterError("transient", `${label} at ${[...at, ...parsed.error.issues[0]?.path ?? []].map(String).join(".") || "(root)"}`);
13203
+ }
13204
+ //#endregion
13122
13205
  //#region ../adapters/src/runner/http.ts
13123
13206
  /** Classifies a failed response; `now` is the current time in epoch milliseconds. */
13124
13207
  function classifyHttpFailure(failure, now) {
@@ -13142,26 +13225,35 @@ function retryAt(headers, now) {
13142
13225
  }
13143
13226
  //#endregion
13144
13227
  //#region ../adapters/src/github/client.ts
13228
+ const MALFORMED$2 = "Malformed GitHub response";
13229
+ const graphErrorWire = z.object({
13230
+ message: z.string(),
13231
+ path: z.array(z.union([z.string(), z.number()])).optional(),
13232
+ type: z.string().optional()
13233
+ });
13234
+ const envelopeWire = z.object({
13235
+ errors: z.array(graphErrorWire).optional(),
13236
+ data: z.unknown()
13237
+ });
13238
+ const dataWire = z.looseObject({ rateLimit: z.object({
13239
+ remaining: z.int().nonnegative(),
13240
+ resetAt: z.string()
13241
+ }) });
13242
+ const pageInfoWire = z.object({
13243
+ hasNextPage: z.boolean(),
13244
+ endCursor: z.string().nullable()
13245
+ });
13246
+ function connectionWire(node) {
13247
+ return z.object({
13248
+ nodes: z.array(node),
13249
+ pageInfo: pageInfoWire
13250
+ });
13251
+ }
13145
13252
  function teamNameScopeDenied(error, query) {
13146
13253
  if (error.type !== "INSUFFICIENT_SCOPES" || !query.includes("... on Team { name }")) return false;
13147
13254
  if (error.path !== void 0) return error.path.includes("reviewRequests") && error.path.includes("requestedReviewer") && error.path.at(-1) === "name";
13148
13255
  return /\bname\b/i.test(error.message) && /\bread:(?:org|discussion)\b/i.test(error.message);
13149
13256
  }
13150
- function record$2(value) {
13151
- if (value === null || typeof value !== "object" || Array.isArray(value)) throw new AdapterError("transient", "Malformed GitHub response");
13152
- return value;
13153
- }
13154
- function list(value) {
13155
- if (!Array.isArray(value)) throw new AdapterError("transient", "Malformed GitHub connection");
13156
- return value;
13157
- }
13158
- function connectionNodes(value) {
13159
- return list(record$2(value).nodes).map(record$2);
13160
- }
13161
- function string$4(value) {
13162
- if (typeof value !== "string") throw new AdapterError("transient", "Malformed GitHub field");
13163
- return value;
13164
- }
13165
13257
  const prFields = (number) => `id number url title updatedAt state isDraft mergeable mergeStateStatus
13166
13258
  author { login } headRefName headRefOid
13167
13259
  statusCheckRollup { contexts(first: 100) { nodes {
@@ -13217,49 +13309,42 @@ var GithubClient = class {
13217
13309
  headers: response.headers,
13218
13310
  body: await response.text()
13219
13311
  }, Date.now());
13220
- let wire;
13312
+ let body;
13221
13313
  try {
13222
- wire = record$2(await response.json());
13314
+ body = await response.json();
13223
13315
  } catch (cause) {
13224
- throw new AdapterError("transient", "Malformed GitHub response", { cause });
13316
+ throw new AdapterError("transient", MALFORMED$2, { cause });
13225
13317
  }
13226
- const errors = wire.errors === void 0 ? [] : list(wire.errors).map((e) => {
13227
- const item = record$2(e);
13228
- return {
13229
- message: string$4(item.message),
13230
- ...typeof item.type === "string" ? { type: item.type } : {},
13231
- ...Array.isArray(item.path) ? { path: item.path.filter((p) => typeof p === "string" || typeof p === "number") } : {}
13232
- };
13233
- });
13318
+ const wire = parseWire(envelopeWire, body, MALFORMED$2);
13319
+ const errors = wire.errors ?? [];
13234
13320
  if (errors.some((error) => error.type === "RATE_LIMITED" || /rate limit/i.test(error.message))) throw classifyHttpFailure({
13235
13321
  status: 429,
13236
13322
  headers: response.headers
13237
13323
  }, Date.now());
13238
13324
  if (errors.some((error) => teamNameScopeDenied(error, query))) throw new AdapterError("auth", "GitHub token needs read:org for team review requests");
13239
13325
  if (errors.some((error) => error.type === "INSUFFICIENT_SCOPES")) throw new AdapterError("auth", "GitHub token lacks a required GraphQL read scope");
13240
- const data = record$2(wire.data);
13241
- const rate = record$2(data.rateLimit);
13242
- const remaining = rate.remaining;
13243
- if (typeof remaining !== "number" || !Number.isInteger(remaining) || remaining < 0) throw new AdapterError("transient", "Malformed GitHub budget");
13326
+ const data = parseWire(dataWire, wire.data, MALFORMED$2, ["data"]);
13244
13327
  return {
13245
13328
  data,
13246
13329
  errors,
13247
- budget: {
13248
- remaining,
13249
- resetAt: string$4(rate.resetAt)
13250
- }
13330
+ budget: data.rateLimit
13251
13331
  };
13252
13332
  }
13253
13333
  };
13254
13334
  //#endregion
13255
13335
  //#region ../adapters/src/github/discovery.ts
13336
+ const timestamp$1 = z.string().min(1).refine((value) => !Number.isNaN(Date.parse(value)));
13337
+ const discoveryNodeWire = z.object({
13338
+ number: z.int().positive(),
13339
+ updatedAt: timestamp$1,
13340
+ author: z.object({ login: z.string() }).nullable()
13341
+ });
13342
+ const baselineNodeWire = z.object({ updatedAt: timestamp$1 });
13256
13343
  function latestUpdatedAt(nodes, previous) {
13257
13344
  let high = previous;
13258
13345
  for (const node of nodes) {
13259
- const updated = sourceCursorSchema.parse(string$4(node.updatedAt));
13260
- const updatedMs = Date.parse(updated);
13261
- if (Number.isNaN(updatedMs)) throw new Error("Malformed GitHub updatedAt");
13262
- if (high === void 0 || updatedMs > Date.parse(high)) high = updated;
13346
+ const updated = sourceCursorSchema.parse(node.updatedAt);
13347
+ if (high === void 0 || Date.parse(updated) > Date.parse(high)) high = updated;
13263
13348
  }
13264
13349
  return high;
13265
13350
  }
@@ -13268,15 +13353,12 @@ function discover(nodes, previous, login) {
13268
13353
  let high = previous;
13269
13354
  const numbers = /* @__PURE__ */ new Set();
13270
13355
  for (const node of nodes) {
13271
- const updated = sourceCursorSchema.parse(string$4(node.updatedAt));
13356
+ const updated = sourceCursorSchema.parse(node.updatedAt);
13272
13357
  const updatedMs = Date.parse(updated);
13273
- if (Number.isNaN(updatedMs)) throw new Error("Malformed GitHub updatedAt");
13274
13358
  if (high === void 0 || updatedMs > Date.parse(high)) high = updated;
13275
13359
  if (previous !== void 0 && updatedMs < Date.parse(previous)) continue;
13276
- const author = record$2(node.author);
13277
- if (typeof author.login !== "string" || author.login.toLowerCase() !== login.toLowerCase()) continue;
13278
- const number = node.number;
13279
- if (typeof number === "number" && Number.isInteger(number) && number > 0) numbers.add(number);
13360
+ if (node.author?.login.toLowerCase() !== login.toLowerCase()) continue;
13361
+ numbers.add(node.number);
13280
13362
  }
13281
13363
  return {
13282
13364
  numbers: [...numbers],
@@ -13285,35 +13367,79 @@ function discover(nodes, previous, login) {
13285
13367
  }
13286
13368
  /** Pages are sorted newest first; older nodes end the scan, while ties must be revisited. */
13287
13369
  function pastCursor(nodes, previous) {
13288
- if (previous === void 0 || nodes.length === 0) return false;
13289
- const oldest = nodes[nodes.length - 1];
13290
- const updatedMs = Date.parse(string$4(oldest?.updatedAt));
13291
- if (Number.isNaN(updatedMs)) throw new Error("Malformed GitHub updatedAt");
13292
- return updatedMs < Date.parse(previous);
13370
+ const oldest = nodes.at(-1);
13371
+ if (previous === void 0 || oldest === void 0) return false;
13372
+ return Date.parse(oldest.updatedAt) < Date.parse(previous);
13293
13373
  }
13294
13374
  function nextPage(connection) {
13295
- const info = record$2(record$2(connection).pageInfo);
13296
- if (info.hasNextPage === false) return void 0;
13297
- if (info.hasNextPage !== true || typeof info.endCursor !== "string" || info.endCursor.length === 0) throw new Error("Malformed GitHub pagination");
13298
- return string$4(info.endCursor);
13375
+ const { hasNextPage, endCursor } = connection.pageInfo;
13376
+ if (!hasNextPage) return void 0;
13377
+ if (!endCursor) throw new Error("Malformed GitHub pagination");
13378
+ return endCursor;
13299
13379
  }
13300
13380
  //#endregion
13301
13381
  //#region ../adapters/src/github/prBatch.ts
13302
- function lower(value) {
13303
- return string$4(value).toLowerCase();
13304
- }
13305
- function optionalLogin(value) {
13306
- if (value === null || value === void 0) return void 0;
13307
- const login = record$2(value).login;
13308
- return typeof login === "string" ? login : void 0;
13309
- }
13382
+ const KEPT_REVIEWS = [
13383
+ "approved",
13384
+ "changes_requested",
13385
+ "dismissed"
13386
+ ];
13387
+ const actor = z.object({ login: z.string().optional() }).nullish();
13388
+ const checkRunWire = z.object({
13389
+ __typename: z.literal("CheckRun"),
13390
+ name: z.string(),
13391
+ status: z.string(),
13392
+ conclusion: z.string().nullable(),
13393
+ startedAt: z.string().nullish(),
13394
+ completedAt: z.string().nullable(),
13395
+ checkSuite: z.object({ createdAt: z.string() }).nullish(),
13396
+ isRequired: z.boolean().nullish()
13397
+ }).refine((run) => run.status !== "COMPLETED" || run.conclusion !== null, { path: ["conclusion"] });
13398
+ const statusContextWire = z.object({
13399
+ __typename: z.literal("StatusContext"),
13400
+ context: z.string(),
13401
+ state: z.string(),
13402
+ createdAt: z.string(),
13403
+ isRequired: z.boolean().nullish()
13404
+ });
13405
+ const contextWire = z.discriminatedUnion("__typename", [checkRunWire, statusContextWire]);
13406
+ const reviewWire = z.object({
13407
+ author: actor,
13408
+ state: z.string(),
13409
+ commit: z.object({ oid: z.string() }).nullable(),
13410
+ submittedAt: z.string().nullish()
13411
+ }).refine((review) => review.commit !== null || !review.author?.login || review.submittedAt == null || !KEPT_REVIEWS.includes(review.state.toLowerCase()), { path: ["commit"] });
13412
+ const nodes = (node) => z.object({ nodes: z.array(node) });
13413
+ const prWire = z.object({
13414
+ number: z.number(),
13415
+ url: z.string(),
13416
+ title: z.string(),
13417
+ updatedAt: z.string(),
13418
+ state: z.string(),
13419
+ isDraft: z.boolean(),
13420
+ mergeable: z.string(),
13421
+ mergeStateStatus: z.string(),
13422
+ author: actor,
13423
+ headRefName: z.string(),
13424
+ headRefOid: z.string(),
13425
+ statusCheckRollup: z.object({ contexts: nodes(contextWire) }).nullish(),
13426
+ reviews: nodes(reviewWire),
13427
+ reviewThreads: nodes(z.object({ isResolved: z.boolean() })),
13428
+ reviewRequests: nodes(z.object({
13429
+ requestedReviewer: z.object({
13430
+ login: z.string().nullish(),
13431
+ name: z.string().nullish()
13432
+ }),
13433
+ asCodeOwner: z.boolean()
13434
+ }))
13435
+ });
13310
13436
  function checkState(node) {
13311
13437
  if (node.__typename === "StatusContext") {
13312
- const state = lower(node.state);
13438
+ const state = node.state.toLowerCase();
13313
13439
  return state === "success" ? "success" : state === "pending" ? "pending" : state === "expected" ? "expected" : "failure";
13314
13440
  }
13315
13441
  if (node.status !== "COMPLETED") return "pending";
13316
- const value = lower(node.conclusion);
13442
+ const value = node.conclusion?.toLowerCase();
13317
13443
  return [
13318
13444
  "success",
13319
13445
  "neutral",
@@ -13328,11 +13454,10 @@ function checkState(node) {
13328
13454
  function latestChecks(nodes) {
13329
13455
  const latest = /* @__PURE__ */ new Map();
13330
13456
  for (const node of nodes) {
13331
- const name = string$4(node.__typename === "StatusContext" ? node.context : node.name);
13332
- const completedAt = node.__typename === "StatusContext" ? null : node.completedAt === null ? null : string$4(node.completedAt);
13333
- const startedAt = node.startedAt;
13334
- const suite = node.checkSuite;
13335
- const at = node.__typename === "StatusContext" ? string$4(node.createdAt) : typeof startedAt === "string" ? startedAt : suite === null || suite === void 0 ? completedAt ?? "" : string$4(record$2(suite).createdAt);
13457
+ const status = node.__typename === "StatusContext";
13458
+ const name = status ? node.context : node.name;
13459
+ const completedAt = status ? null : node.completedAt;
13460
+ const at = status ? node.createdAt : node.startedAt ?? node.checkSuite?.createdAt ?? completedAt ?? "";
13336
13461
  const old = latest.get(name);
13337
13462
  if (old !== void 0 && old.at > at) continue;
13338
13463
  latest.set(name, {
@@ -13354,19 +13479,15 @@ function latestChecks(nodes) {
13354
13479
  function latestReviews(nodes) {
13355
13480
  const latest = /* @__PURE__ */ new Map();
13356
13481
  for (const node of nodes) {
13357
- const reviewer = optionalLogin(node.author);
13358
- if (!reviewer || node.submittedAt === null || node.submittedAt === void 0) continue;
13359
- const state = lower(node.state);
13360
- if (![
13361
- "approved",
13362
- "changes_requested",
13363
- "dismissed"
13364
- ].includes(state)) continue;
13482
+ const reviewer = node.author?.login;
13483
+ if (!reviewer || node.submittedAt == null || node.commit === null) continue;
13484
+ const state = node.state.toLowerCase();
13485
+ if (!KEPT_REVIEWS.includes(state)) continue;
13365
13486
  const review = {
13366
13487
  reviewer,
13367
13488
  state,
13368
- commitSha: string$4(record$2(node.commit).oid),
13369
- submittedAt: string$4(node.submittedAt)
13489
+ commitSha: node.commit.oid,
13490
+ submittedAt: node.submittedAt
13370
13491
  };
13371
13492
  const old = latest.get(reviewer);
13372
13493
  if (old === void 0 || old.submittedAt <= review.submittedAt) latest.set(reviewer, review);
@@ -13383,13 +13504,12 @@ function ticketKeys(title, branch, prefixes) {
13383
13504
  }
13384
13505
  return [...keys];
13385
13506
  }
13386
- function normalizePr(repo, wire, prefixes) {
13387
- const rollupValue = wire.statusCheckRollup;
13388
- const rollup = rollupValue === null || rollupValue === void 0 ? null : record$2(rollupValue);
13389
- const checks = latestChecks(rollup === null ? [] : connectionNodes(record$2(rollup).contexts));
13507
+ function normalizePr(repo, value, prefixes) {
13508
+ const wire = parseWire(prWire, value, "Malformed GitHub PR response");
13509
+ const checks = latestChecks(wire.statusCheckRollup?.contexts.nodes ?? []);
13390
13510
  const state = wire.state === "MERGED" ? "merged" : wire.state === "CLOSED" ? "closed" : "open";
13391
13511
  const mergeable = wire.mergeable === "MERGEABLE" ? "mergeable" : wire.mergeable === "CONFLICTING" ? "conflicting" : "unknown";
13392
- const rawMerge = lower(wire.mergeStateStatus);
13512
+ const rawMerge = wire.mergeStateStatus.toLowerCase();
13393
13513
  const mergeState = [
13394
13514
  "behind",
13395
13515
  "blocked",
@@ -13399,14 +13519,14 @@ function normalizePr(repo, wire, prefixes) {
13399
13519
  "has_hooks",
13400
13520
  "unstable"
13401
13521
  ].includes(rawMerge) ? rawMerge : "unknown";
13402
- const title = string$4(wire.title);
13403
- const headBranch = string$4(wire.headRefName);
13522
+ const title = wire.title;
13523
+ const headBranch = wire.headRefName;
13404
13524
  const facts = {
13405
13525
  repo,
13406
13526
  number: wire.number,
13407
13527
  url: wire.url,
13408
13528
  title,
13409
- author: optionalLogin(wire.author),
13529
+ author: wire.author?.login,
13410
13530
  headSha: wire.headRefOid,
13411
13531
  headBranch,
13412
13532
  state,
@@ -13414,15 +13534,12 @@ function normalizePr(repo, wire, prefixes) {
13414
13534
  mergeable,
13415
13535
  mergeState,
13416
13536
  ...checks,
13417
- reviews: latestReviews(connectionNodes(wire.reviews)),
13418
- reviewThreads: connectionNodes(wire.reviewThreads).map((node) => ({ resolved: node.isResolved })),
13419
- reviewRequests: connectionNodes(wire.reviewRequests).map((node) => {
13420
- const reviewer = record$2(node.requestedReviewer);
13421
- return {
13422
- reviewer: reviewer.login ?? reviewer.name,
13423
- asCodeOwner: node.asCodeOwner
13424
- };
13425
- }),
13537
+ reviews: latestReviews(wire.reviews.nodes),
13538
+ reviewThreads: wire.reviewThreads.nodes.map((node) => ({ resolved: node.isResolved })),
13539
+ reviewRequests: wire.reviewRequests.nodes.map((node) => ({
13540
+ reviewer: node.requestedReviewer.login ?? node.requestedReviewer.name,
13541
+ asCodeOwner: node.asCodeOwner
13542
+ })),
13426
13543
  ticketKeys: ticketKeys(title, headBranch, prefixes),
13427
13544
  updatedAt: wire.updatedAt
13428
13545
  };
@@ -13432,6 +13549,18 @@ function normalizePr(repo, wire, prefixes) {
13432
13549
  }
13433
13550
  //#endregion
13434
13551
  //#region ../adapters/src/github/index.ts
13552
+ const MALFORMED$1 = "Malformed GitHub response";
13553
+ const discoveryRootWire = z.object({ pullRequests: connectionWire(discoveryNodeWire) });
13554
+ const baselineRootWire = z.object({ mergedBaseline: z.object({ nodes: z.array(baselineNodeWire) }) });
13555
+ const pagingWire = connectionWire(z.unknown());
13556
+ const prPagingWire = z.looseObject({
13557
+ reviews: pagingWire,
13558
+ reviewThreads: pagingWire,
13559
+ reviewRequests: pagingWire,
13560
+ statusCheckRollup: z.object({ contexts: pagingWire }).nullish()
13561
+ });
13562
+ const aliasWire = z.object({ pullRequest: prPagingWire.nullish() }).nullish();
13563
+ const pageRootWire = z.object({ pullRequest: prPagingWire.partial() });
13435
13564
  function sourceId(project, repo) {
13436
13565
  return `github:${project}:${repo.toLowerCase()}`;
13437
13566
  }
@@ -13481,27 +13610,30 @@ function rejectUnscoped(errors, roots) {
13481
13610
  function status(error) {
13482
13611
  return error.type === "NOT_FOUND" ? "not_found" : "no_access";
13483
13612
  }
13484
- function aliasPr(data, alias) {
13485
- const value = data[alias];
13486
- return value === null || value === void 0 ? null : nested(data, alias, "pullRequest");
13487
- }
13488
- function nested(value, ...path) {
13489
- let current = value;
13490
- for (const field of path) current = record$2(current)[field];
13491
- return current;
13613
+ function connectionOf(pr, field) {
13614
+ return field === "contexts" ? pr.statusCheckRollup?.contexts : pr[field];
13492
13615
  }
13493
- function contexts(pr) {
13494
- const value = pr.statusCheckRollup;
13495
- return value === null || value === void 0 ? void 0 : record$2(record$2(value).contexts);
13616
+ function withConnection(pr, field, connection) {
13617
+ return field === "contexts" ? {
13618
+ ...pr,
13619
+ statusCheckRollup: {
13620
+ ...pr.statusCheckRollup,
13621
+ contexts: connection
13622
+ }
13623
+ } : {
13624
+ ...pr,
13625
+ [field]: connection
13626
+ };
13496
13627
  }
13497
- async function fullPr(client, pr, owner, name, number, signal, budget) {
13628
+ async function fullPr(client, first, owner, name, number, signal, budget) {
13629
+ let pr = first;
13498
13630
  for (const field of [
13499
13631
  "reviews",
13500
13632
  "reviewThreads",
13501
13633
  "reviewRequests",
13502
13634
  "contexts"
13503
13635
  ]) {
13504
- const target = field === "contexts" ? contexts(pr) : record$2(pr[field]);
13636
+ let target = connectionOf(pr, field);
13505
13637
  if (target === void 0) continue;
13506
13638
  let cursor = nextPage(target);
13507
13639
  const seen = /* @__PURE__ */ new Set();
@@ -13518,12 +13650,14 @@ async function fullPr(client, pr, owner, name, number, signal, budget) {
13518
13650
  rejectUnscoped(response.errors, ["repository"]);
13519
13651
  requireCheckAccess(response.errors);
13520
13652
  if (response.errors.length > 0) return void 0;
13521
- const pagePr = record$2(nested(response.data, "repository", "pullRequest"));
13522
- const page = field === "contexts" ? contexts(pagePr) : record$2(pagePr[field]);
13653
+ const page = connectionOf(parseWire(pageRootWire, response.data.repository, MALFORMED$1, ["data", "repository"]).pullRequest, field);
13523
13654
  if (page === void 0) throw new AdapterError("transient", "Malformed GitHub pagination");
13524
- list(target.nodes).push(...list(page.nodes));
13655
+ target = {
13656
+ nodes: [...target.nodes, ...page.nodes],
13657
+ pageInfo: page.pageInfo
13658
+ };
13659
+ pr = withConnection(pr, field, target);
13525
13660
  cursor = nextPage(page);
13526
- target.pageInfo = page.pageInfo ?? null;
13527
13661
  }
13528
13662
  }
13529
13663
  return pr;
@@ -13547,8 +13681,8 @@ async function pollRepository({ id, repo, login, prefixes, client, ctx }) {
13547
13681
  const entities = [];
13548
13682
  const items = [];
13549
13683
  let discoveryOk = scoped(response.errors, "repository").length === 0;
13550
- const first = discoveryOk ? nested(response.data, "repository", "pullRequests") : void 0;
13551
- const nodes = first === void 0 ? [] : connectionNodes(first);
13684
+ const first = discoveryOk ? parseWire(discoveryRootWire, response.data.repository, MALFORMED$1, ["data", "repository"]).pullRequests : void 0;
13685
+ const nodes = first === void 0 ? [] : [...first.nodes];
13552
13686
  let cursor = first === void 0 || pastCursor(nodes, ctx.cursor) ? void 0 : nextPage(first);
13553
13687
  const seenPages = /* @__PURE__ */ new Set();
13554
13688
  while (cursor !== void 0 && discoveryOk) {
@@ -13565,15 +13699,14 @@ async function pollRepository({ id, repo, login, prefixes, client, ctx }) {
13565
13699
  discoveryOk = false;
13566
13700
  break;
13567
13701
  }
13568
- const connection = nested(page.data, "repository", "pullRequests");
13569
- const pageNodes = connectionNodes(connection);
13570
- nodes.push(...pageNodes);
13571
- cursor = pastCursor(pageNodes, ctx.cursor) ? void 0 : nextPage(connection);
13702
+ const connection = parseWire(discoveryRootWire, page.data.repository, MALFORMED$1, ["data", "repository"]).pullRequests;
13703
+ nodes.push(...connection.nodes);
13704
+ cursor = pastCursor(connection.nodes, ctx.cursor) ? void 0 : nextPage(connection);
13572
13705
  }
13573
13706
  if (!discoveryOk) complete = false;
13574
13707
  const found = discover(nodes, ctx.cursor, login);
13575
- const bootstrapCursor = bootstrap && discoveryOk ? latestUpdatedAt(connectionNodes(nested(response.data, "repository", "mergedBaseline")), found.cursor) ?? sourceCursorSchema.parse("1970-01-01T00:00:00.000Z") : void 0;
13576
- const process = async (number, wire, errors, ref) => {
13708
+ const bootstrapCursor = bootstrap && discoveryOk ? latestUpdatedAt(parseWire(baselineRootWire, response.data.repository, MALFORMED$1, ["data", "repository"]).mergedBaseline.nodes, found.cursor) ?? sourceCursorSchema.parse("1970-01-01T00:00:00.000Z") : void 0;
13709
+ const process = async (number, alias, data, errors, ref) => {
13577
13710
  requireCheckAccess(errors);
13578
13711
  const error = errors[0];
13579
13712
  if (error !== void 0) {
@@ -13585,6 +13718,7 @@ async function pollRepository({ id, repo, login, prefixes, client, ctx }) {
13585
13718
  });
13586
13719
  return false;
13587
13720
  }
13721
+ const wire = parseWire(aliasWire, data[alias], MALFORMED$1, ["data", alias])?.pullRequest;
13588
13722
  if (wire === null || wire === void 0) {
13589
13723
  if (ref) entities.push({
13590
13724
  ref,
@@ -13593,7 +13727,7 @@ async function pollRepository({ id, repo, login, prefixes, client, ctx }) {
13593
13727
  else complete = false;
13594
13728
  return false;
13595
13729
  }
13596
- const full = await fullPr(client, record$2(wire), owner, name, number, ctx.signal, (next) => {
13730
+ const full = await fullPr(client, wire, owner, name, number, ctx.signal, (next) => {
13597
13731
  budget = next;
13598
13732
  });
13599
13733
  if (full === void 0) {
@@ -13619,7 +13753,7 @@ async function pollRepository({ id, repo, login, prefixes, client, ctx }) {
13619
13753
  for (const [i, number] of numbers.entries()) {
13620
13754
  const alias = `pr${String(i)}`;
13621
13755
  const errors = scoped(response.errors, alias);
13622
- if (!await process(number, aliasPr(response.data, alias), errors, byNumber.get(number)) && found.numbers.includes(number)) discoveredOk = false;
13756
+ if (!await process(number, alias, response.data, errors, byNumber.get(number)) && found.numbers.includes(number)) discoveredOk = false;
13623
13757
  }
13624
13758
  const discovered = found.numbers.filter((number) => !byNumber.has(number));
13625
13759
  for (let offset = 0; offset < discovered.length; offset += 50) {
@@ -13632,7 +13766,7 @@ async function pollRepository({ id, repo, login, prefixes, client, ctx }) {
13632
13766
  rejectUnscoped(detail.errors, chunk.map((_, i) => `pr${String(i)}`));
13633
13767
  for (const [i, number] of chunk.entries()) {
13634
13768
  const alias = `pr${String(i)}`;
13635
- if (!await process(number, aliasPr(detail.data, alias), scoped(detail.errors, alias))) discoveredOk = false;
13769
+ if (!await process(number, alias, detail.data, scoped(detail.errors, alias))) discoveredOk = false;
13636
13770
  }
13637
13771
  }
13638
13772
  if (ctx.signal.aborted) throw new AdapterError("transient", "GitHub poll aborted");
@@ -13656,52 +13790,50 @@ var GithubIssuesHttpError = class extends AdapterError {
13656
13790
  this.status = status;
13657
13791
  }
13658
13792
  };
13659
- function object$3(value) {
13660
- if (value !== null && typeof value === "object" && !Array.isArray(value)) return value;
13661
- throw new AdapterError("transient", "Malformed GitHub issue response");
13662
- }
13663
- function string$3(value) {
13664
- if (typeof value === "string" && value.length > 0) return value;
13665
- throw new AdapterError("transient", "Malformed GitHub issue response");
13666
- }
13667
- function number(value) {
13668
- if (typeof value === "number" && Number.isSafeInteger(value) && value > 0) return value;
13669
- throw new AdapterError("transient", "Malformed GitHub issue response");
13670
- }
13793
+ const MALFORMED = "Malformed GitHub issue response";
13794
+ const text$2 = z.string().min(1);
13795
+ const issueWire$1 = z.object({
13796
+ node_id: text$2,
13797
+ number: z.int().positive(),
13798
+ title: text$2,
13799
+ state: text$2,
13800
+ html_url: text$2,
13801
+ updated_at: text$2.refine((value) => !Number.isNaN(Date.parse(value))),
13802
+ labels: z.array(z.object({ name: text$2 })),
13803
+ assignee: z.object({ login: text$2 }).nullish(),
13804
+ milestone: z.object({ title: text$2 }).nullish(),
13805
+ pull_request: z.unknown().optional()
13806
+ });
13807
+ const milestoneWire = z.object({
13808
+ title: z.string(),
13809
+ number: z.int().positive()
13810
+ });
13671
13811
  function issueNumber(ref, repo) {
13672
13812
  const match = /^(.+)#([1-9]\d*)$/.exec(ref.key);
13673
13813
  if (match?.[1]?.toLowerCase() !== repo.toLowerCase()) throw new AdapterError("config", "Requested issue is outside its configured repository");
13674
- return number(Number(match[2]));
13675
- }
13676
- function normalize(value, trackerId, repo, inFilter) {
13677
- const issue = object$3(value);
13678
- if (issue["pull_request"] !== void 0) throw new AdapterError("transient", "A pull request cannot be a tracker ticket");
13679
- const updatedAt = new Date(string$3(issue["updated_at"]));
13680
- if (Number.isNaN(updatedAt.getTime())) throw new AdapterError("transient", "Malformed GitHub issue timestamp");
13681
- const labels = issue["labels"];
13682
- if (!Array.isArray(labels)) throw new AdapterError("transient", "Malformed GitHub issue labels");
13683
- const assignee = issue["assignee"] == null ? null : string$3(object$3(issue["assignee"])["login"]);
13684
- const milestone = issue["milestone"] == null ? null : string$3(object$3(issue["milestone"])["title"]);
13814
+ const value = Number(match[2]);
13815
+ if (!Number.isSafeInteger(value) || value <= 0) throw new AdapterError("transient", MALFORMED);
13816
+ return value;
13817
+ }
13818
+ function normalize(issue, trackerId, repo, inFilter) {
13819
+ if (issue.pull_request !== void 0) throw new AdapterError("transient", "A pull request cannot be a tracker ticket");
13685
13820
  return {
13686
13821
  trackerId,
13687
- id: string$3(issue["node_id"]),
13688
- key: `${repo}#${String(number(issue["number"]))}`,
13689
- title: string$3(issue["title"]),
13690
- status: string$3(issue["state"]),
13691
- assignee,
13692
- sprint: milestone,
13693
- labels: labels.map((label) => string$3(object$3(label)["name"])),
13822
+ id: issue.node_id,
13823
+ key: `${repo}#${String(issue.number)}`,
13824
+ title: issue.title,
13825
+ status: issue.state,
13826
+ assignee: issue.assignee?.login ?? null,
13827
+ sprint: issue.milestone?.title ?? null,
13828
+ labels: issue.labels.map((label) => label.name),
13694
13829
  inFilter,
13695
- url: string$3(issue["html_url"]),
13696
- updatedAt: updatedAt.toISOString()
13830
+ url: issue.html_url,
13831
+ updatedAt: new Date(issue.updated_at).toISOString()
13697
13832
  };
13698
13833
  }
13699
13834
  function matchesFilter(issue, tracker) {
13700
- if (tracker.label !== void 0) {
13701
- const labels = issue["labels"];
13702
- return Array.isArray(labels) && labels.some((label) => object$3(label)["name"] === tracker.label);
13703
- }
13704
- return issue["milestone"] != null && object$3(issue["milestone"])["title"] === tracker.milestone;
13835
+ if (tracker.label !== void 0) return issue.labels.some((label) => label.name === tracker.label);
13836
+ return issue.milestone?.title === tracker.milestone;
13705
13837
  }
13706
13838
  /** Lists tracker issues and resolves manually included keys outside the filter. */
13707
13839
  function createGithubIssuesAdapter(options) {
@@ -13771,8 +13903,7 @@ function createGithubIssuesAdapter(options) {
13771
13903
  };
13772
13904
  throw error;
13773
13905
  }
13774
- if (!Array.isArray(page.value)) throw new AdapterError("transient", "Malformed GitHub issue listing");
13775
- results.push(...page.value);
13906
+ results.push(...parseWire(z.array(z.unknown()), page.value, "Malformed GitHub issue listing"));
13776
13907
  next = page.next;
13777
13908
  }
13778
13909
  return {
@@ -13789,9 +13920,9 @@ function createGithubIssuesAdapter(options) {
13789
13920
  if (error instanceof GithubIssuesHttpError && error.status === 404) throw new AdapterError("config", "GitHub Issues repository is unavailable");
13790
13921
  throw error;
13791
13922
  }
13792
- const match = milestones.map(object$3).find((entry) => entry["title"] === options.tracker.milestone);
13923
+ const match = parseWire(z.array(milestoneWire), milestones, MALFORMED).find((entry) => entry.title === options.tracker.milestone);
13793
13924
  if (match === void 0) throw new AdapterError("config", "Configured GitHub milestone is missing");
13794
- return number(match["number"]);
13925
+ return match.number;
13795
13926
  }
13796
13927
  return {
13797
13928
  id: options.id,
@@ -13817,10 +13948,9 @@ function createGithubIssuesAdapter(options) {
13817
13948
  }
13818
13949
  const facts = /* @__PURE__ */ new Map();
13819
13950
  for (const value of listed) {
13820
- const issue = object$3(value);
13821
- if (issue["pull_request"] !== void 0) continue;
13822
- const fact = normalize(issue, options.id, options.tracker.repo, true);
13823
- facts.set(number(issue["number"]), fact);
13951
+ const issue = parseWire(issueWire$1, value, MALFORMED);
13952
+ if (issue.pull_request !== void 0) continue;
13953
+ facts.set(issue.number, normalize(issue, options.id, options.tracker.repo, true));
13824
13954
  }
13825
13955
  const entities = [];
13826
13956
  for (const ref of ctx.observe.tickets) {
@@ -13828,8 +13958,8 @@ function createGithubIssuesAdapter(options) {
13828
13958
  const issueNo = issueNumber(ref, options.tracker.repo);
13829
13959
  let fact = facts.get(issueNo);
13830
13960
  if (fact === void 0) try {
13831
- const detail = object$3((await request(`${root}/issues/${String(issueNo)}`, ctx.signal)).value);
13832
- if (detail["pull_request"] !== void 0) {
13961
+ const detail = parseWire(issueWire$1, (await request(`${root}/issues/${String(issueNo)}`, ctx.signal)).value, MALFORMED);
13962
+ if (detail.pull_request !== void 0) {
13833
13963
  entities.push({
13834
13964
  ref,
13835
13965
  status: "not_found"
@@ -13882,6 +14012,37 @@ const MAX_GET_SEARCH_URL_LENGTH = 2e3;
13882
14012
  const OUTSIDE_BATCH_SIZE = 50;
13883
14013
  const FALLBACK_REQUEST_LIMIT = 100;
13884
14014
  const SPRINT_SCHEMA = "com.pyxis.greenhopper.jira:gh-sprint";
14015
+ const INVALID = "Invalid Jira response";
14016
+ const text$1 = z.string().min(1);
14017
+ const timestamp = text$1.refine((value) => !Number.isNaN(Date.parse(value)));
14018
+ const statusesWire = z.array(z.object({ statuses: z.array(z.object({ name: text$1 })) }));
14019
+ const fieldWire = z.object({
14020
+ id: text$1,
14021
+ schema: z.object({ custom: z.string().optional() }).nullish()
14022
+ });
14023
+ const issueWire = z.object({
14024
+ id: text$1,
14025
+ key: text$1,
14026
+ fields: z.looseObject({
14027
+ summary: text$1,
14028
+ status: z.object({ name: text$1 }),
14029
+ assignee: z.object({
14030
+ accountId: z.string().nullish(),
14031
+ displayName: z.string().nullish()
14032
+ }).refine((assignee) => (assignee.accountId ?? assignee.displayName ?? "").length > 0, { path: ["accountId"] }).nullish(),
14033
+ labels: z.array(text$1),
14034
+ updated: timestamp
14035
+ })
14036
+ });
14037
+ const searchPageWire = z.object({
14038
+ issues: z.array(issueWire),
14039
+ nextPageToken: z.string().nullish(),
14040
+ isLast: z.boolean().optional()
14041
+ });
14042
+ const sprintWire = z.array(z.union([z.string(), z.object({
14043
+ name: z.string().optional(),
14044
+ state: z.string().optional()
14045
+ })])).nullish();
13885
14046
  var JiraHttpError = class extends AdapterError {
13886
14047
  status;
13887
14048
  constructor(status, failure) {
@@ -13889,18 +14050,6 @@ var JiraHttpError = class extends AdapterError {
13889
14050
  this.status = status;
13890
14051
  }
13891
14052
  };
13892
- function object$2(value) {
13893
- if (value !== null && typeof value === "object" && !Array.isArray(value)) return value;
13894
- throw new AdapterError("transient", "Invalid Jira response");
13895
- }
13896
- function string$2(value) {
13897
- if (typeof value === "string" && value.length > 0) return value;
13898
- throw new AdapterError("transient", "Invalid Jira response");
13899
- }
13900
- function array(value) {
13901
- if (Array.isArray(value)) return value;
13902
- throw new AdapterError("transient", "Invalid Jira response");
13903
- }
13904
14053
  function keyQuery(refs) {
13905
14054
  return `key in (${refs.map((ref) => `"${ref.key.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"")}"`).join(", ")})`;
13906
14055
  }
@@ -13924,51 +14073,34 @@ function membershipQuery(jql, refs) {
13924
14073
  return `(${jql.trim()}) AND ${keyQuery(refs)}`;
13925
14074
  }
13926
14075
  function sprintName(value) {
13927
- if (!Array.isArray(value)) return null;
13928
- const sprints = value.map((entry) => {
13929
- if (typeof entry === "string") return {
13930
- state: /(?:^|,)state=([^,\]]+)/i.exec(entry)?.[1]?.toLowerCase(),
13931
- name: /(?:^|,)name=(.*?)(?:,goal=|,startDate=|,endDate=|\]$)/i.exec(entry)?.[1]
13932
- };
13933
- if (entry !== null && typeof entry === "object" && !Array.isArray(entry)) {
13934
- const sprint = entry;
13935
- return {
13936
- state: sprint["state"],
13937
- name: sprint["name"]
13938
- };
13939
- }
14076
+ const sprints = (value ?? []).map((entry) => {
14077
+ if (typeof entry !== "string") return entry;
13940
14078
  return {
13941
- state: void 0,
13942
- name: void 0
14079
+ state: /(?:^|,)state=([^,\]]+)/i.exec(entry)?.[1],
14080
+ name: /(?:^|,)name=(.*?)(?:,goal=|,startDate=|,endDate=|\]$)/i.exec(entry)?.[1]
13943
14081
  };
13944
14082
  });
13945
14083
  for (const state of ["active", "future"]) {
13946
- const selected = sprints.find((sprint) => typeof sprint.state === "string" && sprint.state.toLowerCase() === state && typeof sprint.name === "string" && sprint.name.length > 0);
13947
- if (typeof selected?.name === "string") return selected.name;
14084
+ const selected = sprints.find((sprint) => sprint.state?.toLowerCase() === state && (sprint.name?.length ?? 0) > 0);
14085
+ if (selected?.name !== void 0) return selected.name;
13948
14086
  }
13949
14087
  return null;
13950
14088
  }
13951
- function issueFacts(value, trackerId, baseUrl, sprintField, inFilter) {
13952
- const issue = object$2(value);
13953
- const fields = object$2(issue["fields"]);
13954
- const status = object$2(fields["status"]);
13955
- const assignee = fields["assignee"] == null ? null : object$2(fields["assignee"]);
13956
- const key = string$2(issue["key"]);
13957
- const updated = string$2(fields["updated"]);
13958
- const updatedAt = new Date(updated);
13959
- if (Number.isNaN(updatedAt.getTime())) throw new AdapterError("transient", "Invalid Jira response");
14089
+ function issueFacts(issue, trackerId, baseUrl, sprintField, inFilter) {
14090
+ const { fields, key } = issue;
14091
+ const assignee = fields.assignee ?? null;
13960
14092
  return {
13961
14093
  trackerId,
13962
- id: string$2(issue["id"]),
14094
+ id: issue.id,
13963
14095
  key,
13964
- title: string$2(fields["summary"]),
13965
- status: string$2(status["name"]),
13966
- assignee: assignee === null ? null : string$2(assignee["accountId"] ?? assignee["displayName"]),
13967
- sprint: sprintField === null ? null : sprintName(fields[sprintField]),
13968
- labels: array(fields["labels"]).map(string$2),
14096
+ title: fields.summary,
14097
+ status: fields.status.name,
14098
+ assignee: assignee === null ? null : assignee.accountId ?? assignee.displayName ?? null,
14099
+ sprint: sprintField === null ? null : sprintName(parseWire(sprintWire, fields[sprintField], INVALID, ["fields", sprintField])),
14100
+ labels: fields.labels,
13969
14101
  inFilter,
13970
14102
  url: new URL(`/browse/${encodeURIComponent(key)}`, baseUrl).toString(),
13971
- updatedAt: updatedAt.toISOString()
14103
+ updatedAt: new Date(fields.updated).toISOString()
13972
14104
  };
13973
14105
  }
13974
14106
  /** Creates one Jira source. Credentials and transport come from the eventual runtime caller. */
@@ -14001,7 +14133,7 @@ function createJiraAdapter(options) {
14001
14133
  try {
14002
14134
  return await response.json();
14003
14135
  } catch {
14004
- throw new AdapterError("transient", "Invalid Jira response");
14136
+ throw new AdapterError("transient", INVALID);
14005
14137
  }
14006
14138
  }
14007
14139
  async function validate(tracker, signal) {
@@ -14014,20 +14146,12 @@ function createJiraAdapter(options) {
14014
14146
  if (error instanceof JiraHttpError && error.status === 404) throw new AdapterError("config", `Unknown Jira project key ${key}`);
14015
14147
  throw error;
14016
14148
  }
14017
- const names = new Set(array(result).flatMap((entry) => array(object$2(entry)["statuses"]).map((status) => string$2(object$2(status)["name"]))));
14149
+ const names = new Set(parseWire(statusesWire, result, INVALID).flatMap((entry) => entry.statuses.map((status) => status.name)));
14018
14150
  for (const name of [...tracker.doneStatuses, ...tracker.readyStatuses]) if (!names.has(name)) throw new AdapterError("config", `Unknown Jira status ${name} in project ${key}`);
14019
14151
  }
14020
14152
  }
14021
14153
  async function findSprintField(tracker, signal) {
14022
- const fields = array(await request(tracker.baseUrl, "/rest/api/3/field", signal));
14023
- for (const field of fields) {
14024
- const entry = object$2(field);
14025
- const schema = entry["schema"];
14026
- if (schema !== null && typeof schema === "object" && !Array.isArray(schema)) {
14027
- if (schema["custom"] === SPRINT_SCHEMA) return string$2(entry["id"]);
14028
- }
14029
- }
14030
- return null;
14154
+ return parseWire(z.array(fieldWire), await request(tracker.baseUrl, "/rest/api/3/field", signal), INVALID).find((field) => field.schema?.custom === SPRINT_SCHEMA)?.id ?? null;
14031
14155
  }
14032
14156
  async function search(tracker, signal, jql, sprintField, beforePage) {
14033
14157
  const issues = [];
@@ -14056,17 +14180,17 @@ function createJiraAdapter(options) {
14056
14180
  ...token === void 0 ? {} : { nextPageToken: token }
14057
14181
  }).toString()}` : "/rest/api/3/search/jql";
14058
14182
  if (options.searchMethod === "GET" && new URL(path, tracker.baseUrl).href.length > MAX_GET_SEARCH_URL_LENGTH) throw new AdapterError("config", `Jira GET search URL is too long (over ${String(MAX_GET_SEARCH_URL_LENGTH)} characters)`);
14059
- const result = object$2(await request(tracker.baseUrl, path, signal, options.searchMethod === "GET" ? void 0 : body));
14060
- issues.push(...array(result["issues"]));
14061
- const next = result["nextPageToken"];
14183
+ const result = parseWire(searchPageWire, await request(tracker.baseUrl, path, signal, options.searchMethod === "GET" ? void 0 : body), INVALID);
14184
+ issues.push(...result.issues);
14185
+ const next = result.nextPageToken;
14062
14186
  if (next == null || next === "") {
14063
- if (result["isLast"] === false) throw new AdapterError("transient", "Jira search omitted its next page token");
14187
+ if (result.isLast === false) throw new AdapterError("transient", "Jira search omitted its next page token");
14064
14188
  return {
14065
14189
  issues,
14066
14190
  complete: true
14067
14191
  };
14068
14192
  }
14069
- token = string$2(next);
14193
+ token = next;
14070
14194
  if (seen.has(token)) throw new AdapterError("transient", "Jira search repeated a page token");
14071
14195
  seen.add(token);
14072
14196
  }
@@ -14078,8 +14202,8 @@ function createJiraAdapter(options) {
14078
14202
  async function fetchById(tracker, ref, signal, beforeRequest) {
14079
14203
  try {
14080
14204
  beforeRequest();
14081
- const issue = object$2(await request(tracker.baseUrl, `/rest/api/3/issue/${encodeURIComponent(ref.id)}`, signal));
14082
- if (string$2(issue["id"]) !== ref.id) throw new AdapterError("transient", "Jira returned a different ticket id");
14205
+ const issue = parseWire(issueWire, await request(tracker.baseUrl, `/rest/api/3/issue/${encodeURIComponent(ref.id)}`, signal), INVALID);
14206
+ if (issue.id !== ref.id) throw new AdapterError("transient", "Jira returned a different ticket id");
14083
14207
  return issue;
14084
14208
  } catch (error) {
14085
14209
  if (error instanceof JiraHttpError && (error.status === 404 || error.status === 403 && error.kind === "auth")) return null;
@@ -14104,8 +14228,8 @@ function createJiraAdapter(options) {
14104
14228
  }
14105
14229
  async function fetchPending(tracker, ref, signal) {
14106
14230
  try {
14107
- const issue = object$2(await request(tracker.baseUrl, `/rest/api/3/issue/${encodeURIComponent(ref.key)}`, signal));
14108
- if (string$2(issue["key"]) !== ref.key) throw new AdapterError("transient", "Jira returned a different ticket key");
14231
+ const issue = parseWire(issueWire, await request(tracker.baseUrl, `/rest/api/3/issue/${encodeURIComponent(ref.key)}`, signal), INVALID);
14232
+ if (issue.key !== ref.key) throw new AdapterError("transient", "Jira returned a different ticket key");
14109
14233
  return {
14110
14234
  status: "ok",
14111
14235
  issue
@@ -14156,7 +14280,7 @@ function createJiraAdapter(options) {
14156
14280
  if (issue === null) return [];
14157
14281
  const current = await search(tracker, ctx.signal, membershipQuery(tracker.jql, [{
14158
14282
  ...ref,
14159
- key: string$2(issue["key"])
14283
+ key: issue.key
14160
14284
  }]), sprintField, countFallbackRequest);
14161
14285
  if (!current.complete) throw new AdapterError("transient", "Jira membership search reached its page limit");
14162
14286
  return current.issues;
@@ -14658,7 +14782,7 @@ function createSpurAdapter(options) {
14658
14782
  status: listResponse.status,
14659
14783
  headers: listResponse.headers
14660
14784
  }, Date.now());
14661
- const listed = z.array(sessionWire).parse(listBody);
14785
+ const listed = parseWire(z.array(sessionWire), listBody, "Invalid Spur response");
14662
14786
  const byId = new Map(listed.map((wire) => [wire.id, wire]));
14663
14787
  const detail = /* @__PURE__ */ new Map();
14664
14788
  for (const ref of ctx.observe.sessions) {
@@ -14672,7 +14796,7 @@ function createSpurAdapter(options) {
14672
14796
  status: response.status,
14673
14797
  headers: response.headers
14674
14798
  }, Date.now());
14675
- const wire = sessionWire.parse(body);
14799
+ const wire = parseWire(sessionWire, body, "Invalid Spur response");
14676
14800
  if (wire.id !== ref.id) throw new AdapterError("transient", "Unresolved Spur session detail");
14677
14801
  detail.set(ref.id, wire);
14678
14802
  }