@vercel/board 0.48.0 → 0.49.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.
Files changed (84) hide show
  1. package/dist/{access-C06pIr0M.mjs → access-B8DnrnHa.mjs} +29 -17
  2. package/dist/access.d.mts +2 -2
  3. package/dist/access.mjs +5 -5
  4. package/dist/{actors-Dkyg-oo0.mjs → actors-DewJKyqy.mjs} +4 -3
  5. package/dist/{auth-B9-wXQ-x.mjs → auth-CEU06Nyp.mjs} +2 -2
  6. package/dist/{auth-li3lKwJG.d.mts → auth-Z9-Khvvw.d.mts} +1 -1
  7. package/dist/{backend-UBP6HimX.d.mts → backend-BzCXxVZ-.d.mts} +19 -5
  8. package/dist/backend-local.d.mts +1 -1
  9. package/dist/backend-local.mjs +1 -1
  10. package/dist/{bots-CLKKMgYf.mjs → bots-CqPYxkqK.mjs} +15 -8
  11. package/dist/{chat-provider-kNWd6MQC.mjs → chat-provider-BS_fr61g.mjs} +2 -2
  12. package/dist/{chat-provider-iN0DFsSE.d.mts → chat-provider-DQ1GHm4o.d.mts} +2 -2
  13. package/dist/cli-commands.d.mts +1 -1
  14. package/dist/cli-commands.mjs +1 -1
  15. package/dist/cli-embedded.d.mts +2 -2
  16. package/dist/cli-embedded.mjs +3 -3
  17. package/dist/cli.mjs +6 -6
  18. package/dist/client-C2T4eaXd.d.mts +544 -0
  19. package/dist/{commands-CJsOA-hf.d.mts → commands-Cm4sODIu.d.mts} +12 -8
  20. package/dist/{commands-Dk6_cHLS.mjs → commands-nN8WpvCe.mjs} +75 -58
  21. package/dist/{conformance-CDP8y2Zm.mjs → conformance-0xONNKcB.mjs} +102 -20
  22. package/dist/conformance.d.mts +1 -1
  23. package/dist/conformance.mjs +1 -1
  24. package/dist/{engine-B3Yd0OPc.mjs → engine-BH_nfJ3N.mjs} +10 -8
  25. package/dist/{errors-QhkdzI-o.mjs → errors-DwV7I0g4.mjs} +53 -174
  26. package/dist/{events-B-qyxNsJ.mjs → events-B76-4bNp.mjs} +2 -2
  27. package/dist/{exports-inhbjAWi.d.mts → exports-CKEK1fxf.d.mts} +4 -4
  28. package/dist/{exports-B5xOYHj_.mjs → exports-DLzyKwEp.mjs} +336 -82
  29. package/dist/{external-BuVTXT1R.mjs → external-BLI4W_-V.mjs} +1 -1
  30. package/dist/{index-B0Fnhvk7.d.mts → index-DxqSw8yd.d.mts} +2 -2
  31. package/dist/index.d.mts +6 -6
  32. package/dist/index.mjs +4 -4
  33. package/dist/index.node.d.mts +7 -7
  34. package/dist/index.node.mjs +4 -4
  35. package/dist/inspect/app.js +39 -39
  36. package/dist/inspect/engine.js +3 -3
  37. package/dist/inspect-B2ImmOvw.mjs +272 -0
  38. package/dist/inspect-DnRQUmP8.mjs +2 -0
  39. package/dist/inspect.d.mts +17 -0
  40. package/dist/inspect.mjs +196 -0
  41. package/dist/{local-CKMP4xH3.mjs → local-DPpSEq2_.mjs} +132 -50
  42. package/dist/{main-DZZQEFVl.mjs → main-CqX7JqzE.mjs} +217 -49
  43. package/dist/{memory-CMm-Fk_A.mjs → memory-DzqkXIB-.mjs} +2 -2
  44. package/dist/{middleware-CT6vMNUc.mjs → middleware-ysFm2S4v.mjs} +2 -2
  45. package/dist/{page-D-OzDOAX.mjs → page-7KWSGxyC.mjs} +12 -2
  46. package/dist/page-CN77B014.mjs +2 -0
  47. package/dist/profile-header-Cj0Cb1cf.mjs +163 -0
  48. package/dist/{provider-DC3WHUXo.d.mts → provider-Dwb_9mnu.d.mts} +3 -529
  49. package/dist/{routes-CjA6Mp4D.d.mts → routes-B6SEA9yw.d.mts} +130 -4
  50. package/dist/{routes-ABXf3CKq.mjs → routes-qS92xz8U.mjs} +33 -7
  51. package/dist/{schemas-7VFdomFB.mjs → schemas-TeVe4Udh.mjs} +4 -2
  52. package/dist/{serve-DBJTP0xd.mjs → serve-CYr4RwRM.mjs} +5 -5
  53. package/dist/{server-DmlyIzMj.mjs → server-V7qyVUiJ.mjs} +11 -9
  54. package/dist/{serving-BNdiReQT.mjs → serving-BzNxlnDV.mjs} +1 -1
  55. package/dist/{inspect-CAz9PGLf.mjs → shell-BLHZoP-x.mjs} +25 -274
  56. package/dist/{sql-IEbO5vXs.mjs → sql-DIKQd5Me.mjs} +2 -2
  57. package/dist/{sqlite-CVG8XKHm.mjs → sqlite-BF9kBDh1.mjs} +2 -2
  58. package/dist/{sqlite-db-BJjPQYx4.mjs → sqlite-db-CSYwiZ4E.mjs} +1 -1
  59. package/dist/sync-chat-sdk.d.mts +2 -2
  60. package/dist/sync-chat-sdk.mjs +2 -2
  61. package/dist/sync-github.d.mts +2 -2
  62. package/dist/sync-github.mjs +2 -2
  63. package/dist/sync-linear.d.mts +3 -3
  64. package/dist/sync-linear.mjs +2 -2
  65. package/dist/sync-slack.d.mts +3 -3
  66. package/dist/sync-slack.mjs +12 -8
  67. package/dist/sync.d.mts +2 -2
  68. package/dist/sync.mjs +2 -2
  69. package/dist/{task-batch-CmKvTLSu.mjs → task-batch-CujTLmTB.mjs} +10 -11
  70. package/dist/{tokens-BCp4EWTQ.mjs → tokens-BmCDAT4N.mjs} +2 -2
  71. package/dist/version-BCoWGLEW.mjs +5 -0
  72. package/docs/01-board/01-mounting.md +8 -0
  73. package/docs/01-board/04-messages.md +6 -2
  74. package/docs/01-board/05-reading.md +17 -2
  75. package/docs/01-board/09-access.md +40 -6
  76. package/docs/01-board/11-tasks.md +3 -3
  77. package/docs/03-guides/02-inspector.md +31 -0
  78. package/docs/04-reference/01-cli.md +81 -32
  79. package/docs/04-reference/02-board.md +14 -3
  80. package/docs/04-reference/03-http.md +5 -3
  81. package/docs/04-reference/05-conformance.md +7 -0
  82. package/package.json +5 -1
  83. package/dist/inspect-CNECs4UG.mjs +0 -2
  84. package/dist/page-Dr9Aqlej.mjs +0 -2
