@vercel/board 0.38.0 → 0.40.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 (85) hide show
  1. package/README.md +5 -3
  2. package/dist/{access-CVkjSfxj.mjs → access-Bl_k_Hpa.mjs} +1 -1
  3. package/dist/access.d.mts +2 -2
  4. package/dist/access.mjs +4 -4
  5. package/dist/{actors-kfMejhaw.mjs → actors-yBRWTpt5.mjs} +38 -53
  6. package/dist/{auth-B3bBYOqf.mjs → auth-C8URZHLx.mjs} +2 -2
  7. package/dist/{auth-BXLCkeB0.d.mts → auth-DtmZzlHm.d.mts} +5 -2
  8. package/dist/{backend-BkQlF1LQ.d.mts → backend-BW5NbBsp.d.mts} +37 -11
  9. package/dist/backend-local.d.mts +1 -1
  10. package/dist/backend-local.mjs +1 -1
  11. package/dist/blocks-CVoBC7ur.mjs +402 -0
  12. package/dist/blocks-DGvh2alZ.d.mts +33 -0
  13. package/dist/{chat-provider-DyNy5xdC.d.mts → chat-provider-Bbb9JguG.d.mts} +2 -2
  14. package/dist/cli-commands.d.mts +1 -1
  15. package/dist/cli-commands.mjs +1 -1
  16. package/dist/cli-embedded.d.mts +2 -2
  17. package/dist/cli-embedded.mjs +3 -3
  18. package/dist/cli.mjs +5 -5
  19. package/dist/{commands-B5d-lmNN.d.mts → commands-BJLocuXj.d.mts} +10 -0
  20. package/dist/{commands-BLS7erNu.mjs → commands-D6VWegVY.mjs} +88 -8
  21. package/dist/{conformance-qJF96jZI.mjs → conformance-BWhZ0k8T.mjs} +256 -13
  22. package/dist/conformance.d.mts +4 -3
  23. package/dist/conformance.mjs +1 -1
  24. package/dist/data-values-C-Cq80hz.mjs +176 -0
  25. package/dist/digest-D32GV_mX.mjs +4 -0
  26. package/dist/{engine-eUgO5jTM.mjs → engine-Djif8XVk.mjs} +191 -77
  27. package/dist/{errors-rYDxZEuN.mjs → errors-CNRJqUuL.mjs} +16 -14
  28. package/dist/{exports-BsfcChdp.mjs → exports-C2OWIbLU.mjs} +639 -258
  29. package/dist/exports-FyRBIAMs.d.mts +4 -0
  30. package/dist/{index-DpVyZa9b.d.mts → index-Cuxbz_E0.d.mts} +2 -2
  31. package/dist/index.d.mts +7 -6
  32. package/dist/index.mjs +6 -5
  33. package/dist/index.node.d.mts +7 -6
  34. package/dist/index.node.mjs +5 -4
  35. package/dist/inspect/app.js +110 -109
  36. package/dist/inspect/engine.js +5 -5
  37. package/dist/inspect-CLy6FrOZ.mjs +2 -0
  38. package/dist/{inspect-DtCbBtOW.mjs → inspect-cGcP8ZO9.mjs} +4 -4
  39. package/dist/{local-Bo3XzEKB.mjs → local-CsleYuyM.mjs} +664 -752
  40. package/dist/{main-0nvLgajF.mjs → main-D97xuqWZ.mjs} +177 -59
  41. package/dist/{memory-DkoqhxIH.mjs → memory-BvVoglGv.mjs} +2 -2
  42. package/dist/{mentions-CB6ShY4R.mjs → mentions-CT2bN5eP.mjs} +17 -3
  43. package/dist/{middleware-CPqAuRtp.mjs → middleware-BF9vnPPS.mjs} +70 -2
  44. package/dist/{targets-B4Uikw0J.mjs → origin-DLCmrwmE.mjs} +47 -39
  45. package/dist/{page-UsfvSIWc.mjs → page-6BTCZWGY.mjs} +2 -2
  46. package/dist/page-BnY8FhPn.mjs +2 -0
  47. package/dist/{provider-D5yVFisj.d.mts → provider-YqkF1E2k.d.mts} +23 -13
  48. package/dist/{routes-BffuaoTX.d.mts → routes-CAjd5ARa.d.mts} +101 -25
  49. package/dist/schemas.d.mts +37 -0
  50. package/dist/schemas.mjs +3 -0
  51. package/dist/{serve-D7I3KisQ.mjs → serve-Cs-e0Jke.mjs} +4 -4
  52. package/dist/{server-Cc3nYq3H.mjs → server-CIfMdIt3.mjs} +43 -98
  53. package/dist/{serving-DJMcG0dT.mjs → serving-B4l0nLng.mjs} +1 -1
  54. package/dist/{sql-l3ysn4O5.mjs → sql-Bv-RQu8n.mjs} +73 -10
  55. package/dist/{sqlite-CAwNHbQD.mjs → sqlite-D4mkYihG.mjs} +2 -2
  56. package/dist/{sqlite-db-cm5yhrD-.mjs → sqlite-db-BraLvHtf.mjs} +1 -1
  57. package/dist/sync-chat-sdk.d.mts +2 -2
  58. package/dist/sync-github.d.mts +2 -2
  59. package/dist/sync-linear.d.mts +3 -3
  60. package/dist/sync-slack.d.mts +14 -8
  61. package/dist/sync-slack.mjs +42 -15
  62. package/dist/sync.d.mts +2 -2
  63. package/dist/{tokens-DA9ipsZ-.mjs → tokens-CrrXAVGz.mjs} +2 -2
  64. package/docs/01-board/01-mounting.md +7 -5
  65. package/docs/01-board/03-identity.md +71 -39
  66. package/docs/01-board/04-messages.md +58 -1
  67. package/docs/01-board/05-reading.md +3 -3
  68. package/docs/01-board/06-watchers.md +10 -14
  69. package/docs/01-board/07-schedules.md +2 -4
  70. package/docs/01-board/08-middleware.md +1 -1
  71. package/docs/01-board/09-access.md +25 -22
  72. package/docs/02-sync/01-overview.md +72 -7
  73. package/docs/02-sync/02-functions.md +11 -6
  74. package/docs/02-sync/03-slack.md +40 -16
  75. package/docs/02-sync/06-providers.md +9 -4
  76. package/docs/04-reference/01-cli.md +110 -18
  77. package/docs/04-reference/02-board.md +63 -10
  78. package/docs/04-reference/03-http.md +157 -31
  79. package/docs/04-reference/05-conformance.md +13 -6
  80. package/docs/index.md +1 -1
  81. package/package.json +5 -1
  82. package/dist/digest-DAxy9Ula.mjs +0 -4
  83. package/dist/exports-BJ3wmEMY.d.mts +0 -4
  84. package/dist/inspect-5mkjJYMS.mjs +0 -2
  85. package/dist/page-R0RoE_gM.mjs +0 -2
