@eve/board 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,100 +4,365 @@ import { createRequire as __eveCreateRequire } from "node:module";
4
4
  const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
+ import { BOARD_ID_PATTERN, getCached, isVercelBoardName, listTeamBoards, normalizeBoardName, setCached } from "./client.mjs";
7
8
  import { normalizeBoardRouteBase } from "./route.mjs";
8
9
  const DEFAULT_BOARD_KEY = "default";
9
10
  const DEFAULT_WATCH_CHANNEL = "eve-config/watches";
11
+ const DISCOVERY_TTL_MS = 6e4;
12
+ const WAKE_MISS_WINDOW_MS = 6e4;
13
+ const MAX_WAKE_MISS_REFRESHES = 5;
14
+ const MAX_DIRECTORY_TEAMS = 32;
15
+ const directoryCache = new Map();
16
+ function hasBoardUrlEnv() {
17
+ return Boolean(process.env.BOARD_URL?.trim());
18
+ }
19
+ function normalizedNameKey(name) {
20
+ return normalizeBoardName(name).toLowerCase();
21
+ }
22
+ function directoryKey(team) {
23
+ return JSON.stringify([
24
+ team ?? null,
25
+ process.env.BOARD_TOKEN ?? null,
26
+ process.env.VERCEL_ORG_ID ?? null,
27
+ process.env.VERCEL_AUTH_TOKEN ?? null
28
+ ]);
29
+ }
30
+ function directoryEntry(team) {
31
+ const key = directoryKey(team);
32
+ const existing = getCached(directoryCache, key);
33
+ if (existing !== void 0) return existing;
34
+ const created = {
35
+ fetchedAt: 0,
36
+ wakeRefreshes: []
37
+ };
38
+ setCached(directoryCache, key, created, MAX_DIRECTORY_TEAMS);
39
+ return created;
40
+ }
41
+ async function getDirectory(team, options = {}) {
42
+ const entry = directoryEntry(team);
43
+ const now = Date.now();
44
+ if (options.fresh !== true && entry.listed !== void 0 && now - entry.fetchedAt < DISCOVERY_TTL_MS) return {
45
+ listed: entry.listed,
46
+ refreshed: false
47
+ };
48
+ if (entry.inFlight === void 0) {
49
+ if (options.throttle === true) {
50
+ entry.wakeRefreshes = entry.wakeRefreshes.filter((timestamp) => now - timestamp < WAKE_MISS_WINDOW_MS);
51
+ if (entry.wakeRefreshes.length >= MAX_WAKE_MISS_REFRESHES) return {
52
+ listed: entry.listed,
53
+ refreshed: false
54
+ };
55
+ entry.wakeRefreshes.push(now);
56
+ }
57
+ const request = listTeamBoards(team === void 0 ? void 0 : { team }).then((listed) => {
58
+ entry.listed = listed;
59
+ entry.fetchedAt = Date.now();
60
+ if (entry.inFlight === request) entry.inFlight = void 0;
61
+ return listed;
62
+ }, (error) => {
63
+ if (entry.inFlight === request) entry.inFlight = void 0;
64
+ throw error;
65
+ });
66
+ entry.inFlight = request;
67
+ }
68
+ return {
69
+ listed: await entry.inFlight,
70
+ refreshed: true
71
+ };
72
+ }
73
+ function defaultListedBoard(directory) {
74
+ return directory.defaultBoardId == null ? void 0 : directory.boards.find((board) => board.id === directory.defaultBoardId);
75
+ }
76
+ function findListedBoard(directory, query) {
77
+ if (BOARD_ID_PATTERN.test(query)) return directory.boards.find((board) => board.id === query);
78
+ if (!isVercelBoardName(query)) return void 0;
79
+ const normalized = normalizedNameKey(query);
80
+ const byName = directory.boards.find((board) => normalizedNameKey(board.name) === normalized);
81
+ if (byName !== void 0) return byName;
82
+ return normalized === "general" ? defaultListedBoard(directory) : void 0;
83
+ }
84
+ async function entryListedBoard(entry, fallback, directory, throttle = false) {
85
+ if (entry.url !== void 0) return void 0;
86
+ let own = directory;
87
+ if (own === void 0 || (entry.team ?? null) !== (fallback.team ?? null)) {
88
+ ({listed: own} = await getDirectory(entry.team, { throttle }));
89
+ if (own === void 0) throw Object.assign(new Error(`Couldn't verify the settings for board "${entry.key}". Try again shortly.`), { code: "board_unverified" });
90
+ }
91
+ return findListedBoard(own, entry.id ?? entry.name ?? "");
92
+ }
93
+ async function matchStaticOverride(set, fallback, listed, directory, throttle = false) {
94
+ const entries = [...set.byKey.values()];
95
+ const byId = entries.find((entry) => entry.id === listed.id);
96
+ if (byId !== void 0) return byId;
97
+ const listedName = normalizedNameKey(listed.name);
98
+ const isDefault = listed.id === directory.defaultBoardId;
99
+ for (const entry of entries) {
100
+ if (entry.id !== void 0 || entry.name === void 0) continue;
101
+ const name = normalizedNameKey(entry.name);
102
+ if (name !== listedName && !(isDefault && name === "general")) continue;
103
+ if ((await entryListedBoard(entry, fallback, directory, throttle))?.id === listed.id) return entry;
104
+ }
105
+ }
106
+ function fallbackBoardConfig(set, fallback, id, name) {
107
+ return {
108
+ ...fallback,
109
+ id,
110
+ key: id,
111
+ ...name !== void 0 && { name },
112
+ registrationRouteBase: `${set.routeBase}/${id}`,
113
+ routeBase: set.routeBase,
114
+ shorthand: false
115
+ };
116
+ }
117
+ async function dynamicBoardConfig(set, fallback, listed, directory, throttle = false) {
118
+ const override = await matchStaticOverride(set, fallback, listed, directory, throttle);
119
+ if (override !== void 0) return {
120
+ ...override,
121
+ id: listed.id,
122
+ name: listed.name
123
+ };
124
+ return fallbackBoardConfig(set, fallback, listed.id, listed.name);
125
+ }
126
+ function lookupStaticOrId(set, ref) {
127
+ const direct = set.byKey.get(ref);
128
+ if (direct !== void 0) return direct;
129
+ if (!BOARD_ID_PATTERN.test(ref)) return void 0;
130
+ return [...set.byKey.values()].find((entry) => entry.id === ref);
131
+ }
132
+ async function resolveFromDirectory(set, fallback, pick, throttle = false) {
133
+ let { listed, refreshed } = await getDirectory(fallback.team, { throttle });
134
+ let found = listed === void 0 ? void 0 : pick(listed);
135
+ if (found === void 0 && !refreshed) {
136
+ ({listed} = await getDirectory(fallback.team, {
137
+ fresh: true,
138
+ throttle
139
+ }));
140
+ found = listed === void 0 ? void 0 : pick(listed);
141
+ }
142
+ if (found === void 0 || listed === void 0) return void 0;
143
+ return await dynamicBoardConfig(set, fallback, found, listed, throttle);
144
+ }
145
+ async function enrichMetadata(fallback, board, needsMetadata) {
146
+ if (needsMetadata !== true) return board;
147
+ const match = await entryListedBoard(board, fallback).catch(() => void 0);
148
+ return match === void 0 ? board : {
149
+ ...board,
150
+ id: match.id,
151
+ name: match.name
152
+ };
153
+ }
154
+ function staticBoardSummary(entry, extra) {
155
+ return {
156
+ board: entry.key,
157
+ ...extra?.default !== void 0 && { default: extra.default },
158
+ ...entry.id !== void 0 && { id: entry.id },
159
+ ...entry.name !== void 0 && { name: entry.name },
160
+ ...entry.team !== void 0 && { team: entry.team }
161
+ };
162
+ }
163
+ function singleBoardSet(routeBase, entry) {
164
+ const resolved = {
165
+ ...entry,
166
+ key: DEFAULT_BOARD_KEY,
167
+ registrationRouteBase: routeBase,
168
+ routeBase,
169
+ shorthand: true
170
+ };
171
+ return {
172
+ byKey: new Map([[DEFAULT_BOARD_KEY, resolved]]),
173
+ keys: [DEFAULT_BOARD_KEY],
174
+ routeBase,
175
+ shorthand: true
176
+ };
177
+ }
178
+ function matchesBoard(board, ref) {
179
+ return board.key === ref || board.id === ref;
180
+ }
10
181
  function resolveBoards(settings) {
11
182
  const routeBase = normalizeBoardRouteBase(settings.route);
12
- if (settings.boards === void 0) {
13
- const entry = {
14
- authorize: settings.authorize,
15
- can: settings.can,
16
- key: DEFAULT_BOARD_KEY,
17
- name: settings.name,
18
- profile: settings.profile,
19
- registrationRouteBase: routeBase,
20
- routeBase,
21
- shorthand: true,
22
- team: settings.team,
23
- url: settings.url,
24
- watchChannel: settings.watchChannel ?? "eve-config/watches"
25
- };
26
- return {
27
- byKey: new Map([[DEFAULT_BOARD_KEY, entry]]),
28
- keys: [DEFAULT_BOARD_KEY],
29
- routeBase,
30
- shorthand: true
31
- };
32
- }
183
+ const pinnedByEnv = hasBoardUrlEnv();
184
+ if (settings.boards === void 0 && (settings.id !== void 0 || settings.name !== void 0 || settings.url !== void 0 || pinnedByEnv)) return singleBoardSet(routeBase, {
185
+ authorize: settings.authorize,
186
+ can: settings.can,
187
+ ...settings.id !== void 0 && { id: settings.id },
188
+ ...settings.name !== void 0 && { name: settings.name },
189
+ profile: settings.profile,
190
+ team: settings.team,
191
+ url: settings.url,
192
+ watchChannel: settings.watchChannel ?? "eve-config/watches"
193
+ });
194
+ const rawBoards = settings.boards ?? {};
195
+ const wildcard = rawBoards["*"];
196
+ const wildcardObj = typeof wildcard === "object" && wildcard !== null ? wildcard : void 0;
197
+ const discover = !pinnedByEnv && wildcard !== false;
33
198
  const byKey = new Map();
34
199
  const keys = [];
35
- for (const [key, entry] of Object.entries(settings.boards)) {
200
+ for (const [key, entry] of Object.entries(rawBoards)) {
201
+ if (key === "*" || typeof entry !== "object" || entry === null) continue;
202
+ const keyDerivedName = entry.name === void 0 && entry.id === void 0 && entry.url === void 0;
203
+ const effectiveName = keyDerivedName ? key : entry.name;
36
204
  byKey.set(key, {
37
205
  authorize: entry.authorize ?? settings.authorize,
38
- can: entry.can,
206
+ can: entry.can ?? settings.can,
207
+ ...keyDerivedName && { ensure: false },
208
+ ...entry.id !== void 0 && { id: entry.id },
39
209
  key,
40
- name: entry.name,
210
+ ...effectiveName !== void 0 && { name: effectiveName },
41
211
  profile: entry.profile ?? settings.profile,
42
212
  registrationRouteBase: `${routeBase}/${key}`,
43
213
  routeBase,
44
214
  shorthand: false,
45
- team: entry.team,
215
+ team: entry.team ?? settings.team,
46
216
  url: entry.url,
47
217
  watchChannel: entry.watchChannel ?? settings.watchChannel ?? "eve-config/watches"
48
218
  });
49
219
  keys.push(key);
50
220
  }
51
- if (keys.length === 0) throw new Error("Board extension `boards` must configure at least one board.");
221
+ if (!discover && keys.length === 0) {
222
+ if (pinnedByEnv && wildcard !== false) return singleBoardSet(routeBase, {
223
+ authorize: wildcardObj?.authorize ?? settings.authorize,
224
+ can: wildcardObj?.can ?? settings.can,
225
+ profile: wildcardObj?.profile ?? settings.profile,
226
+ team: wildcardObj?.team ?? settings.team,
227
+ watchChannel: wildcardObj?.watchChannel ?? settings.watchChannel ?? "eve-config/watches"
228
+ });
229
+ throw new Error("Board extension `boards` with `\"*\": false` must configure at least one board.");
230
+ }
231
+ const fallback = discover ? {
232
+ authorize: wildcardObj?.authorize ?? settings.authorize,
233
+ can: wildcardObj?.can ?? settings.can,
234
+ profile: wildcardObj?.profile ?? settings.profile,
235
+ team: wildcardObj?.team ?? settings.team,
236
+ watchChannel: wildcardObj?.watchChannel ?? settings.watchChannel ?? "eve-config/watches"
237
+ } : void 0;
52
238
  return {
53
239
  byKey,
240
+ ...fallback !== void 0 && { fallback },
54
241
  keys,
55
242
  routeBase,
56
243
  shorthand: false
57
244
  };
58
245
  }
59
- function lookupBoard(set, key) {
60
- return set.byKey.get(key);
61
- }
62
- function selectBoard(set, requestedKey, sessionKey) {
246
+ function selectStaticBoard(set, requestedKey, sessionKey) {
63
247
  if (requestedKey !== void 0) {
64
- const found = lookupBoard(set, requestedKey);
248
+ const found = lookupStaticOrId(set, requestedKey);
65
249
  if (found !== void 0) return found;
66
250
  throw new Error(`Unknown board "${requestedKey}". Configured boards: ${set.keys.join(", ")}.`);
67
251
  }
68
252
  if (sessionKey != null && sessionKey.length > 0) {
69
- const found = lookupBoard(set, sessionKey);
253
+ const found = lookupStaticOrId(set, sessionKey);
70
254
  if (found !== void 0) return found;
71
255
  throw new Error(`Board "${sessionKey}" from this session is no longer configured. Configured boards: ${set.keys.join(", ")}.`);
72
256
  }
73
257
  if (set.byKey.size === 1) return set.byKey.values().next().value;
74
258
  throw new Error(`Pass \`board\` to choose which board to use. Configured boards: ${set.keys.join(", ")}.`);
75
259
  }
76
- function resolveSessionBoard(settings, sessionKey) {
260
+ async function selectBoardAsync(settings, requestedKey, sessionKey, options = {}) {
77
261
  const set = resolveBoards(settings);
262
+ const fallback = set.fallback;
263
+ if (fallback === void 0) return selectStaticBoard(set, requestedKey, sessionKey);
264
+ if (requestedKey !== void 0) {
265
+ const staticHit = lookupStaticOrId(set, requestedKey);
266
+ if (staticHit !== void 0) return await enrichMetadata(fallback, staticHit, options.needsMetadata);
267
+ const resolved = BOARD_ID_PATTERN.test(requestedKey) || isVercelBoardName(requestedKey) ? await resolveFromDirectory(set, fallback, (directory) => findListedBoard(directory, requestedKey)) : void 0;
268
+ if (resolved !== void 0) return resolved;
269
+ throw new Error(`Unknown or inaccessible board "${requestedKey}". Call \`boards\` to list boards you can access.`);
270
+ }
78
271
  if (sessionKey != null && sessionKey.length > 0) {
79
- const found = lookupBoard(set, sessionKey);
80
- if (found !== void 0) return found;
81
- throw new Error(`Board "${sessionKey}" from this session is no longer configured. Configured boards: ${set.keys.join(", ")}.`);
272
+ const staticHit = lookupStaticOrId(set, sessionKey);
273
+ if (staticHit !== void 0) return await enrichMetadata(fallback, staticHit, options.needsMetadata);
274
+ if (BOARD_ID_PATTERN.test(sessionKey)) {
275
+ if (options.needsMetadata !== true && options.verify !== true && ![...set.byKey.values()].some((entry) => entry.id === void 0 && entry.url === void 0)) return fallbackBoardConfig(set, fallback, sessionKey);
276
+ const resolved = await resolveFromDirectory(set, fallback, (directory) => directory.boards.find((board) => board.id === sessionKey));
277
+ if (resolved !== void 0) return resolved;
278
+ throw new Error(`Board "${sessionKey}" from this session is no longer accessible.`);
279
+ }
280
+ throw new Error(`Board "${sessionKey}" from this session is no longer configured.`);
82
281
  }
83
- if (set.byKey.size === 1) return set.byKey.values().next().value;
84
- throw new Error(`This board session has no board key, and multiple boards are configured (${set.keys.join(", ")}).`);
282
+ const defaultBoard = await resolveFromDirectory(set, fallback, defaultListedBoard);
283
+ if (defaultBoard !== void 0) return defaultBoard;
284
+ throw new Error("This deployment has no access to the team's default board. Pass `board` (call `boards` to list available boards) or grant access to the default board.");
285
+ }
286
+ async function resolveWakeBoard(settings, boardParam) {
287
+ const set = resolveBoards(settings);
288
+ const fallback = set.fallback;
289
+ if (boardParam === void 0) {
290
+ if (set.shorthand) return set.byKey.values().next().value;
291
+ if (fallback === void 0) return void 0;
292
+ return await resolveFromDirectory(set, fallback, defaultListedBoard, true);
293
+ }
294
+ if (set.shorthand) return void 0;
295
+ const staticHit = set.byKey.get(boardParam);
296
+ if (staticHit !== void 0) return staticHit;
297
+ if (fallback === void 0 || !BOARD_ID_PATTERN.test(boardParam)) return void 0;
298
+ return await resolveFromDirectory(set, fallback, (directory) => directory.boards.find((board) => board.id === boardParam), true);
299
+ }
300
+ async function listAccessibleBoards(settings) {
301
+ const set = resolveBoards(settings);
302
+ if (set.shorthand) {
303
+ const entry = set.byKey.values().next().value;
304
+ return {
305
+ boards: [staticBoardSummary(entry, { default: true })],
306
+ defaultBoardId: entry.id ?? null
307
+ };
308
+ }
309
+ const fallback = set.fallback;
310
+ if (fallback === void 0) return {
311
+ boards: [...set.byKey.values()].map((entry) => staticBoardSummary(entry)),
312
+ defaultBoardId: null
313
+ };
314
+ const { listed } = await getDirectory(fallback.team, { fresh: true });
315
+ const directory = listed;
316
+ const matchedStaticKeys = new Set();
317
+ const boards = await Promise.all(directory.boards.map(async (entry) => {
318
+ const override = await matchStaticOverride(set, fallback, entry, directory);
319
+ if (override !== void 0) matchedStaticKeys.add(override.key);
320
+ const team = override?.team ?? fallback.team;
321
+ return {
322
+ board: override?.key ?? entry.id,
323
+ default: entry.id === directory.defaultBoardId,
324
+ id: entry.id,
325
+ name: entry.name,
326
+ ...team !== void 0 && { team },
327
+ ...entry.visibility !== void 0 && { visibility: entry.visibility }
328
+ };
329
+ }));
330
+ for (const entry of set.byKey.values()) if (!matchedStaticKeys.has(entry.key)) boards.push(staticBoardSummary(entry));
331
+ return {
332
+ boards,
333
+ defaultBoardId: directory.defaultBoardId
334
+ };
85
335
  }
86
336
  function formatConfiguredBoards(settings) {
87
337
  const set = resolveBoards(settings);
88
338
  if (set.shorthand) return null;
89
- const lines = [...set.byKey.values()].map((entry) => {
90
- const label = entry.name ?? "team default board";
339
+ const staticLines = [...set.byKey.values()].map((entry) => {
340
+ const label = entry.name ?? entry.id ?? "team default board";
91
341
  const team = entry.team === void 0 ? "" : ` (team \`${entry.team}\`)`;
92
342
  return `- \`${entry.key}\`: ${label}${team}`;
93
343
  });
94
- const requirement = set.keys.length > 1 ? "Outside a board session, pass `board` with one of the keys above to choose which board to use (except `watches`, which lists every board when `board` is omitted)." : `Pass \`board: "${set.keys[0]}"\` or leave \`board\` out to use it.`;
344
+ if (set.fallback === void 0) {
345
+ const requirement = set.keys.length > 1 ? "Outside a board session, pass `board` with one of the keys above to choose which board to use (except `watches`, which lists every board when `board` is omitted)." : `Pass \`board: "${set.keys[0]}"\` or leave \`board\` out to use it.`;
346
+ return [
347
+ "## Configured boards",
348
+ "",
349
+ ...staticLines,
350
+ "",
351
+ `In a session a board started, replies stay on that board and board tools default to that board. ${requirement}`
352
+ ].join("\n");
353
+ }
95
354
  return [
96
- "## Configured boards",
355
+ "## Boards",
97
356
  "",
98
- ...lines,
357
+ `You can use any accessible board on ${set.fallback.team === void 0 ? "your team" : `team \`${set.fallback.team}\``}. Call \`boards\` to discover available boards.`,
358
+ ...staticLines.length > 0 ? [
359
+ "",
360
+ "Configured boards:",
361
+ "",
362
+ ...staticLines
363
+ ] : [],
99
364
  "",
100
- `In a session a board started, replies stay on that board and board tools default to that board. ${requirement}`
365
+ "In a session a board started, replies stay on that board and board tools default to that board. Outside a board session, omitting `board` uses the team's default board (`General`); pass `board` with a board's name, ID (`brd_…`), or configured key to target another board."
101
366
  ].join("\n");
102
367
  }
103
- export { DEFAULT_BOARD_KEY, DEFAULT_WATCH_CHANNEL, formatConfiguredBoards, lookupBoard, resolveBoards, resolveSessionBoard, selectBoard };
368
+ export { DEFAULT_BOARD_KEY, DEFAULT_WATCH_CHANNEL, formatConfiguredBoards, listAccessibleBoards, matchesBoard, resolveBoards, resolveWakeBoard, selectBoardAsync };
@@ -25,7 +25,7 @@ export declare function settlementOf(output: unknown, taskId: string, capability
25
25
  readonly kind: string;
26
26
  readonly name: string;
27
27
  }): BoardSettlement | undefined;
28
- export declare function renewClaimDuringCall(client: () => BoardClient, claim: BoardClaim | null, callId: string): void;
28
+ export declare function renewClaimDuringCall(client: () => BoardClient | Promise<BoardClient>, claim: BoardClaim | null, callId: string): void;
29
29
  export declare function stopClaimRenewal(token: string): void;
30
30
  export declare function endClaimRenewal(slot: ClaimSlot, callId?: string): void;
31
31
  export declare function keepClaimInSlot(client: BoardClient, slot: ClaimSlot): Promise<void>;
@@ -4,7 +4,7 @@ import { createRequire as __eveCreateRequire } from "node:module";
4
4
  const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
- import { resolveSessionBoard } from "./boards.mjs";
7
+ import { selectBoardAsync } from "./boards.mjs";
8
8
  import { boardErrorCode } from "./client.mjs";
9
9
  import { boardClients } from "./watches.mjs";
10
10
  import { createLogger } from "eve/internal/channels";
@@ -85,8 +85,9 @@ function renewClaimDuringCall(client, claim, callId) {
85
85
  try {
86
86
  let resolved;
87
87
  try {
88
- resolved = client();
88
+ resolved = await client();
89
89
  } catch (error) {
90
+ if (boardErrorCode(error) !== void 0) return;
90
91
  log.warn("board task claim's board is no longer configured; dropping renewal", {
91
92
  error,
92
93
  task: renewal.claim.taskId
@@ -170,10 +171,17 @@ function sessionSlot() {
170
171
  };
171
172
  }
172
173
  function createBoardClaimsHook(settings) {
173
- const resolveClient = (boardKey) => {
174
+ const resolveClient = async (boardKey) => {
174
175
  try {
175
- return boardClients(resolveSessionBoard(settings(), boardKey)).deployment;
176
+ return boardClients(await selectBoardAsync(settings(), void 0, boardKey)).deployment;
176
177
  } catch (error) {
178
+ if (boardErrorCode(error) !== void 0) {
179
+ log.warn("couldn't resolve the held task's board; keeping the claim", {
180
+ board: boardKey,
181
+ error
182
+ });
183
+ return null;
184
+ }
177
185
  log.warn("board task claim's board is no longer configured; clearing the session claim", {
178
186
  board: boardKey,
179
187
  error
@@ -186,13 +194,13 @@ function createBoardClaimsHook(settings) {
186
194
  async "turn.started"() {
187
195
  const held = readSessionClaim();
188
196
  if (held === null) return;
189
- const client = resolveClient(held.board);
197
+ const client = await resolveClient(held.board);
190
198
  if (client !== null) await keepClaimInSlot(client, sessionSlot());
191
199
  },
192
200
  async "call.requested"() {
193
201
  const held = readSessionClaim();
194
202
  if (held === null) return;
195
- const client = resolveClient(held.board);
203
+ const client = await resolveClient(held.board);
196
204
  if (client !== null) await keepClaimInSlot(client, sessionSlot());
197
205
  },
198
206
  async "call.started"(event) {
@@ -200,10 +208,10 @@ function createBoardClaimsHook(settings) {
200
208
  if (held === null) return;
201
209
  const boardKey = held.board;
202
210
  if (event.data.taskId === void 0) {
203
- if (resolveClient(boardKey) === null) return;
204
- renewClaimDuringCall(() => boardClients(resolveSessionBoard(settings(), boardKey)).deployment, held.claim, event.data.callId);
211
+ if (await resolveClient(boardKey) === null) return;
212
+ renewClaimDuringCall(async () => boardClients(await selectBoardAsync(settings(), void 0, boardKey)).deployment, held.claim, event.data.callId);
205
213
  } else {
206
- const client = resolveClient(boardKey);
214
+ const client = await resolveClient(boardKey);
207
215
  if (client !== null) await renewClaimBeforeTask(client, sessionSlot());
208
216
  }
209
217
  },
@@ -211,7 +219,7 @@ function createBoardClaimsHook(settings) {
211
219
  endClaimRenewal(sessionSlot(), event.data.callId);
212
220
  const held = readSessionClaim();
213
221
  if (held === null) return;
214
- const client = resolveClient(held.board);
222
+ const client = await resolveClient(held.board);
215
223
  if (client !== null) await keepClaimInSlot(client, sessionSlot());
216
224
  },
217
225
  "turn.settled"() {
@@ -192,6 +192,16 @@ export interface BoardDiscovery {
192
192
  readonly url: string;
193
193
  readonly wake_by_path?: boolean;
194
194
  }
195
+ export interface ListedBoard {
196
+ readonly id: string;
197
+ readonly name: string;
198
+ readonly teamId?: string;
199
+ readonly visibility?: "team" | "private";
200
+ }
201
+ export interface ListedBoardsResult {
202
+ readonly boards: readonly ListedBoard[];
203
+ readonly defaultBoardId: string | null;
204
+ }
195
205
  export type BoardCan = "all" | readonly BoardPermission[] | Readonly<Record<string, "all" | readonly BoardPermission[]>>;
196
206
  export declare const BOARD_PERMISSIONS: readonly ["read", "post", "react", "label", "sync", "manage"];
197
207
  export type BoardPermission = (typeof BOARD_PERMISSIONS)[number];
@@ -264,14 +274,24 @@ export declare const BOARD_TEXT_LIMIT = 10000;
264
274
  export declare const BOARD_TAIL_LIMIT = 1000;
265
275
  export declare const BOARD_UPLOAD_LIMIT: number;
266
276
  export declare const BOARD_NAME_PATTERN: RegExp;
277
+ export declare const BOARD_ID_PATTERN: RegExp;
267
278
  export declare const BOARD_CHANNEL_SELECTOR: RegExp;
268
279
  export declare const BOARD_TASK_NOTE_LIMIT = 1000;
269
280
  export declare const BOARD_HOLD_KIND_PATTERN: RegExp;
270
281
  export declare const DEFAULT_BOARD_PROFILE = "eve";
282
+ export declare function normalizeBoardName(name: string): string;
283
+ export declare function isVercelBoardName(name: string): boolean;
284
+ export declare function listTeamBoards(options?: {
285
+ readonly team?: string;
286
+ }): Promise<ListedBoardsResult>;
271
287
  export declare function boardPostId(key: string): string;
272
288
  export declare function boardAllows(can: BoardCan | undefined, channel: string, permission: string): boolean;
273
289
  export declare function boardErrorCode(error: unknown): string | undefined;
274
- type BoardRef = Pick<BoardSettings, "name" | "team" | "url" | "profile">;
290
+ export declare function getCached<T>(cache: Map<string, T>, key: string): T | undefined;
291
+ export declare function setCached<T>(cache: Map<string, T>, key: string, value: T, max?: number): void;
292
+ type BoardRef = Pick<BoardSettings, "id" | "name" | "team" | "url" | "profile"> & {
293
+ readonly ensure?: boolean;
294
+ };
275
295
  export declare function createBoardClient(board: BoardRef, can?: BoardCan): BoardClient;
276
296
  export declare function withHints<T extends object>(target: T): T;
277
297
  export {};
@@ -5,7 +5,7 @@ const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { createHash } from "node:crypto";
8
- import { board } from "@vercel/board";
8
+ import { board, listBoards } from "@vercel/board";
9
9
  import { compileAccess } from "@vercel/board/access";
10
10
  const BOARD_TASK_STATES = [
11
11
  "waiting",
@@ -28,10 +28,34 @@ const BOARD_TEXT_LIMIT = 1e4;
28
28
  const BOARD_TAIL_LIMIT = 1e3;
29
29
  const BOARD_UPLOAD_LIMIT = 4194304;
30
30
  const BOARD_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9-]{0,31}$/u;
31
+ const BOARD_ID_PATTERN = /^brd_[^\s/]+$/u;
32
+ const VERCEL_BOARD_NAME_PATTERN = /^[^/]{1,64}$/u;
31
33
  const BOARD_CHANNEL_SELECTOR = /^[a-z0-9][a-z0-9_-]*(?:\/[a-z0-9][a-z0-9_-]*)*\/?$/u;
32
34
  const BOARD_TASK_NOTE_LIMIT = 1e3;
33
35
  const BOARD_HOLD_KIND_PATTERN = /^[a-z0-9][a-z0-9_.-]{0,63}$/u;
34
36
  const DEFAULT_BOARD_PROFILE = "eve";
37
+ function normalizeBoardName(name) {
38
+ return name.trim().normalize("NFC");
39
+ }
40
+ function isVercelBoardName(name) {
41
+ return VERCEL_BOARD_NAME_PATTERN.test(normalizeBoardName(name));
42
+ }
43
+ async function listTeamBoards(options) {
44
+ try {
45
+ const listed = await listBoards(options?.team === void 0 ? {} : { team: options.team });
46
+ return {
47
+ boards: listed.boards.map((entry) => ({
48
+ id: entry.id,
49
+ name: entry.name,
50
+ ...entry.teamId !== void 0 && { teamId: entry.teamId },
51
+ ...entry.visibility !== void 0 && { visibility: entry.visibility }
52
+ })),
53
+ defaultBoardId: listed.defaultBoardId
54
+ };
55
+ } catch (error) {
56
+ throw hinted(error);
57
+ }
58
+ }
35
59
  function boardPostId(key) {
36
60
  return `eve-${createHash("sha256").update(key).digest("hex").slice(0, 32)}`;
37
61
  }
@@ -46,20 +70,45 @@ function boardErrorCode(error) {
46
70
  const code = error.code;
47
71
  return typeof code === "string" ? code : void 0;
48
72
  }
73
+ const MAX_CACHED_HANDLES = 256;
49
74
  const handles = new Map();
50
75
  const principals = new Map();
51
- function handleKey({ name, team, url }) {
76
+ function getCached(cache, key) {
77
+ const value = cache.get(key);
78
+ if (value === void 0) return void 0;
79
+ cache.delete(key);
80
+ cache.set(key, value);
81
+ return value;
82
+ }
83
+ function setCached(cache, key, value, max = MAX_CACHED_HANDLES) {
84
+ cache.delete(key);
85
+ cache.set(key, value);
86
+ if (cache.size > max) {
87
+ const oldest = cache.keys().next().value;
88
+ if (oldest !== void 0) cache.delete(oldest);
89
+ }
90
+ }
91
+ function handleKey({ ensure, id, name, team, url }) {
52
92
  return JSON.stringify([
53
- name ?? null,
93
+ id ?? null,
94
+ id !== void 0 ? null : name ?? null,
95
+ id !== void 0 ? null : ensure ?? null,
54
96
  team ?? null,
55
97
  url?.trim().replace(/\/+$/u, "") || process.env.BOARD_URL?.trim().replace(/\/+$/u, "") || null,
56
- process.env.BOARD_TOKEN ?? null
98
+ process.env.BOARD_TOKEN ?? null,
99
+ process.env.VERCEL_ORG_ID ?? null,
100
+ process.env.VERCEL_AUTH_TOKEN ?? null
57
101
  ]);
58
102
  }
59
103
  function createBoardHandle(board$1) {
60
- const { name, team, url } = board$1;
61
- const options = {
104
+ const { ensure, id, name, team, url } = board$1;
105
+ if (id !== void 0 && url === void 0 && Boolean(process.env.BOARD_URL?.trim())) throw new Error(`Cannot target board "${id}" by ID while BOARD_URL is set; unset BOARD_URL to reach Vercel Board by ID.`);
106
+ const options = id !== void 0 ? {
107
+ id,
108
+ ...team !== void 0 && { team }
109
+ } : {
62
110
  ...name !== void 0 && { name },
111
+ ...name !== void 0 && ensure !== void 0 && { ensure },
63
112
  ...team !== void 0 && { team }
64
113
  };
65
114
  if (url === void 0) return board(options);
@@ -76,10 +125,10 @@ function createBoardClient(board, can) {
76
125
  const profile = (board.profile ?? "eve").toLowerCase();
77
126
  if (!BOARD_NAME_PATTERN.test(profile)) throw new Error(`Board profile "${board.profile}" is invalid: use a letter, then up to 31 letters, numbers, or hyphens.`);
78
127
  const key = handleKey(board);
79
- let base = handles.get(key);
128
+ let base = getCached(handles, key);
80
129
  if (base === void 0) {
81
130
  base = createBoardHandle(board);
82
- handles.set(key, base);
131
+ setCached(handles, key, base);
83
132
  }
84
133
  const handle = withHints(base.as(profile, can === void 0 ? void 0 : { can }));
85
134
  const meKey = `${key}\n${profile}`;
@@ -116,7 +165,7 @@ function createBoardClient(board, can) {
116
165
  profile,
117
166
  discovery: async () => await handle.discovery(),
118
167
  me: () => {
119
- let me = principals.get(meKey);
168
+ let me = getCached(principals, meKey);
120
169
  if (me === void 0) {
121
170
  me = handle.me().then(({ actor, principal }) => ({
122
171
  actor,
@@ -125,7 +174,7 @@ function createBoardClient(board, can) {
125
174
  principals.delete(meKey);
126
175
  throw error;
127
176
  });
128
- principals.set(meKey, me);
177
+ setCached(principals, meKey, me);
129
178
  }
130
179
  return me;
131
180
  },
@@ -389,4 +438,4 @@ function scheduleOf(schedule) {
389
438
  text: schedule.text
390
439
  };
391
440
  }
392
- export { BOARD_CHANNEL_SELECTOR, BOARD_HOLD_KIND_PATTERN, BOARD_NAME_PATTERN, BOARD_PERMISSIONS, BOARD_TAIL_LIMIT, BOARD_TASK_NOTE_LIMIT, BOARD_TASK_STATES, BOARD_TEXT_LIMIT, BOARD_UPLOAD_LIMIT, DEFAULT_BOARD_PROFILE, boardAllows, boardErrorCode, boardPostId, createBoardClient, withHints };
441
+ export { BOARD_CHANNEL_SELECTOR, BOARD_HOLD_KIND_PATTERN, BOARD_ID_PATTERN, BOARD_NAME_PATTERN, BOARD_PERMISSIONS, BOARD_TAIL_LIMIT, BOARD_TASK_NOTE_LIMIT, BOARD_TASK_STATES, BOARD_TEXT_LIMIT, BOARD_UPLOAD_LIMIT, DEFAULT_BOARD_PROFILE, boardAllows, boardErrorCode, boardPostId, createBoardClient, getCached, isVercelBoardName, listTeamBoards, normalizeBoardName, setCached, withHints };