@@ -1,13 +1,15 @@
1
- import { S as fileName, _ as formatProfileHeader, a as duplicateId, c as notFound, d as unauthorized, f as BoardError, h as eventsState, i as batchTooLarge, m as duration, n as RejectedError, o as forbidden, p as createBoardClient, r as badRequest, s as json, t as HttpError, u as toErrorResponse, w as mediaType, x as IMPORT_BYTES_MAX, y as ATTACHMENT_BYTES_MAX } from "./errors-QhkdzI-o.mjs";
2
- import { v as RESERVED_LABEL_PREFIX, w as TASK_LABEL, y as RemoteWatcherId } from "./schemas-7VFdomFB.mjs";
3
- import { A as RegisterBody, B as SyncFindQuery, C as LabelBody, D as PostBody, E as MessagesQuery, F as SchemaBody, G as ThreadsQuery, H as SyncReceiptBody, I as SourceJoinBody, J as UploadStartBody, K as TypingBody, L as SourceReadQuery, M as RenewTaskBody, N as ScheduleBody, O as ReactBody, P as SchedulesQuery, R as SyncBody, S as InboxQuery, T as MatchesQuery, U as TaskNeedsBody, V as SyncImportBody, W as TasksQuery, Y as routes, a as ClaimReadyTaskBody, b as InboxNextQuery, c as CreateChannelBody, d as CreatedTasksQuery, f as DeleteBody, g as FailTaskBody, h as ExplainQuery, i as CancelTaskBody, j as ReleaseTaskBody, k as Ref, l as CreateTaskBody, m as EventsQuery, n as AssignTaskBody, o as ClaimTaskBody, p as EditBody, q as UpdateGrantBody, r as BlockTaskBody, s as CompleteTaskBody, t as AckBody, u as CreateTasksBody, v as GrantBody, w as LinkedQuery, x as InboxPushBody, y as InboxAckBody, z as SyncCopiesQuery } from "./routes-ABXf3CKq.mjs";
4
- import { _ as sha256, a as waitUntil, c as platformProfile, d as userIdOf, m as derivedId, o as actorParts, r as runMiddleware, s as importedHandle, t as DroppedError, u as underPrincipal } from "./middleware-CT6vMNUc.mjs";
1
+ import { i as ATTACHMENT_BYTES_MAX, l as mediaType, n as formatProfileHeader, o as IMPORT_BYTES_MAX, s as fileName } from "./profile-header-Cj0Cb1cf.mjs";
2
+ import { v as RESERVED_LABEL_PREFIX, w as TASK_LABEL, y as RemoteWatcherId } from "./schemas-TeVe4Udh.mjs";
3
+ import { A as Ref, B as SyncBody, C as InboxQuery, D as MessagesQuery, E as MatchesQuery, F as ScheduleBody, G as TaskNeedsBody, H as SyncFindQuery, I as SchedulesQuery, J as TypingBody, K as TasksQuery, L as SchemaBody, M as ReleaseTaskBody, N as RenewTaskBody, O as PostBody, P as RevokeGrantBody, R as SourceJoinBody, S as InboxPushBody, T as LinkedQuery, U as SyncImportBody, V as SyncCopiesQuery, W as SyncReceiptBody, X as UploadStartBody, Y as UpdateGrantBody, Z as routes, _ as FailTaskBody, a as ClaimReadyTaskBody, b as InboxAckBody, c as CreateChannelBody, d as CreateTasksBody, f as CreatedTasksQuery, g as ExplainQuery, h as EventsQuery, i as CancelTaskBody, j as RegisterBody, k as ReactBody, l as CreateGrantsBody, m as EditBody, n as AssignTaskBody, o as ClaimTaskBody, p as DeleteBody, q as ThreadsQuery, r as BlockTaskBody, s as CompleteTaskBody, t as AckBody, u as CreateTaskBody, w as LabelBody, x as InboxNextQuery, y as GrantBody, z as SourceReadQuery } from "./routes-qS92xz8U.mjs";
4
+ import { a as duplicateId, c as notFound, d as unauthorized, f as BoardError, h as eventsState, i as batchTooLarge, m as duration, n as RejectedError, o as forbidden, p as createBoardClient, r as badRequest, s as json, t as HttpError, u as toErrorResponse } from "./errors-DwV7I0g4.mjs";
5
+ import { _ as sha256, a as waitUntil, c as platformProfile, d as userIdOf, m as derivedId, o as actorParts, r as runMiddleware, s as importedHandle, t as DroppedError, u as underPrincipal } from "./middleware-ysFm2S4v.mjs";
5
6
  import { n as blocksIn, r as findBlocks } from "./blocks-CVoBC7ur.mjs";
6
7
  import { a as replaceMentions, i as mentionTerms, o as settleMentions, r as mentionTerm, t as extractMentions } from "./mentions-CnWt9Z5b.mjs";