@@ -1,8 +1,8 @@
1
- import { d as createBoardClient, o as json, t as HttpError, u as BoardError } from "./errors-rYDxZEuN.mjs";
1
+ import { d as createBoardClient, t as HttpError, u as BoardError } from "./errors-CNRJqUuL.mjs";
2
2
  import "./schemas-AZkxk06N.mjs";
3
- import { F as RegisterBody, X as routes, i as canonicalWatchers, l as METHODS, o as compileWatcher } from "./targets-B4Uikw0J.mjs";
4
- import { l as keyId, o as DERIVED_ID, u as sha256 } from "./middleware-CPqAuRtp.mjs";
5
- import { a as registrant, o as wakePath, r as createVercel, t as createBoard } from "./exports-BsfcChdp.mjs";
3
+ import { X as routes, a as compileWatcher, c as METHODS } from "./origin-DLCmrwmE.mjs";
4
+ import { g as keyId, p as DERIVED_ID } from "./middleware-BF9vnPPS.mjs";
5
+ import { a as tailWatchers, o as deployedOnVercel, r as createVercel, t as createBoard } from "./exports-C2OWIbLU.mjs";
6
6
  import { execFile } from "node:child_process";
7
7
  import { createHash } from "node:crypto";
8
8
  import { mkdir, readFile, readdir, stat, unlink, writeFile } from "node:fs/promises";
@@ -749,12 +749,8 @@ function createHttp(url, options, environment) {
749
749
  const remote = (url ?? environment.url()).replace(/\/+$/, "");
750
750
  const doFetch = options.fetch ?? environment?.fetch(remote) ?? ((input, init) => globalThis.fetch(input, init));
751
751
  let binding = null;
752
- const specs = {};
753
- /** This board's sync entries, registered there when it syncs. */
754
- let sync = [];
755
- let hash = null;
756
- /** What every wake-up carries, so the board it uses can tell it's stale. */
757
- const watchersHash = () => hash ??= sha256(canonicalWatchers(specs, sync)).then((hex) => hex.slice(0, 32));
752
+ /** This board's watchers, compiled: they run here, as tails of the board it uses. */
753
+ const tails = {};
758
754
  const bound = () => {
759
755
  if (!binding) throw new Error("http: this backend isn't serving a board yet: pass it to board({ backend })");
760
756
  return binding;
@@ -867,10 +863,9 @@ function createHttp(url, options, environment) {
867
863
  }
868
864
  /** A protocol method, called on the board it uses, as `caller`. */
869
865
  async function remoteCall(method, caller, input, signal) {
870
- const registering = start();
871
- if ("identity" in caller) throw new HttpError(404, "not_found", `this board uses ${remote}, and answers only wake-ups and webhooks`);
866
+ start();
867
+ if ("identity" in caller) throw new HttpError(404, "not_found", `this board uses ${remote}, and answers nothing itself`);
872
868
  const client = clientOf(caller);
873
- if ("self" in caller && caller.origin.via?.kind === "engine") await registering;
874
869
  if ((method === "post" || method === "posted") && "self" in caller && typeof input.id === "string" && DERIVED_ID.test(input.id)) input = {
875
870
  ...input,
876
871
  id: await ownKey(input.id).catch(rethrow)
@@ -882,104 +877,54 @@ function createHttp(url, options, environment) {
882
877
  ...Object.fromEntries(METHODS.map((method) => [method, (caller, input, signal) => remoteCall(method, caller, input, signal)])),
883
878
  async discovery() {
884
879
  return discovery();
885
- },
886
- async readSource(caller, input, signal) {
887
- if ("self" in caller && bound().sync.some((entry) => entry.key === input.key)) return bound().readSource(input.key, input.target, input.limit ?? 50, input.after ?? null);
888
- return remoteCall("readSource", caller, input, signal);
889
- },
890
- async joinSource(caller, input, signal) {
891
- if ("self" in caller && bound().sync.some((entry) => entry.key === input.key)) return bound().joinSource(input.key, input.target);
892
- return remoteCall("joinSource", caller, input, signal);
893
- },
894
- async synced(caller, input, signal) {
895
- const { targets } = await remoteCall("synced", caller, input, signal);
896
- return { targets: await Promise.all(targets.map(async (row) => ({
897
- ...row,
898
- url: row.url ?? (row.thread !== null && row.message !== null ? await bound().linkOf(row.key, row.thread, row.message) : null)
899
- }))) };
900
- },
901
- async linked(caller, input, signal) {
902
- const missing = () => new HttpError(404, "message_not_found", "no message on this board for that link");
903
- const first = async () => {
904
- for (const { platform, thread, message } of bound().locate(input.url)) for (const entry of bound().sync.filter((candidate) => candidate.platform === platform)) {
905
- const at = await own.syncFind({
906
- thread: `${entry.key}:${thread}`,
907
- ...message !== null ? { message } : {}
908
- }, { signal }).catch(rethrow);
909
- const found = message !== null ? at.message : at.thread === null ? null : (await own.syncThread(at.thread).catch(rethrow)).root;
910
- if (found !== null) return found;
911
- }
912
- return null;
913
- };
914
- const id = await first();
915
- if (id === null) return remoteCall("linked", caller, input, signal);
916
- try {
917
- return await methods.message(caller, { id }, signal);
918
- } catch (error) {
919
- if (error instanceof HttpError && error.status === 404) throw missing();
920
- throw error;
921
- }
922
- },
923
- async typing(caller, input, signal) {
924
- const { targets } = await remoteCall("typing", caller, input, signal);
925
- if (!("self" in caller) || bound().sync.length === 0) return { targets };
926
- const { message, replies } = await methods.message(caller, { id: input.id }, signal);
927
- const here = await bound().typing([message, ...replies], input.status).catch((error) => {
928
- console.warn("[board] skipped typing where this board syncs:", describe(error));
929
- return [];
930
- });
931
- return { targets: [...targets, ...here] };
932
880
  }
933
881
  };
882
+ let running = null;
883
+ /** Whether they won't run, or won't again: on Vercel, or once closed. */
884
+ let stopped = false;
934
885
  /**
935
- * Where the remote wakes this board: on a board that wakes by path, the path on this project,
936
- * which gets through its Deployment Protection (`wakePath`); anywhere else, its URL.
886
+ * On first use, this board's watchers start following the board it uses, in this process, as
887
+ * `vb tail` does. Nothing wakes a board on http(). A deployment's function doesn't outlive its
888
+ * request, so on Vercel none run.
937
889
  */
938
- async function wakeAt(here) {
939
- const path = wakePath(here);
940
- return path && (await discovery()).wake_by_path ? path : { url: here };
890
+ function start() {
891
+ if (running || stopped || Object.keys(tails).length === 0) return;
892
+ if (deployedOnVercel()) {
893
+ stopped = true;
894
+ console.error(`[board] watchers on a board that uses ${remote} run only in a process that stays up: on Vercel, none run`);
895
+ return;
896
+ }
897
+ running = tailWatchers({
898
+ watchers: tails,
899
+ events: async (query, signal) => (await call(own, "events", query, signal)).json(),
900
+ actorOf: async (id) => (await asProfile(id).me().catch(rethrow)).actor,
901
+ run: (id, event, meta) => bound().run(id, event, meta)
902
+ });
903
+ running.start();
941
904
  }
942
- const runner = registrant({
943
- remote,
944
- registry: {
945
- register: (where) => own.register({
946
- ...where,
947
- watch: specs,
948
- ...sync.length > 0 ? { sync } : {}
949
- }),
950
- matches: (query) => own.matches(query),
951
- ack: (id, body) => own.ack(id, body)
952
- },
953
- wakeAt,
954
- binding: bound,
955
- hash: watchersHash,
956
- hasWork: () => Object.keys(specs).length > 0 || sync.length > 0,
957
- rethrow,
958
- registerFor: async (caller, request) => json(await methods.register(caller, RegisterBody.parse(await request.json()), request.signal))
959
- });
960
- const start = runner.start;
961
905
  return {
962
906
  ...methods,
963
- routes: runner.routes,
907
+ routes: [],
964
908
  keeps: false,
965
909
  bind(next) {
966
910
  if (binding) throw new Error("http: this backend already serves a board: create one http() per board()");
967
911
  for (const [id, spec] of Object.entries(next.subscriptions)) {
968
- if (spec.kind === "sync") {
969
- if (id === "@sync") sync = next.sync.map((entry) => ({ ...entry }));
970
- continue;
971
- }
912
+ if (spec.kind === "sync") throw new Error(`http: sync doesn't run on a board that uses ${remote}: sync from that board's own config`);
972
913
  if (!PROFILE.test(id)) throw new Error(`watch ${id}: ${PROFILE_RULE}`);
973
- compileWatcher(id, spec);
974
- specs[id] = { tail: spec.tail };
914
+ const { filters, all } = compileWatcher(id, spec);
915
+ tails[id] = {
916
+ filters,
917
+ all
918
+ };
975
919
  }
976
- hash = null;
977
920
  binding = next;
978
921
  },
979
- /** Registers this board's watchers with the board it uses now, as `POST /watchers` does. */
980
- registerWatchers: runner.registerNow,
981
- /** Stops pulling, for a board that pulls on its own. */
982
- close: runner.close
922
+ /** Stops its watchers' tails. */
923
+ close: () => {
924
+ stopped = true;
925
+ running?.close();
926
+ running = null;
927
+ }
983
928
  };
984
929
  }
985
930
  //#endregion
@@ -1097,8 +1042,8 @@ function vercel(options = {}) {
1097
1042
  function board(options = {}) {
1098
1043
  return createBoard(options, {
1099
1044
  backend: (fetch) => process.env.BOARD_URL?.trim() ? http() : vercel(fetch ? { fetch } : {}),
1100
- sync: () => import("./engine-eUgO5jTM.mjs"),
1101
- serving: () => import("./serving-DJMcG0dT.mjs")
1045
+ sync: () => import("./engine-Djif8XVk.mjs"),
1046
+ serving: () => import("./serving-B4l0nLng.mjs")
1102
1047
  });
1103
1048
  }
1104
1049
  //#endregion
@@ -1,2 +1,2 @@
1
- import { i as ownTeamId, n as discoveryIdentity, r as ownProjectId, t as oidcTokens } from "./tokens-DA9ipsZ-.mjs";
1
+ import { i as ownTeamId, n as discoveryIdentity, r as ownProjectId, t as oidcTokens } from "./tokens-CrrXAVGz.mjs";
2
2
  export { discoveryIdentity, oidcTokens, ownProjectId, ownTeamId };
@@ -2,6 +2,7 @@ import { _ as actorKind } from "./schemas-AZkxk06N.mjs";
2
2
  import { c as externalMessageKey, l as isThreadTarget } from "./external-CHDxWIVf.mjs";
3
3
  import { t as canonicalEmoji } from "./emoji-CTLpvH-A.mjs";
4
4
  import { n as setOwn, t as own } from "./own-OwgPWdmh.mjs";
5
+ import { i as mentionTerms } from "./mentions-CT2bN5eP.mjs";
5
6
  //#region src/contract/folds.ts
6
7
  const iso = (date) => typeof date === "string" ? date : date.toISOString();
7
8
  function foldMessages(state, event) {
@@ -24,7 +25,6 @@ function foldMessage(state, event) {
24
25
  thread: payload.thread,
25
26
  labels: { ...payload.labels },
26
27
  reactions: {},
27
- mentions: payload.mentions,
28
28
  by: payload.by,
29
29
  noSync: payload.noSync,
30
30
  origin: payload.origin,
@@ -46,8 +46,9 @@ function foldMessage(state, event) {
46
46
  const message = state.byId[event.payload.id];
47
47
  if (!message || message.deleted) return void 0;
48
48
  message.text = event.payload.text;
49
- message.mentions = event.payload.mentions;
50
49
  message.editedAt = iso(event.createdAt);
50
+ if (message.from === null && event.payload.from !== null) message.platformText = true;
51
+ else delete message.platformText;
51
52
  return message;
52
53
  }
53
54
  case "message.deleted": {
@@ -57,7 +58,6 @@ function foldMessage(state, event) {
57
58
  message.text = "";
58
59
  message.reactions = {};
59
60
  message.labels = {};
60
- message.mentions = [];
61
61
  message.attachments = [];
62
62
  message.links = [];
63
63
  return message;
@@ -115,7 +115,7 @@ function foldMessage(state, event) {
115
115
  /** Who's who: `actor.seen`. */
116
116
  function foldActors(state, event) {
117
117
  if (event.type !== "actor.seen") return state;
118
- const { actor, kind, handle, name, avatar, host } = event.payload;
118
+ const { actor, kind, handle, name, avatar, via, platform, host, verified } = event.payload;
119
119
  const previous = own(state.byId, actor);
120
120
  if (previous) {
121
121
  const key = previous.handle.toLowerCase();
@@ -129,7 +129,10 @@ function foldActors(state, event) {
129
129
  handle,
130
130
  name,
131
131
  avatar,
132
- ...host || previous?.host ? { host: true } : {}
132
+ ...via ? { via: { ...via } } : {},
133
+ ...platform ? { platform } : {},
134
+ ...host || previous?.host ? { host: true } : {},
135
+ ...verified ? { verified: true } : {}
133
136
  });
134
137
  const key = handle.toLowerCase();
135
138
  const ids = own(state.byHandle, key) ?? setOwn(state.byHandle, key, []);
@@ -214,7 +217,7 @@ function concernedMessageId(event) {
214
217
  }
215
218
  const termsOf = (message) => JSON.stringify([
216
219
  message.labels,
217
- message.mentions,
220
+ mentionTerms(message.text),
218
221
  message.attachments.map((file) => file.id)
219
222
  ]);
220
223
  /**
@@ -384,9 +387,12 @@ function ddl() {
384
387
  key text primary key,
385
388
  message_id integer not null
386
389
  )`,
387
- "drop index if exists board_messages_recent"
390
+ "drop index if exists board_messages_recent",
391
+ "create table if not exists board_meta (\n key text primary key,\n value text not null\n)"
388
392
  ];
389
393
  }
394
+ /** `board_meta`'s key for the mention index taken from each message's text. */
395
+ const MENTION_TERMS = "mention_terms";
390
396
  /**
391
397
  * The board refuses NUL in text and a lone surrogate, and a log from before
392
398
  * that may hold them. Nothing a reader filters on needs either, so keys and
@@ -394,7 +400,10 @@ function ddl() {
394
400
  * that find them do the same.
395
401
  */
396
402
  const clean = (value) => value.replaceAll("\0", "").toWellFormed();
397
- /** A mention's term. Label keys start with a letter or digit, so it's never a label's. */
403
+ /**
404
+ * A mention's term, each one as the text has it (`mentionTerms`). Label keys start with a letter or
405
+ * digit, so it's never a label's.
406
+ */
398
407
  const MENTION = "@";
399
408
  /** An attachment's term, the same way. */
400
409
  const ATTACHMENT = "^";
@@ -432,7 +441,14 @@ function clauses(filter, p) {
432
441
  const either = [...actors.length ? [`m.by_actor in (${p.list(actors)})`] : [], ...principals.length ? [`m.by_principal in (${p.list(principals)})`] : []];
433
442
  out.push(either.length ? `(${either.join(" or ")})` : "1 = 0");
434
443
  }
435
- if (filter.mentions) out.push(filter.mentions.length ? `exists (select 1 from board_terms t where t.message_id = m.id and t.term = '${MENTION}' and t.value in (${p.list(filter.mentions)}))` : "1 = 0");
444
+ if (filter.mentions) {
445
+ const { terms, prefixes } = filter.mentions;
446
+ const either = [...terms.length ? [`t.value in (${p.list(terms)})`] : [], ...prefixes.map((prefix) => {
447
+ const at = `cast(${p.add(prefix)} as text)`;
448
+ return `substr(t.value, 1, length(${at})) = ${at}`;
449
+ })];
450
+ out.push(either.length ? `exists (select 1 from board_terms t where t.message_id = m.id and t.term = '${MENTION}' and (${either.join(" or ")}))` : "1 = 0");
451
+ }
436
452
  if (filter.from !== void 0) out.push(`coalesce(m.from_key, 'board') = ${p.add(filter.from)}`);
437
453
  if (filter.text !== void 0) out.push(`m.text_lower like ${p.add(`%${likeEscape(filter.text)}%`)} escape '\\'`);
438
454
  for (const label of filter.labels ?? []) {
@@ -444,6 +460,51 @@ function clauses(filter, p) {
444
460
  const parse = (row) => row === void 0 || row.data === null || row.data === void 0 ? null : JSON.parse(String(row.data));
445
461
  /** The tables on a SQL database. */
446
462
  function sqlTables(db) {
463
+ /**
464
+ * Tables from before mentions were text index a message's mentions as the actor IDs its write
465
+ * resolved them to. Once per database, each message whose text has an `@` gets the terms its
466
+ * text has instead, unless a writer changed its text in between, which reindexed it already.
467
+ * A read that filters on mentions waits for it.
468
+ */
469
+ async function reindexMentions() {
470
+ if ((await db.all({
471
+ text: "select 1 from board_meta where key = $1",
472
+ values: [MENTION_TERMS]
473
+ })).length > 0) return;
474
+ const rows = await db.all({
475
+ text: "select id, data from board_messages where text_lower like '%@%'",
476
+ values: []
477
+ });
478
+ const writes = [];
479
+ for (const row of rows) {
480
+ const message = parse(row);
481
+ const unchanged = "json_extract((select data from board_messages where id = $1), '$.text') = $2";
482
+ writes.push({
483
+ text: `delete from board_terms where message_id = $1 and term = '${MENTION}' and ${unchanged}`,
484
+ values: [message.id, message.text]
485
+ });
486
+ for (const term of mentionTerms(message.text)) writes.push({
487
+ text: `insert or ignore into board_terms (message_id, term, value) select $1, '${MENTION}', $3 where ${unchanged}`,
488
+ values: [
489
+ message.id,
490
+ message.text,
491
+ clean(term)
492
+ ]
493
+ });
494
+ }
495
+ await db.commit({
496
+ text: "insert into board_meta (key, value) values ($1, 'text') on conflict (key) do nothing returning 1 as claimed",
497
+ values: [MENTION_TERMS]
498
+ }, writes);
499
+ }
500
+ let reindexed = null;
501
+ const mentionsReady = () => {
502
+ reindexed ??= reindexMentions().catch((error) => {
503
+ reindexed = null;
504
+ throw error;
505
+ });
506
+ return reindexed;
507
+ };
447
508
  const positionSql = {
448
509
  text: "select log_index from board_positions where consumer = $1",
449
510
  values: [TABLES_CONSUMER]
@@ -555,7 +616,7 @@ function sqlTables(db) {
555
616
  },
556
617
  terms: m && change.message.terms ? [
557
618
  ...Object.entries(m.labels).map(([key, value]) => [key, clean(value)]),
558
- ...[...new Set(m.mentions)].map((actor) => [MENTION, clean(actor)]),
619
+ ...mentionTerms(m.text).map((term) => [MENTION, clean(term)]),
559
620
  ...[...new Set(m.attachments.map((file) => file.id))].map((id) => [ATTACHMENT, clean(id)])
560
621
  ] : null,
561
622
  summary: change.summary ?? null,
@@ -715,6 +776,7 @@ where v.message_id in (${p.list([...new Set(ids)])})
715
776
  })).map((found) => parse(found));
716
777
  },
717
778
  async messages(filter, page) {
779
+ if (filter.mentions) await mentionsReady();
718
780
  const p = new Params();
719
781
  const where = clauses(filter, p);
720
782
  if (page.before !== void 0) where.push(`m.id < ${p.add(page.before)}`);
@@ -732,6 +794,7 @@ where v.message_id in (${p.list([...new Set(ids)])})
732
794
  };
733
795
  },
734
796
  async threads(filter, page) {
797
+ if (filter.mentions) await mentionsReady();
735
798
  const [positions, rows] = await db.read([positionSql, threadsQuery(filter, page)]);
736
799
  const threads = rows.map((found) => ({
737
800
  root: parse(found),
@@ -1,6 +1,6 @@
1
- import { r as sqlTables } from "./sql-l3ysn4O5.mjs";
1
+ import { r as sqlTables } from "./sql-Bv-RQu8n.mjs";
2
2
  import { t as sqlite$1 } from "./store-sqlite-D6fIszST.mjs";
3
- import { t as sqliteDb } from "./sqlite-db-cm5yhrD-.mjs";
3
+ import { t as sqliteDb } from "./sqlite-db-BraLvHtf.mjs";
4
4
  //#region src/store/sqlite.ts
5
5
  /**
6
6
  * A local board in one SQLite file, its log and board's tables side by side. It
@@ -1,4 +1,4 @@
1
- import { n as ddl } from "./sql-l3ysn4O5.mjs";
1
+ import { n as ddl } from "./sql-Bv-RQu8n.mjs";
2
2
  import { mkdirSync } from "node:fs";
3
3
  import { dirname, resolve } from "node:path";
4
4
  //#region src/store/sqlite-db.ts
@@ -1,5 +1,5 @@
1
- import { b as channels, g as SyncFn, p as SyncProvider } from "./provider-D5yVFisj.mjs";
2
- import { r as ChatTransport, t as ChatInput } from "./chat-provider-DyNy5xdC.mjs";
1
+ import { _ as SyncFn, m as SyncProvider, x as channels } from "./provider-YqkF1E2k.mjs";
2
+ import { r as ChatTransport, t as ChatInput } from "./chat-provider-Bbb9JguG.mjs";
3
3
  import { z } from "zod";
4
4
  import { ReactionEvent } from "chat";
5
5
  //#region src/sync/chat-sdk.d.ts
@@ -1,5 +1,5 @@
1
- import { f as SyncContext, g as SyncFn, y as SyncUnit } from "./provider-D5yVFisj.mjs";
2
- import { n as ChatSyncProvider } from "./chat-provider-DyNy5xdC.mjs";
1
+ import { _ as SyncFn, b as SyncUnit, p as SyncContext } from "./provider-YqkF1E2k.mjs";
2
+ import { n as ChatSyncProvider } from "./chat-provider-Bbb9JguG.mjs";
3
3
  import { z } from "zod";
4
4
  import { Adapter } from "chat";
5
5
  //#region src/sync/github.d.ts
@@ -1,6 +1,6 @@
1
- import { st as SourceRead } from "./routes-BffuaoTX.mjs";
2
- import { c as ReceivedEvent, d as ResolvedTarget, f as SyncContext, g as SyncFn, o as ProviderPost, r as ProviderDelivery, y as SyncUnit } from "./provider-D5yVFisj.mjs";
3
- import { n as ChatSyncProvider, t as ChatInput } from "./chat-provider-DyNy5xdC.mjs";
1
+ import { dt as SourceRead } from "./routes-CAjd5ARa.mjs";
2
+ import { _ as SyncFn, b as SyncUnit, f as ResolvedTarget, l as ReceivedEvent, o as ProviderPost, p as SyncContext, r as ProviderDelivery } from "./provider-YqkF1E2k.mjs";
3
+ import { n as ChatSyncProvider, t as ChatInput } from "./chat-provider-Bbb9JguG.mjs";
4
4
  import { z } from "zod";
5
5
  import { Adapter } from "chat";
6
6
  //#region src/sync/linear.d.ts
@@ -1,6 +1,6 @@
1
- import { cn as ExternalLink } from "./routes-BffuaoTX.mjs";
2
- import { b as channels, d as ResolvedTarget, f as SyncContext, g as SyncFn, o as ProviderPost, r as ProviderDelivery } from "./provider-D5yVFisj.mjs";
3
- import { n as ChatSyncProvider, t as ChatInput } from "./chat-provider-DyNy5xdC.mjs";
1
+ import { fn as ExternalLink } from "./routes-CAjd5ARa.mjs";
2
+ import { _ as SyncFn, f as ResolvedTarget, o as ProviderPost, p as SyncContext, r as ProviderDelivery, s as ProviderSender, x as channels } from "./provider-YqkF1E2k.mjs";
3
+ import { n as ChatSyncProvider, t as ChatInput } from "./chat-provider-Bbb9JguG.mjs";
4
4
  import { z } from "zod";
5
5
  import { Adapter } from "chat";
6
6
  //#region src/sync/slack.d.ts
@@ -128,6 +128,11 @@ type SlackPost = {
128
128
  unfurl_links?: boolean;
129
129
  unfurl_media?: boolean;
130
130
  };
131
+ /**
132
+ * A sender's name as Slack shows it, at most 80 characters: a long name is cut, never whose word it
133
+ * is. Null when that alone doesn't fit, for the message to go as the app with its label.
134
+ */
135
+ export declare function slackUsername({ name, attribution }: Pick<ProviderSender, 'name' | 'attribution'>): string | null;
131
136
  /** The `**name**: ` a message's text opens with, taken out when Slack shows the name as the sender. */
132
137
  export declare function withoutLabel(markdown: string, name: string): string;
133
138
  /** GitHub's markdown allows inline HTML, which Slack shows as raw tags: as markdown instead, outside code. */
@@ -368,9 +373,10 @@ export declare class SlackProvider extends ChatSyncProvider<SlackEvent> {
368
373
  private scopes;
369
374
  constructor(given: SlackOptions, sync: SyncFn<SlackEvent>);
370
375
  /**
371
- * An agent's message goes out under its own name (`clever-lemur via vboard-factory`), and its
372
- * picture when it has one Slack can show, instead of the app's, with the text's
373
- * `**name**: ` label dropped. Without `chat:write.customize` it posts as the app, label and all.
376
+ * A message goes out under its author's name (`Julián Benegas`, `clever-lemur via vboard-factory`,
377
+ * `Malte via support (slack)`), and their picture when it has one Slack can show, instead of the
378
+ * app's, with the text's `**name**: ` label dropped. Without `chat:write.customize` it posts as
379
+ * the app, label and all.
374
380
  */
375
381
  post(target: string, kind: ResolvedTarget['kind'], body: ProviderPost): Promise<ProviderDelivery>;
376
382
  /**
@@ -381,14 +387,14 @@ export declare class SlackProvider extends ChatSyncProvider<SlackEvent> {
381
387
  * (`files:read`) to find that message.
382
388
  */
383
389
  private postWithFiles;
384
- /** An edit keeps the label out only where the message went out under the agent's name. */
390
+ /** An edit keeps the label out only where the message went out under its author's name. */
385
391
  edit(thread: string, message: string, body: ProviderPost): Promise<void>;
386
392
  private postNamed;
387
393
  /** Whether the app may set a message's username and icon (`chat:write.customize`). */
388
394
  private canCustomize;
389
395
  /** Whether the app has a scope, from its scopes, asked once. */
390
396
  private hasScope;
391
- /** Whether a message Slack has went out under `name`. */
397
+ /** Whether a message Slack has went out under the sender's name. */
392
398
  private sentAs;
393
399
  /**
394
400
  * Slack's link to the event's message, from `chat.getPermalink`, so it has the workspace's
@@ -7,6 +7,23 @@ import { stringifyMarkdown } from "chat";
7
7
  import { createSlackAdapter } from "@chat-adapter/slack";
8
8
  import { connectSlackAdapter } from "@vercel/connect/chat";
9
9
  //#region src/sync/slack.ts
10
+ /** The most characters Slack shows of a message's username. */
11
+ const USERNAME_MAX = 80;
12
+ /**
13
+ * A sender's name as Slack shows it, at most 80 characters: a long name is cut, never whose word it
14
+ * is. Null when that alone doesn't fit, for the message to go as the app with its label.
15
+ */
16
+ function slackUsername({ name, attribution = "" }) {
17
+ if (Array.from(name).length <= USERNAME_MAX) return name;
18
+ const room = USERNAME_MAX - Array.from(attribution).length - 1;
19
+ if (room < 1) return null;
20
+ let cut = "";
21
+ for (const { segment } of new Intl.Segmenter().segment(name.slice(0, name.length - attribution.length))) {
22
+ if (Array.from(cut + segment).length > room) break;
23
+ cut += segment;
24
+ }
25
+ return `${cut.trimEnd()}…${attribution}`;
26
+ }
10
27
  /** The `**name**: ` a message's text opens with, taken out when Slack shows the name as the sender. */
11
28
  function withoutLabel(markdown, name) {
12
29
  const label = new RegExp(`^\\*\\*${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\*\\*: `);
@@ -653,9 +670,10 @@ var SlackProvider = class extends ChatSyncProvider {
653
670
  this.web = client;
654
671
  }
655
672
  /**
656
- * An agent's message goes out under its own name (`clever-lemur via vboard-factory`), and its
657
- * picture when it has one Slack can show, instead of the app's, with the text's
658
- * `**name**: ` label dropped. Without `chat:write.customize` it posts as the app, label and all.
673
+ * A message goes out under its author's name (`Julián Benegas`, `clever-lemur via vboard-factory`,
674
+ * `Malte via support (slack)`), and their picture when it has one Slack can show, instead of the
675
+ * app's, with the text's `**name**: ` label dropped. Without `chat:write.customize` it posts as
676
+ * the app, label and all.
659
677
  */
660
678
  async post(target, kind, body) {
661
679
  const { as, ...given } = body;
@@ -696,13 +714,19 @@ var SlackProvider = class extends ChatSyncProvider {
696
714
  }))
697
715
  })).files?.[0]?.files ?? []).map((file) => file.id).filter((id) => !!id);
698
716
  const found = async () => {
717
+ let failure = /* @__PURE__ */ new Error("never shared");
699
718
  for (let attempt = 0; attempt < SHARE_POLLS; attempt++) {
700
- const shares = (await web.files.info({ file: ids[0] })).file?.shares;
701
- const ts = shares?.public?.[channel]?.[0]?.ts ?? shares?.private?.[channel]?.[0]?.ts;
702
- if (ts) return ts;
719
+ try {
720
+ const shares = (await web.files.info({ file: ids[0] })).file?.shares;
721
+ const ts = shares?.public?.[channel]?.[0]?.ts ?? shares?.private?.[channel]?.[0]?.ts;
722
+ if (ts) return ts;
723
+ } catch (error) {
724
+ if (REFUSED.has(error?.data?.error ?? "")) throw error;
725
+ failure = error;
726
+ }
703
727
  await new Promise((resolve) => setTimeout(resolve, Math.min(250 * 2 ** attempt, 2e3)));
704
728
  }
705
- throw new Error("never shared");
729
+ throw failure;
706
730
  };
707
731
  if (!ids[0]) throw new Error("slack: files.uploadV2 returned no file IDs");
708
732
  let ts;
@@ -717,14 +741,14 @@ var SlackProvider = class extends ChatSyncProvider {
717
741
  files: ids
718
742
  };
719
743
  }
720
- /** An edit keeps the label out only where the message went out under the agent's name. */
744
+ /** An edit keeps the label out only where the message went out under its author's name. */
721
745
  async edit(thread, message, body) {
722
746
  const { as, ...given } = body;
723
747
  const post = {
724
748
  ...given,
725
749
  markdown: withoutHtml(given.markdown)
726
750
  };
727
- const named = as ? await this.sentAs(thread, message, as.name) : false;
751
+ const named = as && await this.web().then((web) => !!web && this.canCustomize(web), () => false) ? await this.sentAs(thread, message, as) : false;
728
752
  await super.edit(thread, message, named && as ? {
729
753
  ...post,
730
754
  markdown: withoutLabel(post.markdown, as.name)
@@ -733,7 +757,8 @@ var SlackProvider = class extends ChatSyncProvider {
733
757
  async postNamed(target, as, markdown) {
734
758
  const adapter = await this.ready();
735
759
  const web = await this.web();
736
- if (!web?.chat || !adapter.formatConverter?.toSlackPayload || !await this.canCustomize(web)) return null;
760
+ const username = slackUsername(as);
761
+ if (!web?.chat || !adapter.formatConverter?.toSlackPayload || username === null || !await this.canCustomize(web)) return null;
737
762
  const threadId = this.toChat(target);
738
763
  const { channel, threadTs } = adapter.decodeThreadId(threadId);
739
764
  const message = { markdown: withoutLabel(markdown, as.name) };
@@ -745,7 +770,7 @@ var SlackProvider = class extends ChatSyncProvider {
745
770
  ...adapter.formatConverter.toSlackPayload(resolved),
746
771
  unfurl_links: false,
747
772
  unfurl_media: false,
748
- username: as.name.slice(0, 80),
773
+ username,
749
774
  ...icon ? { icon_url: icon } : {}
750
775
  });
751
776
  if (!sent.ts) throw new Error("slack: chat.postMessage returned no ts");
@@ -767,8 +792,10 @@ var SlackProvider = class extends ChatSyncProvider {
767
792
  });
768
793
  return (await this.scopes).includes(scope);
769
794
  }
770
- /** Whether a message Slack has went out under `name`. */
771
- async sentAs(thread, message, name) {
795
+ /** Whether a message Slack has went out under the sender's name. */
796
+ async sentAs(thread, message, as) {
797
+ const username = slackUsername(as);
798
+ if (username === null) return false;
772
799
  const web = await this.web().catch(() => void 0);
773
800
  const channel = thread.slice(0, thread.indexOf(":"));
774
801
  if (!web?.conversations.replies || !channel) return false;
@@ -779,7 +806,7 @@ var SlackProvider = class extends ChatSyncProvider {
779
806
  latest: message,
780
807
  inclusive: true,
781
808
  limit: 1
782
- }).then((page) => page.messages?.find((m) => m.ts === message), () => void 0))?.username === name.slice(0, 80);
809
+ }).then((page) => page.messages?.find((m) => m.ts === message), () => void 0))?.username === username;
783
810
  }
784
811
  /**
785
812
  * Slack's link to the event's message, from `chat.getPermalink`, so it has the workspace's
@@ -815,4 +842,4 @@ var SlackProvider = class extends ChatSyncProvider {
815
842
  }
816
843
  };
817
844
  //#endregion
818
- export { SlackEvent, SlackProvider, channels, forwardText, slack, slackFileName, slackIcon, slackLinks, withoutHtml, withoutLabel };
845
+ export { SlackEvent, SlackProvider, channels, forwardText, slack, slackFileName, slackIcon, slackLinks, slackUsername, withoutHtml, withoutLabel };
package/dist/sync.d.mts CHANGED
@@ -1,3 +1,3 @@
1
- import { an as ExternalAuthor, on as ExternalEvent, sn as ExternalFile } from "./routes-BffuaoTX.mjs";
2
- import { A as envelope, C as render, D as SyncOverrides, E as RootOverride, O as SyncResult, S as mirror, T as ProviderEvent, _ as SyncIn, a as ProviderOptions, b as channels, c as ReceivedEvent, d as ResolvedTarget, f as SyncContext, g as SyncFn, h as Sync, i as ProviderFile, j as eventSchema, k as SyncRoot, l as RenderInput, m as UnreadableError, n as FileDelivery, o as ProviderPost, p as SyncProvider, r as ProviderDelivery, s as Receive, u as Renderer, v as SyncOut, w as EventBase, x as into, y as SyncUnit } from "./provider-D5yVFisj.mjs";
1
+ import { dn as ExternalFile, ln as ExternalAuthor, un as ExternalEvent } from "./routes-CAjd5ARa.mjs";
2
+ import { A as SyncRoot, C as mirror, D as RootOverride, E as ProviderEvent, M as eventSchema, O as SyncOverrides, S as into, T as EventBase, _ as SyncFn, a as ProviderOptions, b as SyncUnit, c as Receive, d as Renderer, f as ResolvedTarget, g as Sync, h as UnreadableError, i as ProviderFile, j as envelope, k as SyncResult, l as ReceivedEvent, m as SyncProvider, n as FileDelivery, o as ProviderPost, p as SyncContext, r as ProviderDelivery, u as RenderInput, v as SyncIn, w as render, x as channels, y as SyncOut } from "./provider-YqkF1E2k.mjs";
3
3
  export { EventBase, type ExternalAuthor, ExternalEvent, type ExternalFile, type FileDelivery, type ProviderDelivery, type ProviderEvent, type ProviderFile, type ProviderOptions, type ProviderPost, type Receive, ReceivedEvent, type RenderInput, type Renderer, ResolvedTarget, type RootOverride, type Sync, type SyncContext, type SyncFn, type SyncIn, type SyncOut, SyncOverrides, SyncProvider, type SyncResult, type SyncRoot, type SyncUnit, UnreadableError, channels, envelope, eventSchema, into, mirror, render };
@@ -1,5 +1,5 @@
1
- import { l as unauthorized } from "./errors-rYDxZEuN.mjs";
2
- import { _ as privateHost, a as VERCEL_ISSUER, b as trustedIssuers, g as markVerified, i as TOKENS, m as issuerName } from "./auth-B3bBYOqf.mjs";
1
+ import { l as unauthorized } from "./errors-CNRJqUuL.mjs";
2
+ import { _ as privateHost, a as VERCEL_ISSUER, b as trustedIssuers, g as markVerified, i as TOKENS, m as issuerName } from "./auth-C8URZHLx.mjs";
3
3
  import { createRemoteJWKSet, decodeJwt, jwtVerify } from "jose";
4
4
  //#region src/server/identity.ts
5
5
  let fromDisk;