7
- import { a as runMatch, d as openapi, f as queryObject, g as VERSION, h as SYNC, i as canonicalWatchers, l as METHODS, m as readJson, n as SYNC_ACTOR, o as compileWatcher, p as readCapped, r as syncTarget, t as batchPlan, u as createRouter } from "./task-batch-CmKvTLSu.mjs";
8
- import { a as canText, c as compileAccess, d as parsePattern, n as InvalidCan, r as PERMISSIONS, t as FULL_ACCESS, u as parseCan } from "./access-C06pIr0M.mjs";
9
- import { C as verifiesTokens, E as explainGrants, S as verifiedIssuers, d as createAuthority, f as fromTokens, m as hostPrincipal, o as VERCEL_ISSUER, p as grantIssuers, t as DEFAULT_CAN$1, v as namesByLogin } from "./auth-B9-wXQ-x.mjs";
10
- import { a as resolveActor, o as viaOf, r as claimsOf, t as KNOWN_AGENTS } from "./actors-Dkyg-oo0.mjs";
8
+ import { t as VERSION } from "./version-BCoWGLEW.mjs";
9
+ import { a as canText, c as compileAccess, d as parsePattern, n as InvalidCan, r as PERMISSIONS, t as FULL_ACCESS, u as parseCan } from "./access-B8DnrnHa.mjs";
10
+ import { a as runMatch, d as openapi, f as queryObject, h as SYNC, i as canonicalWatchers, l as METHODS, m as readJson, n as SYNC_ACTOR, o as compileWatcher, p as readCapped, r as syncTarget, t as batchPlan, u as createRouter } from "./task-batch-CujTLmTB.mjs";
11
+ import { C as verifiesTokens, E as explainGrants, S as verifiedIssuers, d as createAuthority, f as fromTokens, m as hostPrincipal, o as VERCEL_ISSUER, p as grantIssuers, t as DEFAULT_CAN$1, v as namesByLogin } from "./auth-CEU06Nyp.mjs";
12
+ import { a as resolveActor, o as viaOf, r as claimsOf, t as KNOWN_AGENTS } from "./actors-DewJKyqy.mjs";
11
13
  import { t as checkValue } from "./data-values-CoTP0SQG.mjs";
12
14
  //#region src/server/registrant.ts
13
15
  /** Registering again this soon after the same registration only repeats it. */
@@ -607,6 +609,8 @@ const API_CURSOR = /^c1\./;
607
609
  /** The API's longest page of a channel's messages, and longest long-poll, in seconds. */
608
610
  const PAGE_MAX = 100;
609
611
  const WAIT_MAX_S = 25;
612
+ /** The most threads a page of the API's thread list holds (`limit`): without it, 25. */
613
+ const THREAD_PAGE_MAX = 100;
610
614
  /** The most recent inbox events the API lists at once. */
611
615
  const INBOX_LIST_MAX = 100;
612
616
  /** The API's codes board()'s sync doesn't know: on sync's routes, each is answered as the board's code for its status. */
@@ -701,6 +705,24 @@ function retryWait(attempt, retryAfter) {
701
705
  const asked = retryAfter !== null && /^\d+$/.test(retryAfter) && Number(retryAfter) > 0 ? Number(retryAfter) * 1e3 : Infinity;
702
706
  return Math.min(asked, RETRY_MS * 2 ** attempt * (1 + Math.random()));
703
707
  }
708
+ /**
709
+ * A 429 the API still answered after `retries` tries again in `ms`: how many requests a minute it
710
+ * takes (`x-ratelimit-limit`), from whom, and when to send again. That's when its window resets
711
+ * (`x-ratelimit-reset`, in Unix seconds), or what `Retry-After` asks where it doesn't say.
712
+ */
713
+ function throttled(response, code, retries, ms) {
714
+ const header = (name) => {
715
+ const value = response.headers.get(name);
716
+ return value !== null && /^\d{1,12}$/.test(value) ? Number(value) : void 0;
717
+ };
718
+ const reset = header("x-ratelimit-reset");
719
+ const untilReset = reset !== void 0 ? reset - Math.floor(Date.now() / 1e3) : void 0;
720
+ const retryAfter = untilReset !== void 0 && untilReset > 0 && untilReset <= 3600 ? untilReset : header("retry-after");
721
+ const limit = header("x-ratelimit-limit");
722
+ const tried = retries > 0 ? `rate-limited ${retries + 1} tries in ${Math.max(1, Math.round(ms / 1e3))}s` : "rate-limited it";
723
+ const takes = limit !== void 0 ? `takes ${limit} requests a minute` : "limits requests";
724
+ return new HttpError(429, code, `Vercel's API ${tried}. It ${takes} per login or token, for all its agents and profiles together.`, { ...retryAfter !== void 0 ? { retryAfter } : {} });
725
+ }
704
726
  /** `ms` passing, or `signal` stopping it first. */
705
727
  const pause = (ms, signal) => ms <= 0 || signal?.aborted ? Promise.resolve() : new Promise((resolve) => {
706
728
  const timer = setTimeout(resolve, ms);
@@ -1027,6 +1049,7 @@ function createVercel(options, environment) {
1027
1049
  ...who.can !== void 0 ? { "x-board-can": who.can } : {}
1028
1050
  };
1029
1051
  const repeatable = method !== "POST" && method !== "PATCH" || typeof init.body?.operationId === "string";
1052
+ const started = Date.now();
1030
1053
  for (let attempt = 0;; attempt++) {
1031
1054
  let response;
1032
1055
  try {
@@ -1053,6 +1076,7 @@ function createVercel(options, environment) {
1053
1076
  continue;
1054
1077
  }
1055
1078
  const error = body?.error;
1079
+ if (response.status === 429) throw throttled(response, error?.code ?? "rate_limited", attempt, Date.now() - started);
1056
1080
  const refused = new HttpError(response.status, error?.code ?? "remote_error", error?.message ?? `Vercel's API answered ${response.status}`);
1057
1081
  if (typeof error?.reason === "string" && /^[a-z_]{1,64}$/.test(error.reason)) reasons.set(refused, error.reason);
1058
1082
  throw refused;
@@ -1171,6 +1195,30 @@ function createVercel(options, environment) {
1171
1195
  if (found) named.set(name, found);
1172
1196
  return found ?? null;
1173
1197
  }
1198
+ const inChannel = (channel) => channel.id !== void 0 ? { channelId: channel.id } : { channel: channel.name };
1199
+ /** Whether the API refused `error`'s request for a query parameter it doesn't know, `name`: an API from before it had one answers 400 and says which. */
1200
+ const unknownParameter = (error, name) => error instanceof HttpError && error.status === 400 && new RegExp(`additional property \\W?${name}\\b`, "i").test(error.message);
1201
+ /** Whether the API reads a channel by its name (`channel=`): until it refuses the parameter, it's asked. */
1202
+ let readsByName = true;
1203
+ /**
1204
+ * A read of the one channel `name` names, with the name itself: the API finds the channel, so the
1205
+ * read costs no lookup before it. An API from before `channel=` takes no parameter it doesn't know
1206
+ * and answers 400: the channel is looked up and read by its ID, as before, and it's never asked
1207
+ * again. Whatever else the API refuses the name with is looked up and read by its ID too, this
1208
+ * once, so it answers as it did before names: a name it finds nothing for or won't show the caller
1209
+ * (404, 403) is null when the lookup finds none either, and any other 400 but a cursor's is the
1210
+ * read's own by its ID.
1211
+ */
1212
+ async function inNamed(who, name, read) {
1213
+ if (readsByName && !named.has(name)) try {
1214
+ return await read({ name });
1215
+ } catch (error) {
1216
+ if (unknownParameter(error, "channel")) readsByName = false;
1217
+ else if (!(error instanceof HttpError && (error.code === "channel_not_found" || error.status === 403 || error.status === 400 && error.code !== "invalid_cursor"))) throw error;
1218
+ }
1219
+ const channel = await channelNamed(who, name);
1220
+ return channel ? read(channel) : null;
1221
+ }
1174
1222
  /** Channels' names by ID, as posts without a client ID named them: a post's own channel, which it may not be able to list. */
1175
1223
  const posted = /* @__PURE__ */ new Map();
1176
1224
  /**
@@ -1179,6 +1227,17 @@ function createVercel(options, environment) {
1179
1227
  * already read answers first, and one the API won't show by ID is looked for in the list, as before.
1180
1228
  */
1181
1229
  const byChannelId = /* @__PURE__ */ new Map();
1230
+ /** A channel an answer named by both its ID and its name: nothing in this process asks for it again. */
1231
+ const learn = ({ id, name }) => {
1232
+ named.set(name, {
1233
+ id,
1234
+ name
1235
+ });
1236
+ byChannelId.set(id, Promise.resolve({
1237
+ id,
1238
+ name
1239
+ }));
1240
+ };
1182
1241
  async function channelById(who, id) {
1183
1242
  const listed = channels ? (await loadChannels(who)).find((channel) => channel.id === id) : void 0;
1184
1243
  if (listed) return listed;
@@ -1239,17 +1298,41 @@ function createVercel(options, environment) {
1239
1298
  const path = filter.slice(0, -1);
1240
1299
  return listed.filter((channel) => channel.name === path || channel.name.startsWith(filter));
1241
1300
  }
1242
- async function messageById(who, id, signal) {
1301
+ async function messageById(who, id, signal, include) {
1243
1302
  if (!locate(id)) throw notFound(`message not found: ${id}`, "message_not_found");
1244
1303
  try {
1245
- return await api(who, "GET", await onBoard(who, `/messages/${encodeURIComponent(id)}`), signal ? { signal } : {});
1304
+ return await reading(who, await onBoard(who, `/messages/${encodeURIComponent(id)}`), {
1305
+ ...include ? { query: { include } } : {},
1306
+ ...signal ? { signal } : {}
1307
+ });
1246
1308
  } catch (error) {
1247
1309
  if (error instanceof HttpError && error.code === "thread_not_found") throw notFound(`message not found: ${id}`, "message_not_found");
1248
1310
  throw error;
1249
1311
  }
1250
1312
  }
1251
- /** A message, and its channel. */
1313
+ /** Whether the API answers a message with its channel (`include=channel`): until it refuses the parameter, it's asked. */
1314
+ let messagesWithChannel = true;
1315
+ /**
1316
+ * A message, and its channel, which the API answers with it, so naming it costs no request of its
1317
+ * own. An API from before `include=channel` takes no parameter it doesn't know and answers 400: the
1318
+ * channel is asked for by its ID, as before, and it's never asked with the message again. Any other
1319
+ * 400 or 403 for the two together reads them apart this once.
1320
+ */
1252
1321
  async function messageIn(who, id, signal) {
1322
+ if (messagesWithChannel) try {
1323
+ const { channel, ...found } = await messageById(who, id, signal, "channel");
1324
+ if (channel) learn(channel);
1325
+ return {
1326
+ ...found,
1327
+ channel: channel ? {
1328
+ id: channel.id,
1329
+ name: channel.name
1330
+ } : await channelById(who, found.thread.channelId)
1331
+ };
1332
+ } catch (error) {
1333
+ if (unknownParameter(error, "include")) messagesWithChannel = false;
1334
+ else if (!(error instanceof HttpError && (error.status === 400 || error.status === 403))) throw error;
1335
+ }
1253
1336
  const found = await messageById(who, id, signal);
1254
1337
  return {
1255
1338
  ...found,
@@ -1277,7 +1360,20 @@ function createVercel(options, environment) {
1277
1360
  };
1278
1361
  /** A message's labels: a deleted message keeps none, though the API still holds them. */
1279
1362
  const labelsOf = (message) => message.deletedAt === void 0 ? { ...message.labels } : {};
1280
- const threadMessages = async (who, threadId, signal) => all(who, await onBoard(who, `/threads/${encodeURIComponent(threadId)}/messages`), "messages", {}, signal);
1363
+ const threadMessages = async (who, threadId, signal) => {
1364
+ const path = await onBoard(who, `/threads/${encodeURIComponent(threadId)}/messages`);
1365
+ const messages = [];
1366
+ let cursor;
1367
+ do {
1368
+ const page = await reading(who, path, {
1369
+ query: { cursor },
1370
+ ...signal ? { signal } : {}
1371
+ });
1372
+ messages.push(...page.messages);
1373
+ cursor = page.cursor ?? void 0;
1374
+ } while (cursor);
1375
+ return messages;
1376
+ };
1281
1377
  /** Who reacted with each emoji. The API counts them on the message and lists them apart. */
1282
1378
  async function reactors(who, message) {
1283
1379
  if (!message.reactions || Object.keys(message.reactions).length === 0) return {};
@@ -1354,6 +1450,87 @@ function createVercel(options, environment) {
1354
1450
  const naming = (who, actors) => {
1355
1451
  if (namesById) for (const actor of actors) byId(who, actor.id);
1356
1452
  };
1453
+ /** Everyone a read's answer names, the actors the API answers with it when asked. */
1454
+ const namedIn = (read) => [
1455
+ ...(read.threads ?? (read.thread ? [read.thread] : [])).flatMap((thread) => [thread.createdBy, ...[
1456
+ thread.lastMessage,
1457
+ thread.rootMessage,
1458
+ thread.latestMessage
1459
+ ].flatMap((message) => message ? [message.createdBy] : [])]),
1460
+ ...(read.messages ?? (read.message ? [read.message] : [])).map((message) => message.createdBy),
1461
+ ...(read.events ?? []).flatMap((change) => [change.actor, ...change.currentMessage ? [change.currentMessage.createdBy] : []])
1462
+ ];
1463
+ /** Whether the API answers a read's actors with it (`with=actors`): unknown until a read with the parameter is answered, and false once one is refused it. */
1464
+ let actorsWithReads;
1465
+ /** The first read that asks for them, while it's out: reads that start meanwhile wait for its answer, so an API that refuses the parameter refuses it once. */
1466
+ let askingActors = null;
1467
+ /** `waited`, or the signal's reason as soon as it stops: a read that waits on another's answer stops when its own caller does. */
1468
+ async function stoppable(waited, signal) {
1469
+ if (!signal) return waited;
1470
+ signal.throwIfAborted();
1471
+ let stop = () => {};
1472
+ try {
1473
+ await Promise.race([waited, new Promise((_, reject) => {
1474
+ stop = () => reject(signal.reason);
1475
+ signal.addEventListener("abort", stop, { once: true });
1476
+ })]);
1477
+ } finally {
1478
+ signal.removeEventListener("abort", stop);
1479
+ }
1480
+ }
1481
+ /**
1482
+ * A read of threads, messages, or changes, with the actors it names where the API sends them, so naming
1483
+ * them costs no request of its own: they're kept as if each had been asked for by ID, one the API left out
1484
+ * as one it doesn't have. An API from before `with=actors` takes no parameter it doesn't know and answers
1485
+ * 400: the read is made again without it, and it's never asked again. Reads that go out together, one a
1486
+ * channel, wait for the first of them to learn which API this is. A long-poll holds nobody: it may take its
1487
+ * whole wait to answer.
1488
+ */
1489
+ async function reading(who, path, init = {}) {
1490
+ if (!namesById) return api(who, "GET", path, init);
1491
+ while (actorsWithReads === void 0 && askingActors) await stoppable(askingActors, init.signal);
1492
+ if (actorsWithReads === false) return api(who, "GET", path, init);
1493
+ let answered = () => {};
1494
+ if (actorsWithReads === void 0 && init.query?.wait === void 0) {
1495
+ const first = new Promise((resolve) => {
1496
+ answered = () => {
1497
+ if (askingActors === first) askingActors = null;
1498
+ resolve();
1499
+ };
1500
+ });
1501
+ askingActors = first;
1502
+ }
1503
+ let read;
1504
+ try {
1505
+ read = await api(who, "GET", path, {
1506
+ ...init,
1507
+ query: {
1508
+ ...init.query,
1509
+ with: "actors"
1510
+ }
1511
+ });
1512
+ actorsWithReads = true;
1513
+ } catch (error) {
1514
+ if (!(error instanceof HttpError && error.status === 400 && /additional property\W*with\b/i.test(error.message))) throw error;
1515
+ actorsWithReads = false;
1516
+ return api(who, "GET", path, init);
1517
+ } finally {
1518
+ answered();
1519
+ }
1520
+ if (!read.actors) return read;
1521
+ const views = new Map(read.actors.map((view) => [view.id, view]));
1522
+ const { asked } = namesOf(who);
1523
+ const at = Date.now();
1524
+ if (asked.size >= 1e4) asked.clear();
1525
+ for (const { id } of namedIn(read)) {
1526
+ const view = views.get(id);
1527
+ if (view || !asked.has(id) || at - asked.get(id).at > NAMES_FRESH_MS) asked.set(id, {
1528
+ at,
1529
+ view: Promise.resolve(view)
1530
+ });
1531
+ }
1532
+ return read;
1533
+ }
1357
1534
  /**
1358
1535
  * An actor as the API names them, asked for by ID with everyone else named in the same turn: the
1359
1536
  * authors on a page cost one request however many actors the board has. Undefined for one the API
@@ -1627,15 +1804,19 @@ function createVercel(options, environment) {
1627
1804
  }
1628
1805
  /** Each channel's feed now, taken before a read, so what's posted while it reads comes after. */
1629
1806
  async function heads(who, listed) {
1630
- const path = await onBoard(who, "/changes");
1631
- const found = await Promise.all(listed.map((channel) => api(who, "GET", path, { query: {
1632
- channelId: channel.id,
1807
+ const found = await Promise.all(listed.map((channel) => head(who, channel)));
1808
+ return Object.fromEntries(listed.map((channel, i) => [channel.id, found[i]]));
1809
+ }
1810
+ /** One channel's feed now. */
1811
+ async function head(who, channel) {
1812
+ const { cursor } = await api(who, "GET", await onBoard(who, "/changes"), { query: {
1813
+ ...inChannel(channel),
1633
1814
  from: "latest"
1634
- } })));
1635
- return Object.fromEntries(listed.map((channel, i) => [channel.id, {
1636
- at: found[i].cursor,
1815
+ } });
1816
+ return {
1817
+ at: cursor,
1637
1818
  skip: 0
1638
- }]));
1819
+ };
1639
1820
  }
1640
1821
  /**
1641
1822
  * Who `--by` names: `me`, the actor itself; or an actor, a principal and its agents, a profile, or
@@ -1737,7 +1918,8 @@ function createVercel(options, environment) {
1737
1918
  const page = await threadPage(who, path, {
1738
1919
  channelId: channel.id,
1739
1920
  label,
1740
- cursor
1921
+ cursor,
1922
+ limit: THREAD_PAGE_MAX
1741
1923
  }, signal);
1742
1924
  out.push(...page.threads);
1743
1925
  cursor = page.cursor ?? void 0;
@@ -1758,28 +1940,52 @@ function createVercel(options, environment) {
1758
1940
  }
1759
1941
  /** Whether the API lists threads with their first and newest messages (`include=messages`): until it refuses the parameter, it's asked. */
1760
1942
  let threadsWithMessages = true;
1943
+ /** Whether the API takes how many threads a page holds (`limit`): until it refuses the parameter, it's asked. */
1944
+ let threadsByLimit = true;
1945
+ /** Whether a page of threads was answered, so what the thread list takes is known: until one is, reads of it wait for the first. */
1946
+ let threadListKnown = false;
1947
+ /** The first read of the thread list, while it's out: reads that start meanwhile wait for its answer, so an API that refuses a parameter refuses it once. */
1948
+ let askingThreads = null;
1761
1949
  /**
1762
1950
  * A page of a channel's threads, each with its first and newest message where the API sends them, so
1763
- * showing them costs no read of its own. An API from before `include=messages` takes no parameter
1764
- * it doesn't know and answers 400: the page is read again without it, and it's never asked again.
1951
+ * showing them costs no read of its own, and `limit` of them where the API takes it, so a long list
1952
+ * costs a request per 100 threads and not per 25. An API from before either takes no parameter it
1953
+ * doesn't know and answers 400 naming it: the page is read again without that one, and it's never
1954
+ * asked again. Reads that go out together, one a channel, wait for the first to learn which API this is.
1765
1955
  */
1766
1956
  async function threadPage(who, path, query, signal) {
1767
- if (threadsWithMessages) try {
1768
- return await api(who, "GET", path, {
1769
- query: {
1770
- ...query,
1771
- include: "messages"
1772
- },
1773
- signal
1957
+ while (!threadListKnown && askingThreads) await stoppable(askingThreads, signal);
1958
+ let answered = () => {};
1959
+ if (!threadListKnown) {
1960
+ const first = new Promise((resolve) => {
1961
+ answered = () => {
1962
+ if (askingThreads === first) askingThreads = null;
1963
+ resolve();
1964
+ };
1774
1965
  });
1775
- } catch (error) {
1776
- if (!(error instanceof HttpError && error.status === 400 && /additional property/i.test(error.message))) throw error;
1777
- threadsWithMessages = false;
1966
+ askingThreads = first;
1967
+ }
1968
+ const { limit, ...rest } = query;
1969
+ try {
1970
+ for (;;) try {
1971
+ const page = await reading(who, path, {
1972
+ query: {
1973
+ ...rest,
1974
+ ...threadsWithMessages ? { include: "messages" } : {},
1975
+ ...threadsByLimit ? { limit: String(limit) } : {}
1976
+ },
1977
+ signal
1978
+ });
1979
+ threadListKnown = true;
1980
+ return page;
1981
+ } catch (error) {
1982
+ if (threadsWithMessages && unknownParameter(error, "include")) threadsWithMessages = false;
1983
+ else if (threadsByLimit && unknownParameter(error, "limit")) threadsByLimit = false;
1984
+ else throw error;
1985
+ }
1986
+ } finally {
1987
+ answered();
1778
1988
  }
1779
- return api(who, "GET", path, {
1780
- query,
1781
- signal
1782
- });
1783
1989
  }
1784
1990
  /**
1785
1991
  * A channel's threads, as far as a read needs: the API lists them most recently active first, so
@@ -1792,10 +1998,12 @@ function createVercel(options, environment) {
1792
1998
  const out = [];
1793
1999
  let cursor;
1794
2000
  do {
2001
+ const wanted = label === void 0 && page.after === void 0 && page.limit !== void 0 ? page.limit - out.length : THREAD_PAGE_MAX;
1795
2002
  const found = await threadPage(who, path, {
1796
2003
  channelId: channel.id,
1797
2004
  label,
1798
- cursor
2005
+ cursor,
2006
+ limit: Math.min(wanted, THREAD_PAGE_MAX)
1799
2007
  }, signal);
1800
2008
  out.push(...found.threads);
1801
2009
  cursor = found.cursor ?? void 0;
@@ -1820,7 +2028,7 @@ function createVercel(options, environment) {
1820
2028
  } catch {
1821
2029
  throw refused;
1822
2030
  }
1823
- if (typeof scope !== "string" || !scope.split("#").includes(channel.id)) throw refused;
2031
+ if (typeof scope !== "string" || channel.id !== void 0 && !scope.split("#").includes(channel.id)) throw refused;
1824
2032
  }
1825
2033
  return {
1826
2034
  cursor: found[1] || void 0,
@@ -1842,9 +2050,10 @@ function createVercel(options, environment) {
1842
2050
  const out = [];
1843
2051
  do {
1844
2052
  const found = await threadPage(who, path, {
1845
- channelId: channel.id,
2053
+ ...inChannel(channel),
1846
2054
  label: void 0,
1847
- cursor
2055
+ cursor,
2056
+ limit: Math.min(skip + limit - out.length, THREAD_PAGE_MAX)
1848
2057
  }, signal).catch((error) => {
1849
2058
  if (error instanceof HttpError && error.status === 400 && error.code === "invalid_cursor") throw new HttpError(400, "invalid_cursor", `before isn't a page of #${channel.name}'s threads: pass a page's older as it came`);
1850
2059
  throw error;
@@ -2008,7 +2217,7 @@ function createVercel(options, environment) {
2008
2217
  const asked = Math.min(limit, PAGE_MAX);
2009
2218
  const pages = await Promise.all(listed.map(async (channel) => ({
2010
2219
  channel,
2011
- ...await api(who, "GET", path, {
2220
+ ...await reading(who, path, {
2012
2221
  query: {
2013
2222
  channelId: channel.id,
2014
2223
  limit: String(asked)
@@ -2128,7 +2337,7 @@ function createVercel(options, environment) {
2128
2337
  const path = await onBoard(who, "/changes");
2129
2338
  const pages = await Promise.all(listed.map(async (channel) => {
2130
2339
  const from = position.feeds[channel.id];
2131
- const page = await api(who, "GET", path, {
2340
+ const page = await reading(who, path, {
2132
2341
  query: {
2133
2342
  channelId: channel.id,
2134
2343
  include: "message",
@@ -2246,9 +2455,9 @@ function createVercel(options, environment) {
2246
2455
  const keep = async (message) => !narrowed || await matches(query, message, query.label?.length ? await thread(message.threadId) : { id: message.threadId }, narrow);
2247
2456
  const kept = [];
2248
2457
  if (query.after === void 0) {
2249
- const page = await api(who, "GET", path, {
2458
+ const page = await reading(who, path, {
2250
2459
  query: {
2251
- channelId: channel.id,
2460
+ ...inChannel(channel),
2252
2461
  limit: String(narrowed ? PAGE_MAX : Math.min(limit, PAGE_MAX))
2253
2462
  },
2254
2463
  signal
@@ -2261,9 +2470,9 @@ function createVercel(options, environment) {
2261
2470
  }
2262
2471
  let cursor = query.after;
2263
2472
  for (let pages = 0; pages < SCAN_PAGES && kept.length < limit; pages++) {
2264
- const page = await api(who, "GET", path, {
2473
+ const page = await reading(who, path, {
2265
2474
  query: {
2266
- channelId: channel.id,
2475
+ ...inChannel(channel),
2267
2476
  after: cursor,
2268
2477
  limit: String(Math.min(limit - kept.length, PAGE_MAX))
2269
2478
  },
@@ -2287,9 +2496,9 @@ function createVercel(options, environment) {
2287
2496
  let cursor = query.after;
2288
2497
  for (;;) {
2289
2498
  const wait = Math.min(WAIT_MAX_S, Math.max(0, Math.ceil((until - Date.now()) / 1e3)));
2290
- const page = await api(who, "GET", path, {
2499
+ const page = await reading(who, path, {
2291
2500
  query: {
2292
- channelId: channel.id,
2501
+ ...inChannel(channel),
2293
2502
  include: "message",
2294
2503
  ...cursor === void 0 ? { from: "latest" } : { cursor },
2295
2504
  ...wait > 0 ? { wait: String(wait) } : {}
@@ -2317,8 +2526,9 @@ function createVercel(options, environment) {
2317
2526
  }
2318
2527
  /** A read of the feed, as `vb tail` makes it: one channel's feed when it names one, or every channel's. */
2319
2528
  async function eventsAs(who, query, signal) {
2320
- const channel = await oneChannel(who, query);
2321
- if (channel) return channelEvents(who, channel, query, signal);
2529
+ const name = oneChannel(query);
2530
+ const found = name === null ? null : await inNamed(who, name, (channel) => channelEvents(who, channel, query, signal));
2531
+ if (found) return found;
2322
2532
  if (query.after !== void 0 && API_CURSOR.test(query.after)) throw new HttpError(400, "invalid_request", `after: ${query.after} is one channel's cursor: read that channel`);
2323
2533
  const listed = query.re === void 0 ? await channelsFor(who, query.channel) : await channelOfThread(who, query.re, query.channel, signal);
2324
2534
  let position = query.after === void 0 ? {
@@ -2353,12 +2563,11 @@ function createVercel(options, environment) {
2353
2563
  if (within !== void 0 && !(await channelsFor(who, within)).some((channel) => channel.id === found.channel.id)) return [];
2354
2564
  return [found.channel];
2355
2565
  }
2356
- /** The one channel a read names, when the API can read it directly: not a subtree, and from one of its cursors or now. */
2357
- async function oneChannel(who, query) {
2566
+ /** The one channel a read names, by its name, when the API can read it directly: not a subtree, and from one of its cursors or now. */
2567
+ function oneChannel(query) {
2358
2568
  if (query.channel === void 0 || query.channel.endsWith("/") || query.re !== void 0) return null;
2359
2569
  if (query.after !== void 0 && !API_CURSOR.test(query.after)) return null;
2360
- const [channel] = await channelsFor(who, query.channel);
2361
- return channel ?? null;
2570
+ return query.channel;
2362
2571
  }
2363
2572
  /** A watcher's tail registers with the API as its own: an API watcher, so a match is the API's to make. */
2364
2573
  const tagOf = async (watch, sync) => (await sha256(canonicalWatchers(watch, sync))).slice(0, 32);
@@ -2532,12 +2741,12 @@ function createVercel(options, environment) {
2532
2741
  }
2533
2742
  /** A match as vboard hands it out: its event as `vb tail --json` prints it, with its message as it is now. */
2534
2743
  async function matchOf(who, match, filters) {
2535
- const found = await messageById(who, match.event.messageId).catch((error) => {
2744
+ const found = await messageIn(who, match.event.messageId).catch((error) => {
2536
2745
  if (error instanceof HttpError && error.status === 404) return null;
2537
2746
  throw error;
2538
2747
  });
2539
- const channel = found && await channelById(who, found.thread.channelId);
2540
- if (!found || !channel) return null;
2748
+ if (!found) return null;
2749
+ const { channel } = found;
2541
2750
  const event = match.event.type === "thread.synced" ? await syncedOf(who, match, found.message, channel.name) : await eventOf(who, match.event, channel.name, match.id, filters, await narrowOf(who, filters), found);
2542
2751
  if (!event?.message) return null;
2543
2752
  const handed = match.watcher === "@sync" && event.type === "labels.changed" ? {
@@ -3165,14 +3374,12 @@ function createVercel(options, environment) {
3165
3374
  },
3166
3375
  async messages(caller, query, signal) {
3167
3376
  const who = whoOf(caller);
3168
- const channel = query.before === void 0 ? await oneChannel(who, query) : null;
3169
- if (channel) {
3170
- const page = await channelMessages(who, channel, query, signal);
3171
- return {
3172
- messages: await Promise.all(page.messages.map((message) => view(who, message, channel.name))),
3173
- cursor: page.cursor
3174
- };
3175
- }
3377
+ const name = query.before === void 0 ? oneChannel(query) : null;
3378
+ const direct = name === null ? null : await inNamed(who, name, (channel) => channelMessages(who, channel, query, signal));
3379
+ if (name !== null && direct) return {
3380
+ messages: await Promise.all(direct.messages.map((message) => view(who, message, name))),
3381
+ cursor: direct.cursor
3382
+ };
3176
3383
  if (query.after !== void 0 && API_CURSOR.test(query.after)) throw new HttpError(400, "invalid_request", `after: ${query.after} is one channel's cursor: read that channel`);
3177
3384
  const limit = query.limit ?? 50;
3178
3385
  if (query.re === void 0 && query.after === void 0 && query.before === void 0 && !filtered(query)) {
@@ -3208,21 +3415,41 @@ function createVercel(options, environment) {
3208
3415
  };
3209
3416
  const byMessage = query.re !== void 0 || query.by !== void 0 || query.mentions !== void 0 || query.text !== void 0 || query.from !== void 0;
3210
3417
  if (query.channel !== void 0 && !query.channel.endsWith("/") && !byMessage && !query.label?.length && after === void 0) {
3211
- const listed = await channelsFor(who, query.channel);
3212
- const feeds = await heads(who, listed);
3213
- const found = await Promise.all(listed.map((channel) => threadsBefore(who, channel, query.before, limit, signal)));
3214
- const page = listed.flatMap((channel, i) => found[i].threads.map((thread) => ({
3418
+ const name = query.channel;
3419
+ const read = await inNamed(who, name, async (channel) => {
3420
+ const feed = await head(who, channel);
3421
+ const found = await threadsBefore(who, channel, query.before, limit, signal);
3422
+ return {
3423
+ feed,
3424
+ found,
3425
+ id: channel.id ?? found.threads[0]?.channelId
3426
+ };
3427
+ });
3428
+ if (!read) return {
3429
+ threads: [],
3430
+ cursor: cursorOf({
3431
+ t: 0,
3432
+ feeds: {}
3433
+ }),
3434
+ older: null
3435
+ };
3436
+ if (read.id !== void 0) learn({
3437
+ id: read.id,
3438
+ name
3439
+ });
3440
+ const id = read.id ?? (await channelNamed(who, name))?.id;
3441
+ const page = read.found.threads.map((thread) => ({
3215
3442
  thread,
3216
- channel,
3443
+ channel: { name },
3217
3444
  at: thread.lastActivityAt
3218
- }))).reverse();
3445
+ })).reverse();
3219
3446
  return {
3220
3447
  threads: await summaries(who, page, signal),
3221
3448
  cursor: cursorOf({
3222
3449
  t: page.reduce((max, { at }) => Math.max(max, at), 0),
3223
- feeds
3450
+ feeds: id === void 0 ? {} : { [id]: read.feed }
3224
3451
  }),
3225
- older: found[0]?.older ?? null
3452
+ older: read.found.older
3226
3453
  };
3227
3454
  }
3228
3455
  if (query.before !== void 0) throw new HttpError(400, "invalid_request", "before: this board pages one channel's threads, with no filters");
@@ -3493,6 +3720,17 @@ function createVercel(options, environment) {
3493
3720
  }).catch(grantRefused);
3494
3721
  return { grant: grantFrom(grant) };
3495
3722
  },
3723
+ async createGrants(caller, input, signal) {
3724
+ const who = whoOf(caller);
3725
+ const { grants } = await api(who, "POST", await onBoard(who, "/grants/batch"), {
3726
+ body: {
3727
+ operationId: operationId(),
3728
+ ...input
3729
+ },
3730
+ ...signal ? { signal } : {}
3731
+ }).catch(grantRefused);
3732
+ return { grants: grants.map(grantFrom) };
3733
+ },
3496
3734
  async updateGrant(caller, { id, ...change }, signal) {
3497
3735
  const who = whoOf(caller);
3498
3736
  const { grant } = await api(who, "PATCH", await onBoard(who, `/grants/${encodeURIComponent(id)}`), {
@@ -3515,10 +3753,13 @@ function createVercel(options, environment) {
3515
3753
  grants: explained.grants.map(grantFrom)
3516
3754
  };
3517
3755
  },
3518
- async revokeGrant(caller, { id }, signal) {
3756
+ async revokeGrant(caller, { id, ...options }, signal) {
3519
3757
  const who = whoOf(caller);
3520
3758
  return api(who, "POST", await onBoard(who, `/grants/${encodeURIComponent(id)}/revoke`), {
3521
- body: { operationId: operationId() },
3759
+ body: {
3760
+ operationId: operationId(),
3761
+ ...options
3762
+ },
3522
3763
  ...signal ? { signal } : {}
3523
3764
  });
3524
3765
  },
@@ -3586,15 +3827,24 @@ function createVercel(options, environment) {
3586
3827
  if (!found) return { schedules: [] };
3587
3828
  filter.threadId = found.thread.id;
3588
3829
  }
3589
- if (query.channel !== void 0) {
3590
- const channel = await channelNamed(who, query.channel);
3591
- if (!channel) return { schedules: [] };
3592
- filter.channelId = channel.id;
3593
- }
3594
3830
  if (query.by?.startsWith("vercel:")) filter.createdBy = query.by;
3831
+ if (query.by === "me") filter.createdBy = await actorOf(who);
3595
3832
  const by = await byOf(who, query.by);
3596
3833
  const created = (actor) => by === void 0 || by(actor);
3597
- const listed = await all(who, await onBoard(who, "/schedules"), "schedules", filter, signal);
3834
+ const path = await onBoard(who, "/schedules");
3835
+ const name = query.channel;
3836
+ const listed = name === void 0 ? await all(who, path, "schedules", filter, signal) : await inNamed(who, name, async (channel) => {
3837
+ const found = await all(who, path, "schedules", {
3838
+ ...filter,
3839
+ ...inChannel(channel)
3840
+ }, signal);
3841
+ if (found[0]) learn({
3842
+ id: found[0].channelId,
3843
+ name
3844
+ });
3845
+ return found;
3846
+ });
3847
+ if (!listed) return { schedules: [] };
3598
3848
  return { schedules: await Promise.all(listed.filter((schedule) => created(schedule.createdBy)).map((schedule) => scheduleView(who, schedule))) };
3599
3849
  },
3600
3850
  async cancelSchedule(caller, { id }, signal) {
@@ -4541,7 +4791,6 @@ async function inputOf(name, request, url, params) {
4541
4791
  case "cancelSchedule":
4542
4792
  case "unblockTask":
4543
4793
  case "reopenTask":
4544
- case "revokeGrant":
4545
4794
  case "schema":
4546
4795
  case "attachment":
4547
4796
  case "uploadFinish": return { id };
@@ -4608,10 +4857,15 @@ async function inputOf(name, request, url, params) {
4608
4857
  ...CancelTaskBody.parse(await body())
4609
4858
  };
4610
4859
  case "createGrant": return GrantBody.parse(await body());
4860
+ case "createGrants": return CreateGrantsBody.parse(await body());
4611
4861
  case "updateGrant": return {
4612
4862
  id,
4613
4863
  ...UpdateGrantBody.parse(await body())
4614
4864
  };
4865
+ case "revokeGrant": return {
4866
+ id,
4867
+ ...RevokeGrantBody.parse(await body()) ?? {}
4868
+ };
4615
4869
  case "explain": return ExplainQuery.parse(queryObject(url));
4616
4870
  case "createSchema": return SchemaBody.parse(await body());
4617
4871
  case "register": return RegisterBody.parse(await body());