@vercel/board 0.31.0 → 0.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -20
- package/dist/{access-CY5xVMIK.mjs → access-N3XmkKXg.mjs} +3 -3
- package/dist/access.d.mts +4 -5
- package/dist/access.mjs +5 -5
- package/dist/{actors-Bm-ojWWT.mjs → actors-ihyN47OV.mjs} +3 -3
- package/dist/{auth-DLYSt_-A.d.mts → auth-D6z3rMNj.d.mts} +11 -93
- package/dist/{auth-CyO2aw5n.mjs → auth-r-_PeZyw.mjs} +39 -151
- package/dist/{backend-Bob-5CM7.d.mts → backend-CWpyR1A7.d.mts} +81 -51
- package/dist/backend-local.d.mts +28 -0
- package/dist/backend-local.mjs +2 -0
- package/dist/{chat-provider-DkFp2hrh.mjs → chat-provider-9hCT654s.mjs} +2 -2
- package/dist/{chat-provider-BChYrrA7.d.mts → chat-provider-DJpFUaFv.d.mts} +2 -3
- package/dist/cli-commands.d.mts +1 -1
- package/dist/cli-commands.mjs +1 -1
- package/dist/cli-embedded.d.mts +2 -2
- package/dist/cli-embedded.mjs +2 -2
- package/dist/cli.mjs +6 -6
- package/dist/{commands-DK4W3HCJ.d.mts → commands-BOBQHVqM.d.mts} +14 -0
- package/dist/{commands-L1JSGz2Z.mjs → commands-CHoMl06v.mjs} +39 -12
- package/dist/{conformance-DK43HiHf.mjs → conformance-qKmGLTAT.mjs} +40 -5
- package/dist/conformance.d.mts +1 -1
- package/dist/conformance.mjs +1 -1
- package/dist/{engine-DurYIRt8.mjs → engine-JxgZiikU.mjs} +6 -8
- package/dist/{errors-CJXhhzvT.mjs → errors-Pk0XV1hK.mjs} +56 -2
- package/dist/{events-lujPA3gQ.mjs → events-IQg0k281.mjs} +2 -2
- package/dist/exports-BuKjVq2t.d.mts +4 -0
- package/dist/exports-gHDHlg0i.mjs +3207 -0
- package/dist/{external-D3p5T57R.mjs → external-CYe424fO.mjs} +1 -1
- package/dist/{folds-DLUzfibJ.d.mts → folds-DjFTiqIM.d.mts} +38 -44
- package/dist/index-CXvvYNYj.d.mts +11 -0
- package/dist/index.d.mts +9 -8
- package/dist/index.mjs +21 -8
- package/dist/index.node.d.mts +5 -6
- package/dist/index.node.mjs +3 -3
- package/dist/inspect/app.js +95 -95
- package/dist/{internal-CvsrprnU-zZMpDiRY.mjs → internal-CvsrprnU-CEPOUpAv.mjs} +63 -43
- package/dist/local-BbLjA5vI.mjs +8818 -0
- package/dist/{main-Dz-8komG.mjs → main-CQpCZJFw.mjs} +140 -36
- package/dist/{backend-a2/store-memory.mjs → memory-7RRnLa4X.mjs} +3 -3
- package/dist/middleware-BU7rVi9F.mjs +103 -0
- package/dist/{client-COfYrgfV.d.mts → provider-BlzUvcM9.d.mts} +665 -5
- package/dist/{schemas-DBmUO6pr.mjs → schemas-BG205xds.mjs} +2 -5
- package/dist/{serve-CTmow-YH.mjs → serve-D8_W4UN6.mjs} +33 -24
- package/dist/{node-BgeGcwX0.mjs → server-BiIUXWbU.mjs} +419 -6
- package/dist/{serving-DBFRo6U_.mjs → serving-D7rcUtSC.mjs} +1 -1
- package/dist/{sql-CT5xVuGr.mjs → sql-BQzKUqQt.mjs} +349 -114
- package/dist/sqlite-DCtZFEVm.mjs +30 -0
- package/dist/{sqlite-db-0WeSOEZN.mjs → sqlite-db-qLTs52Ny.mjs} +2 -3
- package/dist/{store-codec-pAG2oPgQ-SqDXlPBR.mjs → store-N8PXxDAS-BdL4Sq-f.mjs} +6 -2
- package/dist/{store-memory-B0PkVSuQ.mjs → store-memory-CKQVEzXN.mjs} +2 -4
- package/dist/store-memory-OdGsc-t_.mjs +2 -0
- package/dist/{store-polling-BZt2Rf3D-Div-bJ_D.mjs → store-polling-BZt2Rf3D-oh3aU_An.mjs} +1 -1
- package/dist/store-sqlite-CTxAVCcz.mjs +2 -0
- package/dist/{store-sqlite-D85t3tE7.mjs → store-sqlite-D6fIszST.mjs} +3 -4
- package/dist/sync-chat-sdk.d.mts +2 -2
- package/dist/sync-chat-sdk.mjs +2 -2
- package/dist/sync-github.d.mts +2 -2
- package/dist/sync-github.mjs +2 -2
- package/dist/sync-linear.d.mts +2 -3
- package/dist/sync-linear.mjs +2 -2
- package/dist/sync-slack.d.mts +3 -3
- package/dist/sync-slack.mjs +4 -4
- package/dist/sync.d.mts +2 -2
- package/dist/sync.mjs +2 -2
- package/dist/{watchers-hash-BjwlnGD9.mjs → targets-CknPGGVi.mjs} +40 -10
- package/dist/{tokens-Dnyd_y1n.mjs → tokens-DPKjl3jf.mjs} +15 -43
- package/docs/01-board/01-mounting.md +243 -288
- package/docs/01-board/03-identity.md +41 -50
- package/docs/01-board/04-messages.md +19 -16
- package/docs/01-board/05-reading.md +3 -3
- package/docs/01-board/06-watchers.md +58 -105
- package/docs/01-board/07-schedules.md +21 -41
- package/docs/01-board/08-middleware.md +11 -17
- package/docs/01-board/09-access.md +76 -313
- package/docs/01-board/10-local.md +81 -0
- package/docs/01-quickstart.md +49 -126
- package/docs/02-sync/01-overview.md +25 -80
- package/docs/02-sync/02-functions.md +10 -16
- package/docs/02-sync/03-slack.md +13 -26
- package/docs/02-sync/04-github.md +8 -20
- package/docs/02-sync/07-linear.md +6 -10
- package/docs/03-guides/02-inspector.md +3 -3
- package/docs/03-guides/03-ci.md +88 -128
- package/docs/03-guides/04-triage.md +7 -15
- package/docs/03-guides/05-agent-factory.md +30 -36
- package/docs/04-reference/01-cli.md +118 -32
- package/docs/04-reference/02-board.md +60 -74
- package/docs/04-reference/03-http.md +119 -57
- package/docs/04-reference/05-conformance.md +31 -45
- package/docs/index.md +41 -65
- package/package.json +12 -83
- package/dist/a2-DngWY2Eb.mjs +0 -4238
- package/dist/access-DPcrKIH_.d.mts +0 -37
- package/dist/backend-a2/blob-vercel.d.mts +0 -8
- package/dist/backend-a2/blob-vercel.mjs +0 -81
- package/dist/backend-a2/contract.d.mts +0 -828
- package/dist/backend-a2/contract.mjs +0 -5
- package/dist/backend-a2/scheduler-local.d.mts +0 -11
- package/dist/backend-a2/scheduler-local.mjs +0 -2
- package/dist/backend-a2/scheduler-qstash.d.mts +0 -79
- package/dist/backend-a2/scheduler-qstash.mjs +0 -522
- package/dist/backend-a2/scheduler-vercel.d.mts +0 -38
- package/dist/backend-a2/scheduler-vercel.mjs +0 -204
- package/dist/backend-a2/store-memory.d.mts +0 -11
- package/dist/backend-a2/store-postgres.d.mts +0 -38
- package/dist/backend-a2/store-postgres.mjs +0 -2977
- package/dist/backend-a2/store-redis-http.d.mts +0 -17
- package/dist/backend-a2/store-redis-http.mjs +0 -520
- package/dist/backend-a2/store-redis.d.mts +0 -31
- package/dist/backend-a2/store-redis.mjs +0 -88
- package/dist/backend-a2/store-sqlite.d.mts +0 -12
- package/dist/backend-a2/store-sqlite.mjs +0 -31
- package/dist/backend-a2.d.mts +0 -2633
- package/dist/backend-a2.mjs +0 -3
- package/dist/backend-http-BRrRbjRx.d.mts +0 -672
- package/dist/backend-http-CvUKOn-m.mjs +0 -585
- package/dist/backend-http-D8mUzuKQ.mjs +0 -18
- package/dist/backend-http.d.mts +0 -10
- package/dist/backend-http.mjs +0 -2
- package/dist/backend-http.node.d.mts +0 -10
- package/dist/backend-http.node.mjs +0 -2
- package/dist/backend-vercel-Ba8JDtqW.mjs +0 -86
- package/dist/backend-vercel-BaSEUdwg.d.mts +0 -674
- package/dist/backend-vercel-CmY9yZ9m.mjs +0 -1656
- package/dist/backend-vercel.d.mts +0 -9
- package/dist/backend-vercel.mjs +0 -11
- package/dist/backend-vercel.node.d.mts +0 -17
- package/dist/backend-vercel.node.mjs +0 -2
- package/dist/blob-Bx8QPWEd.d.mts +0 -40
- package/dist/blob-WbB2DJKn.mjs +0 -201
- package/dist/errors-2vGs49Db.d.mts +0 -16
- package/dist/exports-CWIdN0Ub.mjs +0 -1389
- package/dist/exports-FBOQWT7O.d.mts +0 -5
- package/dist/files-SniSmeEr.mjs +0 -47
- package/dist/folds-Cu9Q9zyQ.mjs +0 -207
- package/dist/index-Ho-ayyQL.d.mts +0 -11
- package/dist/index.default-BUcwDaAe.mjs +0 -12
- package/dist/local-C76Fy5ad.mjs +0 -44
- package/dist/middleware-BavYSDUa.mjs +0 -62
- package/dist/platform-B4TnJtWu-Do3agKr5.mjs +0 -32
- package/dist/project-CQ4VUibA.mjs +0 -124
- package/dist/provider-gynDUoyW.d.mts +0 -665
- package/dist/redis-tables-DHf85ixI.mjs +0 -3895
- package/dist/reducer-Bswr11ar-P324o9vn.mjs +0 -74
- package/dist/reducer-CYPHsSmd-BXjGiptm.d.mts +0 -170
- package/dist/reducers-DcENwtwZ.mjs +0 -538
- package/dist/retryable-lazy-DZWmHpii-DpTc5PIP.mjs +0 -19
- package/dist/scheduler-task-X1SToDjP-D2Il2rln.mjs +0 -69
- package/dist/server-B9gu0qi1-DI1WvcVK.d.mts +0 -391
- package/dist/server-DG8D6VV0.mjs +0 -17
- package/dist/server-DX7mM6nm-D7N_7bug.mjs +0 -3611
- package/dist/session-clear-XJYpmUpg-2q8l_FJR.mjs +0 -63
- package/dist/store-DEzcHZOA-B-5vhxef.d.mts +0 -540
- package/dist/store-N8PXxDAS-DWWgv-Vz.mjs +0 -5
- package/dist/store-memory-4IBl0Ztu.mjs +0 -2
- package/dist/store-presence-polling-JuAy2Ck2-Dh-g_KYM.mjs +0 -109
- package/dist/store-sqlite-iBTYYKBj.mjs +0 -2
- package/dist/stream-buffer-DrTyiIuo-Be10yOBR.mjs +0 -53
- package/dist/targets-Cgjs29T0.mjs +0 -33
- package/dist/types-CmrFjpml.d.mts +0 -102
- package/dist/wait-until-Dw4XrIDQ.mjs +0 -42
- package/docs/01-board/02-database.md +0 -258
- package/docs/04-reference/04-log.md +0 -247
- package/sql/postgres/board.sql +0 -145
- package/sql/postgres/notifications.sql +0 -24
- package/sql/postgres/schema.sql +0 -451
|
@@ -0,0 +1,3207 @@
|
|
|
1
|
+
import { a as forbidden, c as toErrorResponse, d as createBoardClient, f as duration, g as fileName, h as IMPORT_BYTES_MAX, l as unauthorized, n as RejectedError, o as json, p as ATTACHMENT_BYTES_MAX, r as badRequest, s as notFound, t as HttpError, u as BoardError, v as mediaType } from "./errors-Pk0XV1hK.mjs";
|
|
2
|
+
import { m as RemoteWatcherId } from "./schemas-BG205xds.mjs";
|
|
3
|
+
import { A as PostBody, B as SyncFindQuery, C as InboxNextQuery, D as LinkedQuery, E as LabelBody, F as SchedulesQuery, G as TypingBody, H as SyncReceiptBody, I as SourceJoinBody, K as UploadStartBody, L as SourceReadQuery, M as Ref, N as RegisterBody, O as MatchesQuery, P as ScheduleBody, R as SyncBody, S as InboxAckBody, T as InboxQuery, U as ThreadsQuery, V as SyncImportBody, W as TokenBody, _ as CreateChannelBody, a as compileWatcher, b as EventsQuery, c as METHODS, d as queryObject, f as readCapped, g as AckBody, h as VERSION, i as canonicalWatchers, j as ReactBody, k as MessagesQuery, l as createRouter, m as SYNC, n as syncTarget, p as readJson, r as withEmailMentions, t as mentionsEmails, u as openapi, v as DeleteBody, w as InboxPushBody, x as GrantBody, y as EditBody, z as SyncCopiesQuery } from "./targets-CknPGGVi.mjs";
|
|
4
|
+
import { i as waitUntil, l as sha256, o as derivedId, r as runMiddleware, t as DroppedError } from "./middleware-BU7rVi9F.mjs";
|
|
5
|
+
import { a as parsePattern, i as compileAccess, n as PERMISSIONS, o as parseScope, s as scopeOf } from "./access-N3XmkKXg.mjs";
|
|
6
|
+
import { i as resolveActor, r as claimsOf, t as KNOWN_AGENTS } from "./actors-ihyN47OV.mjs";
|
|
7
|
+
import { _ as verifiesTokens, a as VERCEL_ISSUER, c as createAuthority, d as hostPrincipal, h as tokenHash, l as fromTokens, u as grantIssuers } from "./auth-r-_PeZyw.mjs";
|
|
8
|
+
//#region src/server/registrant.ts
|
|
9
|
+
/** Registering again this soon after the same registration only repeats it. */
|
|
10
|
+
const REGISTER_EVERY_MS = 1e4;
|
|
11
|
+
/** How long one wake-up runs matches before it leaves the rest to the next. */
|
|
12
|
+
const DRAIN_MS = 24e4;
|
|
13
|
+
/** How long a wake-up waits for what it pulled to run before it answers: under the 3 seconds Vercel's API gives it. */
|
|
14
|
+
const WAKE_ANSWER_MS = 2e3;
|
|
15
|
+
/** A pull with nothing to hand out holds this long, when the board pulls on its own. */
|
|
16
|
+
const POLL_WAIT_S = 25;
|
|
17
|
+
const describe = (error) => ((error instanceof Error ? error.message : String(error)) || "unknown error").slice(0, 500);
|
|
18
|
+
/** Only an https URL can be woken; anything else pulls on its own. */
|
|
19
|
+
const wakeable = (here) => here?.startsWith("https://") ? here : null;
|
|
20
|
+
/**
|
|
21
|
+
* A path on this Vercel project for a board that wakes by path, from `here`, this board's URL:
|
|
22
|
+
* from production, or from a preview of a branch, which it names. Null anywhere else (off Vercel,
|
|
23
|
+
* development, a custom environment), where only a URL wakes it.
|
|
24
|
+
*/
|
|
25
|
+
function wakePath(here) {
|
|
26
|
+
const env = typeof process !== "undefined" && process.env.VERCEL === "1" ? process.env : null;
|
|
27
|
+
const environment = env?.VERCEL_TARGET_ENV || env?.VERCEL_ENV;
|
|
28
|
+
const branch = environment === "preview" ? env?.VERCEL_GIT_COMMIT_REF || null : null;
|
|
29
|
+
if (!here || environment !== "production" && !branch) return null;
|
|
30
|
+
return {
|
|
31
|
+
path: new URL(here).pathname,
|
|
32
|
+
...branch ? { branch } : {}
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Runs a board's watchers on another board that matches them: it registers them there, is woken
|
|
37
|
+
* when one matches, with nothing in the wake-up but a hash, and pulls what matched with its own
|
|
38
|
+
* credentials, runs it, and acks it. When it can't be woken (no https URL of its own: a dev
|
|
39
|
+
* server, say), it pulls on its own. http() and vercel() run their watchers this way.
|
|
40
|
+
*/
|
|
41
|
+
function registrant(options) {
|
|
42
|
+
const { registry, rethrow } = options;
|
|
43
|
+
const bound = options.binding;
|
|
44
|
+
let last = null;
|
|
45
|
+
let registering = null;
|
|
46
|
+
/** Registers this board's watchers with the other board, as itself, replacing its last registration. */
|
|
47
|
+
async function register(here) {
|
|
48
|
+
const current = await options.hash();
|
|
49
|
+
if (last && last.url === here && last.result.hash === current && Date.now() - last.at < REGISTER_EVERY_MS) return last.result;
|
|
50
|
+
registering ??= options.wakeAt(here).then((where) => registry.register(where)).then((result) => {
|
|
51
|
+
last = {
|
|
52
|
+
url: here,
|
|
53
|
+
at: Date.now(),
|
|
54
|
+
result
|
|
55
|
+
};
|
|
56
|
+
return result;
|
|
57
|
+
}).finally(() => {
|
|
58
|
+
registering = null;
|
|
59
|
+
});
|
|
60
|
+
return registering;
|
|
61
|
+
}
|
|
62
|
+
/** Runs one match and acks it: done, its error, or a skip for a watcher this board no longer has. */
|
|
63
|
+
async function runOne(match) {
|
|
64
|
+
let outcome = {};
|
|
65
|
+
if (!bound().subscriptions[match.watcher]) outcome = { skip: true };
|
|
66
|
+
else try {
|
|
67
|
+
await bound().run(match.watcher, match.event, {
|
|
68
|
+
trigger: `watch:${match.watcher}:${match.id}`,
|
|
69
|
+
attempt: match.attempt + 1
|
|
70
|
+
});
|
|
71
|
+
} catch (error) {
|
|
72
|
+
console.error(`[board] watcher ${match.watcher} failed:`, error);
|
|
73
|
+
outcome = { error: describe(error) };
|
|
74
|
+
}
|
|
75
|
+
await registry.ack(match.id, {
|
|
76
|
+
lease: match.lease,
|
|
77
|
+
...outcome
|
|
78
|
+
}).catch((error) => console.error(`[board] couldn't ack a match:`, describe(error)));
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Pulls and runs what's matched until nothing's left, or this run's time is up, and what sync
|
|
82
|
+
* queued in its inbox. A thread's matches come one at a time.
|
|
83
|
+
*/
|
|
84
|
+
async function drain() {
|
|
85
|
+
let ran = 0;
|
|
86
|
+
const until = Date.now() + DRAIN_MS;
|
|
87
|
+
while (Date.now() < until) {
|
|
88
|
+
const matches = await registry.matches({ limit: 10 });
|
|
89
|
+
if (matches.length === 0) break;
|
|
90
|
+
await Promise.all(matches.map(runOne));
|
|
91
|
+
ran += matches.length;
|
|
92
|
+
}
|
|
93
|
+
return ran + await bound().pull();
|
|
94
|
+
}
|
|
95
|
+
let polling = null;
|
|
96
|
+
/** For a board that can't be woken: pulls on its own, each pull held open until something matches. */
|
|
97
|
+
function poll() {
|
|
98
|
+
if (polling) return;
|
|
99
|
+
const controller = polling = new AbortController();
|
|
100
|
+
(async () => {
|
|
101
|
+
for (let pause = 1e3; !controller.signal.aborted;) try {
|
|
102
|
+
await register(null);
|
|
103
|
+
const matches = await registry.matches({
|
|
104
|
+
limit: 10,
|
|
105
|
+
wait: POLL_WAIT_S,
|
|
106
|
+
signal: controller.signal
|
|
107
|
+
});
|
|
108
|
+
await Promise.all(matches.map(runOne));
|
|
109
|
+
await bound().pull();
|
|
110
|
+
pause = 1e3;
|
|
111
|
+
} catch (error) {
|
|
112
|
+
if (controller.signal.aborted) break;
|
|
113
|
+
console.error(`[board] couldn't pull matches from ${options.remote}:`, describe(error));
|
|
114
|
+
await new Promise((resolve) => setTimeout(resolve, pause));
|
|
115
|
+
pause = Math.min(pause * 2, 6e4);
|
|
116
|
+
}
|
|
117
|
+
})();
|
|
118
|
+
}
|
|
119
|
+
let started = null;
|
|
120
|
+
let failedAt = 0;
|
|
121
|
+
/**
|
|
122
|
+
* On first use, a board with watchers or sync registers them if it knows its URL. One on Vercel
|
|
123
|
+
* learns its mount path from a request (a `POST /watchers`, a webhook, or a wake-up); one that
|
|
124
|
+
* can't be woken registers without one and pulls instead. Resolves once the first try is done.
|
|
125
|
+
* One that fails tries again on a later use, at most every `REGISTER_EVERY_MS`: nothing would
|
|
126
|
+
* wake a board the other doesn't know.
|
|
127
|
+
*/
|
|
128
|
+
function start() {
|
|
129
|
+
if (started) return started;
|
|
130
|
+
if (!options.hasWork() || Date.now() - failedAt < REGISTER_EVERY_MS) return Promise.resolve();
|
|
131
|
+
const here = wakeable(bound().url());
|
|
132
|
+
if (!here && typeof process !== "undefined" && process.env.VERCEL === "1") return Promise.resolve();
|
|
133
|
+
started = register(here).then(() => {}, (error) => {
|
|
134
|
+
started = null;
|
|
135
|
+
failedAt = Date.now();
|
|
136
|
+
console.error(`[board] couldn't register with ${options.remote}:`, describe(error));
|
|
137
|
+
});
|
|
138
|
+
if (!here) poll();
|
|
139
|
+
return started;
|
|
140
|
+
}
|
|
141
|
+
return {
|
|
142
|
+
start,
|
|
143
|
+
routes: [{
|
|
144
|
+
method: "POST",
|
|
145
|
+
path: "/wake",
|
|
146
|
+
async handle(request) {
|
|
147
|
+
started ??= Promise.resolve();
|
|
148
|
+
const stale = request.headers.get("x-board-watchers") !== await options.hash();
|
|
149
|
+
const running = (async () => {
|
|
150
|
+
if (stale) await register(wakeable(bound().url()));
|
|
151
|
+
return drain();
|
|
152
|
+
})();
|
|
153
|
+
waitUntil(running.catch((error) => console.error(`[board] couldn't run what woke it:`, describe(error))));
|
|
154
|
+
let timer;
|
|
155
|
+
const waited = new Promise((resolve) => timer = setTimeout(() => resolve(null), WAKE_ANSWER_MS));
|
|
156
|
+
try {
|
|
157
|
+
const ran = await Promise.race([running.catch(rethrow), waited]);
|
|
158
|
+
return ran === null ? new Response(null, { status: 202 }) : json({ ran });
|
|
159
|
+
} finally {
|
|
160
|
+
clearTimeout(timer);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}, {
|
|
164
|
+
method: "POST",
|
|
165
|
+
path: "/watchers",
|
|
166
|
+
async handle(request, { caller }) {
|
|
167
|
+
if (caller) return options.registerFor(caller, request);
|
|
168
|
+
started ??= Promise.resolve();
|
|
169
|
+
const here = wakeable(bound().url());
|
|
170
|
+
const registration = await register(here).catch(rethrow);
|
|
171
|
+
if (!here) poll();
|
|
172
|
+
return json(registration);
|
|
173
|
+
}
|
|
174
|
+
}],
|
|
175
|
+
/** Registers this board's watchers with the other board now, as `POST /watchers` does. */
|
|
176
|
+
registerNow: () => register(wakeable(bound().url())),
|
|
177
|
+
/** Stops pulling, for a board that pulls on its own. */
|
|
178
|
+
close: () => {
|
|
179
|
+
polling?.abort();
|
|
180
|
+
polling = null;
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
//#endregion
|
|
185
|
+
//#region src/server/backend-vercel.ts
|
|
186
|
+
const PROFILE = /^[A-Za-z][A-Za-z0-9-]{0,31}$/;
|
|
187
|
+
const SESSION = /^[A-Za-z0-9_.:-]{1,128}$/;
|
|
188
|
+
const CLIENT_ID = /^[A-Za-z0-9_.:-]{1,128}$/;
|
|
189
|
+
const MESSAGE_ID = /^msg_([0-9a-f-]{36})_([1-9]\d*)$/;
|
|
190
|
+
/** Whether `value` is a message ID Vercel's API hands out (`msg_<thread>_<n>`): the CLI takes one as a message, even where a channel has its name. */
|
|
191
|
+
const isApiMessageId = (value) => MESSAGE_ID.test(value);
|
|
192
|
+
/** A cursor this backend made: a time, then the position it names, in base 36. */
|
|
193
|
+
const CURSOR = /^([0-9a-z]+)(?:\.([0-9a-z]+))?$/;
|
|
194
|
+
/** The API's own cursor for one channel, which its message list and feed share, and any process resumes. */
|
|
195
|
+
const API_CURSOR = /^c1\./;
|
|
196
|
+
/** The API's longest page of a channel's messages, and longest long-poll, in seconds. */
|
|
197
|
+
const PAGE_MAX = 100;
|
|
198
|
+
const WAIT_MAX_S = 25;
|
|
199
|
+
/** Pages a filtered read of one channel scans for matches before it answers with what it found. */
|
|
200
|
+
const SCAN_PAGES = 10;
|
|
201
|
+
/** A file as the board names it. */
|
|
202
|
+
const fileOf = ({ id, name, type, size }) => ({
|
|
203
|
+
id,
|
|
204
|
+
name,
|
|
205
|
+
type,
|
|
206
|
+
size
|
|
207
|
+
});
|
|
208
|
+
const notSupported = (what) => new HttpError(501, "not_supported", `Vercel's boards don't support ${what} yet`);
|
|
209
|
+
/** What credentials may do when the API doesn't say: read, post, react, and label everywhere, as any it lets in. */
|
|
210
|
+
const DEFAULT_CAN = { "*": [
|
|
211
|
+
"read",
|
|
212
|
+
"post",
|
|
213
|
+
"react",
|
|
214
|
+
"label"
|
|
215
|
+
] };
|
|
216
|
+
/**
|
|
217
|
+
* What the API says these credentials may do, in board's words: each channel pattern board can
|
|
218
|
+
* read, with the permissions board knows, the rest dropped, and what those imply. `DEFAULT_CAN`
|
|
219
|
+
* when it says nothing board reads as one.
|
|
220
|
+
*/
|
|
221
|
+
function canOf(can) {
|
|
222
|
+
if (typeof can !== "object" || can === null || Array.isArray(can)) return DEFAULT_CAN;
|
|
223
|
+
const known = new Set(PERMISSIONS);
|
|
224
|
+
const out = {};
|
|
225
|
+
for (const [pattern, permissions] of Object.entries(can)) {
|
|
226
|
+
if (!Array.isArray(permissions)) continue;
|
|
227
|
+
try {
|
|
228
|
+
parsePattern(pattern);
|
|
229
|
+
} catch {
|
|
230
|
+
continue;
|
|
231
|
+
}
|
|
232
|
+
out[pattern] = permissions.filter((permission) => known.has(permission));
|
|
233
|
+
}
|
|
234
|
+
return compileAccess(out).summary();
|
|
235
|
+
}
|
|
236
|
+
/** Epoch milliseconds before this are the year 2001: a number under it is epoch seconds, as a JWT's `exp` is. */
|
|
237
|
+
const SECONDS_BEFORE = 0xe8d4a51000;
|
|
238
|
+
/**
|
|
239
|
+
* When the API says these credentials stop working, as an ISO time: from epoch milliseconds (or
|
|
240
|
+
* epoch seconds, under `SECONDS_BEFORE`) or a time it gives, null for none.
|
|
241
|
+
*/
|
|
242
|
+
function expiryOf(at) {
|
|
243
|
+
if (typeof at === "number" && Number.isFinite(at)) return new Date(at < SECONDS_BEFORE ? at * 1e3 : at).toISOString();
|
|
244
|
+
if (typeof at === "string" && !Number.isNaN(Date.parse(at))) return new Date(at).toISOString();
|
|
245
|
+
return null;
|
|
246
|
+
}
|
|
247
|
+
/** What a caller board() verified gets: board() serves no requests for a board on Vercel's, so it never sends one. */
|
|
248
|
+
const servesNone = () => new HttpError(404, "not_found", "this board uses Vercel's, and answers only wake-ups and webhooks");
|
|
249
|
+
const apiKind = (kind) => kind === "app" ? "workflow" : kind;
|
|
250
|
+
/** A UUIDv7, which the API takes as an operation ID. */
|
|
251
|
+
function operationId() {
|
|
252
|
+
const bytes = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16));
|
|
253
|
+
const now = BigInt(Date.now());
|
|
254
|
+
for (let i = 0; i < 6; i++) bytes[i] = Number(now >> BigInt(8 * (5 - i)) & 255n);
|
|
255
|
+
bytes[6] = bytes[6] & 15 | 112;
|
|
256
|
+
bytes[8] = bytes[8] & 63 | 128;
|
|
257
|
+
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
258
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
259
|
+
}
|
|
260
|
+
const iso = (ms) => new Date(ms).toISOString();
|
|
261
|
+
const idAt = (threadId, sequence) => `msg_${threadId.slice(4)}_${sequence}`;
|
|
262
|
+
/** Where a message ID points: its thread and its place in it. Null for one that isn't a message's. */
|
|
263
|
+
function locate(id) {
|
|
264
|
+
const found = MESSAGE_ID.exec(id);
|
|
265
|
+
return found ? {
|
|
266
|
+
threadId: `thr_${found[1]}`,
|
|
267
|
+
sequence: Number(found[2])
|
|
268
|
+
} : null;
|
|
269
|
+
}
|
|
270
|
+
/** A principal as board names it: `vercel:user:<id>`, `vercel:app:<id>`, `vercel:project:<id>:<env>`. */
|
|
271
|
+
function principalId(principal) {
|
|
272
|
+
if (principal.type === "user") return `vercel:user:${principal.userId}`;
|
|
273
|
+
if (principal.type === "app") return `vercel:app:${principal.clientId}`;
|
|
274
|
+
return `vercel:project:${principal.projectId}:${principal.environment}`;
|
|
275
|
+
}
|
|
276
|
+
const authorOf = (actor) => ({
|
|
277
|
+
actor: actor.id,
|
|
278
|
+
principal: principalId(actor.principal),
|
|
279
|
+
profile: actor.profile?.name ?? null,
|
|
280
|
+
session: actor.session ?? null
|
|
281
|
+
});
|
|
282
|
+
/** Who cancels a schedule when no one did: the API, once its creator can no longer post it, as a local board's scheduler. */
|
|
283
|
+
const SCHEDULER = {
|
|
284
|
+
actor: "board:schedule",
|
|
285
|
+
principal: "board:schedule",
|
|
286
|
+
profile: null,
|
|
287
|
+
session: null
|
|
288
|
+
};
|
|
289
|
+
/** The API names nobody, so an actor's handle is its profile, or a short form of its principal. */
|
|
290
|
+
function actorView(actor) {
|
|
291
|
+
const { principal } = actor;
|
|
292
|
+
const base = principal.type === "user" ? `user-${principal.userId.slice(0, 6).toLowerCase()}` : principal.type === "app" ? `app-${principal.clientId.slice(0, 6).toLowerCase()}` : principal.environment === "production" ? principal.projectId : `${principal.projectId}@${principal.environment}`;
|
|
293
|
+
const handle = actor.profile?.name ?? base;
|
|
294
|
+
const kind = actor.profile ? "agent" : principal.type === "user" ? "person" : principal.type === "project" ? "deployment" : "workflow";
|
|
295
|
+
return {
|
|
296
|
+
id: actor.id,
|
|
297
|
+
kind,
|
|
298
|
+
handle,
|
|
299
|
+
name: handle,
|
|
300
|
+
avatar: actor.profile?.avatar ?? null
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Vercel's board for your team, in Vercel's API: this deployment keeps nothing and reads and writes
|
|
305
|
+
* it as itself, its people as themselves. Messages, threads, reactions, labels, a channel's
|
|
306
|
+
* changes, schedules, files, and watchers work; what the API keeps none of yet (sync) answers 501.
|
|
307
|
+
*/
|
|
308
|
+
function createVercel(options, environment) {
|
|
309
|
+
const origin = (options.api ?? "https://api.vercel.com").replace(/\/+$/, "");
|
|
310
|
+
if (!/^https:\/\/[^/]+$|^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(origin)) throw new Error(`vercel: ${origin} isn't Vercel's API: pass an https origin`);
|
|
311
|
+
if (!options.fetch && !environment) throw new Error("vercel: pass a fetch that sends credentials: outside Node there's no environment to find them in");
|
|
312
|
+
const doFetch = options.fetch ?? environment.fetch();
|
|
313
|
+
const filesFetch = options.files ?? fetch;
|
|
314
|
+
let binding = null;
|
|
315
|
+
/** This board's own code's names, which a caller here never takes as its profile. */
|
|
316
|
+
const own = /* @__PURE__ */ new Set();
|
|
317
|
+
/** The board `board({ name })` names: null for the team's default board, or when `board` names one by its ID. */
|
|
318
|
+
const boardName = () => options.board ? null : binding?.name ?? null;
|
|
319
|
+
let team = null;
|
|
320
|
+
const teamId = () => {
|
|
321
|
+
const given = binding?.team ?? options.team;
|
|
322
|
+
return team ??= given ? Promise.resolve(given) : environment?.team() ?? Promise.resolve(null);
|
|
323
|
+
};
|
|
324
|
+
/** One request to the API, as `who`. Its errors are the API's own, with its status and code. */
|
|
325
|
+
async function api(who, method, path, init = {}) {
|
|
326
|
+
const url = new URL(`${origin}/v1/messageboard${path}`);
|
|
327
|
+
const id = await teamId();
|
|
328
|
+
if (id) url.searchParams.set(id.startsWith("team_") ? "teamId" : "slug", id);
|
|
329
|
+
for (const [name, value] of Object.entries(init.query ?? {})) if (value !== void 0) url.searchParams.set(name, value);
|
|
330
|
+
const headers = { "content-type": "application/json" };
|
|
331
|
+
if (who.profile) headers["x-board-profile"] = who.profile.name;
|
|
332
|
+
if (who.profile?.avatar?.startsWith("https://")) headers["x-board-avatar"] = who.profile.avatar;
|
|
333
|
+
if (who.session && SESSION.test(who.session)) headers["x-board-session"] = who.session;
|
|
334
|
+
let response;
|
|
335
|
+
try {
|
|
336
|
+
response = await doFetch(url, {
|
|
337
|
+
method,
|
|
338
|
+
headers,
|
|
339
|
+
redirect: "error",
|
|
340
|
+
...init.body !== void 0 ? { body: JSON.stringify(init.body) } : {},
|
|
341
|
+
...init.signal ? { signal: init.signal } : {}
|
|
342
|
+
});
|
|
343
|
+
} catch (error) {
|
|
344
|
+
if (error instanceof HttpError || error instanceof Error && error.name === "AbortError") throw error;
|
|
345
|
+
throw new HttpError(502, "unreachable", `Vercel's API didn't answer: ${error instanceof Error ? error.message : String(error)}`);
|
|
346
|
+
}
|
|
347
|
+
const text = await response.text();
|
|
348
|
+
let body;
|
|
349
|
+
try {
|
|
350
|
+
body = text ? JSON.parse(text) : void 0;
|
|
351
|
+
} catch {}
|
|
352
|
+
if (response.ok) return body;
|
|
353
|
+
const error = body?.error;
|
|
354
|
+
throw new HttpError(response.status, error?.code ?? "remote_error", error?.message ?? `Vercel's API answered ${response.status}`);
|
|
355
|
+
}
|
|
356
|
+
/** Every page of a list, in order. */
|
|
357
|
+
async function all(who, path, key, query = {}, signal) {
|
|
358
|
+
const out = [];
|
|
359
|
+
let cursor;
|
|
360
|
+
do {
|
|
361
|
+
const page = await api(who, "GET", path, {
|
|
362
|
+
query: {
|
|
363
|
+
...query,
|
|
364
|
+
cursor
|
|
365
|
+
},
|
|
366
|
+
...signal ? { signal } : {}
|
|
367
|
+
});
|
|
368
|
+
out.push(...page[key]);
|
|
369
|
+
cursor = page.cursor ?? void 0;
|
|
370
|
+
} while (cursor);
|
|
371
|
+
return out;
|
|
372
|
+
}
|
|
373
|
+
/**
|
|
374
|
+
* The board named `name` in the team: the one the API lists for it. Where it lists none, the
|
|
375
|
+
* caller makes it (a project's is granted to that project, in its environment), unless it says
|
|
376
|
+
* not to (`ensure: false`) and is told there's none it can see. Names are unique across the
|
|
377
|
+
* team's boards, the ones you can't see included.
|
|
378
|
+
*/
|
|
379
|
+
async function boardNamed(who, name) {
|
|
380
|
+
if (!/^[^/]{1,64}$/.test(name)) throw new HttpError(400, "invalid_board_name", `${JSON.stringify(name)} isn't a board's name: one is 1 to 64 characters with no /.`, { origin: "handle" });
|
|
381
|
+
const { boards } = await api(who, "GET", "/boards", { query: { name } });
|
|
382
|
+
if (boards[0]) return boards[0].id;
|
|
383
|
+
const { principal } = (await self(who)).actor;
|
|
384
|
+
if (binding?.ensure === false) throw new HttpError(404, "no_board", `no board named ${name} on this team, or none you can see.`, {
|
|
385
|
+
hint: "Check the name, or make it: leave out ensure: false",
|
|
386
|
+
origin: "handle"
|
|
387
|
+
});
|
|
388
|
+
try {
|
|
389
|
+
const { board: made } = await api(who, "POST", "/boards/ensure", { body: {
|
|
390
|
+
name,
|
|
391
|
+
operationId: operationId()
|
|
392
|
+
} });
|
|
393
|
+
return made.id;
|
|
394
|
+
} catch (error) {
|
|
395
|
+
if (error instanceof HttpError && error.code === "board_not_granted") throw notLetIn(`board ${name}`, principal);
|
|
396
|
+
if (error instanceof HttpError && error.code === "board_name_taken") throw new HttpError(409, "board_name_taken", `the board name ${name} is taken.`, {
|
|
397
|
+
hint: "Pick another name, or ask whoever can see it for access.",
|
|
398
|
+
origin: "handle"
|
|
399
|
+
});
|
|
400
|
+
throw error;
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
/** A project a board's grants don't let in: they were narrowed, since every project on the team gets in by default. */
|
|
404
|
+
const notLetIn = (board, principal) => new HttpError(403, "board_not_granted", `this project has no access to ${board}${principal.type === "project" ? ` (${principal.projectId}, ${principal.environment})` : ""}.`, {
|
|
405
|
+
hint: "Someone who manages the board can grant it.",
|
|
406
|
+
origin: "handle"
|
|
407
|
+
});
|
|
408
|
+
let board = null;
|
|
409
|
+
/**
|
|
410
|
+
* The board's ID: the one given, the one `board({ name })` names, or the team's, which the API
|
|
411
|
+
* names only to those it lets in. A team with none gets one the first time a person uses it, as
|
|
412
|
+
* the API asks of its clients; a project can't make it, and needs a person to grant it the board
|
|
413
|
+
* anyway. Each is asked for once.
|
|
414
|
+
*/
|
|
415
|
+
const boardId = (who) => (board ??= options.board ? Promise.resolve(options.board) : boardName() ? boardNamed(who, boardName()) : api(who, "GET", "/boards").then(async ({ defaultBoardId }) => {
|
|
416
|
+
if (defaultBoardId) return defaultBoardId;
|
|
417
|
+
const { principal } = (await self(who)).actor;
|
|
418
|
+
if (principal.type === "project") throw notLetIn("the team's board", principal);
|
|
419
|
+
const { board: made } = await api(who, "POST", "/boards/default", { body: { operationId: operationId() } });
|
|
420
|
+
return made.id;
|
|
421
|
+
})).catch((error) => {
|
|
422
|
+
board = null;
|
|
423
|
+
throw error;
|
|
424
|
+
});
|
|
425
|
+
const onBoard = async (who, path = "") => `/boards/${encodeURIComponent(await boardId(who))}${path}`;
|
|
426
|
+
let channels = null;
|
|
427
|
+
const loadChannels = async (who, fresh = false) => {
|
|
428
|
+
if (fresh) channels = null;
|
|
429
|
+
channels ??= onBoard(who, "/channels").then((path) => all(who, path, "channels"));
|
|
430
|
+
return channels.catch((error) => {
|
|
431
|
+
channels = null;
|
|
432
|
+
throw error;
|
|
433
|
+
});
|
|
434
|
+
};
|
|
435
|
+
/** The channel by `name`, which the API finds without listing the board's. */
|
|
436
|
+
const named = /* @__PURE__ */ new Map();
|
|
437
|
+
async function channelNamed(who, name) {
|
|
438
|
+
const known = named.get(name);
|
|
439
|
+
if (known) return known;
|
|
440
|
+
const { channels: [found] } = await api(who, "GET", await onBoard(who, "/channels"), { query: { name } });
|
|
441
|
+
if (found) named.set(name, found);
|
|
442
|
+
return found ?? null;
|
|
443
|
+
}
|
|
444
|
+
async function channelById(who, id) {
|
|
445
|
+
const found = (await loadChannels(who)).find((channel) => channel.id === id) ?? (await loadChannels(who, true)).find((channel) => channel.id === id);
|
|
446
|
+
if (!found) throw new HttpError(502, "remote_error", `Vercel's API names a channel it doesn't list: ${id}`);
|
|
447
|
+
return found;
|
|
448
|
+
}
|
|
449
|
+
/** The channel by `name`, made if it isn't there: `created` says whether this made it. */
|
|
450
|
+
async function ensureChannel(who, name) {
|
|
451
|
+
const found = await channelNamed(who, name);
|
|
452
|
+
if (found) return {
|
|
453
|
+
channel: found,
|
|
454
|
+
created: false
|
|
455
|
+
};
|
|
456
|
+
try {
|
|
457
|
+
const { channel } = await api(who, "POST", await onBoard(who, "/channels"), { body: {
|
|
458
|
+
operationId: operationId(),
|
|
459
|
+
name
|
|
460
|
+
} });
|
|
461
|
+
channels = null;
|
|
462
|
+
named.set(name, channel);
|
|
463
|
+
return {
|
|
464
|
+
channel,
|
|
465
|
+
created: true
|
|
466
|
+
};
|
|
467
|
+
} catch (error) {
|
|
468
|
+
if (error instanceof HttpError && error.code === "channel_name_taken") {
|
|
469
|
+
const made = await channelNamed(who, name);
|
|
470
|
+
if (made) return {
|
|
471
|
+
channel: made,
|
|
472
|
+
created: false
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
throw error;
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
/** A channel to post in, made the first time something posts to it, as on any board. */
|
|
479
|
+
const channelToPost = async (who, name) => (await ensureChannel(who, name)).channel;
|
|
480
|
+
/** The channels a filter names: one, a channel and those under it (`dev/`), or every one. */
|
|
481
|
+
async function channelsFor(who, filter) {
|
|
482
|
+
if (filter !== void 0 && !filter.endsWith("/")) {
|
|
483
|
+
const found = await channelNamed(who, filter);
|
|
484
|
+
return found ? [found] : [];
|
|
485
|
+
}
|
|
486
|
+
const listed = await loadChannels(who, true);
|
|
487
|
+
if (filter === void 0) return listed;
|
|
488
|
+
const path = filter.slice(0, -1);
|
|
489
|
+
return listed.filter((channel) => channel.name === path || channel.name.startsWith(filter));
|
|
490
|
+
}
|
|
491
|
+
async function messageById(who, id, signal) {
|
|
492
|
+
if (!locate(id)) throw notFound(`message not found: ${id}`, "message_not_found");
|
|
493
|
+
try {
|
|
494
|
+
return await api(who, "GET", await onBoard(who, `/messages/${encodeURIComponent(id)}`), signal ? { signal } : {});
|
|
495
|
+
} catch (error) {
|
|
496
|
+
if (error instanceof HttpError && error.code === "thread_not_found") throw notFound(`message not found: ${id}`, "message_not_found");
|
|
497
|
+
throw error;
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
/** A message, and its channel. */
|
|
501
|
+
async function messageIn(who, id, signal) {
|
|
502
|
+
const found = await messageById(who, id, signal);
|
|
503
|
+
return {
|
|
504
|
+
...found,
|
|
505
|
+
channel: await channelById(who, found.thread.channelId)
|
|
506
|
+
};
|
|
507
|
+
}
|
|
508
|
+
/**
|
|
509
|
+
* Each thread a read needs, read once, with the labels its messages match on: a label matches on
|
|
510
|
+
* its root's, which the API keeps on the thread. It reads the root, which names its thread, so it
|
|
511
|
+
* knows when the root is deleted.
|
|
512
|
+
*/
|
|
513
|
+
function threadReader(who, signal) {
|
|
514
|
+
const read = /* @__PURE__ */ new Map();
|
|
515
|
+
return (id) => {
|
|
516
|
+
let thread = read.get(id);
|
|
517
|
+
if (!thread) read.set(id, thread = messageById(who, idAt(id, 1), signal).then(({ thread, message }) => labeledBy(thread, message)));
|
|
518
|
+
return thread;
|
|
519
|
+
};
|
|
520
|
+
}
|
|
521
|
+
/** A thread as its root's labels find it: the API keeps a deleted root's labels on its thread, and a deleted message has none. */
|
|
522
|
+
const labeledBy = (thread, root) => {
|
|
523
|
+
if (root?.deletedAt === void 0) return thread;
|
|
524
|
+
const { labels: _kept, ...rest } = thread;
|
|
525
|
+
return rest;
|
|
526
|
+
};
|
|
527
|
+
/** A message's labels: a deleted message keeps none, though the API still holds them. */
|
|
528
|
+
const labelsOf = (message) => message.deletedAt === void 0 ? { ...message.labels } : {};
|
|
529
|
+
const threadMessages = async (who, threadId, signal) => all(who, await onBoard(who, `/threads/${encodeURIComponent(threadId)}/messages`), "messages", {}, signal);
|
|
530
|
+
/** Who reacted with each emoji. The API counts them on the message and lists them apart. */
|
|
531
|
+
async function reactors(who, message) {
|
|
532
|
+
if (!message.reactions || Object.keys(message.reactions).length === 0) return {};
|
|
533
|
+
const named = message.reactors ?? {};
|
|
534
|
+
if (Object.entries(message.reactions).every(([emoji, count]) => (named[emoji]?.length ?? 0) >= count)) return Object.fromEntries(Object.entries(named).map(([emoji, actors]) => [emoji, [...actors]]));
|
|
535
|
+
const path = await onBoard(who, `/threads/${encodeURIComponent(message.threadId)}/messages/${message.sequence}/reactions`);
|
|
536
|
+
const out = {};
|
|
537
|
+
for (const reaction of await all(who, path, "reactions")) (out[reaction.emoji] ??= []).push(reaction.actor.id);
|
|
538
|
+
return out;
|
|
539
|
+
}
|
|
540
|
+
/** Who's written here, by actor ID, as the API names them: messages carry only the actor. */
|
|
541
|
+
let actorNames = null;
|
|
542
|
+
/** How long names are kept before they're read again: someone renamed shows by their new name after this. */
|
|
543
|
+
const NAMES_FRESH_MS = 3e5;
|
|
544
|
+
/** Actors a list read again for them didn't have: it isn't read again for them. */
|
|
545
|
+
const unlisted = /* @__PURE__ */ new Set();
|
|
546
|
+
/** Reads the list, kept as the current one; a read that fails isn't kept, so the next name tries again. */
|
|
547
|
+
const readNames = (who) => {
|
|
548
|
+
const views = (async () => new Map((await all(who, await onBoard(who, "/actors"), "actors")).map((view) => [view.id, view])))();
|
|
549
|
+
const read = {
|
|
550
|
+
at: Date.now(),
|
|
551
|
+
views
|
|
552
|
+
};
|
|
553
|
+
actorNames = read;
|
|
554
|
+
views.catch(() => {
|
|
555
|
+
if (actorNames === read) actorNames = null;
|
|
556
|
+
});
|
|
557
|
+
return read;
|
|
558
|
+
};
|
|
559
|
+
/** The actor in a read of the list, or undefined when it doesn't have them or failed. */
|
|
560
|
+
const inList = (read, id) => read.views.then((views) => views.get(id), () => void 0);
|
|
561
|
+
/**
|
|
562
|
+
* An actor as board shows them: a person by their Vercel username and name, and an agent acting
|
|
563
|
+
* for a person by its profile under them, as the API names them; anyone else (a project, an app,
|
|
564
|
+
* an agent of one), or someone the API doesn't list, by their principal. The list is read again
|
|
565
|
+
* every few minutes, and at once for someone who wrote since it was.
|
|
566
|
+
*/
|
|
567
|
+
async function nameOf(who, actor) {
|
|
568
|
+
const current = !actorNames || Date.now() - actorNames.at > NAMES_FRESH_MS ? readNames(who) : actorNames;
|
|
569
|
+
let found = await inList(current, actor.id);
|
|
570
|
+
if (!found && !unlisted.has(actor.id)) {
|
|
571
|
+
const again = actorNames && actorNames !== current ? actorNames : readNames(who);
|
|
572
|
+
found = await inList(again, actor.id);
|
|
573
|
+
if (!found && await again.views.then(() => true, () => false)) unlisted.add(actor.id);
|
|
574
|
+
}
|
|
575
|
+
const kind = found && apiKind(found.kind);
|
|
576
|
+
if (!found || !(kind === "person" || kind === "agent" && actor.principal.type === "user")) return actorView(actor);
|
|
577
|
+
return {
|
|
578
|
+
id: actor.id,
|
|
579
|
+
kind,
|
|
580
|
+
handle: found.handle,
|
|
581
|
+
name: found.name ?? found.handle,
|
|
582
|
+
avatar: found.avatar ?? null
|
|
583
|
+
};
|
|
584
|
+
}
|
|
585
|
+
async function view(who, message, channel) {
|
|
586
|
+
const root = message.sequence === 1;
|
|
587
|
+
return {
|
|
588
|
+
id: message.id,
|
|
589
|
+
channel,
|
|
590
|
+
text: message.text,
|
|
591
|
+
re: root ? null : idAt(message.threadId, 1),
|
|
592
|
+
replyTo: message.replyTo !== void 0 && message.replyTo !== 1 ? idAt(message.threadId, message.replyTo) : null,
|
|
593
|
+
thread: message.threadId,
|
|
594
|
+
labels: labelsOf(message),
|
|
595
|
+
reactions: message.deletedAt === void 0 ? await reactors(who, message) : {},
|
|
596
|
+
mentions: [],
|
|
597
|
+
by: authorOf(message.createdBy),
|
|
598
|
+
noSync: false,
|
|
599
|
+
origin: null,
|
|
600
|
+
from: null,
|
|
601
|
+
createdAt: iso(message.createdAt),
|
|
602
|
+
editedAt: message.editedAt === void 0 ? null : iso(message.editedAt),
|
|
603
|
+
deleted: message.deletedAt !== void 0,
|
|
604
|
+
undelivered: {},
|
|
605
|
+
attachments: message.attachments ?? [],
|
|
606
|
+
links: [],
|
|
607
|
+
version: message.version,
|
|
608
|
+
revision: message.revision,
|
|
609
|
+
author: await nameOf(who, message.createdBy),
|
|
610
|
+
...message.schedule ? { schedule: {
|
|
611
|
+
id: message.schedule.id,
|
|
612
|
+
n: message.schedule.n
|
|
613
|
+
} } : {}
|
|
614
|
+
};
|
|
615
|
+
}
|
|
616
|
+
async function scheduleView(who, schedule) {
|
|
617
|
+
const { canceled } = schedule;
|
|
618
|
+
return {
|
|
619
|
+
id: schedule.id,
|
|
620
|
+
channel: (await channelById(who, schedule.channelId)).name,
|
|
621
|
+
re: schedule.threadId === void 0 ? null : idAt(schedule.threadId, 1),
|
|
622
|
+
text: schedule.text,
|
|
623
|
+
labels: { ...schedule.labels },
|
|
624
|
+
noSync: false,
|
|
625
|
+
attachments: [],
|
|
626
|
+
first: iso(schedule.firstAt),
|
|
627
|
+
every: schedule.every ?? null,
|
|
628
|
+
until: schedule.until === void 0 ? null : iso(schedule.until),
|
|
629
|
+
times: schedule.times ?? null,
|
|
630
|
+
sent: schedule.sent,
|
|
631
|
+
next: schedule.nextAt === null ? null : iso(schedule.nextAt),
|
|
632
|
+
last: schedule.lastMessageId ?? null,
|
|
633
|
+
state: schedule.state,
|
|
634
|
+
canceled: canceled ? {
|
|
635
|
+
by: canceled.by ? authorOf(canceled.by) : SCHEDULER,
|
|
636
|
+
reason: canceled.reason === "disabled" ? "revoked" : canceled.reason
|
|
637
|
+
} : null,
|
|
638
|
+
by: authorOf(schedule.createdBy),
|
|
639
|
+
author: await nameOf(who, schedule.createdBy),
|
|
640
|
+
createdAt: iso(schedule.createdAt)
|
|
641
|
+
};
|
|
642
|
+
}
|
|
643
|
+
const positions = /* @__PURE__ */ new Map();
|
|
644
|
+
function cursorOf(position) {
|
|
645
|
+
const key = `${position.t.toString(36)}.${Math.floor(Math.random() * 36 ** 8).toString(36)}`;
|
|
646
|
+
positions.set(key, position);
|
|
647
|
+
if (positions.size > 1e4) positions.delete(positions.keys().next().value);
|
|
648
|
+
return key;
|
|
649
|
+
}
|
|
650
|
+
function positionOf(cursor) {
|
|
651
|
+
const kept = positions.get(cursor);
|
|
652
|
+
if (kept) return kept;
|
|
653
|
+
const found = CURSOR.exec(cursor);
|
|
654
|
+
if (!found) throw new HttpError(400, "invalid_cursor", `after: ${cursor} isn't a cursor here or a message's ID`);
|
|
655
|
+
return {
|
|
656
|
+
t: parseInt(found[1], 36),
|
|
657
|
+
feeds: {}
|
|
658
|
+
};
|
|
659
|
+
}
|
|
660
|
+
/** A time a read goes on from: a cursor's, or a message's own. */
|
|
661
|
+
async function timeOf(who, after) {
|
|
662
|
+
return locate(after) ? (await messageById(who, after)).message.createdAt : positionOf(after).t;
|
|
663
|
+
}
|
|
664
|
+
/** Each channel's feed now, taken before a read, so what's posted while it reads comes after. */
|
|
665
|
+
async function heads(who, listed) {
|
|
666
|
+
const path = await onBoard(who, "/changes");
|
|
667
|
+
const found = await Promise.all(listed.map((channel) => api(who, "GET", path, { query: {
|
|
668
|
+
channelId: channel.id,
|
|
669
|
+
from: "latest"
|
|
670
|
+
} })));
|
|
671
|
+
return Object.fromEntries(listed.map((channel, i) => [channel.id, {
|
|
672
|
+
at: found[i].cursor,
|
|
673
|
+
skip: 0
|
|
674
|
+
}]));
|
|
675
|
+
}
|
|
676
|
+
/**
|
|
677
|
+
* Whether a message matches a read's filters. A label matches on the message or its thread's root:
|
|
678
|
+
* `thread`'s labels, as `labeledBy` gives them when the read filters on labels.
|
|
679
|
+
*/
|
|
680
|
+
function matches(filters, message, thread, me) {
|
|
681
|
+
if (filters.re !== void 0 && filters.re !== message.id && filters.re !== idAt(thread.id, 1)) return false;
|
|
682
|
+
if (filters.by !== void 0) {
|
|
683
|
+
const { createdBy } = message;
|
|
684
|
+
const names = [
|
|
685
|
+
createdBy.id,
|
|
686
|
+
principalId(createdBy.principal),
|
|
687
|
+
createdBy.profile?.name
|
|
688
|
+
];
|
|
689
|
+
if (!(filters.by === "me" ? createdBy.id === me : names.includes(filters.by))) return false;
|
|
690
|
+
}
|
|
691
|
+
if (filters.mentions !== void 0) return false;
|
|
692
|
+
if (filters.from !== void 0 && filters.from !== "board") return false;
|
|
693
|
+
if (filters.text !== void 0 && !message.text.toLowerCase().includes(filters.text.toLowerCase())) return false;
|
|
694
|
+
for (const [key, values] of filters.label ?? []) {
|
|
695
|
+
const on = (labels) => labels !== void 0 && Object.hasOwn(labels, key) && (values === null || values.includes(labels[key]));
|
|
696
|
+
if (!on(labelsOf(message)) && !on(thread.labels)) return false;
|
|
697
|
+
}
|
|
698
|
+
return true;
|
|
699
|
+
}
|
|
700
|
+
/** The label the API's index can narrow a channel's threads by: a root's `key` or `key=value`. */
|
|
701
|
+
function indexed(filters) {
|
|
702
|
+
const first = filters.label?.find(([, values]) => values === null || values.length === 1);
|
|
703
|
+
return first && (first[1] === null ? first[0] : `${first[0]}=${first[1][0]}`);
|
|
704
|
+
}
|
|
705
|
+
async function threadsOf(who, channel, filters, signal) {
|
|
706
|
+
const label = indexed(filters);
|
|
707
|
+
return all(who, await onBoard(who, "/threads"), "threads", {
|
|
708
|
+
channelId: channel.id,
|
|
709
|
+
label
|
|
710
|
+
}, signal);
|
|
711
|
+
}
|
|
712
|
+
/**
|
|
713
|
+
* A channel's threads, as far as a read needs: the API lists them most recently active first, so
|
|
714
|
+
* it stops at the first not active since `after`, or at the `limit` newest when it's given one
|
|
715
|
+
* (not when the read filters what's listed). One it lists by a label comes oldest first, so it
|
|
716
|
+
* reads every page.
|
|
717
|
+
*/
|
|
718
|
+
async function latestThreads(who, channel, label, page, signal) {
|
|
719
|
+
const path = await onBoard(who, "/threads");
|
|
720
|
+
const out = [];
|
|
721
|
+
let cursor;
|
|
722
|
+
do {
|
|
723
|
+
const found = await api(who, "GET", path, {
|
|
724
|
+
query: {
|
|
725
|
+
channelId: channel.id,
|
|
726
|
+
label,
|
|
727
|
+
cursor
|
|
728
|
+
},
|
|
729
|
+
signal
|
|
730
|
+
});
|
|
731
|
+
out.push(...found.threads);
|
|
732
|
+
cursor = found.cursor ?? void 0;
|
|
733
|
+
const last = out.at(-1);
|
|
734
|
+
if (label === void 0 && (page.after !== void 0 ? last !== void 0 && last.lastActivityAt <= page.after : page.limit !== void 0 && out.length >= page.limit)) break;
|
|
735
|
+
} while (cursor);
|
|
736
|
+
return out;
|
|
737
|
+
}
|
|
738
|
+
/** A thread at a glance: its root, its reply count, and its latest reply, read by reference. */
|
|
739
|
+
async function summary(who, thread, channel, signal) {
|
|
740
|
+
const [root, last] = await Promise.all([messageById(who, idAt(thread.id, 1), signal), thread.lastMessage && thread.lastMessage.sequence > 1 ? messageById(who, thread.lastMessage.id, signal) : null]);
|
|
741
|
+
return {
|
|
742
|
+
message: await view(who, root.message, channel.name),
|
|
743
|
+
replies: thread.messageCount - 1,
|
|
744
|
+
last: last && await view(who, last.message, channel.name)
|
|
745
|
+
};
|
|
746
|
+
}
|
|
747
|
+
let me = null;
|
|
748
|
+
/** Who these credentials are, asked once. */
|
|
749
|
+
const self = (who) => (me ??= api(who, "GET", "/me")).catch((error) => {
|
|
750
|
+
me = null;
|
|
751
|
+
throw error;
|
|
752
|
+
});
|
|
753
|
+
/** The actor `who` writes as: the credentials' principal, and its profile, as the API names it. */
|
|
754
|
+
const actorOf = async (who) => `${principalId((await self(who)).actor.principal)}${who.profile ? `+${who.profile.name.toLowerCase()}` : ""}`;
|
|
755
|
+
/** Who a caller acts as there: its profile and session, beside this deployment's credentials. */
|
|
756
|
+
function whoOf(caller) {
|
|
757
|
+
if ("identity" in caller) throw servesNone();
|
|
758
|
+
const named = (profile) => {
|
|
759
|
+
if (profile === null) return null;
|
|
760
|
+
const name = typeof profile === "string" ? profile : profile.name;
|
|
761
|
+
if (!PROFILE.test(name)) throw new HttpError(400, "invalid_request", `as: ${name}: profiles start with a letter and use up to 32 letters, numbers, and hyphens`);
|
|
762
|
+
return typeof profile === "string" || !profile.avatar ? { name } : {
|
|
763
|
+
name,
|
|
764
|
+
avatar: profile.avatar
|
|
765
|
+
};
|
|
766
|
+
};
|
|
767
|
+
if (caller.origin.via?.kind === "client") {
|
|
768
|
+
const asked = "profile" in caller ? caller.profile : caller.self ?? void 0;
|
|
769
|
+
const found = environment?.profile() ?? {
|
|
770
|
+
profile: null,
|
|
771
|
+
session: null
|
|
772
|
+
};
|
|
773
|
+
if (asked === void 0) return {
|
|
774
|
+
profile: named(found.profile),
|
|
775
|
+
session: found.session
|
|
776
|
+
};
|
|
777
|
+
return {
|
|
778
|
+
profile: named(asked),
|
|
779
|
+
session: asked === null ? null : found.session
|
|
780
|
+
};
|
|
781
|
+
}
|
|
782
|
+
return {
|
|
783
|
+
profile: named(caller.self ?? "client"),
|
|
784
|
+
session: null
|
|
785
|
+
};
|
|
786
|
+
}
|
|
787
|
+
/** A post's client ID, as the API takes one: its own when it fits, a hash of it when it doesn't. */
|
|
788
|
+
const clientIdOf = async (id) => CLIENT_ID.test(id) ? id : `h.${(await sha256(id)).slice(0, 64)}`;
|
|
789
|
+
/** Messages a read covers, newest last: every thread's in the channels it names, or one thread's. */
|
|
790
|
+
async function collect(who, filters, signal) {
|
|
791
|
+
let listed;
|
|
792
|
+
let threads;
|
|
793
|
+
if (filters.re !== void 0) {
|
|
794
|
+
const found = await messageIn(who, filters.re, signal).catch((error) => {
|
|
795
|
+
if (error instanceof HttpError && error.status === 404) return null;
|
|
796
|
+
throw error;
|
|
797
|
+
});
|
|
798
|
+
if (!found) return {
|
|
799
|
+
messages: [],
|
|
800
|
+
feeds: {},
|
|
801
|
+
newest: 0
|
|
802
|
+
};
|
|
803
|
+
const { channel } = found;
|
|
804
|
+
if (filters.channel !== void 0 && !(await channelsFor(who, filters.channel)).some((c) => c.id === channel.id)) return {
|
|
805
|
+
messages: [],
|
|
806
|
+
feeds: {},
|
|
807
|
+
newest: 0
|
|
808
|
+
};
|
|
809
|
+
listed = [channel];
|
|
810
|
+
threads = [{
|
|
811
|
+
thread: found.thread,
|
|
812
|
+
channel
|
|
813
|
+
}];
|
|
814
|
+
} else {
|
|
815
|
+
listed = await channelsFor(who, filters.channel);
|
|
816
|
+
threads = (await Promise.all(listed.map(async (channel) => (await threadsOf(who, channel, filters, signal)).map((thread) => ({
|
|
817
|
+
thread,
|
|
818
|
+
channel
|
|
819
|
+
}))))).flat();
|
|
820
|
+
}
|
|
821
|
+
const feeds = await heads(who, listed);
|
|
822
|
+
const mine = await actorOf(who);
|
|
823
|
+
let newest = 0;
|
|
824
|
+
const messages = [];
|
|
825
|
+
for (const { thread, channel } of threads) {
|
|
826
|
+
const all = await threadMessages(who, thread.id, signal);
|
|
827
|
+
const labeled = labeledBy(thread, all.find((message) => message.sequence === 1));
|
|
828
|
+
for (const message of all) {
|
|
829
|
+
newest = Math.max(newest, message.createdAt);
|
|
830
|
+
if (matches(filters, message, labeled, mine)) messages.push({
|
|
831
|
+
message,
|
|
832
|
+
thread,
|
|
833
|
+
channel
|
|
834
|
+
});
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
messages.sort((a, b) => a.message.createdAt - b.message.createdAt || a.thread.id.localeCompare(b.thread.id) || a.message.sequence - b.message.sequence);
|
|
838
|
+
return {
|
|
839
|
+
messages,
|
|
840
|
+
feeds,
|
|
841
|
+
newest
|
|
842
|
+
};
|
|
843
|
+
}
|
|
844
|
+
/** A change in the API's feed as a board event, with the message as it is now. Null for what isn't a message's. */
|
|
845
|
+
async function eventOf(who, change, channel, cursor, filters, me, given, threads = threadReader(who)) {
|
|
846
|
+
if (!change.messageId || !change.type.startsWith("message.")) return null;
|
|
847
|
+
let found = given ?? await messageById(who, change.messageId).catch((error) => {
|
|
848
|
+
if (error instanceof HttpError && error.status === 404) return null;
|
|
849
|
+
throw error;
|
|
850
|
+
});
|
|
851
|
+
if (found && !given && filters.label?.length) found = {
|
|
852
|
+
...found,
|
|
853
|
+
thread: found.message.sequence === 1 ? labeledBy(found.thread, found.message) : await threads(found.thread.id)
|
|
854
|
+
};
|
|
855
|
+
if (!found || !matches(filters, found.message, found.thread, me)) return null;
|
|
856
|
+
const message = await view(who, found.message, channel);
|
|
857
|
+
const by = authorOf(change.actor);
|
|
858
|
+
const base = {
|
|
859
|
+
id: message.id,
|
|
860
|
+
thread: message.thread
|
|
861
|
+
};
|
|
862
|
+
let type;
|
|
863
|
+
let payload;
|
|
864
|
+
switch (change.type) {
|
|
865
|
+
case "message.posted":
|
|
866
|
+
type = "message.posted";
|
|
867
|
+
payload = {
|
|
868
|
+
channel,
|
|
869
|
+
text: message.text,
|
|
870
|
+
re: message.re,
|
|
871
|
+
replyTo: message.replyTo,
|
|
872
|
+
thread: message.thread,
|
|
873
|
+
labels: message.labels,
|
|
874
|
+
noSync: false,
|
|
875
|
+
mentions: [],
|
|
876
|
+
by,
|
|
877
|
+
origin: null,
|
|
878
|
+
from: null,
|
|
879
|
+
attachments: message.attachments,
|
|
880
|
+
links: []
|
|
881
|
+
};
|
|
882
|
+
break;
|
|
883
|
+
case "message.edited":
|
|
884
|
+
type = "message.edited";
|
|
885
|
+
payload = {
|
|
886
|
+
...base,
|
|
887
|
+
text: message.text,
|
|
888
|
+
mentions: [],
|
|
889
|
+
by,
|
|
890
|
+
from: null
|
|
891
|
+
};
|
|
892
|
+
break;
|
|
893
|
+
case "message.deleted":
|
|
894
|
+
type = "message.deleted";
|
|
895
|
+
payload = {
|
|
896
|
+
...base,
|
|
897
|
+
by,
|
|
898
|
+
from: null
|
|
899
|
+
};
|
|
900
|
+
break;
|
|
901
|
+
case "message.reaction_added":
|
|
902
|
+
case "message.reaction_removed":
|
|
903
|
+
type = change.type === "message.reaction_added" ? "reaction.added" : "reaction.removed";
|
|
904
|
+
payload = {
|
|
905
|
+
...base,
|
|
906
|
+
emoji: change.emoji,
|
|
907
|
+
by,
|
|
908
|
+
from: null
|
|
909
|
+
};
|
|
910
|
+
break;
|
|
911
|
+
case "message.labeled": {
|
|
912
|
+
const changed = Object.entries(change.labels ?? {});
|
|
913
|
+
type = "labels.changed";
|
|
914
|
+
payload = {
|
|
915
|
+
...base,
|
|
916
|
+
set: Object.fromEntries(changed.flatMap(([key, { to }]) => to === void 0 ? [] : [[key, to]])),
|
|
917
|
+
unset: changed.flatMap(([key, { to }]) => to === void 0 ? [key] : []),
|
|
918
|
+
by
|
|
919
|
+
};
|
|
920
|
+
break;
|
|
921
|
+
}
|
|
922
|
+
default: return null;
|
|
923
|
+
}
|
|
924
|
+
return {
|
|
925
|
+
cursor,
|
|
926
|
+
type,
|
|
927
|
+
createdAt: iso(change.createdAt),
|
|
928
|
+
payload,
|
|
929
|
+
message,
|
|
930
|
+
actor: await nameOf(who, change.actor)
|
|
931
|
+
};
|
|
932
|
+
}
|
|
933
|
+
/**
|
|
934
|
+
* One read of every channel's feed from `position`: its events, merged by time, each with the
|
|
935
|
+
* position right after it, and the position after them all.
|
|
936
|
+
*/
|
|
937
|
+
async function read(who, listed, position, filters, signal) {
|
|
938
|
+
const path = await onBoard(who, "/changes");
|
|
939
|
+
const pages = await Promise.all(listed.map(async (channel) => {
|
|
940
|
+
const from = position.feeds[channel.id];
|
|
941
|
+
const page = await api(who, "GET", path, {
|
|
942
|
+
query: {
|
|
943
|
+
channelId: channel.id,
|
|
944
|
+
...from?.at ? { cursor: from.at } : {}
|
|
945
|
+
},
|
|
946
|
+
signal
|
|
947
|
+
});
|
|
948
|
+
const skip = from?.skip ?? 0;
|
|
949
|
+
const events = page.events.map((change, i) => ({
|
|
950
|
+
change,
|
|
951
|
+
i
|
|
952
|
+
})).slice(skip).filter(({ change }) => from || change.createdAt > position.t);
|
|
953
|
+
return {
|
|
954
|
+
channel,
|
|
955
|
+
at: from?.at ?? null,
|
|
956
|
+
next: page.cursor,
|
|
957
|
+
events
|
|
958
|
+
};
|
|
959
|
+
}));
|
|
960
|
+
const mine = await actorOf(who);
|
|
961
|
+
const threads = threadReader(who, signal);
|
|
962
|
+
const running = { ...position.feeds };
|
|
963
|
+
const merged = pages.flatMap((page) => page.events.map((event) => ({
|
|
964
|
+
...event,
|
|
965
|
+
page
|
|
966
|
+
}))).sort((a, b) => a.change.createdAt - b.change.createdAt);
|
|
967
|
+
const events = [];
|
|
968
|
+
for (const { change, i, page } of merged) {
|
|
969
|
+
running[page.channel.id] = {
|
|
970
|
+
at: page.at,
|
|
971
|
+
skip: i + 1
|
|
972
|
+
};
|
|
973
|
+
const event = await eventOf(who, change, page.channel.name, cursorOf({
|
|
974
|
+
t: change.createdAt,
|
|
975
|
+
feeds: { ...running }
|
|
976
|
+
}), filters, mine, void 0, threads);
|
|
977
|
+
if (event) events.push(event);
|
|
978
|
+
}
|
|
979
|
+
const after = { ...position.feeds };
|
|
980
|
+
for (const page of pages) after[page.channel.id] = {
|
|
981
|
+
at: page.next,
|
|
982
|
+
skip: 0
|
|
983
|
+
};
|
|
984
|
+
return {
|
|
985
|
+
events,
|
|
986
|
+
position: {
|
|
987
|
+
t: Math.max(position.t, ...merged.map(({ change }) => change.createdAt)),
|
|
988
|
+
feeds: after
|
|
989
|
+
}
|
|
990
|
+
};
|
|
991
|
+
}
|
|
992
|
+
/** `ms` passing, or `signal` stopping it first. */
|
|
993
|
+
const pause = (ms, signal) => ms <= 0 || signal.aborted ? Promise.resolve() : new Promise((resolve) => {
|
|
994
|
+
const timer = setTimeout(resolve, ms);
|
|
995
|
+
signal.addEventListener("abort", () => (clearTimeout(timer), resolve()), { once: true });
|
|
996
|
+
});
|
|
997
|
+
/**
|
|
998
|
+
* Until one of `listed`'s feeds has something after `position` (true), or it's `until` (false). The API's feed is
|
|
999
|
+
* one channel's, and only it can wait for what comes next, so this waits on each at once and lets
|
|
1000
|
+
* the rest go when the first answers with something: a read across channels costs a request a
|
|
1001
|
+
* channel each time it waits, not each second it does.
|
|
1002
|
+
*/
|
|
1003
|
+
async function changed(who, listed, position, until, signal) {
|
|
1004
|
+
const wait = Math.min(WAIT_MAX_S, Math.ceil((until - Date.now()) / 1e3));
|
|
1005
|
+
if (wait <= 0) return false;
|
|
1006
|
+
if (listed.length === 0) {
|
|
1007
|
+
await pause(until - Date.now(), signal);
|
|
1008
|
+
return false;
|
|
1009
|
+
}
|
|
1010
|
+
const stop = new AbortController();
|
|
1011
|
+
const either = AbortSignal.any([signal, stop.signal]);
|
|
1012
|
+
const path = await onBoard(who, "/changes");
|
|
1013
|
+
try {
|
|
1014
|
+
return await new Promise((resolve, reject) => {
|
|
1015
|
+
let pending = listed.length;
|
|
1016
|
+
for (const channel of listed) {
|
|
1017
|
+
const at = position.feeds[channel.id]?.at;
|
|
1018
|
+
api(who, "GET", path, {
|
|
1019
|
+
query: {
|
|
1020
|
+
channelId: channel.id,
|
|
1021
|
+
...at ? { cursor: at } : { from: "latest" },
|
|
1022
|
+
wait: String(wait)
|
|
1023
|
+
},
|
|
1024
|
+
signal: either
|
|
1025
|
+
}).then((page) => {
|
|
1026
|
+
if (page.events.length > 0) resolve(true);
|
|
1027
|
+
else if (--pending === 0) resolve(false);
|
|
1028
|
+
}).catch((error) => stop.signal.aborted && !signal.aborted ? void 0 : reject(error));
|
|
1029
|
+
}
|
|
1030
|
+
});
|
|
1031
|
+
} finally {
|
|
1032
|
+
stop.abort();
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
/** Whether a read filters on what messages say, who wrote them, or their labels: what the API can't narrow by. */
|
|
1036
|
+
const filtered = (filters) => filters.by !== void 0 || filters.mentions !== void 0 || filters.text !== void 0 || filters.from !== void 0 || (filters.label?.length ?? 0) > 0;
|
|
1037
|
+
/**
|
|
1038
|
+
* One channel's messages, from the API's message list: the latest `limit`, or those after one of
|
|
1039
|
+
* its cursors. A filtered read checks each page here, and asks only for as many as it still needs,
|
|
1040
|
+
* so the cursor it answers with never passes a match it left out.
|
|
1041
|
+
*/
|
|
1042
|
+
async function channelMessages(who, channel, query, signal) {
|
|
1043
|
+
const path = await onBoard(who, "/messages");
|
|
1044
|
+
const limit = query.limit ?? 50;
|
|
1045
|
+
const thread = threadReader(who, signal);
|
|
1046
|
+
const narrowed = filtered(query);
|
|
1047
|
+
const me = narrowed ? await actorOf(who) : null;
|
|
1048
|
+
const keep = async (message) => !narrowed || matches(query, message, query.label?.length ? await thread(message.threadId) : { id: message.threadId }, me);
|
|
1049
|
+
const kept = [];
|
|
1050
|
+
if (query.after === void 0) {
|
|
1051
|
+
const page = await api(who, "GET", path, {
|
|
1052
|
+
query: {
|
|
1053
|
+
channelId: channel.id,
|
|
1054
|
+
limit: String(narrowed ? PAGE_MAX : Math.min(limit, PAGE_MAX))
|
|
1055
|
+
},
|
|
1056
|
+
signal
|
|
1057
|
+
});
|
|
1058
|
+
for (const message of page.messages) if (await keep(message)) kept.push(message);
|
|
1059
|
+
return {
|
|
1060
|
+
messages: kept.slice(-limit),
|
|
1061
|
+
cursor: page.cursor
|
|
1062
|
+
};
|
|
1063
|
+
}
|
|
1064
|
+
let cursor = query.after;
|
|
1065
|
+
for (let pages = 0; pages < SCAN_PAGES && kept.length < limit; pages++) {
|
|
1066
|
+
const page = await api(who, "GET", path, {
|
|
1067
|
+
query: {
|
|
1068
|
+
channelId: channel.id,
|
|
1069
|
+
after: cursor,
|
|
1070
|
+
limit: String(Math.min(limit - kept.length, PAGE_MAX))
|
|
1071
|
+
},
|
|
1072
|
+
signal
|
|
1073
|
+
});
|
|
1074
|
+
cursor = page.cursor;
|
|
1075
|
+
for (const message of page.messages) if (await keep(message)) kept.push(message);
|
|
1076
|
+
if (page.messages.length === 0) break;
|
|
1077
|
+
}
|
|
1078
|
+
return {
|
|
1079
|
+
messages: kept,
|
|
1080
|
+
cursor
|
|
1081
|
+
};
|
|
1082
|
+
}
|
|
1083
|
+
/** One channel's events, from the API's feed after one of its cursors, or from now: a long-poll holds there, not here. */
|
|
1084
|
+
async function channelEvents(who, channel, query, signal) {
|
|
1085
|
+
const path = await onBoard(who, "/changes");
|
|
1086
|
+
const thread = threadReader(who, signal);
|
|
1087
|
+
const me = await actorOf(who);
|
|
1088
|
+
const until = Date.now() + (query.wait ?? 0) * 1e3;
|
|
1089
|
+
let cursor = query.after;
|
|
1090
|
+
for (;;) {
|
|
1091
|
+
const wait = Math.min(WAIT_MAX_S, Math.max(0, Math.ceil((until - Date.now()) / 1e3)));
|
|
1092
|
+
const page = await api(who, "GET", path, {
|
|
1093
|
+
query: {
|
|
1094
|
+
channelId: channel.id,
|
|
1095
|
+
include: "message",
|
|
1096
|
+
...cursor === void 0 ? { from: "latest" } : { cursor },
|
|
1097
|
+
...wait > 0 ? { wait: String(wait) } : {}
|
|
1098
|
+
},
|
|
1099
|
+
signal
|
|
1100
|
+
});
|
|
1101
|
+
cursor = page.cursor;
|
|
1102
|
+
const events = [];
|
|
1103
|
+
for (const change of page.events) {
|
|
1104
|
+
const message = change.currentMessage;
|
|
1105
|
+
const found = message && change.threadId ? {
|
|
1106
|
+
message,
|
|
1107
|
+
thread: query.label?.length ? await thread(change.threadId) : { id: change.threadId }
|
|
1108
|
+
} : null;
|
|
1109
|
+
if (!found) continue;
|
|
1110
|
+
const event = await eventOf(who, change, channel.name, change.cursor ?? page.cursor, query, me, found);
|
|
1111
|
+
if (event) events.push(event);
|
|
1112
|
+
}
|
|
1113
|
+
if (events.length > 0 || Date.now() >= until || signal.aborted) return {
|
|
1114
|
+
events,
|
|
1115
|
+
cursor
|
|
1116
|
+
};
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
1119
|
+
/** The one channel a read names, when the API can read it directly: not a subtree, and from one of its cursors or now. */
|
|
1120
|
+
async function oneChannel(who, query) {
|
|
1121
|
+
if (query.channel === void 0 || query.channel.endsWith("/") || query.re !== void 0) return null;
|
|
1122
|
+
if (query.after !== void 0 && !API_CURSOR.test(query.after)) return null;
|
|
1123
|
+
const [channel] = await channelsFor(who, query.channel);
|
|
1124
|
+
return channel ?? null;
|
|
1125
|
+
}
|
|
1126
|
+
/** A watcher's tail registers with the API as its own: an API watcher, so a match is the API's to make. */
|
|
1127
|
+
const tagOf = async (watch) => (await sha256(canonicalWatchers(watch))).slice(0, 32);
|
|
1128
|
+
/** Who `--by` names, as the API's authors: an actor, a principal, or everyone here with that handle or profile, as of now. */
|
|
1129
|
+
async function authorsOf(who, by) {
|
|
1130
|
+
if (by === "me") return [await actorOf(who)];
|
|
1131
|
+
if (by.startsWith("vercel:")) return [by];
|
|
1132
|
+
const named = (await all(who, await onBoard(who, "/actors"), "actors")).filter((actor) => actor.handle === by || actor.id.endsWith(`+${by.toLowerCase()}`)).map((actor) => actor.id);
|
|
1133
|
+
if (named.length === 0) throw new HttpError(400, "bad_watcher", `--by ${by}: nobody here goes by that yet: name them by their actor ID`);
|
|
1134
|
+
return named;
|
|
1135
|
+
}
|
|
1136
|
+
/**
|
|
1137
|
+
* A tail as the filter the API matches. The API reads no tails: channels, people, and threads are
|
|
1138
|
+
* looked up here, now, and what it can't match (mentions, other sources) is refused rather than
|
|
1139
|
+
* left to match nothing.
|
|
1140
|
+
*/
|
|
1141
|
+
async function filterOf(who, id, spec) {
|
|
1142
|
+
const bad = (message) => new HttpError(400, "bad_watcher", `watch ${id}: ${message}`);
|
|
1143
|
+
if (!RemoteWatcherId.safeParse(id).success) throw bad("ids start with a letter and use up to 32 letters, numbers, and hyphens");
|
|
1144
|
+
let filters;
|
|
1145
|
+
try {
|
|
1146
|
+
({filters} = compileWatcher(id, spec));
|
|
1147
|
+
} catch (error) {
|
|
1148
|
+
throw new HttpError(400, "bad_watcher", error.message);
|
|
1149
|
+
}
|
|
1150
|
+
if (filters.mentions !== void 0) throw bad("Vercel's boards can't match mentions yet");
|
|
1151
|
+
if (filters.from !== void 0 && filters.from !== "board") throw bad(`nothing comes from ${filters.from} here: every message is written on the board`);
|
|
1152
|
+
const filter = {};
|
|
1153
|
+
if (filters.channel !== void 0) {
|
|
1154
|
+
if (filters.channel.endsWith("/")) filter.channelTree = filters.channel.slice(0, -1);
|
|
1155
|
+
else {
|
|
1156
|
+
const found = await channelNamed(who, filters.channel);
|
|
1157
|
+
if (found) filter.channelIds = [found.id];
|
|
1158
|
+
else filter.channelTree = filters.channel;
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1161
|
+
if (filters.re !== void 0) {
|
|
1162
|
+
const at = locate(filters.re);
|
|
1163
|
+
if (!at) throw bad(`--re ${filters.re} names no message here`);
|
|
1164
|
+
filter.threadId = at.threadId;
|
|
1165
|
+
}
|
|
1166
|
+
if (filters.by !== void 0) filter.authors = await authorsOf(who, filters.by);
|
|
1167
|
+
if (filters.text !== void 0) filter.text = filters.text;
|
|
1168
|
+
if (filters.label?.length) filter.labels = filters.label.map(([key, values]) => values === null ? { key } : {
|
|
1169
|
+
key,
|
|
1170
|
+
values: [...values]
|
|
1171
|
+
});
|
|
1172
|
+
return {
|
|
1173
|
+
filter,
|
|
1174
|
+
when: spec.when ?? "matches"
|
|
1175
|
+
};
|
|
1176
|
+
}
|
|
1177
|
+
/** A filter shown as a tail again, for listing: what it matches, if not always as it was written. */
|
|
1178
|
+
async function tailOf(who, { filter }) {
|
|
1179
|
+
const parts = [];
|
|
1180
|
+
if (filter.channelIds?.[0]) parts.push((await channelById(who, filter.channelIds[0])).name);
|
|
1181
|
+
else if (filter.channelTree !== void 0) parts.push(`${filter.channelTree}/`);
|
|
1182
|
+
if (filter.threadId !== void 0) parts.push(`--re ${idAt(filter.threadId, 1)}`);
|
|
1183
|
+
if (filter.authors?.[0]) parts.push(`--by ${filter.authors[0]}`);
|
|
1184
|
+
if (filter.text !== void 0) parts.push(`--text ${JSON.stringify(filter.text)}`);
|
|
1185
|
+
for (const { key, values } of filter.labels ?? []) parts.push(`--label ${values ? `${key}=${values.join("|")}` : key}`);
|
|
1186
|
+
return parts.join(" ");
|
|
1187
|
+
}
|
|
1188
|
+
/** Where a registration is woken, as board shows it: its URL, or a path on its project (and a preview's branch). */
|
|
1189
|
+
const whereOf = (found) => found.path ? {
|
|
1190
|
+
url: null,
|
|
1191
|
+
path: found.path,
|
|
1192
|
+
...found.branch ? { branch: found.branch } : {}
|
|
1193
|
+
} : { url: found.url };
|
|
1194
|
+
async function registerAs(who, where, watch) {
|
|
1195
|
+
const specs = Object.fromEntries(Object.entries(watch).map(([id, spec]) => [id, {
|
|
1196
|
+
tail: spec.tail,
|
|
1197
|
+
when: spec.when ?? "matches"
|
|
1198
|
+
}]));
|
|
1199
|
+
const filters = Object.fromEntries(await Promise.all(Object.entries(specs).map(async ([id, spec]) => [id, await filterOf(who, id, spec)])));
|
|
1200
|
+
const made = await api(who, "PUT", await onBoard(who, "/watchers"), { body: {
|
|
1201
|
+
...where,
|
|
1202
|
+
watch: filters,
|
|
1203
|
+
tag: await tagOf(specs)
|
|
1204
|
+
} });
|
|
1205
|
+
return {
|
|
1206
|
+
owner: made.owner,
|
|
1207
|
+
...whereOf(made),
|
|
1208
|
+
watch: specs,
|
|
1209
|
+
sync: [],
|
|
1210
|
+
hash: made.hash
|
|
1211
|
+
};
|
|
1212
|
+
}
|
|
1213
|
+
/** A match as vboard hands it out: its event as `vb tail --json` prints it, with its message as it is now. */
|
|
1214
|
+
async function matchOf(who, match, me) {
|
|
1215
|
+
const found = await messageById(who, match.event.messageId).catch((error) => {
|
|
1216
|
+
if (error instanceof HttpError && error.status === 404) return null;
|
|
1217
|
+
throw error;
|
|
1218
|
+
});
|
|
1219
|
+
const channel = found && await channelById(who, found.thread.channelId);
|
|
1220
|
+
const event = found && channel && await eventOf(who, match.event, channel.name, match.id, {}, me, found);
|
|
1221
|
+
if (!event?.message) return null;
|
|
1222
|
+
return {
|
|
1223
|
+
id: match.id,
|
|
1224
|
+
watcher: match.watcher,
|
|
1225
|
+
thread: event.message.thread,
|
|
1226
|
+
lease: match.lease,
|
|
1227
|
+
attempt: match.attempt,
|
|
1228
|
+
event
|
|
1229
|
+
};
|
|
1230
|
+
}
|
|
1231
|
+
async function pullAs(who, query, signal) {
|
|
1232
|
+
const { matches } = await api(who, "GET", await onBoard(who, "/watchers/matches"), {
|
|
1233
|
+
query: {
|
|
1234
|
+
limit: query.limit?.toString(),
|
|
1235
|
+
wait: query.wait?.toString()
|
|
1236
|
+
},
|
|
1237
|
+
...signal ? { signal } : {}
|
|
1238
|
+
});
|
|
1239
|
+
const me = await actorOf(who);
|
|
1240
|
+
const shown = await Promise.all(matches.map((match) => matchOf(who, match, me)));
|
|
1241
|
+
await Promise.all(matches.map((match, i) => shown[i] ? null : ackAs(who, match.id, {
|
|
1242
|
+
lease: match.lease,
|
|
1243
|
+
skip: true
|
|
1244
|
+
}).catch(() => {})));
|
|
1245
|
+
return shown.filter((match) => match !== null);
|
|
1246
|
+
}
|
|
1247
|
+
async function ackAs(who, id, body) {
|
|
1248
|
+
await api(who, "POST", await onBoard(who, `/watchers/matches/${encodeURIComponent(id)}/ack`), { body: {
|
|
1249
|
+
lease: body.lease,
|
|
1250
|
+
...body.error !== void 0 ? { error: body.error } : {},
|
|
1251
|
+
...body.skip ? { skip: true } : {}
|
|
1252
|
+
} });
|
|
1253
|
+
}
|
|
1254
|
+
/** This deployment's own: what its config's watchers run as. */
|
|
1255
|
+
const deployment = {
|
|
1256
|
+
profile: null,
|
|
1257
|
+
session: null
|
|
1258
|
+
};
|
|
1259
|
+
/** This board's config's watchers, which run here when the API wakes it. */
|
|
1260
|
+
let tails = {};
|
|
1261
|
+
const bound = () => {
|
|
1262
|
+
if (!binding) throw new Error("vercel: used before board() bound it");
|
|
1263
|
+
return binding;
|
|
1264
|
+
};
|
|
1265
|
+
const runner = registrant({
|
|
1266
|
+
remote: "Vercel's API",
|
|
1267
|
+
registry: {
|
|
1268
|
+
register: (where) => registerAs(deployment, where, tails),
|
|
1269
|
+
matches: ({ signal, ...query }) => pullAs(deployment, query, signal),
|
|
1270
|
+
ack: (id, body) => ackAs(deployment, id, body)
|
|
1271
|
+
},
|
|
1272
|
+
wakeAt: async (here) => wakePath(here) ?? { url: here },
|
|
1273
|
+
binding: bound,
|
|
1274
|
+
hash: () => tagOf(tails),
|
|
1275
|
+
hasWork: () => Object.keys(tails).length > 0,
|
|
1276
|
+
rethrow: (error) => {
|
|
1277
|
+
throw error;
|
|
1278
|
+
},
|
|
1279
|
+
registerFor: async (caller, request) => json(await methods.register(caller, RegisterBody.parse(await request.json()), request.signal))
|
|
1280
|
+
});
|
|
1281
|
+
const methods = {
|
|
1282
|
+
...Object.fromEntries(METHODS.map((method) => [method, async () => {
|
|
1283
|
+
throw notSupported(method === "register" || method === "watchers" || method === "matches" || method === "ack" ? "watchers" : method);
|
|
1284
|
+
}])),
|
|
1285
|
+
async discovery() {
|
|
1286
|
+
const who = {
|
|
1287
|
+
profile: null,
|
|
1288
|
+
session: null
|
|
1289
|
+
};
|
|
1290
|
+
const team = await teamId();
|
|
1291
|
+
if (options.board) await api(who, "GET", await onBoard(who));
|
|
1292
|
+
const id = team?.startsWith("team_") ? team : (await self(who)).teamId;
|
|
1293
|
+
return {
|
|
1294
|
+
version: VERSION,
|
|
1295
|
+
url: `${origin}/v1/messageboard${await onBoard(who)}?teamId=${encodeURIComponent(id)}`,
|
|
1296
|
+
audience: origin,
|
|
1297
|
+
team_id: id,
|
|
1298
|
+
project_id: null,
|
|
1299
|
+
sync: [],
|
|
1300
|
+
wake_by_path: true
|
|
1301
|
+
};
|
|
1302
|
+
},
|
|
1303
|
+
async me(caller) {
|
|
1304
|
+
const found = await api(whoOf(caller), "GET", "/me");
|
|
1305
|
+
const { view: named } = found;
|
|
1306
|
+
const shown = named ? {
|
|
1307
|
+
kind: apiKind(named.kind),
|
|
1308
|
+
handle: named.handle,
|
|
1309
|
+
name: named.name ?? named.handle,
|
|
1310
|
+
avatar: named.avatar ?? null
|
|
1311
|
+
} : actorView(found.actor);
|
|
1312
|
+
return {
|
|
1313
|
+
actor: found.actor.id,
|
|
1314
|
+
principal: principalId(found.actor.principal),
|
|
1315
|
+
kind: shown.kind,
|
|
1316
|
+
handle: shown.handle,
|
|
1317
|
+
name: shown.name,
|
|
1318
|
+
avatar: shown.avatar,
|
|
1319
|
+
profile: found.actor.profile?.name ?? null,
|
|
1320
|
+
session: found.actor.session ?? null,
|
|
1321
|
+
expiresAt: expiryOf(found.expiresAt),
|
|
1322
|
+
can: canOf(found.can)
|
|
1323
|
+
};
|
|
1324
|
+
},
|
|
1325
|
+
async channels(caller) {
|
|
1326
|
+
return {
|
|
1327
|
+
channels: (await channelsFor(whoOf(caller), void 0)).map((channel) => ({ path: channel.name })).sort((a, b) => a.path.localeCompare(b.path)),
|
|
1328
|
+
cursor: cursorOf({
|
|
1329
|
+
t: Date.now(),
|
|
1330
|
+
feeds: {}
|
|
1331
|
+
})
|
|
1332
|
+
};
|
|
1333
|
+
},
|
|
1334
|
+
async createChannel(caller, { path }) {
|
|
1335
|
+
const { created } = await ensureChannel(whoOf(caller), path);
|
|
1336
|
+
return {
|
|
1337
|
+
channel: { path },
|
|
1338
|
+
created
|
|
1339
|
+
};
|
|
1340
|
+
},
|
|
1341
|
+
async actors(caller, _input, signal) {
|
|
1342
|
+
const who = whoOf(caller);
|
|
1343
|
+
return {
|
|
1344
|
+
actors: (await all(who, await onBoard(who, "/actors"), "actors", {}, signal)).map((actor) => ({
|
|
1345
|
+
id: actor.id,
|
|
1346
|
+
kind: apiKind(actor.kind),
|
|
1347
|
+
handle: actor.handle,
|
|
1348
|
+
name: actor.name ?? actor.handle,
|
|
1349
|
+
avatar: actor.avatar ?? null
|
|
1350
|
+
})),
|
|
1351
|
+
cursor: cursorOf({
|
|
1352
|
+
t: Date.now(),
|
|
1353
|
+
feeds: {}
|
|
1354
|
+
})
|
|
1355
|
+
};
|
|
1356
|
+
},
|
|
1357
|
+
async messages(caller, query, signal) {
|
|
1358
|
+
const who = whoOf(caller);
|
|
1359
|
+
const channel = query.before === void 0 ? await oneChannel(who, query) : null;
|
|
1360
|
+
if (channel) {
|
|
1361
|
+
const page = await channelMessages(who, channel, query, signal);
|
|
1362
|
+
return {
|
|
1363
|
+
messages: await Promise.all(page.messages.map((message) => view(who, message, channel.name))),
|
|
1364
|
+
cursor: page.cursor
|
|
1365
|
+
};
|
|
1366
|
+
}
|
|
1367
|
+
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`);
|
|
1368
|
+
const { messages, feeds, newest } = await collect(who, query, signal);
|
|
1369
|
+
const after = query.after !== void 0 ? await timeOf(who, query.after) : void 0;
|
|
1370
|
+
const before = query.before !== void 0 ? await timeOf(who, query.before) : void 0;
|
|
1371
|
+
const limit = query.limit ?? 50;
|
|
1372
|
+
const bounded = messages.filter(({ message }) => (after === void 0 || message.createdAt > after) && (before === void 0 || message.createdAt < before));
|
|
1373
|
+
const page = after !== void 0 ? bounded.slice(0, limit) : bounded.slice(-limit);
|
|
1374
|
+
return {
|
|
1375
|
+
messages: await Promise.all(page.map(({ message, channel }) => view(who, message, channel.name))),
|
|
1376
|
+
cursor: cursorOf({
|
|
1377
|
+
t: newest,
|
|
1378
|
+
feeds
|
|
1379
|
+
})
|
|
1380
|
+
};
|
|
1381
|
+
},
|
|
1382
|
+
async threads(caller, query, signal) {
|
|
1383
|
+
const who = whoOf(caller);
|
|
1384
|
+
const after = query.after !== void 0 ? await timeOf(who, query.after) : void 0;
|
|
1385
|
+
const limit = query.limit ?? 50;
|
|
1386
|
+
const pick = (found) => {
|
|
1387
|
+
const ordered = found.filter(({ at }) => after === void 0 || at > after).sort((a, b) => a.at - b.at);
|
|
1388
|
+
return after !== void 0 ? ordered.slice(0, limit) : ordered.slice(-limit);
|
|
1389
|
+
};
|
|
1390
|
+
if (query.re !== void 0 || query.by !== void 0 || query.mentions !== void 0 || query.text !== void 0 || query.from !== void 0 && query.from !== "board") {
|
|
1391
|
+
const { messages, feeds, newest } = await collect(who, query, signal);
|
|
1392
|
+
const latest = /* @__PURE__ */ new Map();
|
|
1393
|
+
for (const { message, thread, channel } of messages) latest.set(thread.id, {
|
|
1394
|
+
thread,
|
|
1395
|
+
channel,
|
|
1396
|
+
at: Math.max(latest.get(thread.id)?.at ?? 0, message.createdAt)
|
|
1397
|
+
});
|
|
1398
|
+
return {
|
|
1399
|
+
threads: await Promise.all(pick([...latest.values()]).map(({ thread, channel }) => summary(who, thread, channel, signal))),
|
|
1400
|
+
cursor: cursorOf({
|
|
1401
|
+
t: newest,
|
|
1402
|
+
feeds
|
|
1403
|
+
})
|
|
1404
|
+
};
|
|
1405
|
+
}
|
|
1406
|
+
const listed = await channelsFor(who, query.channel);
|
|
1407
|
+
const feeds = await heads(who, listed);
|
|
1408
|
+
const label = indexed(query);
|
|
1409
|
+
const found = (await Promise.all(listed.map(async (channel) => (await latestThreads(who, channel, label, {
|
|
1410
|
+
...after !== void 0 ? { after } : {},
|
|
1411
|
+
...query.label?.length ? {} : { limit }
|
|
1412
|
+
}, signal)).map((thread) => ({
|
|
1413
|
+
thread,
|
|
1414
|
+
channel,
|
|
1415
|
+
at: thread.lastActivityAt
|
|
1416
|
+
}))))).flat();
|
|
1417
|
+
const rooted = found.filter(({ thread }) => (query.label ?? []).every(([key, values]) => thread.labels !== void 0 && Object.hasOwn(thread.labels, key) && (values === null || values.includes(thread.labels[key]))));
|
|
1418
|
+
const newest = found.reduce((max, { at }) => Math.max(max, at), 0);
|
|
1419
|
+
if (!query.label?.length) return {
|
|
1420
|
+
threads: await Promise.all(pick(rooted).map(({ thread, channel }) => summary(who, thread, channel, signal))),
|
|
1421
|
+
cursor: cursorOf({
|
|
1422
|
+
t: newest,
|
|
1423
|
+
feeds
|
|
1424
|
+
})
|
|
1425
|
+
};
|
|
1426
|
+
const candidates = rooted.filter(({ at }) => after === void 0 || at > after).sort((a, b) => a.at - b.at);
|
|
1427
|
+
if (after === void 0) candidates.reverse();
|
|
1428
|
+
const threads = [];
|
|
1429
|
+
for (let next = 0; next < candidates.length && threads.length < limit;) {
|
|
1430
|
+
const page = candidates.slice(next, next + limit - threads.length);
|
|
1431
|
+
next += page.length;
|
|
1432
|
+
for (const shown of await Promise.all(page.map(({ thread, channel }) => summary(who, thread, channel, signal)))) if (!shown.message.deleted) threads.push(shown);
|
|
1433
|
+
}
|
|
1434
|
+
if (after === void 0) threads.reverse();
|
|
1435
|
+
return {
|
|
1436
|
+
threads,
|
|
1437
|
+
cursor: cursorOf({
|
|
1438
|
+
t: newest,
|
|
1439
|
+
feeds
|
|
1440
|
+
})
|
|
1441
|
+
};
|
|
1442
|
+
},
|
|
1443
|
+
async message(caller, { id }, signal) {
|
|
1444
|
+
const who = whoOf(caller);
|
|
1445
|
+
const { thread, channel } = await messageIn(who, id, signal);
|
|
1446
|
+
const [root, ...replies] = await threadMessages(who, thread.id, signal);
|
|
1447
|
+
if (!root) throw notFound(`message not found: ${id}`, "message_not_found");
|
|
1448
|
+
return {
|
|
1449
|
+
message: await view(who, root, channel.name),
|
|
1450
|
+
replies: await Promise.all(replies.map((reply) => view(who, reply, channel.name))),
|
|
1451
|
+
cursor: cursorOf({
|
|
1452
|
+
t: Math.max(root.createdAt, ...replies.map((reply) => reply.createdAt)),
|
|
1453
|
+
feeds: {}
|
|
1454
|
+
})
|
|
1455
|
+
};
|
|
1456
|
+
},
|
|
1457
|
+
async upload(caller, { data, name, type }) {
|
|
1458
|
+
const who = whoOf(caller);
|
|
1459
|
+
if (data.byteLength === 0) throw new HttpError(400, "bad_request", "the file is empty");
|
|
1460
|
+
if (data.byteLength > 26214400) throw new HttpError(413, "too_large", `attachments are at most ${IMPORT_BYTES_MAX / 1024 / 1024} MB`);
|
|
1461
|
+
const bytes = new Uint8Array(data);
|
|
1462
|
+
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
|
|
1463
|
+
const started = await api(who, "POST", await onBoard(who, "/attachments"), { body: {
|
|
1464
|
+
operationId: operationId(),
|
|
1465
|
+
name: fileName(name),
|
|
1466
|
+
type: mediaType(type),
|
|
1467
|
+
size: data.byteLength,
|
|
1468
|
+
sha256: btoa(String.fromCharCode(...digest))
|
|
1469
|
+
} });
|
|
1470
|
+
const put = await filesFetch(started.upload.url, {
|
|
1471
|
+
method: started.upload.method,
|
|
1472
|
+
headers: started.upload.headers,
|
|
1473
|
+
body: bytes,
|
|
1474
|
+
redirect: "error"
|
|
1475
|
+
});
|
|
1476
|
+
if (!put.ok) throw new HttpError(502, "upload_failed", `the upload to Vercel's storage answered ${put.status}`);
|
|
1477
|
+
const { attachment } = await api(who, "POST", await onBoard(who, `/attachments/${encodeURIComponent(started.attachment.id)}/complete`));
|
|
1478
|
+
return { attachment: fileOf(attachment) };
|
|
1479
|
+
},
|
|
1480
|
+
async uploadStart(caller, { name, type, size, sha256 }) {
|
|
1481
|
+
const who = whoOf(caller);
|
|
1482
|
+
if (sha256 === void 0) throw new HttpError(400, "invalid_request", "Vercel's API signs a direct upload for its bytes' SHA-256: send `sha256`, as board's client does");
|
|
1483
|
+
const started = await api(who, "POST", await onBoard(who, "/attachments"), { body: {
|
|
1484
|
+
operationId: operationId(),
|
|
1485
|
+
name: fileName(name ?? null),
|
|
1486
|
+
type: mediaType(type ?? null),
|
|
1487
|
+
size,
|
|
1488
|
+
sha256
|
|
1489
|
+
} });
|
|
1490
|
+
return {
|
|
1491
|
+
id: started.attachment.id,
|
|
1492
|
+
url: started.upload.url,
|
|
1493
|
+
headers: started.upload.headers,
|
|
1494
|
+
expiresAt: iso(started.upload.expiresAt)
|
|
1495
|
+
};
|
|
1496
|
+
},
|
|
1497
|
+
async uploadFinish(caller, { id }) {
|
|
1498
|
+
const who = whoOf(caller);
|
|
1499
|
+
const { attachment } = await api(who, "POST", await onBoard(who, `/attachments/${encodeURIComponent(id)}/complete`));
|
|
1500
|
+
return { attachment: fileOf(attachment) };
|
|
1501
|
+
},
|
|
1502
|
+
async attachment(caller, { id }, signal) {
|
|
1503
|
+
const who = whoOf(caller);
|
|
1504
|
+
const found = await api(who, "GET", await onBoard(who, `/attachments/${encodeURIComponent(id)}`), signal ? { signal } : {});
|
|
1505
|
+
const response = await filesFetch(found.url, {
|
|
1506
|
+
redirect: "error",
|
|
1507
|
+
...signal ? { signal } : {}
|
|
1508
|
+
});
|
|
1509
|
+
if (!response.ok || !response.body) throw new HttpError(502, "download_failed", `Vercel's storage answered ${response.status}`);
|
|
1510
|
+
return {
|
|
1511
|
+
attachment: fileOf(found.attachment),
|
|
1512
|
+
data: response.body
|
|
1513
|
+
};
|
|
1514
|
+
},
|
|
1515
|
+
async post(caller, input, signal) {
|
|
1516
|
+
if (input.sync?.length) throw notSupported("sync");
|
|
1517
|
+
const who = whoOf(caller);
|
|
1518
|
+
const clientId = input.id !== void 0 ? await clientIdOf(input.id) : void 0;
|
|
1519
|
+
let made;
|
|
1520
|
+
if (input.channel !== void 0) {
|
|
1521
|
+
const channel = await channelToPost(who, input.channel);
|
|
1522
|
+
made = await api(who, "POST", await onBoard(who, "/threads"), {
|
|
1523
|
+
body: {
|
|
1524
|
+
operationId: operationId(),
|
|
1525
|
+
channelId: channel.id,
|
|
1526
|
+
text: input.text,
|
|
1527
|
+
...input.labels && Object.keys(input.labels).length ? { labels: input.labels } : {},
|
|
1528
|
+
...clientId ? { clientId } : {},
|
|
1529
|
+
...input.attachments?.length ? { attachments: input.attachments } : {}
|
|
1530
|
+
},
|
|
1531
|
+
signal
|
|
1532
|
+
});
|
|
1533
|
+
} else {
|
|
1534
|
+
const { thread, message: to, channel } = await messageIn(who, input.re, signal);
|
|
1535
|
+
const after = input.after === void 0 ? void 0 : locate(input.after);
|
|
1536
|
+
if (after !== void 0 && after?.threadId !== thread.id) {
|
|
1537
|
+
const landed = clientId ? await api(who, "GET", await onBoard(who, `/posts/${encodeURIComponent(clientId)}`), { signal }).catch(() => null) : null;
|
|
1538
|
+
if (landed?.thread.id === thread.id) return { message: await view(who, landed.message, channel.name) };
|
|
1539
|
+
throw badRequest(`after: ${input.after} isn't in ${input.re}'s thread`, "invalid_after");
|
|
1540
|
+
}
|
|
1541
|
+
made = await api(who, "POST", await onBoard(who, `/threads/${encodeURIComponent(thread.id)}/messages`), {
|
|
1542
|
+
body: {
|
|
1543
|
+
operationId: operationId(),
|
|
1544
|
+
text: input.text,
|
|
1545
|
+
...to.sequence > 1 ? { replyTo: to.sequence } : {},
|
|
1546
|
+
...clientId ? { clientId } : {},
|
|
1547
|
+
...input.attachments?.length ? { attachments: input.attachments } : {},
|
|
1548
|
+
...after ? { after: after.sequence } : {}
|
|
1549
|
+
},
|
|
1550
|
+
signal
|
|
1551
|
+
}).catch((error) => {
|
|
1552
|
+
if (error instanceof HttpError && error.code === "newer_message") throw new HttpError(409, "newer_message", `a message came after ${input.after}`);
|
|
1553
|
+
throw error;
|
|
1554
|
+
});
|
|
1555
|
+
if (input.labels && Object.keys(input.labels).length) {
|
|
1556
|
+
const labeled = await api(who, "POST", await onBoard(who, `/threads/${encodeURIComponent(thread.id)}/messages/${made.message.sequence}/labels`), {
|
|
1557
|
+
body: {
|
|
1558
|
+
operationId: operationId(),
|
|
1559
|
+
set: input.labels
|
|
1560
|
+
},
|
|
1561
|
+
signal
|
|
1562
|
+
});
|
|
1563
|
+
made = {
|
|
1564
|
+
...made,
|
|
1565
|
+
message: {
|
|
1566
|
+
...made.message,
|
|
1567
|
+
...labeled.meta.labels ? { labels: labeled.meta.labels } : {},
|
|
1568
|
+
version: labeled.meta.version
|
|
1569
|
+
}
|
|
1570
|
+
};
|
|
1571
|
+
}
|
|
1572
|
+
}
|
|
1573
|
+
const channel = await channelById(who, made.thread.channelId);
|
|
1574
|
+
return { message: await view(who, made.message, channel.name) };
|
|
1575
|
+
},
|
|
1576
|
+
async posted(caller, { id }, signal) {
|
|
1577
|
+
const who = whoOf(caller);
|
|
1578
|
+
const found = await api(who, "GET", await onBoard(who, `/posts/${encodeURIComponent(await clientIdOf(id))}`), { signal });
|
|
1579
|
+
const channel = await channelById(who, found.thread.channelId);
|
|
1580
|
+
return { message: await view(who, found.message, channel.name) };
|
|
1581
|
+
},
|
|
1582
|
+
async edit(caller, { id, text, revision }, signal) {
|
|
1583
|
+
const who = whoOf(caller);
|
|
1584
|
+
const at = locate(id);
|
|
1585
|
+
if (!at) throw notFound(`message not found: ${id}`, "message_not_found");
|
|
1586
|
+
await api(who, "PATCH", await onBoard(who, `/threads/${encodeURIComponent(at.threadId)}/messages/${at.sequence}`), {
|
|
1587
|
+
body: {
|
|
1588
|
+
operationId: operationId(),
|
|
1589
|
+
text,
|
|
1590
|
+
...revision !== void 0 ? { revision } : {}
|
|
1591
|
+
},
|
|
1592
|
+
signal
|
|
1593
|
+
});
|
|
1594
|
+
return { ok: true };
|
|
1595
|
+
},
|
|
1596
|
+
async delete(caller, { id, revision }, signal) {
|
|
1597
|
+
const who = whoOf(caller);
|
|
1598
|
+
const at = locate(id);
|
|
1599
|
+
if (!at) throw notFound(`message not found: ${id}`, "message_not_found");
|
|
1600
|
+
await api(who, "POST", await onBoard(who, `/threads/${encodeURIComponent(at.threadId)}/messages/${at.sequence}/delete`), {
|
|
1601
|
+
body: {
|
|
1602
|
+
operationId: operationId(),
|
|
1603
|
+
...revision !== void 0 ? { revision } : {}
|
|
1604
|
+
},
|
|
1605
|
+
signal
|
|
1606
|
+
});
|
|
1607
|
+
return { ok: true };
|
|
1608
|
+
},
|
|
1609
|
+
async react(caller, { id, emoji, remove }, signal) {
|
|
1610
|
+
const who = whoOf(caller);
|
|
1611
|
+
const at = locate(id);
|
|
1612
|
+
if (!at) throw notFound(`message not found: ${id}`, "message_not_found");
|
|
1613
|
+
await api(who, "POST", await onBoard(who, `/threads/${encodeURIComponent(at.threadId)}/messages/${at.sequence}/reactions`), {
|
|
1614
|
+
body: {
|
|
1615
|
+
operationId: operationId(),
|
|
1616
|
+
emoji,
|
|
1617
|
+
...remove ? { remove: true } : {}
|
|
1618
|
+
},
|
|
1619
|
+
signal
|
|
1620
|
+
});
|
|
1621
|
+
return { ok: true };
|
|
1622
|
+
},
|
|
1623
|
+
async label(caller, { id, set, unset, if: expected }, signal) {
|
|
1624
|
+
const who = whoOf(caller);
|
|
1625
|
+
const at = locate(id);
|
|
1626
|
+
if (!at) throw notFound(`message not found: ${id}`, "message_not_found");
|
|
1627
|
+
await api(who, "POST", await onBoard(who, `/threads/${encodeURIComponent(at.threadId)}/messages/${at.sequence}/labels`), {
|
|
1628
|
+
body: {
|
|
1629
|
+
operationId: operationId(),
|
|
1630
|
+
...set ? { set } : {},
|
|
1631
|
+
...unset ? { unset } : {},
|
|
1632
|
+
...expected && Object.keys(expected).length ? { if: expected } : {}
|
|
1633
|
+
},
|
|
1634
|
+
signal
|
|
1635
|
+
});
|
|
1636
|
+
return { ok: true };
|
|
1637
|
+
},
|
|
1638
|
+
async grants(caller, _input, signal) {
|
|
1639
|
+
const who = whoOf(caller);
|
|
1640
|
+
return api(who, "GET", await onBoard(who, "/grants"), signal ? { signal } : {});
|
|
1641
|
+
},
|
|
1642
|
+
async createGrant(caller, input, signal) {
|
|
1643
|
+
const who = whoOf(caller);
|
|
1644
|
+
return api(who, "POST", await onBoard(who, "/grants"), {
|
|
1645
|
+
body: {
|
|
1646
|
+
operationId: operationId(),
|
|
1647
|
+
...input
|
|
1648
|
+
},
|
|
1649
|
+
...signal ? { signal } : {}
|
|
1650
|
+
});
|
|
1651
|
+
},
|
|
1652
|
+
async revokeGrant(caller, { id }, signal) {
|
|
1653
|
+
const who = whoOf(caller);
|
|
1654
|
+
return api(who, "POST", await onBoard(who, `/grants/${encodeURIComponent(id)}/revoke`), {
|
|
1655
|
+
body: { operationId: operationId() },
|
|
1656
|
+
...signal ? { signal } : {}
|
|
1657
|
+
});
|
|
1658
|
+
},
|
|
1659
|
+
async tokens(caller, _input, signal) {
|
|
1660
|
+
const who = whoOf(caller);
|
|
1661
|
+
return api(who, "GET", await onBoard(who, "/tokens"), signal ? { signal } : {});
|
|
1662
|
+
},
|
|
1663
|
+
async createToken(caller, input, signal) {
|
|
1664
|
+
const who = whoOf(caller);
|
|
1665
|
+
return api(who, "POST", await onBoard(who, "/tokens"), {
|
|
1666
|
+
body: {
|
|
1667
|
+
operationId: operationId(),
|
|
1668
|
+
...input
|
|
1669
|
+
},
|
|
1670
|
+
...signal ? { signal } : {}
|
|
1671
|
+
});
|
|
1672
|
+
},
|
|
1673
|
+
async revokeToken(caller, { id }, signal) {
|
|
1674
|
+
const who = whoOf(caller);
|
|
1675
|
+
return api(who, "POST", await onBoard(who, `/tokens/${encodeURIComponent(id)}/revoke`), {
|
|
1676
|
+
body: { operationId: operationId() },
|
|
1677
|
+
...signal ? { signal } : {}
|
|
1678
|
+
});
|
|
1679
|
+
},
|
|
1680
|
+
async schedule(caller, input, signal) {
|
|
1681
|
+
if (input.attachments?.length) throw notSupported("files on scheduled messages");
|
|
1682
|
+
const who = whoOf(caller);
|
|
1683
|
+
const labels = input.labels && Object.keys(input.labels).length ? input.labels : void 0;
|
|
1684
|
+
let target;
|
|
1685
|
+
if (input.channel !== void 0) target = { channelId: (await channelToPost(who, input.channel)).id };
|
|
1686
|
+
else {
|
|
1687
|
+
if (labels) throw notSupported("labels on a scheduled reply");
|
|
1688
|
+
const { thread } = await messageIn(who, input.re, signal);
|
|
1689
|
+
target = { threadId: thread.id };
|
|
1690
|
+
}
|
|
1691
|
+
const ms = (value) => Math.round(duration(value));
|
|
1692
|
+
const firstAt = input.at !== void 0 ? Date.parse(input.at) : Date.now() + ms(input.in ?? input.every);
|
|
1693
|
+
const until = input.until !== void 0 ? Date.parse(input.until) : input.for !== void 0 ? firstAt + ms(input.for) : void 0;
|
|
1694
|
+
const { schedule } = await api(who, "POST", await onBoard(who, "/schedules"), {
|
|
1695
|
+
body: {
|
|
1696
|
+
operationId: operationId(),
|
|
1697
|
+
...target,
|
|
1698
|
+
text: input.text,
|
|
1699
|
+
...labels ? { labels } : {},
|
|
1700
|
+
firstAt,
|
|
1701
|
+
...input.every !== void 0 ? { every: ms(input.every) } : {},
|
|
1702
|
+
...until !== void 0 ? { until } : {},
|
|
1703
|
+
...input.times !== void 0 ? { times: input.times } : {}
|
|
1704
|
+
},
|
|
1705
|
+
signal
|
|
1706
|
+
});
|
|
1707
|
+
return { schedule: await scheduleView(who, schedule) };
|
|
1708
|
+
},
|
|
1709
|
+
async schedules(caller, query, signal) {
|
|
1710
|
+
const who = whoOf(caller);
|
|
1711
|
+
const filter = { state: query.all ? void 0 : "pending" };
|
|
1712
|
+
if (query.re !== void 0) {
|
|
1713
|
+
const found = await messageIn(who, query.re, signal).catch((error) => {
|
|
1714
|
+
if (error instanceof HttpError && error.status === 404) return null;
|
|
1715
|
+
throw error;
|
|
1716
|
+
});
|
|
1717
|
+
if (!found) return { schedules: [] };
|
|
1718
|
+
filter.threadId = found.thread.id;
|
|
1719
|
+
}
|
|
1720
|
+
if (query.channel !== void 0) {
|
|
1721
|
+
const channel = await channelNamed(who, query.channel);
|
|
1722
|
+
if (!channel) return { schedules: [] };
|
|
1723
|
+
filter.channelId = channel.id;
|
|
1724
|
+
}
|
|
1725
|
+
const me = query.by === "me" ? await actorOf(who) : void 0;
|
|
1726
|
+
const by = me ?? query.by;
|
|
1727
|
+
if (by?.startsWith("vercel:")) filter.createdBy = by;
|
|
1728
|
+
const created = (actor) => by === void 0 || (me ? actor.id === me : [
|
|
1729
|
+
actor.id,
|
|
1730
|
+
principalId(actor.principal),
|
|
1731
|
+
actor.profile?.name
|
|
1732
|
+
].includes(by));
|
|
1733
|
+
const listed = await all(who, await onBoard(who, "/schedules"), "schedules", filter, signal);
|
|
1734
|
+
return { schedules: await Promise.all(listed.filter((schedule) => created(schedule.createdBy)).map((schedule) => scheduleView(who, schedule))) };
|
|
1735
|
+
},
|
|
1736
|
+
async cancelSchedule(caller, { id }, signal) {
|
|
1737
|
+
const who = whoOf(caller);
|
|
1738
|
+
const { schedule, canceled } = await api(who, "POST", await onBoard(who, `/schedules/${encodeURIComponent(id)}/cancel`), {
|
|
1739
|
+
body: { operationId: operationId() },
|
|
1740
|
+
signal
|
|
1741
|
+
});
|
|
1742
|
+
return {
|
|
1743
|
+
schedule: await scheduleView(who, schedule),
|
|
1744
|
+
canceled
|
|
1745
|
+
};
|
|
1746
|
+
},
|
|
1747
|
+
async events(caller, query, signal) {
|
|
1748
|
+
const who = whoOf(caller);
|
|
1749
|
+
const channel = await oneChannel(who, query);
|
|
1750
|
+
if (channel) return channelEvents(who, channel, query, signal);
|
|
1751
|
+
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`);
|
|
1752
|
+
const listed = await channelsFor(who, query.channel);
|
|
1753
|
+
let position = query.after === void 0 ? {
|
|
1754
|
+
t: Date.now(),
|
|
1755
|
+
feeds: await heads(who, listed)
|
|
1756
|
+
} : locate(query.after) ? {
|
|
1757
|
+
t: await timeOf(who, query.after),
|
|
1758
|
+
feeds: {}
|
|
1759
|
+
} : positionOf(query.after);
|
|
1760
|
+
const until = Date.now() + (query.wait ?? 0) * 1e3;
|
|
1761
|
+
let busy = false;
|
|
1762
|
+
for (;;) {
|
|
1763
|
+
const started = Date.now();
|
|
1764
|
+
const page = await read(who, listed, position, query, signal);
|
|
1765
|
+
position = page.position;
|
|
1766
|
+
if (page.events.length > 0 || Date.now() >= until || signal.aborted) return {
|
|
1767
|
+
events: page.events,
|
|
1768
|
+
cursor: cursorOf(position)
|
|
1769
|
+
};
|
|
1770
|
+
if (!busy) busy = await changed(who, listed, position, until, signal) && Date.now() - started < 1e3;
|
|
1771
|
+
await pause(Math.min(started + 1e3, until) - Date.now(), signal);
|
|
1772
|
+
}
|
|
1773
|
+
},
|
|
1774
|
+
async typing() {
|
|
1775
|
+
return { targets: [] };
|
|
1776
|
+
},
|
|
1777
|
+
async readSource(_caller, { key }) {
|
|
1778
|
+
throw notFound(`this board doesn't run sync entry ${key}`, "not_synced_here");
|
|
1779
|
+
},
|
|
1780
|
+
async watchers(caller) {
|
|
1781
|
+
const who = whoOf(caller);
|
|
1782
|
+
const { watchers } = await api(who, "GET", await onBoard(who, "/watchers"));
|
|
1783
|
+
return { watchers: await Promise.all(watchers.map(async (found) => ({
|
|
1784
|
+
owner: found.owner,
|
|
1785
|
+
...whereOf(found),
|
|
1786
|
+
watch: Object.fromEntries(await Promise.all(Object.entries(found.watch).map(async ([id, spec]) => [id, {
|
|
1787
|
+
tail: await tailOf(who, spec),
|
|
1788
|
+
when: spec.when
|
|
1789
|
+
}]))),
|
|
1790
|
+
sync: [],
|
|
1791
|
+
hash: found.hash
|
|
1792
|
+
}))) };
|
|
1793
|
+
},
|
|
1794
|
+
async register(caller, body) {
|
|
1795
|
+
if ((body.sync?.length ?? 0) > 0) throw notSupported("sync");
|
|
1796
|
+
return registerAs(whoOf(caller), typeof body.path === "string" ? {
|
|
1797
|
+
path: body.path,
|
|
1798
|
+
...body.branch ? { branch: body.branch } : {}
|
|
1799
|
+
} : { url: body.url ?? null }, body.watch);
|
|
1800
|
+
},
|
|
1801
|
+
async matches(caller, query, signal) {
|
|
1802
|
+
return { matches: await pullAs(whoOf(caller), query, signal) };
|
|
1803
|
+
},
|
|
1804
|
+
async ack(caller, { id, ...body }) {
|
|
1805
|
+
await ackAs(whoOf(caller), id, body);
|
|
1806
|
+
return { ok: true };
|
|
1807
|
+
}
|
|
1808
|
+
};
|
|
1809
|
+
return {
|
|
1810
|
+
...Object.fromEntries(Object.entries(methods).map(([name, method]) => [name, (caller, ...args) => {
|
|
1811
|
+
if ("identity" in caller) throw servesNone();
|
|
1812
|
+
if (binding) runner.start();
|
|
1813
|
+
return method(caller, ...args);
|
|
1814
|
+
}])),
|
|
1815
|
+
routes: runner.routes,
|
|
1816
|
+
keeps: false,
|
|
1817
|
+
sendsSchedulesHere: false,
|
|
1818
|
+
bind(next) {
|
|
1819
|
+
if (binding) throw new Error("vercel: this backend already serves a board: create one vercel() per board()");
|
|
1820
|
+
if (Object.values(next.subscriptions).map((subscription) => subscription.kind).includes("sync")) throw new Error("vercel: Vercel's boards don't run sync yet: leave `sync` out");
|
|
1821
|
+
if (options.team && next.team && options.team !== next.team) throw new Error(`vercel: board() names team ${next.team}, and vercel() team ${options.team}: name the team once`);
|
|
1822
|
+
for (const id of Object.keys(next.subscriptions)) own.add(id);
|
|
1823
|
+
tails = Object.fromEntries(Object.entries(next.subscriptions).flatMap(([id, subscription]) => subscription.kind === "tail" ? [[id, {
|
|
1824
|
+
tail: subscription.tail,
|
|
1825
|
+
when: subscription.when
|
|
1826
|
+
}]] : []));
|
|
1827
|
+
binding = next;
|
|
1828
|
+
},
|
|
1829
|
+
/** Registers this board's watchers with Vercel's API now, as `POST /watchers` does. */
|
|
1830
|
+
registerWatchers: runner.registerNow,
|
|
1831
|
+
/** Stops pulling, for a board that pulls on its own. */
|
|
1832
|
+
close: runner.close
|
|
1833
|
+
};
|
|
1834
|
+
}
|
|
1835
|
+
//#endregion
|
|
1836
|
+
//#region src/server/policy.ts
|
|
1837
|
+
/**
|
|
1838
|
+
* The policy a board's options say: verifying requests, and what they and the principals its
|
|
1839
|
+
* backend stores may do. `keeps`: the backend keeps the board, so it serves requests; one that
|
|
1840
|
+
* uses another board's (Vercel's, or one at `BOARD_URL`) answers only wake-ups and webhooks.
|
|
1841
|
+
*/
|
|
1842
|
+
function createPolicy(options, keeps, serving, trust = null) {
|
|
1843
|
+
const grants = trust ? () => trust.grants() : null;
|
|
1844
|
+
/** The board's own Vercel project and team, from the environment, asked once. */
|
|
1845
|
+
let own = null;
|
|
1846
|
+
const project = () => (own ??= (async () => {
|
|
1847
|
+
if (!serving) return {
|
|
1848
|
+
id: null,
|
|
1849
|
+
teamId: null
|
|
1850
|
+
};
|
|
1851
|
+
const found = await serving();
|
|
1852
|
+
const [id, teamId] = await Promise.all([found.ownProjectId(), found.ownTeamId()]);
|
|
1853
|
+
return {
|
|
1854
|
+
id,
|
|
1855
|
+
teamId
|
|
1856
|
+
};
|
|
1857
|
+
})()).catch((error) => {
|
|
1858
|
+
own = null;
|
|
1859
|
+
throw error;
|
|
1860
|
+
});
|
|
1861
|
+
/** What discovery says the board's project is, as a request shows it: clients mint tokens with it. */
|
|
1862
|
+
async function discoveryIdentity(headers) {
|
|
1863
|
+
if (!serving) return {
|
|
1864
|
+
projectId: null,
|
|
1865
|
+
teamId: null
|
|
1866
|
+
};
|
|
1867
|
+
return (await serving()).discoveryIdentity(headers);
|
|
1868
|
+
}
|
|
1869
|
+
let tokens = null;
|
|
1870
|
+
/** The verifier: `authenticate`, or `oidcTokens()` where this build has it. */
|
|
1871
|
+
const verifier = () => options.authenticate ? Promise.resolve(options.authenticate) : tokens ??= serving ? serving().then((found) => found.oidcTokens()) : Promise.reject(new HttpError(501, "no_verifier", "this build of board verifies no tokens: pass board({ authenticate })"));
|
|
1872
|
+
const authority = createAuthority({
|
|
1873
|
+
project,
|
|
1874
|
+
hosts: options.authenticate !== void 0 && !verifiesTokens(options.authenticate),
|
|
1875
|
+
grants
|
|
1876
|
+
});
|
|
1877
|
+
/** One for every request, so a verifier keeps what it built: its issuers change only when grants name new ones. */
|
|
1878
|
+
const context = {
|
|
1879
|
+
project,
|
|
1880
|
+
issuers: []
|
|
1881
|
+
};
|
|
1882
|
+
/**
|
|
1883
|
+
* Trusts the issuers grants name, before a token from one is verified: only for a token from an
|
|
1884
|
+
* issuer neither Vercel nor GitHub is, so most requests read no grants for it.
|
|
1885
|
+
*/
|
|
1886
|
+
async function learnIssuers(credential) {
|
|
1887
|
+
if (!grants) return;
|
|
1888
|
+
const iss = issuerOf(credential);
|
|
1889
|
+
if (iss === null || !iss.startsWith("https://") || iss === "https://token.actions.githubusercontent.com" || VERCEL_ISSUER.test(iss)) return;
|
|
1890
|
+
const issuers = grantIssuers(await grants());
|
|
1891
|
+
if (issuers.join("\n") !== context.issuers.join("\n")) context.issuers = issuers;
|
|
1892
|
+
}
|
|
1893
|
+
/** Who a board token is: the principal that minted it, narrowed, until it's revoked or expires. */
|
|
1894
|
+
async function tokenPrincipal(secret) {
|
|
1895
|
+
if (!trust) throw unauthorized("this board issues no tokens: send a board token to the board that minted it");
|
|
1896
|
+
const found = await trust.token(await tokenHash(secret));
|
|
1897
|
+
if (!found || found.expiresAt.getTime() <= Date.now()) throw unauthorized("invalid token: revoked, expired, or not this board's");
|
|
1898
|
+
return {
|
|
1899
|
+
...found.minter,
|
|
1900
|
+
expiresAt: found.expiresAt,
|
|
1901
|
+
token: found.id,
|
|
1902
|
+
pinned: found.pinned
|
|
1903
|
+
};
|
|
1904
|
+
}
|
|
1905
|
+
/** Verified principals by credential, until they expire, so a stream's polls don't verify from scratch. */
|
|
1906
|
+
const verified = /* @__PURE__ */ new Map();
|
|
1907
|
+
/** And by request, for one with no credential (a session cookie), for as long as it's served. */
|
|
1908
|
+
const perRequest = /* @__PURE__ */ new WeakMap();
|
|
1909
|
+
/** Who a request's credential is: a 401 or the host's own rejection when it's no one. */
|
|
1910
|
+
async function principalOf(request) {
|
|
1911
|
+
const live = (principal) => principal.expiresAt === null || principal.expiresAt.getTime() > Date.now();
|
|
1912
|
+
const known = perRequest.get(request);
|
|
1913
|
+
if (known) {
|
|
1914
|
+
const principal = await known;
|
|
1915
|
+
if (live(principal)) return principal;
|
|
1916
|
+
}
|
|
1917
|
+
const key = request.credential === null ? null : [request.audience, request.credential].join("");
|
|
1918
|
+
const cached = key === null ? void 0 : verified.get(key);
|
|
1919
|
+
if (cached && cached.until > Date.now()) {
|
|
1920
|
+
perRequest.set(request, cached.principal);
|
|
1921
|
+
return cached.principal;
|
|
1922
|
+
}
|
|
1923
|
+
const principal = verify(request);
|
|
1924
|
+
perRequest.set(request, principal);
|
|
1925
|
+
if (key !== null) principal.then((found) => {
|
|
1926
|
+
if (found.facts?.issuer === "host" || found.expiresAt === null || found.token !== void 0) return;
|
|
1927
|
+
if (verified.size >= 1e3) verified.delete(verified.keys().next().value);
|
|
1928
|
+
verified.set(key, {
|
|
1929
|
+
principal,
|
|
1930
|
+
until: found.expiresAt.getTime()
|
|
1931
|
+
});
|
|
1932
|
+
}, () => perRequest.delete(request));
|
|
1933
|
+
return principal;
|
|
1934
|
+
}
|
|
1935
|
+
async function verify(request) {
|
|
1936
|
+
if (request.credential?.startsWith("board_")) return tokenPrincipal(request.credential);
|
|
1937
|
+
if (request.credential !== null) await learnIssuers(request.credential);
|
|
1938
|
+
const authenticate = await verifier();
|
|
1939
|
+
let result;
|
|
1940
|
+
try {
|
|
1941
|
+
result = await authenticate({
|
|
1942
|
+
...request,
|
|
1943
|
+
board: context
|
|
1944
|
+
});
|
|
1945
|
+
} catch (error) {
|
|
1946
|
+
if (error instanceof Response) throw new RejectedError(error);
|
|
1947
|
+
throw error;
|
|
1948
|
+
}
|
|
1949
|
+
if (result instanceof Response) throw new RejectedError(result);
|
|
1950
|
+
if (result === null || result === void 0) throw unauthorized("missing bearer token");
|
|
1951
|
+
return fromTokens(result) ? result : hostPrincipal(result);
|
|
1952
|
+
}
|
|
1953
|
+
return {
|
|
1954
|
+
/** Whether requests are served at all: only where the backend keeps the board. */
|
|
1955
|
+
open: keeps,
|
|
1956
|
+
project,
|
|
1957
|
+
discoveryIdentity,
|
|
1958
|
+
/**
|
|
1959
|
+
* Who a request is, and what it may do now: verified, under the rules, with the profile it
|
|
1960
|
+
* claims. Each call works its access out again; its principal is verified once per credential
|
|
1961
|
+
* until it expires.
|
|
1962
|
+
*/
|
|
1963
|
+
async identify(request) {
|
|
1964
|
+
const found = await principalOf(request);
|
|
1965
|
+
const claims = found.pinned ? pinnedClaims(found.pinned, request.claims) : request.claims;
|
|
1966
|
+
const scope = found.scope === void 0 ? claims.scope ?? void 0 : claims.scope === null ? found.scope : scopeOf(compileAccess(parseScope(found.scope)).narrow(parseScope(claims.scope)));
|
|
1967
|
+
const principal = scope === void 0 ? found : {
|
|
1968
|
+
...found,
|
|
1969
|
+
scope
|
|
1970
|
+
};
|
|
1971
|
+
const { author, actor } = resolveActor(principal, claims, request.audience);
|
|
1972
|
+
return {
|
|
1973
|
+
principal: {
|
|
1974
|
+
...principal,
|
|
1975
|
+
access: await authority.grant(principal)
|
|
1976
|
+
},
|
|
1977
|
+
author,
|
|
1978
|
+
actor
|
|
1979
|
+
};
|
|
1980
|
+
},
|
|
1981
|
+
/** What a stored principal (a schedule's creator, a watcher's registrant) may do now: null once nothing, its board token's revoking included. */
|
|
1982
|
+
async accessNow(principal) {
|
|
1983
|
+
if (principal.token !== void 0 && !await trust?.live(principal.token)) return null;
|
|
1984
|
+
return authority.accessNow(principal);
|
|
1985
|
+
}
|
|
1986
|
+
};
|
|
1987
|
+
}
|
|
1988
|
+
/** A board token's pins, over what the request says: its profile and session win, and a person's name is the minter's. */
|
|
1989
|
+
function pinnedClaims(pinned, claims) {
|
|
1990
|
+
return {
|
|
1991
|
+
...claims,
|
|
1992
|
+
...pinned.profile !== null ? {
|
|
1993
|
+
profile: pinned.profile,
|
|
1994
|
+
avatar: pinned.avatar
|
|
1995
|
+
} : {},
|
|
1996
|
+
...pinned.session !== null ? { session: pinned.session } : {},
|
|
1997
|
+
handle: pinned.handle,
|
|
1998
|
+
name: pinned.name
|
|
1999
|
+
};
|
|
2000
|
+
}
|
|
2001
|
+
/** A JWT's `iss`, read but not verified: which issuer's keys would check it. Null for anything else. */
|
|
2002
|
+
function issuerOf(credential) {
|
|
2003
|
+
const payload = credential.split(".")[1];
|
|
2004
|
+
if (payload === void 0) return null;
|
|
2005
|
+
try {
|
|
2006
|
+
const json = atob(payload.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(payload.length / 4) * 4, "="));
|
|
2007
|
+
const { iss } = JSON.parse(json);
|
|
2008
|
+
return typeof iss === "string" ? iss : null;
|
|
2009
|
+
} catch {
|
|
2010
|
+
return null;
|
|
2011
|
+
}
|
|
2012
|
+
}
|
|
2013
|
+
//#endregion
|
|
2014
|
+
//#region src/contract/logos.ts
|
|
2015
|
+
const LOGOS = {
|
|
2016
|
+
claude: "m4.7144 15.9555 4.7174-2.6471.079-.2307-.079-.1275h-.2307l-.7893-.0486-2.6956-.0729-2.3375-.0971-2.2646-.1214-.5707-.1215-.5343-.7042.0546-.3522.4797-.3218.686.0608 1.5179.1032 2.2767.1578 1.6514.0972 2.4468.255h.3886l.0546-.1579-.1336-.0971-.1032-.0972L6.973 9.8356l-2.55-1.6879-1.3356-.9714-.7225-.4918-.3643-.4614-.1578-1.0078.6557-.7225.8803.0607.2246.0607.8925.686 1.9064 1.4754 2.4893 1.8336.3643.3035.1457-.1032.0182-.0728-.164-.2733-1.3539-2.4467-1.445-2.4893-.6435-1.032-.17-.6194c-.0607-.255-.1032-.4674-.1032-.7285L6.287.1335 6.6997 0l.9957.1336.419.3642.6192 1.4147 1.0018 2.2282 1.5543 3.0296.4553.8985.2429.8318.091.255h.1579v-.1457l.1275-1.706.2368-2.0947.2307-2.6957.0789-.7589.3764-.9107.7468-.4918.5828.2793.4797.686-.0668.4433-.2853 1.8517-.5586 2.9021-.3643 1.9429h.2125l.2429-.2429.9835-1.3053 1.6514-2.0643.7286-.8196.85-.9046.5464-.4311h1.0321l.759 1.1293-.34 1.1657-1.0625 1.3478-.8804 1.1414-1.2628 1.7-.7893 1.36.0729.1093.1882-.0183 2.8535-.607 1.5421-.2794 1.8396-.3157.8318.3886.091.3946-.3278.8075-1.967.4857-2.3072.4614-3.4364.8136-.0425.0304.0486.0607 1.5482.1457.6618.0364h1.621l3.0175.2247.7892.522.4736.6376-.079.4857-1.2142.6193-1.6393-.3886-3.825-.9107-1.3113-.3279h-.1822v.1093l1.0929 1.0686 2.0035 1.8092 2.5075 2.3314.1275.5768-.3218.4554-.34-.0486-2.2039-1.6575-.85-.7468-1.9246-1.621h-.1275v.17l.4432.6496 2.3436 3.5214.1214 1.0807-.17.3521-.6071.2125-.6679-.1214-1.3721-1.9246L14.38 17.959l-1.1414-1.9428-.1397.079-.674 7.2552-.3156.3703-.7286.2793-.6071-.4614-.3218-.7468.3218-1.4753.3886-1.9246.3157-1.53.2853-1.9004.17-.6314-.0121-.0425-.1397.0182-1.4328 1.9672-2.1796 2.9446-1.7243 1.8456-.4128.164-.7164-.3704.0667-.6618.4008-.5889 2.386-3.0357 1.4389-1.882.929-1.0868-.0062-.1579h-.0546l-6.3385 4.1164-1.1293.1457-.4857-.4554.0608-.7467.2307-.2429 1.9064-1.3114Z",
|
|
2017
|
+
openai: "M22.2819 9.8211a5.9847 5.9847 0 0 0-.5157-4.9108 6.0462 6.0462 0 0 0-6.5098-2.9A6.0651 6.0651 0 0 0 4.9807 4.1818a5.9847 5.9847 0 0 0-3.9977 2.9 6.0462 6.0462 0 0 0 .7427 7.0966 5.98 5.98 0 0 0 .511 4.9107 6.051 6.051 0 0 0 6.5146 2.9001A5.9847 5.9847 0 0 0 13.2599 24a6.0557 6.0557 0 0 0 5.7718-4.2058 5.9894 5.9894 0 0 0 3.9977-2.9001 6.0557 6.0557 0 0 0-.7475-7.0729zm-9.022 12.6081a4.4755 4.4755 0 0 1-2.8764-1.0408l.1419-.0804 4.7783-2.7582a.7948.7948 0 0 0 .3927-.6813v-6.7369l2.02 1.1686a.071.071 0 0 1 .038.052v5.5826a4.504 4.504 0 0 1-4.4945 4.4944zm-9.6607-4.1254a4.4708 4.4708 0 0 1-.5346-3.0137l.142.0852 4.783 2.7582a.7712.7712 0 0 0 .7806 0l5.8428-3.3685v2.3324a.0804.0804 0 0 1-.0332.0615L9.74 19.9502a4.4992 4.4992 0 0 1-6.1408-1.6464zM2.3408 7.8956a4.485 4.485 0 0 1 2.3655-1.9728V11.6a.7664.7664 0 0 0 .3879.6765l5.8144 3.3543-2.0201 1.1685a.0757.0757 0 0 1-.071 0l-4.8303-2.7865A4.504 4.504 0 0 1 2.3408 7.872zm16.5963 3.8558L13.1038 8.364 15.1192 7.2a.0757.0757 0 0 1 .071 0l4.8303 2.7913a4.4944 4.4944 0 0 1-.6765 8.1042v-5.6772a.79.79 0 0 0-.407-.667zm2.0107-3.0231l-.142-.0852-4.7735-2.7818a.7759.7759 0 0 0-.7854 0L9.409 9.2297V6.8974a.0662.0662 0 0 1 .0284-.0615l4.8303-2.7866a4.4992 4.4992 0 0 1 6.6802 4.66zM8.3065 12.863l-2.02-1.1638a.0804.0804 0 0 1-.038-.0567V6.0742a4.4992 4.4992 0 0 1 7.3757-3.4537l-.142.0805L8.704 5.459a.7948.7948 0 0 0-.3927.6813zm1.0976-2.3654l2.602-1.4998 2.6069 1.4998v2.9994l-2.5974 1.4997-2.6067-1.4997Z",
|
|
2018
|
+
x: "M14.234 10.162 22.977 0h-2.072l-7.591 8.824L7.251 0H.258l9.168 13.343L.258 24H2.33l8.016-9.318L16.749 24h6.993zm-2.837 3.299-.929-1.329L3.076 1.56h3.182l5.965 8.532.929 1.329 7.754 11.09h-3.182z",
|
|
2019
|
+
slack: "M5.042 15.165a2.528 2.528 0 0 1-2.52 2.523A2.528 2.528 0 0 1 0 15.165a2.527 2.527 0 0 1 2.522-2.52h2.52v2.52zM6.313 15.165a2.527 2.527 0 0 1 2.521-2.52 2.527 2.527 0 0 1 2.521 2.52v6.313A2.528 2.528 0 0 1 8.834 24a2.528 2.528 0 0 1-2.521-2.522v-6.313zM8.834 5.042a2.528 2.528 0 0 1-2.521-2.52A2.528 2.528 0 0 1 8.834 0a2.528 2.528 0 0 1 2.521 2.522v2.52H8.834zM8.834 6.313a2.528 2.528 0 0 1 2.521 2.521 2.528 2.528 0 0 1-2.521 2.521H2.522A2.528 2.528 0 0 1 0 8.834a2.528 2.528 0 0 1 2.522-2.521h6.312zM18.956 8.834a2.528 2.528 0 0 1 2.522-2.521A2.528 2.528 0 0 1 24 8.834a2.528 2.528 0 0 1-2.522 2.521h-2.522V8.834zM17.688 8.834a2.528 2.528 0 0 1-2.523 2.521 2.527 2.527 0 0 1-2.52-2.521V2.522A2.527 2.527 0 0 1 15.165 0a2.528 2.528 0 0 1 2.523 2.522v6.312zM15.165 18.956a2.528 2.528 0 0 1 2.523 2.522A2.528 2.528 0 0 1 15.165 24a2.527 2.527 0 0 1-2.52-2.522v-2.522h2.52zM15.165 17.688a2.527 2.527 0 0 1-2.52-2.523 2.526 2.526 0 0 1 2.52-2.52h6.313A2.527 2.527 0 0 1 24 15.165a2.528 2.528 0 0 1-2.522 2.523h-6.313z",
|
|
2020
|
+
github: "M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12",
|
|
2021
|
+
whatsapp: "M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z"
|
|
2022
|
+
};
|
|
2023
|
+
//#endregion
|
|
2024
|
+
//#region src/server/avatars.ts
|
|
2025
|
+
/** Each known agent's mark on its color. */
|
|
2026
|
+
const STYLES = {
|
|
2027
|
+
claude: {
|
|
2028
|
+
background: "#D97757",
|
|
2029
|
+
mark: { path: LOGOS.claude }
|
|
2030
|
+
},
|
|
2031
|
+
codex: {
|
|
2032
|
+
background: "#000000",
|
|
2033
|
+
mark: { path: LOGOS.openai }
|
|
2034
|
+
},
|
|
2035
|
+
grok: {
|
|
2036
|
+
background: "#000000",
|
|
2037
|
+
mark: { path: LOGOS.x }
|
|
2038
|
+
},
|
|
2039
|
+
pi: {
|
|
2040
|
+
background: "#1f1f1f",
|
|
2041
|
+
mark: { glyph: "π" }
|
|
2042
|
+
}
|
|
2043
|
+
};
|
|
2044
|
+
/** A built-in avatar for a detected agent; other names get their initial. */
|
|
2045
|
+
function avatarSvg(name) {
|
|
2046
|
+
const style = STYLES[name] ?? {
|
|
2047
|
+
background: "#666666",
|
|
2048
|
+
mark: { glyph: name.slice(0, 1).toUpperCase() }
|
|
2049
|
+
};
|
|
2050
|
+
const mark = "path" in style.mark ? `<path transform="translate(30 30) scale(2.8333)" fill="#ffffff" d="${style.mark.path}"/>` : `<text x="64" y="86" font-family="ui-sans-serif,system-ui,sans-serif" font-size="66" font-weight="600" text-anchor="middle" fill="#ffffff">${style.mark.glyph}</text>`;
|
|
2051
|
+
return `<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128" viewBox="0 0 128 128"><rect width="128" height="128" rx="28" fill="${style.background}"/>${mark}</svg>`;
|
|
2052
|
+
}
|
|
2053
|
+
//#endregion
|
|
2054
|
+
//#region src/server/serve.ts
|
|
2055
|
+
/** The methods whose answer is something new. */
|
|
2056
|
+
const CREATED = /* @__PURE__ */ new Set([
|
|
2057
|
+
"post",
|
|
2058
|
+
"schedule",
|
|
2059
|
+
"upload",
|
|
2060
|
+
"uploadFinish"
|
|
2061
|
+
]);
|
|
2062
|
+
/** An email, as `--mentions` names one: sync looks its platform user up. */
|
|
2063
|
+
const EMAIL = /^[^\s@]+@[^\s@]+$/;
|
|
2064
|
+
/** How long a filter's email lookup holds. */
|
|
2065
|
+
const EMAIL_TTL_MS = 3e5;
|
|
2066
|
+
/** Shown inline only when a browser can't run it: everything else downloads. */
|
|
2067
|
+
const INLINE = /^(image\/(png|jpeg|gif|webp|avif)|video\/(mp4|webm)|text\/plain)$/;
|
|
2068
|
+
/**
|
|
2069
|
+
* The file, sandboxed: it can't run as a page on the board's origin, and only
|
|
2070
|
+
* types a browser can't execute display inline.
|
|
2071
|
+
*/
|
|
2072
|
+
function attachmentResponse({ attachment, data }) {
|
|
2073
|
+
const disposition = INLINE.test(attachment.type) ? "inline" : "attachment";
|
|
2074
|
+
const body = data instanceof Uint8Array ? new Blob([data]) : data;
|
|
2075
|
+
return new Response(body, { headers: {
|
|
2076
|
+
"content-type": attachment.type,
|
|
2077
|
+
"content-length": String(attachment.size),
|
|
2078
|
+
"content-disposition": `${disposition}; filename*=UTF-8''${encodeURIComponent(attachment.name)}`,
|
|
2079
|
+
"content-security-policy": "sandbox; default-src 'none'",
|
|
2080
|
+
"x-content-type-options": "nosniff",
|
|
2081
|
+
"cache-control": "private, max-age=31536000, immutable"
|
|
2082
|
+
} });
|
|
2083
|
+
}
|
|
2084
|
+
/** A method's input, from the request: its path's `:id` or `:key`, its query, or its body, validated. */
|
|
2085
|
+
async function inputOf(name, request, url, params) {
|
|
2086
|
+
const id = params.id ?? "";
|
|
2087
|
+
const key = params.key ?? "";
|
|
2088
|
+
const body = () => readJson(request);
|
|
2089
|
+
switch (name) {
|
|
2090
|
+
case "discovery":
|
|
2091
|
+
case "me":
|
|
2092
|
+
case "channels":
|
|
2093
|
+
case "actors":
|
|
2094
|
+
case "watchers":
|
|
2095
|
+
case "grants":
|
|
2096
|
+
case "tokens": return {};
|
|
2097
|
+
case "message":
|
|
2098
|
+
case "posted":
|
|
2099
|
+
case "synced":
|
|
2100
|
+
case "cancelSchedule":
|
|
2101
|
+
case "revokeGrant":
|
|
2102
|
+
case "revokeToken":
|
|
2103
|
+
case "attachment":
|
|
2104
|
+
case "uploadFinish": return { id };
|
|
2105
|
+
case "messages": return MessagesQuery.parse(queryObject(url));
|
|
2106
|
+
case "threads": return ThreadsQuery.parse(queryObject(url));
|
|
2107
|
+
case "schedules": return SchedulesQuery.parse(queryObject(url));
|
|
2108
|
+
case "matches": return MatchesQuery.parse(queryObject(url));
|
|
2109
|
+
case "events": {
|
|
2110
|
+
const query = EventsQuery.parse(queryObject(url));
|
|
2111
|
+
const last = request.headers.get("last-event-id");
|
|
2112
|
+
if (query.after === void 0 && last && Ref.safeParse(last).success) query.after = last;
|
|
2113
|
+
return query;
|
|
2114
|
+
}
|
|
2115
|
+
case "post": return PostBody.parse(await body());
|
|
2116
|
+
case "createChannel": return CreateChannelBody.parse(await body());
|
|
2117
|
+
case "schedule": return ScheduleBody.parse(await body());
|
|
2118
|
+
case "createGrant": return GrantBody.parse(await body());
|
|
2119
|
+
case "createToken": return TokenBody.parse(await body());
|
|
2120
|
+
case "register": return RegisterBody.parse(await body());
|
|
2121
|
+
case "edit": return {
|
|
2122
|
+
id,
|
|
2123
|
+
...EditBody.parse(await body())
|
|
2124
|
+
};
|
|
2125
|
+
case "delete": return {
|
|
2126
|
+
id,
|
|
2127
|
+
...DeleteBody.parse(await body())
|
|
2128
|
+
};
|
|
2129
|
+
case "react": return {
|
|
2130
|
+
id,
|
|
2131
|
+
...ReactBody.parse(await body())
|
|
2132
|
+
};
|
|
2133
|
+
case "label": return {
|
|
2134
|
+
id,
|
|
2135
|
+
...LabelBody.parse(await body())
|
|
2136
|
+
};
|
|
2137
|
+
case "ack": return {
|
|
2138
|
+
id,
|
|
2139
|
+
...AckBody.parse(await body())
|
|
2140
|
+
};
|
|
2141
|
+
case "upload": {
|
|
2142
|
+
const header = request.headers.get("x-board-filename");
|
|
2143
|
+
let name = null;
|
|
2144
|
+
try {
|
|
2145
|
+
name = header === null ? null : decodeURIComponent(header);
|
|
2146
|
+
} catch {
|
|
2147
|
+
throw badRequest("`x-board-filename` is not URI-encoded");
|
|
2148
|
+
}
|
|
2149
|
+
return {
|
|
2150
|
+
data: await readCapped(request, ATTACHMENT_BYTES_MAX),
|
|
2151
|
+
name,
|
|
2152
|
+
type: request.headers.get("content-type")
|
|
2153
|
+
};
|
|
2154
|
+
}
|
|
2155
|
+
case "uploadStart": return UploadStartBody.parse(await body());
|
|
2156
|
+
case "syncImport": return SyncImportBody.parse(await body());
|
|
2157
|
+
case "syncReceipt": return SyncReceiptBody.parse(await body());
|
|
2158
|
+
case "syncThread": return { thread: params.thread ?? "" };
|
|
2159
|
+
case "syncFind": return SyncFindQuery.parse(queryObject(url));
|
|
2160
|
+
case "syncCopies": return SyncCopiesQuery.parse(queryObject(url));
|
|
2161
|
+
case "inboxPush": return {
|
|
2162
|
+
key,
|
|
2163
|
+
...InboxPushBody.parse(await body())
|
|
2164
|
+
};
|
|
2165
|
+
case "inboxNext": return {
|
|
2166
|
+
key,
|
|
2167
|
+
...InboxNextQuery.parse(queryObject(url))
|
|
2168
|
+
};
|
|
2169
|
+
case "inboxAck": return {
|
|
2170
|
+
key,
|
|
2171
|
+
id,
|
|
2172
|
+
...InboxAckBody.parse(await body())
|
|
2173
|
+
};
|
|
2174
|
+
case "inbox": return {
|
|
2175
|
+
key,
|
|
2176
|
+
...InboxQuery.parse(queryObject(url))
|
|
2177
|
+
};
|
|
2178
|
+
case "typing": return {
|
|
2179
|
+
id,
|
|
2180
|
+
...TypingBody.parse(await body()) ?? {}
|
|
2181
|
+
};
|
|
2182
|
+
case "readSource": return {
|
|
2183
|
+
key,
|
|
2184
|
+
...SourceReadQuery.parse(queryObject(url))
|
|
2185
|
+
};
|
|
2186
|
+
case "joinSource": return {
|
|
2187
|
+
key,
|
|
2188
|
+
...SourceJoinBody.parse(await body())
|
|
2189
|
+
};
|
|
2190
|
+
case "linked": return LinkedQuery.parse(queryObject(url));
|
|
2191
|
+
}
|
|
2192
|
+
}
|
|
2193
|
+
/** A platform user, as the middleware is told who's writing. */
|
|
2194
|
+
const externalActor = (author) => ({
|
|
2195
|
+
id: author.id,
|
|
2196
|
+
kind: "external",
|
|
2197
|
+
handle: author.handle,
|
|
2198
|
+
name: author.name,
|
|
2199
|
+
avatar: author.avatar
|
|
2200
|
+
});
|
|
2201
|
+
/** A write's caller, as the middleware is told: where it came from. The middleware's own handle and sync's lookups skip it. */
|
|
2202
|
+
function sourceOf(caller) {
|
|
2203
|
+
const via = caller.origin.via;
|
|
2204
|
+
if (via?.kind === "middleware" || via?.kind === "engine") return null;
|
|
2205
|
+
return via ?? { kind: "api" };
|
|
2206
|
+
}
|
|
2207
|
+
/** The middleware's own handle: its writes skip the middleware. */
|
|
2208
|
+
const MIDDLEWARE = {
|
|
2209
|
+
self: "middleware",
|
|
2210
|
+
origin: { via: { kind: "middleware" } }
|
|
2211
|
+
};
|
|
2212
|
+
/** board()'s own code, for what it looks up itself. */
|
|
2213
|
+
const OWN = {
|
|
2214
|
+
self: null,
|
|
2215
|
+
origin: { via: {
|
|
2216
|
+
kind: "client",
|
|
2217
|
+
name: null
|
|
2218
|
+
} }
|
|
2219
|
+
};
|
|
2220
|
+
/**
|
|
2221
|
+
* The board, serving the protocol over HTTP on its backend: it routes and validates each request,
|
|
2222
|
+
* verifies its caller, applies `access`, runs the middleware, and calls the backend's method of the
|
|
2223
|
+
* same name with the caller it verified. Sync runs here too, for requests and for its own code.
|
|
2224
|
+
*/
|
|
2225
|
+
async function createServe(context) {
|
|
2226
|
+
const { options, backend, runtime, policy } = context;
|
|
2227
|
+
const entries = options.sync ?? {};
|
|
2228
|
+
const engine = Object.keys(entries).length > 0 ? (await runtime.sync()).createSyncEngine(entries) : null;
|
|
2229
|
+
const streamMaxMs = options.streamMaxMs ?? 28e4;
|
|
2230
|
+
const route = createRouter(backend.routes, options.basePath);
|
|
2231
|
+
const { state, ownUrl, clientAs, handleOf } = context;
|
|
2232
|
+
const watch = options.watch ?? {};
|
|
2233
|
+
const middleware = options.middleware ?? [];
|
|
2234
|
+
/** What a request says about who it is, none of it verified yet: its bearer token, its claims, and the board's URL. */
|
|
2235
|
+
function requestOf(request, audience) {
|
|
2236
|
+
return {
|
|
2237
|
+
credential: (request.headers.get("authorization") ?? "").match(/^Bearer\s+(.+)$/i)?.[1] ?? null,
|
|
2238
|
+
claims: claimsOf(request.headers),
|
|
2239
|
+
audience,
|
|
2240
|
+
headers: request.headers
|
|
2241
|
+
};
|
|
2242
|
+
}
|
|
2243
|
+
/** A request's caller, verified: who it is, and what `access` lets it do now. */
|
|
2244
|
+
async function callerOf(request) {
|
|
2245
|
+
return {
|
|
2246
|
+
identity: await policy.identify(request),
|
|
2247
|
+
origin: { via: { kind: "api" } }
|
|
2248
|
+
};
|
|
2249
|
+
}
|
|
2250
|
+
/** What a board that serves no requests answers them: one that uses another board's. */
|
|
2251
|
+
const servesOnly = () => new HttpError(404, "not_found", `${ownUrl() ?? "this board"} answers only wake-ups and webhooks`);
|
|
2252
|
+
/**
|
|
2253
|
+
* `@[ada@vercel.com]`: an email a synced platform knows becomes that user's mention, and the
|
|
2254
|
+
* board learns who they are; the rest stay plain text.
|
|
2255
|
+
*/
|
|
2256
|
+
async function withEmails(text) {
|
|
2257
|
+
return (await withEmailMentions(text, engine ? learnEmail : void 0)).text;
|
|
2258
|
+
}
|
|
2259
|
+
/**
|
|
2260
|
+
* The synced platform's user with this email, whom the board learns: a post can mention only
|
|
2261
|
+
* an actor it knows, and a platform mention of them resolves only once it does.
|
|
2262
|
+
*/
|
|
2263
|
+
async function learnEmail(email) {
|
|
2264
|
+
const actor = await engine.findByEmail(email);
|
|
2265
|
+
if (actor) await backend.syncImport(engine.caller, {
|
|
2266
|
+
op: "seen",
|
|
2267
|
+
author: {
|
|
2268
|
+
...actor,
|
|
2269
|
+
isBot: false
|
|
2270
|
+
}
|
|
2271
|
+
}, new AbortController().signal);
|
|
2272
|
+
return actor;
|
|
2273
|
+
}
|
|
2274
|
+
/** Emails filters named, as sync found them, for a few minutes: `tail` and `wait` ask at every page. */
|
|
2275
|
+
const mentioned = /* @__PURE__ */ new Map();
|
|
2276
|
+
/**
|
|
2277
|
+
* `--mentions ada@vercel.com`: the synced platform's user with that email, for a caller that may
|
|
2278
|
+
* read somewhere. Anything else, and an email sync doesn't know, goes on as it came.
|
|
2279
|
+
*/
|
|
2280
|
+
async function withMentioned(caller, query) {
|
|
2281
|
+
const email = query.mentions?.toLowerCase();
|
|
2282
|
+
if (!engine || email === void 0 || !EMAIL.test(email)) return query;
|
|
2283
|
+
const access = accessOf(caller);
|
|
2284
|
+
if (access !== null && !access.anywhere("read")) return query;
|
|
2285
|
+
let found = mentioned.get(email);
|
|
2286
|
+
if (!found || Date.now() - found.at > EMAIL_TTL_MS) {
|
|
2287
|
+
if (mentioned.size >= 1e3) mentioned.clear();
|
|
2288
|
+
found = {
|
|
2289
|
+
at: Date.now(),
|
|
2290
|
+
actor: learnEmail(email).catch(() => null)
|
|
2291
|
+
};
|
|
2292
|
+
mentioned.set(email, found);
|
|
2293
|
+
}
|
|
2294
|
+
const actor = await found.actor;
|
|
2295
|
+
return actor ? {
|
|
2296
|
+
...query,
|
|
2297
|
+
mentions: actor.id
|
|
2298
|
+
} : query;
|
|
2299
|
+
}
|
|
2300
|
+
/**
|
|
2301
|
+
* A sync target as the board that syncs it resolves it. One for an entry this board doesn't
|
|
2302
|
+
* have goes on as it is, for the sync that does, unless this board syncs: then it's a mistake.
|
|
2303
|
+
*/
|
|
2304
|
+
async function resolveTarget(target) {
|
|
2305
|
+
if (typeof target !== "string") return target;
|
|
2306
|
+
const at = target.indexOf(":");
|
|
2307
|
+
if (at <= 0) throw badRequest(`sync targets look like <key>:<channel or thread>, got: ${target}`);
|
|
2308
|
+
const key = target.slice(0, at);
|
|
2309
|
+
if (engine && entries[key]) return engine.normalizeTarget(target);
|
|
2310
|
+
if (engine) throw badRequest(`no sync entry named ${key}`);
|
|
2311
|
+
return syncTarget(target);
|
|
2312
|
+
}
|
|
2313
|
+
/**
|
|
2314
|
+
* What a verified caller may do, as board()'s `access` said when it verified them: board() checks
|
|
2315
|
+
* it before it does anything for them past calling the backend (a platform call, an email lookup,
|
|
2316
|
+
* sync's own write, reading an upload, the middleware), so a caller it won't let in starts none of
|
|
2317
|
+
* it. Null for this deployment's own code, which may do everything.
|
|
2318
|
+
*/
|
|
2319
|
+
const accessOf = (caller) => "identity" in caller ? caller.identity.principal.access : null;
|
|
2320
|
+
/**
|
|
2321
|
+
* Whether board() may work for a write of `caller`'s that lands in `channel`, or in the thread of
|
|
2322
|
+
* message `re`, which it must read: `post` there. One it may not goes to the backend as it came,
|
|
2323
|
+
* for the backend to say why.
|
|
2324
|
+
*/
|
|
2325
|
+
async function mayPost(caller, where, signal) {
|
|
2326
|
+
const access = accessOf(caller);
|
|
2327
|
+
if (access === null) return {
|
|
2328
|
+
access: null,
|
|
2329
|
+
channel: where.channel ?? ""
|
|
2330
|
+
};
|
|
2331
|
+
const channel = where.channel ?? (where.re === void 0 ? void 0 : (await lookup(caller, where.re, signal))?.channel);
|
|
2332
|
+
if (channel === void 0) return null;
|
|
2333
|
+
return access.can("post", channel) ? {
|
|
2334
|
+
access,
|
|
2335
|
+
channel
|
|
2336
|
+
} : null;
|
|
2337
|
+
}
|
|
2338
|
+
/** Who this deployment's own code is on its backend, asked once each: the middleware is told who's writing. */
|
|
2339
|
+
const selves = /* @__PURE__ */ new Map();
|
|
2340
|
+
async function whoIs(caller, signal) {
|
|
2341
|
+
if ("identity" in caller) return {
|
|
2342
|
+
principal: caller.identity.principal.id,
|
|
2343
|
+
actor: caller.identity.actor
|
|
2344
|
+
};
|
|
2345
|
+
const key = JSON.stringify([
|
|
2346
|
+
caller.origin.via?.kind ?? "",
|
|
2347
|
+
caller.self,
|
|
2348
|
+
caller.profile ?? null
|
|
2349
|
+
]);
|
|
2350
|
+
let found = selves.get(key);
|
|
2351
|
+
if (!found) {
|
|
2352
|
+
selves.set(key, found = backend.me(caller, {}, signal).then((me) => ({
|
|
2353
|
+
principal: me.principal,
|
|
2354
|
+
actor: {
|
|
2355
|
+
id: me.actor,
|
|
2356
|
+
kind: me.kind,
|
|
2357
|
+
handle: me.handle,
|
|
2358
|
+
name: me.name,
|
|
2359
|
+
avatar: me.avatar
|
|
2360
|
+
}
|
|
2361
|
+
})));
|
|
2362
|
+
found.catch(() => selves.delete(key));
|
|
2363
|
+
}
|
|
2364
|
+
return found;
|
|
2365
|
+
}
|
|
2366
|
+
let middlewareBoard = null;
|
|
2367
|
+
/** Runs the middleware on a write, then `commit`s what it passed on: a `DroppedError` when it drops it. */
|
|
2368
|
+
const screen = (write, author, source, commit) => runMiddleware(middleware, {
|
|
2369
|
+
write,
|
|
2370
|
+
author,
|
|
2371
|
+
source,
|
|
2372
|
+
board: () => middlewareBoard ??= handleOf(MIDDLEWARE, null)
|
|
2373
|
+
}, commit);
|
|
2374
|
+
/** Whether a lookup found what it looked for: a 404 says it didn't. */
|
|
2375
|
+
async function found(lookup) {
|
|
2376
|
+
try {
|
|
2377
|
+
await lookup();
|
|
2378
|
+
return true;
|
|
2379
|
+
} catch (error) {
|
|
2380
|
+
if (error instanceof HttpError && error.status === 404) return false;
|
|
2381
|
+
throw error;
|
|
2382
|
+
}
|
|
2383
|
+
}
|
|
2384
|
+
/** Files a write carries, as the board stored them: each one `caller` may have, or the backend's 404. */
|
|
2385
|
+
async function attachmentsOf(caller, ids, signal) {
|
|
2386
|
+
const attachments = [];
|
|
2387
|
+
for (const id of new Set(ids ?? [])) {
|
|
2388
|
+
const { attachment, data } = await backend.attachment(caller, { id }, signal);
|
|
2389
|
+
if (data instanceof ReadableStream) await data.cancel().catch(() => {});
|
|
2390
|
+
attachments.push(attachment);
|
|
2391
|
+
}
|
|
2392
|
+
return attachments;
|
|
2393
|
+
}
|
|
2394
|
+
/**
|
|
2395
|
+
* A post through the middleware, then `send`: once board() knows it would land (a reply's root is
|
|
2396
|
+
* there, and the caller may post, label, and sync where it does), with the files it may have. A
|
|
2397
|
+
* retry of one that landed stands, whatever the middleware would say now; one that wouldn't land
|
|
2398
|
+
* goes as it came, for the backend to say why.
|
|
2399
|
+
*/
|
|
2400
|
+
async function screenPost(caller, input, signal, send) {
|
|
2401
|
+
const source = sourceOf(caller);
|
|
2402
|
+
if (middleware.length === 0 || source === null) return send(input);
|
|
2403
|
+
if (input.id !== void 0 && await found(() => backend.posted(caller, { id: input.id }, signal))) return send(input);
|
|
2404
|
+
let channel = input.channel;
|
|
2405
|
+
let re = null;
|
|
2406
|
+
if (input.re !== void 0) {
|
|
2407
|
+
const root = await lookup(caller, input.re, signal);
|
|
2408
|
+
if (!root) return send(input);
|
|
2409
|
+
channel = root.channel;
|
|
2410
|
+
re = root.re ?? root.id;
|
|
2411
|
+
}
|
|
2412
|
+
const access = accessOf(caller);
|
|
2413
|
+
const labels = Object.keys(input.labels ?? {}).length > 0;
|
|
2414
|
+
const syncs = input.re === void 0 && (input.sync?.length ?? 0) > 0;
|
|
2415
|
+
if (channel === void 0 || access && (!access.can("post", channel) || labels && !access.can("label", channel) || syncs && !access.can("sync", channel))) return send(input);
|
|
2416
|
+
const attachments = await attachmentsOf(caller, input.attachments, signal);
|
|
2417
|
+
const { actor } = await whoIs(caller, signal);
|
|
2418
|
+
return screen({
|
|
2419
|
+
kind: "post",
|
|
2420
|
+
channel,
|
|
2421
|
+
re,
|
|
2422
|
+
text: input.text,
|
|
2423
|
+
labels: input.labels ?? {},
|
|
2424
|
+
attachments
|
|
2425
|
+
}, actor, source, (write) => send({
|
|
2426
|
+
...input,
|
|
2427
|
+
text: write.text,
|
|
2428
|
+
labels: write.labels
|
|
2429
|
+
}));
|
|
2430
|
+
}
|
|
2431
|
+
/**
|
|
2432
|
+
* A schedule, on a backend whose sends post elsewhere: its message through the middleware once,
|
|
2433
|
+
* as the caller's post of it, since its text and labels never change and no send comes back here.
|
|
2434
|
+
*/
|
|
2435
|
+
function screenSchedule(caller, input, signal) {
|
|
2436
|
+
const { channel, re, text, labels, noSync, attachments } = input;
|
|
2437
|
+
return screenPost(caller, {
|
|
2438
|
+
...channel !== void 0 ? { channel } : {},
|
|
2439
|
+
...re !== void 0 ? { re } : {},
|
|
2440
|
+
text,
|
|
2441
|
+
...labels ? { labels } : {},
|
|
2442
|
+
...noSync !== void 0 ? { noSync } : {},
|
|
2443
|
+
...attachments ? { attachments } : {}
|
|
2444
|
+
}, signal, (screened) => backend.schedule(caller, {
|
|
2445
|
+
...input,
|
|
2446
|
+
text: screened.text,
|
|
2447
|
+
...screened.labels ? { labels: screened.labels } : {}
|
|
2448
|
+
}, signal));
|
|
2449
|
+
}
|
|
2450
|
+
/**
|
|
2451
|
+
* The caller's own message, still there, where it may post: what an edit of it changes. One it
|
|
2452
|
+
* can't read may still be its own, as board()'s own code finds it, only if it was written there
|
|
2453
|
+
* without reading too: one its principal wrote where it reads (a repo's workflows share one) is
|
|
2454
|
+
* as missing to it as one that isn't there.
|
|
2455
|
+
*/
|
|
2456
|
+
async function ownMessage(caller, id, signal) {
|
|
2457
|
+
const access = accessOf(caller);
|
|
2458
|
+
const readable = await lookup(caller, id, signal);
|
|
2459
|
+
const message = readable ?? (access !== null ? await lookup(OWN, id, signal) : null);
|
|
2460
|
+
if (!message || message.deleted || access && !access.can("post", message.channel)) return null;
|
|
2461
|
+
if (!readable && !message.blind) return null;
|
|
2462
|
+
return message.by.principal === (await whoIs(caller, signal)).principal ? message : null;
|
|
2463
|
+
}
|
|
2464
|
+
/** An edit through the middleware, then `send`: only the author's own, of a message that's still there, reaches it. */
|
|
2465
|
+
async function screenEdit(caller, input, signal, send) {
|
|
2466
|
+
const source = sourceOf(caller);
|
|
2467
|
+
if (middleware.length === 0 || source === null) return send(input);
|
|
2468
|
+
const message = await ownMessage(caller, input.id, signal);
|
|
2469
|
+
if (!message) return send(input);
|
|
2470
|
+
const { actor } = await whoIs(caller, signal);
|
|
2471
|
+
return screen({
|
|
2472
|
+
kind: "edit",
|
|
2473
|
+
id: message.id,
|
|
2474
|
+
channel: message.channel,
|
|
2475
|
+
re: message.re,
|
|
2476
|
+
text: input.text
|
|
2477
|
+
}, actor, source, (write) => send({
|
|
2478
|
+
...input,
|
|
2479
|
+
text: write.text
|
|
2480
|
+
}));
|
|
2481
|
+
}
|
|
2482
|
+
/**
|
|
2483
|
+
* Where an import came from, as the middleware is told: the platform event sync says it's from,
|
|
2484
|
+
* or what its entry and origin say. Null when it names an entry its caller doesn't sync, which
|
|
2485
|
+
* the backend refuses.
|
|
2486
|
+
*/
|
|
2487
|
+
async function importSource(caller, body, found, signal) {
|
|
2488
|
+
const key = body.source?.key ?? body.from;
|
|
2489
|
+
if (body.source) {
|
|
2490
|
+
if (!("identity" in caller ? (await backend.watchers(caller, {}, signal)).watchers.some((registration) => registration.owner === caller.identity.principal.id && registration.sync.some((entry) => entry.key === key)) : entries[body.source.key] !== void 0)) return null;
|
|
2491
|
+
}
|
|
2492
|
+
const origin = (body.op === "post" ? body.origin : null) ?? found?.origin ?? null;
|
|
2493
|
+
return {
|
|
2494
|
+
kind: "sync",
|
|
2495
|
+
key: key ?? "",
|
|
2496
|
+
platform: body.author.id.slice(0, Math.max(0, body.author.id.indexOf(":"))),
|
|
2497
|
+
channel: body.source?.channel ?? found?.origin?.channel ?? origin?.channel ?? "",
|
|
2498
|
+
thread: body.source?.thread ?? (origin ? origin.subthread ?? origin.thread : "")
|
|
2499
|
+
};
|
|
2500
|
+
}
|
|
2501
|
+
/** The board message an import changes: the one it names, or the one its platform IDs are on the board as. */
|
|
2502
|
+
async function importTarget(caller, body, signal) {
|
|
2503
|
+
let id = body.message ?? null;
|
|
2504
|
+
if (body.origin !== void 0) {
|
|
2505
|
+
const { thread, message } = await backend.syncFind(caller, {
|
|
2506
|
+
thread: body.origin.thread,
|
|
2507
|
+
...body.origin.message !== void 0 ? { message: body.origin.message } : {}
|
|
2508
|
+
}, signal);
|
|
2509
|
+
id = body.origin.message !== void 0 ? message : thread === null ? null : (await backend.syncThread(caller, { thread }, signal)).root;
|
|
2510
|
+
}
|
|
2511
|
+
return id === null ? null : lookup(caller, id, signal);
|
|
2512
|
+
}
|
|
2513
|
+
/**
|
|
2514
|
+
* An import, through the middleware when it's a post or an edit that would land: what the
|
|
2515
|
+
* middleware passed on, or what it responded when it dropped it, for sync to tell the author on
|
|
2516
|
+
* the platform. A retry of one that landed stands.
|
|
2517
|
+
*/
|
|
2518
|
+
async function syncImport(caller, body, signal) {
|
|
2519
|
+
const send = (patched) => backend.syncImport(caller, patched, signal);
|
|
2520
|
+
if (middleware.length === 0 || caller.origin.via?.kind === "middleware" || body.op !== "post" && body.op !== "edit") return send(body);
|
|
2521
|
+
const access = accessOf(caller);
|
|
2522
|
+
if (access && (!access.anywhere("sync") || "identity" in caller && caller.identity.principal.scope !== void 0)) return send(body);
|
|
2523
|
+
const dropped = async (commit) => {
|
|
2524
|
+
try {
|
|
2525
|
+
return await commit();
|
|
2526
|
+
} catch (error) {
|
|
2527
|
+
if (!(error instanceof DroppedError)) throw error;
|
|
2528
|
+
return {
|
|
2529
|
+
message: null,
|
|
2530
|
+
dropped: [...error.responses]
|
|
2531
|
+
};
|
|
2532
|
+
}
|
|
2533
|
+
};
|
|
2534
|
+
if (body.op === "post") {
|
|
2535
|
+
if (body.id !== void 0 && (await backend.syncFind(caller, { post: body.id }, signal)).message !== null) return send(body);
|
|
2536
|
+
let channel = body.channel;
|
|
2537
|
+
let re = null;
|
|
2538
|
+
if (body.re !== void 0) {
|
|
2539
|
+
const root = await lookup(caller, body.re, signal);
|
|
2540
|
+
if (!root) return send(body);
|
|
2541
|
+
channel = root.channel;
|
|
2542
|
+
re = root.re ?? root.id;
|
|
2543
|
+
}
|
|
2544
|
+
if (channel === void 0 || access && !access.can("sync", channel)) return send(body);
|
|
2545
|
+
const source = await importSource(caller, body, null, signal);
|
|
2546
|
+
if (!source) return send(body);
|
|
2547
|
+
const attachments = await attachmentsOf(caller, body.attachments, signal);
|
|
2548
|
+
return dropped(async () => screen({
|
|
2549
|
+
kind: "post",
|
|
2550
|
+
channel,
|
|
2551
|
+
re,
|
|
2552
|
+
text: body.text,
|
|
2553
|
+
labels: body.labels ?? {},
|
|
2554
|
+
attachments
|
|
2555
|
+
}, externalActor(body.author), source, async (write) => send({
|
|
2556
|
+
...body,
|
|
2557
|
+
text: write.text,
|
|
2558
|
+
labels: write.labels
|
|
2559
|
+
})));
|
|
2560
|
+
}
|
|
2561
|
+
if (body.origin === void 0 === (body.message === void 0)) return send(body);
|
|
2562
|
+
const found = await importTarget(caller, body, signal);
|
|
2563
|
+
if (!found || found.deleted || access && !access.can("sync", found.channel) || body.message !== void 0 && found.by.principal !== body.author.id) return send(body);
|
|
2564
|
+
const source = await importSource(caller, body, found, signal);
|
|
2565
|
+
if (!source) return send(body);
|
|
2566
|
+
return dropped(async () => screen({
|
|
2567
|
+
kind: "edit",
|
|
2568
|
+
id: found.id,
|
|
2569
|
+
channel: found.channel,
|
|
2570
|
+
re: found.re,
|
|
2571
|
+
text: body.text
|
|
2572
|
+
}, externalActor(body.author), source, async (write) => send({
|
|
2573
|
+
...body,
|
|
2574
|
+
text: write.text
|
|
2575
|
+
})));
|
|
2576
|
+
}
|
|
2577
|
+
/** A message as `caller` may read it, or null. */
|
|
2578
|
+
async function lookup(caller, id, signal) {
|
|
2579
|
+
try {
|
|
2580
|
+
const { message, replies } = await backend.message(caller, { id }, signal);
|
|
2581
|
+
return [message, ...replies].find((candidate) => candidate.id === id) ?? null;
|
|
2582
|
+
} catch (error) {
|
|
2583
|
+
if (error instanceof HttpError && error.status === 404) return null;
|
|
2584
|
+
throw error;
|
|
2585
|
+
}
|
|
2586
|
+
}
|
|
2587
|
+
/**
|
|
2588
|
+
* A post, with the emails it mentions resolved once the caller may post there (and sync, for
|
|
2589
|
+
* targets it names), through the middleware.
|
|
2590
|
+
*/
|
|
2591
|
+
async function post(caller, input, signal) {
|
|
2592
|
+
const send = (poster, body) => screenPost(poster, body, signal, (patched) => backend.post(poster, patched, signal));
|
|
2593
|
+
if (!engine) return send(caller, input.sync?.length ? {
|
|
2594
|
+
...input,
|
|
2595
|
+
sync: await Promise.all(input.sync.map(resolveTarget))
|
|
2596
|
+
} : input);
|
|
2597
|
+
const allowed = (input.sync?.length ?? 0) > 0 || mentionsEmails(input.text) ? await mayPost(caller, input, signal) : null;
|
|
2598
|
+
if (!allowed) return send(caller, input);
|
|
2599
|
+
const { access, channel } = allowed;
|
|
2600
|
+
const body = input.re === void 0 && (input.sync?.length ?? 0) > 0 && (access === null || access.can("sync", channel)) ? {
|
|
2601
|
+
...input,
|
|
2602
|
+
sync: await Promise.all(input.sync.map(resolveTarget))
|
|
2603
|
+
} : input;
|
|
2604
|
+
const text = await withEmails(body.text);
|
|
2605
|
+
const answer = await send(caller, {
|
|
2606
|
+
...body,
|
|
2607
|
+
text
|
|
2608
|
+
});
|
|
2609
|
+
return text !== input.text && access !== null && !access.readable(answer.message.channel) ? {
|
|
2610
|
+
...answer,
|
|
2611
|
+
message: {
|
|
2612
|
+
...answer.message,
|
|
2613
|
+
text: input.text
|
|
2614
|
+
}
|
|
2615
|
+
} : answer;
|
|
2616
|
+
}
|
|
2617
|
+
/**
|
|
2618
|
+
* An import's answer, as a sync callback's client gets it: the message it wrote or changed, or the
|
|
2619
|
+
* middleware's responses in the event's platform thread and a `DroppedError` when it dropped it.
|
|
2620
|
+
*/
|
|
2621
|
+
async function landed(caller, answer) {
|
|
2622
|
+
if (!answer.dropped) return answer.message;
|
|
2623
|
+
for (const text of answer.dropped) await caller.platform.respond(text);
|
|
2624
|
+
throw new DroppedError(answer.dropped);
|
|
2625
|
+
}
|
|
2626
|
+
/**
|
|
2627
|
+
* What a sync callback's client does, on any backend. Its own writes are imports, as the platform
|
|
2628
|
+
* user the event came from, which the middleware sees as any import; everything else, its reads
|
|
2629
|
+
* included, it does as sync. A change it names by ID is an import that names it so.
|
|
2630
|
+
*/
|
|
2631
|
+
async function asPlatform(name, caller, input, signal) {
|
|
2632
|
+
const me = engine.caller;
|
|
2633
|
+
const { author, key } = caller.platform;
|
|
2634
|
+
const { via } = caller.origin;
|
|
2635
|
+
const source = {
|
|
2636
|
+
key,
|
|
2637
|
+
channel: via.channel,
|
|
2638
|
+
thread: via.thread
|
|
2639
|
+
};
|
|
2640
|
+
const change = async (body) => {
|
|
2641
|
+
if (await landed(caller, await syncImport(me, body, signal)) === null) throw notFound(`message not found: #${body.message}`, "message_not_found");
|
|
2642
|
+
return { ok: true };
|
|
2643
|
+
};
|
|
2644
|
+
switch (name) {
|
|
2645
|
+
case "post": return importPost(caller, input, signal);
|
|
2646
|
+
case "edit": {
|
|
2647
|
+
const { id, text, revision } = input;
|
|
2648
|
+
return change({
|
|
2649
|
+
op: "edit",
|
|
2650
|
+
author,
|
|
2651
|
+
from: null,
|
|
2652
|
+
message: id,
|
|
2653
|
+
text: await withEmails(text),
|
|
2654
|
+
source,
|
|
2655
|
+
...revision !== void 0 ? { revision } : {}
|
|
2656
|
+
});
|
|
2657
|
+
}
|
|
2658
|
+
case "delete": {
|
|
2659
|
+
const { id, revision } = input;
|
|
2660
|
+
return change({
|
|
2661
|
+
op: "delete",
|
|
2662
|
+
author,
|
|
2663
|
+
from: null,
|
|
2664
|
+
message: id,
|
|
2665
|
+
...revision !== void 0 ? { revision } : {}
|
|
2666
|
+
});
|
|
2667
|
+
}
|
|
2668
|
+
case "react": {
|
|
2669
|
+
const { id, emoji, remove } = input;
|
|
2670
|
+
return change({
|
|
2671
|
+
op: "react",
|
|
2672
|
+
author,
|
|
2673
|
+
from: null,
|
|
2674
|
+
message: id,
|
|
2675
|
+
emoji,
|
|
2676
|
+
...remove !== void 0 ? { remove } : {}
|
|
2677
|
+
});
|
|
2678
|
+
}
|
|
2679
|
+
case "label": {
|
|
2680
|
+
const { id, set, unset, if: expected } = input;
|
|
2681
|
+
return change({
|
|
2682
|
+
op: "labels",
|
|
2683
|
+
author,
|
|
2684
|
+
from: null,
|
|
2685
|
+
message: id,
|
|
2686
|
+
...set ? { set } : {},
|
|
2687
|
+
...unset ? { unset } : {},
|
|
2688
|
+
...expected ? { if: expected } : {}
|
|
2689
|
+
});
|
|
2690
|
+
}
|
|
2691
|
+
default: return invoke(name, me, input, signal);
|
|
2692
|
+
}
|
|
2693
|
+
}
|
|
2694
|
+
/** A sync callback's post, as an import by its platform user: once per client ID, which the backend sees to. */
|
|
2695
|
+
async function importPost(caller, input, signal) {
|
|
2696
|
+
const me = engine.caller;
|
|
2697
|
+
const { author, key } = caller.platform;
|
|
2698
|
+
const { via } = caller.origin;
|
|
2699
|
+
const read = async (id) => {
|
|
2700
|
+
const message = await lookup(me, id, signal);
|
|
2701
|
+
if (!message) throw notFound(`message not found: #${id}`, "message_not_found");
|
|
2702
|
+
return message;
|
|
2703
|
+
};
|
|
2704
|
+
if (input.id !== void 0) {
|
|
2705
|
+
const found = (await backend.syncFind(me, { post: input.id }, signal)).message;
|
|
2706
|
+
if (found !== null) return { message: await read(found) };
|
|
2707
|
+
}
|
|
2708
|
+
const targets = await Promise.all((input.sync ?? []).map(resolveTarget));
|
|
2709
|
+
const message = await landed(caller, await syncImport(me, {
|
|
2710
|
+
op: "post",
|
|
2711
|
+
author,
|
|
2712
|
+
from: null,
|
|
2713
|
+
origin: null,
|
|
2714
|
+
source: {
|
|
2715
|
+
key,
|
|
2716
|
+
channel: via.channel,
|
|
2717
|
+
thread: via.thread
|
|
2718
|
+
},
|
|
2719
|
+
...input.channel !== void 0 ? { channel: input.channel } : { re: input.re },
|
|
2720
|
+
text: await withEmails(input.text),
|
|
2721
|
+
...input.labels ? { labels: input.labels } : {},
|
|
2722
|
+
...input.noSync ? { noSync: true } : {},
|
|
2723
|
+
...input.attachments?.length ? { attachments: input.attachments } : {},
|
|
2724
|
+
...input.id !== void 0 ? { id: input.id } : {},
|
|
2725
|
+
...input.after !== void 0 ? { after: input.after } : {}
|
|
2726
|
+
}, signal));
|
|
2727
|
+
for (const target of targets) await backend.syncReceipt(me, {
|
|
2728
|
+
kind: "thread",
|
|
2729
|
+
message,
|
|
2730
|
+
target: target.target,
|
|
2731
|
+
targetKind: target.kind,
|
|
2732
|
+
cause: "request"
|
|
2733
|
+
}, signal);
|
|
2734
|
+
return { message: await read(message) };
|
|
2735
|
+
}
|
|
2736
|
+
/** The protocol method `name`, as board() serves it: what it posts and edits, and the filters it reads by, with their emails resolved. */
|
|
2737
|
+
async function invoke(name, caller, input, signal) {
|
|
2738
|
+
if (name === "messages" || name === "threads" || name === "events") input = await withMentioned(caller, input);
|
|
2739
|
+
switch (name) {
|
|
2740
|
+
case "post": return post(caller, input, signal);
|
|
2741
|
+
case "edit": {
|
|
2742
|
+
const edit = input;
|
|
2743
|
+
const send = (body) => screenEdit(caller, body, signal, (patched) => backend.edit(caller, patched, signal));
|
|
2744
|
+
if (!engine || !mentionsEmails(edit.text) || !await mayPost(caller, { re: edit.id }, signal)) return send(edit);
|
|
2745
|
+
return send({
|
|
2746
|
+
...edit,
|
|
2747
|
+
text: await withEmails(edit.text)
|
|
2748
|
+
});
|
|
2749
|
+
}
|
|
2750
|
+
case "syncImport": return syncImport(caller, input, signal);
|
|
2751
|
+
case "schedule": {
|
|
2752
|
+
const body = input;
|
|
2753
|
+
const schedule = (made) => backend.sendsSchedulesHere === false ? screenSchedule(caller, made, signal) : backend.schedule(caller, made, signal);
|
|
2754
|
+
const allowed = engine && mentionsEmails(body.text) ? await mayPost(caller, body, signal) : null;
|
|
2755
|
+
if (!allowed) return schedule(body);
|
|
2756
|
+
const text = await withEmails(body.text);
|
|
2757
|
+
const answer = await schedule({
|
|
2758
|
+
...body,
|
|
2759
|
+
text
|
|
2760
|
+
});
|
|
2761
|
+
const { access } = allowed;
|
|
2762
|
+
return text !== body.text && access !== null && !access.readable(answer.schedule.channel) ? {
|
|
2763
|
+
...answer,
|
|
2764
|
+
schedule: {
|
|
2765
|
+
...answer.schedule,
|
|
2766
|
+
text: body.text
|
|
2767
|
+
}
|
|
2768
|
+
} : answer;
|
|
2769
|
+
}
|
|
2770
|
+
case "inbox": {
|
|
2771
|
+
const query = input;
|
|
2772
|
+
if (engine && entries[query.key] && query.channel !== void 0) {
|
|
2773
|
+
const access = accessOf(caller);
|
|
2774
|
+
if (access === null || access.anywhere("sync")) return backend.inbox(caller, {
|
|
2775
|
+
...query,
|
|
2776
|
+
channel: await engine.inboxChannel(query.key, query.channel)
|
|
2777
|
+
}, signal);
|
|
2778
|
+
}
|
|
2779
|
+
return backend.inbox(caller, query, signal);
|
|
2780
|
+
}
|
|
2781
|
+
default: {
|
|
2782
|
+
const method = backend[name];
|
|
2783
|
+
if (typeof method !== "function") throw notFound(`no route: ${name}`);
|
|
2784
|
+
return method.call(backend, caller, input, signal);
|
|
2785
|
+
}
|
|
2786
|
+
}
|
|
2787
|
+
}
|
|
2788
|
+
/** board()'s own routes for a caller: sync's, which run where board() does. */
|
|
2789
|
+
async function serve(name, caller, request, url, params) {
|
|
2790
|
+
const signal = request.signal;
|
|
2791
|
+
switch (name) {
|
|
2792
|
+
case "sync": {
|
|
2793
|
+
const body = SyncBody.parse(await readJson(request));
|
|
2794
|
+
const id = params.id ?? "";
|
|
2795
|
+
const access = accessOf(caller);
|
|
2796
|
+
if (access && engine) {
|
|
2797
|
+
const message = await lookup(caller, id, signal);
|
|
2798
|
+
if (!message) throw notFound(`message not found: #${id}`, "message_not_found");
|
|
2799
|
+
if (!access.can("sync", message.channel)) throw forbidden(`this token can't sync in ${message.channel}`);
|
|
2800
|
+
}
|
|
2801
|
+
const target = await resolveTarget(body.target);
|
|
2802
|
+
const { attached } = await backend.syncReceipt(caller, {
|
|
2803
|
+
kind: "thread",
|
|
2804
|
+
message: id,
|
|
2805
|
+
target: target.target,
|
|
2806
|
+
targetKind: target.kind,
|
|
2807
|
+
cause: "request"
|
|
2808
|
+
}, signal);
|
|
2809
|
+
return json({
|
|
2810
|
+
target: target.target,
|
|
2811
|
+
attached: attached ?? true
|
|
2812
|
+
});
|
|
2813
|
+
}
|
|
2814
|
+
default: throw notFound(`no route: ${request.method} ${url.pathname}`);
|
|
2815
|
+
}
|
|
2816
|
+
}
|
|
2817
|
+
const synced = Object.fromEntries(METHODS.map((name) => [name, name === "syncImport" ? syncImport : (caller, input, signal) => backend[name].call(backend, caller, input, signal)]));
|
|
2818
|
+
engine?.bind({
|
|
2819
|
+
backend: synced,
|
|
2820
|
+
client: (platform, trigger) => clientAs({
|
|
2821
|
+
platform: {
|
|
2822
|
+
author: platform.author,
|
|
2823
|
+
key: platform.key,
|
|
2824
|
+
respond: platform.respond
|
|
2825
|
+
},
|
|
2826
|
+
origin: { via: platform.via }
|
|
2827
|
+
}, trigger)
|
|
2828
|
+
});
|
|
2829
|
+
/**
|
|
2830
|
+
* Server-sent events, from the backend's long-poll: each event's `id` is its cursor, so
|
|
2831
|
+
* `Last-Event-ID` resumes exactly. A request's caller is worked out again for each page, so what
|
|
2832
|
+
* `access` says now holds, and a token that runs out ends it.
|
|
2833
|
+
*/
|
|
2834
|
+
async function sse(caller, query, request, identify) {
|
|
2835
|
+
const first = await backend.events(caller, {
|
|
2836
|
+
...query,
|
|
2837
|
+
wait: 0
|
|
2838
|
+
}, request.signal);
|
|
2839
|
+
const encoder = new TextEncoder();
|
|
2840
|
+
const controller = new AbortController();
|
|
2841
|
+
const deadline = Date.now() + streamMaxMs;
|
|
2842
|
+
const signal = AbortSignal.any([
|
|
2843
|
+
request.signal,
|
|
2844
|
+
controller.signal,
|
|
2845
|
+
AbortSignal.timeout(streamMaxMs)
|
|
2846
|
+
]);
|
|
2847
|
+
const body = new ReadableStream({
|
|
2848
|
+
async start(stream) {
|
|
2849
|
+
const send = (text) => {
|
|
2850
|
+
try {
|
|
2851
|
+
stream.enqueue(encoder.encode(text));
|
|
2852
|
+
} catch {}
|
|
2853
|
+
};
|
|
2854
|
+
const ping = setInterval(() => send(": ping\n\n"), 15e3);
|
|
2855
|
+
try {
|
|
2856
|
+
send(": connected\n\n");
|
|
2857
|
+
let page = first;
|
|
2858
|
+
let after;
|
|
2859
|
+
for (;;) {
|
|
2860
|
+
for (const event of page.events) send(`id: ${event.cursor}\nevent: board\ndata: ${JSON.stringify(event)}\n\n`);
|
|
2861
|
+
if (page.cursor !== (page.events.at(-1)?.cursor ?? after)) send(`id: ${page.cursor}\n\n`);
|
|
2862
|
+
after = page.cursor;
|
|
2863
|
+
const left = deadline - Date.now();
|
|
2864
|
+
if (signal.aborted || left <= 0) break;
|
|
2865
|
+
page = await backend.events(identify ? await identify() : caller, {
|
|
2866
|
+
...query,
|
|
2867
|
+
after,
|
|
2868
|
+
wait: Math.min(300, left / 1e3)
|
|
2869
|
+
}, signal);
|
|
2870
|
+
}
|
|
2871
|
+
} catch (error) {
|
|
2872
|
+
if (!signal.aborted) console.error("[board] feed failed", error);
|
|
2873
|
+
} finally {
|
|
2874
|
+
clearInterval(ping);
|
|
2875
|
+
try {
|
|
2876
|
+
stream.close();
|
|
2877
|
+
} catch {}
|
|
2878
|
+
}
|
|
2879
|
+
},
|
|
2880
|
+
cancel() {
|
|
2881
|
+
controller.abort();
|
|
2882
|
+
}
|
|
2883
|
+
});
|
|
2884
|
+
return new Response(body, { headers: {
|
|
2885
|
+
"content-type": "text/event-stream",
|
|
2886
|
+
"cache-control": "no-cache, no-transform",
|
|
2887
|
+
connection: "keep-alive"
|
|
2888
|
+
} });
|
|
2889
|
+
}
|
|
2890
|
+
/**
|
|
2891
|
+
* Discovery, as a request reaches the board: who the board is to it (the URL a token must be minted
|
|
2892
|
+
* for, and the project people mint them with), which is board()'s to say, and the sync entries
|
|
2893
|
+
* accounts link on. Those are the backend's, where it keeps the board; a board on `http()` lists its own.
|
|
2894
|
+
*/
|
|
2895
|
+
async function discovery(request, url, signal) {
|
|
2896
|
+
const { projectId, teamId } = await policy.discoveryIdentity(request.headers);
|
|
2897
|
+
const sync = backend.keeps ? (await backend.discovery(OWN, {}, signal)).sync : Object.entries(entries).map(([key, entry]) => ({
|
|
2898
|
+
key,
|
|
2899
|
+
platform: entry.platform
|
|
2900
|
+
}));
|
|
2901
|
+
return {
|
|
2902
|
+
version: VERSION,
|
|
2903
|
+
url,
|
|
2904
|
+
audience: url,
|
|
2905
|
+
team_id: teamId,
|
|
2906
|
+
project_id: projectId,
|
|
2907
|
+
sync
|
|
2908
|
+
};
|
|
2909
|
+
}
|
|
2910
|
+
async function dispatch(request, injected) {
|
|
2911
|
+
try {
|
|
2912
|
+
const url = new URL(request.url);
|
|
2913
|
+
const match = route(request.method, url.pathname);
|
|
2914
|
+
if (!match) throw notFound(`no route: ${request.method} ${url.pathname}`);
|
|
2915
|
+
const { target } = match;
|
|
2916
|
+
if (!injected && !match.root && (state.learned === null || state.learned.startsWith(`${match.base}/`))) state.learned = match.base;
|
|
2917
|
+
const boardUrl = (options.url ?? `${url.origin}${match.base}`).replace(/\/+$/, "");
|
|
2918
|
+
if (target.kind === "board" && target.name === "webhook") {
|
|
2919
|
+
if (!engine || !entries[match.params.key ?? ""]) throw notFound(`no sync entry named ${match.params.key}`);
|
|
2920
|
+
return await engine.handleWebhook(match.params.key, request);
|
|
2921
|
+
}
|
|
2922
|
+
if (target.kind === "board" && target.name === "avatar") {
|
|
2923
|
+
const name = match.param ?? "";
|
|
2924
|
+
if (!KNOWN_AGENTS.includes(name)) throw notFound(`no avatar: ${name}`);
|
|
2925
|
+
return new Response(avatarSvg(name), { headers: {
|
|
2926
|
+
"content-type": "image/svg+xml",
|
|
2927
|
+
"cache-control": "public, max-age=86400"
|
|
2928
|
+
} });
|
|
2929
|
+
}
|
|
2930
|
+
if (target.kind === "board" && target.name === "openapi") return json(openapi());
|
|
2931
|
+
if (target.kind === "backend") return await target.route.handle(request, {
|
|
2932
|
+
caller: injected && "platform" in injected ? engine.caller : injected,
|
|
2933
|
+
param: match.param
|
|
2934
|
+
});
|
|
2935
|
+
if (!injected && !policy.open) throw servesOnly();
|
|
2936
|
+
if (!injected && target.kind === "protocol" && target.name === "discovery") return json(await discovery(request, boardUrl, request.signal));
|
|
2937
|
+
if (target.kind === "protocol" && typeof backend[target.name] !== "function") throw notFound(`no route: ${request.method} ${url.pathname}`);
|
|
2938
|
+
const own = injected && "platform" in injected ? engine.caller : injected;
|
|
2939
|
+
const asked = own ? null : requestOf(request, boardUrl);
|
|
2940
|
+
const caller = own ?? await callerOf(asked);
|
|
2941
|
+
if (target.kind === "board") return await serve(target.name, caller, request, url, match.params);
|
|
2942
|
+
const input = await inputOf(target.name, request, url, match.params);
|
|
2943
|
+
if (target.name === "events" && (request.headers.get("accept") ?? "").includes("text/event-stream")) return await sse(caller, await withMentioned(caller, input), request, asked ? () => callerOf(asked) : null);
|
|
2944
|
+
const output = injected && "platform" in injected ? await asPlatform(target.name, injected, input, request.signal) : await invoke(target.name, caller, input, request.signal);
|
|
2945
|
+
if (target.name === "attachment") return attachmentResponse(output);
|
|
2946
|
+
const made = CREATED.has(target.name) || target.name === "createChannel" && output.created;
|
|
2947
|
+
return json(output, made ? 201 : 200);
|
|
2948
|
+
} catch (error) {
|
|
2949
|
+
return toErrorResponse(error);
|
|
2950
|
+
}
|
|
2951
|
+
}
|
|
2952
|
+
return {
|
|
2953
|
+
dispatch,
|
|
2954
|
+
async inject(request, caller, trigger, writes) {
|
|
2955
|
+
if (trigger !== null && request.method === "POST" && new URL(request.url).pathname.endsWith("/messages")) {
|
|
2956
|
+
const body = await request.json() ?? {};
|
|
2957
|
+
body.id ??= await derivedId("board-inbound", trigger, "client", String(writes.made++));
|
|
2958
|
+
request = new Request(request.url, {
|
|
2959
|
+
method: "POST",
|
|
2960
|
+
headers: request.headers,
|
|
2961
|
+
body: JSON.stringify(body)
|
|
2962
|
+
});
|
|
2963
|
+
}
|
|
2964
|
+
return dispatch(request, caller);
|
|
2965
|
+
},
|
|
2966
|
+
async run(id, event, { trigger, attempt }) {
|
|
2967
|
+
if (id === "@sync" && engine) return engine.deliver(event, { attempt });
|
|
2968
|
+
const watcher = watch[id];
|
|
2969
|
+
if (!watcher) throw new Error(`this board has no watcher ${id}`);
|
|
2970
|
+
await watcher.run({
|
|
2971
|
+
event,
|
|
2972
|
+
board: handleOf({
|
|
2973
|
+
self: id,
|
|
2974
|
+
origin: { via: {
|
|
2975
|
+
kind: "watcher",
|
|
2976
|
+
id
|
|
2977
|
+
} }
|
|
2978
|
+
}, trigger)
|
|
2979
|
+
});
|
|
2980
|
+
},
|
|
2981
|
+
async receive(key, item, { id, attempt }) {
|
|
2982
|
+
if (!engine) throw new Error(`this board has no sync, so nothing reads ${key}'s inbox`);
|
|
2983
|
+
await engine.receive(key, item, {
|
|
2984
|
+
id,
|
|
2985
|
+
attempt
|
|
2986
|
+
});
|
|
2987
|
+
},
|
|
2988
|
+
pull: () => engine ? engine.pull() : Promise.resolve(0),
|
|
2989
|
+
async readSource(key, target, limit, after) {
|
|
2990
|
+
if (!engine || !entries[key]) throw notFound(`this board doesn't run sync entry ${key}: read it where its sync runs`, "not_synced_here");
|
|
2991
|
+
return engine.readSource(key, target, limit, after);
|
|
2992
|
+
},
|
|
2993
|
+
async joinSource(key, target) {
|
|
2994
|
+
if (!engine || !entries[key]) throw notFound(`this board doesn't run sync entry ${key}: join it where its sync runs`, "not_synced_here");
|
|
2995
|
+
return engine.joinSource(key, target);
|
|
2996
|
+
},
|
|
2997
|
+
typing: async (messages, status) => engine ? engine.typing(messages, status) : []
|
|
2998
|
+
};
|
|
2999
|
+
}
|
|
3000
|
+
//#endregion
|
|
3001
|
+
//#region src/server/board.ts
|
|
3002
|
+
/** How long a handle's live events wait for the next, in seconds, before asking again. */
|
|
3003
|
+
const EVENTS_WAIT_S = 25;
|
|
3004
|
+
/** A board's name: 1 to 64 characters, no `/`. */
|
|
3005
|
+
const BOARD_NAME = /^[^/]{1,64}$/;
|
|
3006
|
+
/** A team, by its ID or its slug. */
|
|
3007
|
+
const TEAM = /^[^\s/]+$/;
|
|
3008
|
+
/** Whether `name` is a board's name, such as `security`. */
|
|
3009
|
+
const isBoardName = (name) => BOARD_NAME.test(name);
|
|
3010
|
+
/**
|
|
3011
|
+
* A board for this project, on `backend`: Vercel's board for the team by default, `local()` in this
|
|
3012
|
+
* process, or one of your own. What it returns is the handle: its
|
|
3013
|
+
* methods act as the board's caller, and `fetch` serves the protocol over HTTP. Create it once,
|
|
3014
|
+
* at module scope, or one per tenant for a host.
|
|
3015
|
+
*/
|
|
3016
|
+
function createBoard(options, runtime) {
|
|
3017
|
+
if (options.name !== void 0 && !isBoardName(options.name)) throw new Error(`board: ${JSON.stringify(options.name)} isn't a board's name: one is 1 to 64 characters with no /, and another team's board takes its team apart, board({ team, name })`);
|
|
3018
|
+
if (options.team !== void 0 && !TEAM.test(options.team)) throw new Error(`board: ${JSON.stringify(options.team)} isn't a team: pass its ID (team_…) or its slug`);
|
|
3019
|
+
if (options.ensure && options.name === void 0) throw new Error("board: ensure makes the board `name` names: pass name too");
|
|
3020
|
+
const backend = options.backend ?? runtime.backend(options.fetch);
|
|
3021
|
+
const policy = createPolicy(options, backend.keeps, runtime.serving, backend.trust ?? null);
|
|
3022
|
+
const watch = options.watch ?? {};
|
|
3023
|
+
const entries = options.sync ?? {};
|
|
3024
|
+
const state = { learned: null };
|
|
3025
|
+
/** Under the configured mount, so the router accepts the paths an in-process client builds. */
|
|
3026
|
+
const inProcess = `http://in-process.board${(options.basePath ?? "").replace(/\/+$/, "")}`;
|
|
3027
|
+
/**
|
|
3028
|
+
* This board's own URL, where a board elsewhere wakes it: `url`, or on Vercel its production
|
|
3029
|
+
* domain (a preview's own URL there), and never a request's Host, which its sender chooses.
|
|
3030
|
+
*/
|
|
3031
|
+
function ownUrl() {
|
|
3032
|
+
if (options.url) return options.url.replace(/\/+$/, "");
|
|
3033
|
+
const env = typeof process === "undefined" ? void 0 : process.env;
|
|
3034
|
+
const domain = env?.VERCEL_ENV === "production" ? env.VERCEL_PROJECT_PRODUCTION_URL : env?.VERCEL_URL;
|
|
3035
|
+
const base = options.basePath ?? state.learned;
|
|
3036
|
+
return domain && base !== null ? `https://${domain}${base}`.replace(/\/+$/, "") : null;
|
|
3037
|
+
}
|
|
3038
|
+
let loading = null;
|
|
3039
|
+
/** The board's pipeline, made once, when the board first serves, watches, syncs, or a handle calls it. */
|
|
3040
|
+
function server() {
|
|
3041
|
+
loading ??= createServe(context);
|
|
3042
|
+
loading.catch(() => loading = null);
|
|
3043
|
+
return loading;
|
|
3044
|
+
}
|
|
3045
|
+
function clientAs(caller, trigger) {
|
|
3046
|
+
const writes = { made: 0 };
|
|
3047
|
+
return createBoardClient({
|
|
3048
|
+
url: inProcess,
|
|
3049
|
+
token: "in-process",
|
|
3050
|
+
fetch: (async (input, init) => (await server()).inject(new Request(input, init), caller, trigger, writes))
|
|
3051
|
+
});
|
|
3052
|
+
}
|
|
3053
|
+
const serve = async (request) => (await server()).dispatch(request, null);
|
|
3054
|
+
/** A handle on `client`, which `as` gives other profiles of. */
|
|
3055
|
+
function handle(client, url) {
|
|
3056
|
+
const made = {
|
|
3057
|
+
...client,
|
|
3058
|
+
fetch: serve,
|
|
3059
|
+
as
|
|
3060
|
+
};
|
|
3061
|
+
if (url) Object.defineProperty(made, "url", {
|
|
3062
|
+
get: url,
|
|
3063
|
+
enumerable: true
|
|
3064
|
+
});
|
|
3065
|
+
return made;
|
|
3066
|
+
}
|
|
3067
|
+
/**
|
|
3068
|
+
* A handle through board(), as `caller`: a post's `id` is its own, derived under who it writes as,
|
|
3069
|
+
* so a retry posts once and no request can take it first. A verified caller's are a backend's,
|
|
3070
|
+
* derived already (a schedule's send's), so they go as they are.
|
|
3071
|
+
*/
|
|
3072
|
+
function handleOf(caller, trigger) {
|
|
3073
|
+
const client = clientAs(caller, trigger);
|
|
3074
|
+
if ("identity" in caller) return handle({
|
|
3075
|
+
...client,
|
|
3076
|
+
events: (query, opts) => events(client, query, opts)
|
|
3077
|
+
}, () => ownUrl() ?? inProcess);
|
|
3078
|
+
const via = caller.origin.via?.kind ?? "client";
|
|
3079
|
+
const id = (given) => derivedId(`board-${via === "watcher" ? "watch" : via}`, caller.self ?? "", given);
|
|
3080
|
+
const owned = async (input) => typeof input === "string" || input.id === void 0 ? input : {
|
|
3081
|
+
...input,
|
|
3082
|
+
id: await id(input.id)
|
|
3083
|
+
};
|
|
3084
|
+
return handle({
|
|
3085
|
+
...client,
|
|
3086
|
+
post: async (channel, input) => client.post(channel, await owned(input)),
|
|
3087
|
+
reply: async (re, input) => client.reply(re, await owned(input)),
|
|
3088
|
+
posted: async (given) => client.posted(await id(given)),
|
|
3089
|
+
request: (path, init = {}) => {
|
|
3090
|
+
const { as: profile, ...rest } = init;
|
|
3091
|
+
return profile !== void 0 ? as(profile).request(path, rest) : client.request(path, rest);
|
|
3092
|
+
},
|
|
3093
|
+
events: (query, opts) => events(client, query, opts)
|
|
3094
|
+
}, () => ownUrl() ?? inProcess);
|
|
3095
|
+
}
|
|
3096
|
+
const profileCaller = (profile) => {
|
|
3097
|
+
const name = profile === null ? null : typeof profile === "string" ? profile : profile.name;
|
|
3098
|
+
return {
|
|
3099
|
+
self: name,
|
|
3100
|
+
profile,
|
|
3101
|
+
origin: { via: {
|
|
3102
|
+
kind: "client",
|
|
3103
|
+
name
|
|
3104
|
+
} }
|
|
3105
|
+
};
|
|
3106
|
+
};
|
|
3107
|
+
function as(profile) {
|
|
3108
|
+
return handleOf(profileCaller(profile), null);
|
|
3109
|
+
}
|
|
3110
|
+
const context = {
|
|
3111
|
+
options,
|
|
3112
|
+
backend,
|
|
3113
|
+
runtime,
|
|
3114
|
+
policy,
|
|
3115
|
+
state,
|
|
3116
|
+
ownUrl,
|
|
3117
|
+
clientAs,
|
|
3118
|
+
handleOf
|
|
3119
|
+
};
|
|
3120
|
+
const subscriptions = Object.fromEntries(Object.entries(watch).map(([id, watcher]) => [id, {
|
|
3121
|
+
kind: "tail",
|
|
3122
|
+
tail: watcher.tail,
|
|
3123
|
+
when: watcher.when ?? "matches"
|
|
3124
|
+
}]));
|
|
3125
|
+
if (Object.keys(entries).length > 0) subscriptions[SYNC] = { kind: "sync" };
|
|
3126
|
+
/** This board's sync entries, as its sync and discovery see them. */
|
|
3127
|
+
const ownEntries = Object.entries(entries).map(([key, entry]) => ({
|
|
3128
|
+
key,
|
|
3129
|
+
platform: entry.platform
|
|
3130
|
+
}));
|
|
3131
|
+
const binding = {
|
|
3132
|
+
name: options.name ?? null,
|
|
3133
|
+
team: options.team ?? null,
|
|
3134
|
+
ensure: options.ensure ?? true,
|
|
3135
|
+
subscriptions,
|
|
3136
|
+
run: async (id, event, meta) => (await server()).run(id, event, meta),
|
|
3137
|
+
receive: async (key, item, meta) => (await server()).receive(key, item, meta),
|
|
3138
|
+
pull: async () => ownEntries.length > 0 ? (await server()).pull() : 0,
|
|
3139
|
+
sync: ownEntries,
|
|
3140
|
+
readSource: async (key, target, limit, after) => (await server()).readSource(key, target, limit, after),
|
|
3141
|
+
joinSource: async (key, target) => (await server()).joinSource(key, target),
|
|
3142
|
+
locate: (url) => {
|
|
3143
|
+
const read = /* @__PURE__ */ new Map();
|
|
3144
|
+
for (const entry of Object.values(entries)) {
|
|
3145
|
+
const found = entry.locate(url);
|
|
3146
|
+
if (found) read.set(JSON.stringify([
|
|
3147
|
+
entry.platform,
|
|
3148
|
+
found.thread,
|
|
3149
|
+
found.message
|
|
3150
|
+
]), {
|
|
3151
|
+
platform: entry.platform,
|
|
3152
|
+
...found
|
|
3153
|
+
});
|
|
3154
|
+
}
|
|
3155
|
+
return [...read.values()];
|
|
3156
|
+
},
|
|
3157
|
+
linkOf: async (key, thread, message) => {
|
|
3158
|
+
const entry = Object.hasOwn(entries, key) ? entries[key] : void 0;
|
|
3159
|
+
if (!entry || !thread.startsWith(`${key}:`)) return null;
|
|
3160
|
+
return entry.url(thread.slice(key.length + 1), message).catch(() => null);
|
|
3161
|
+
},
|
|
3162
|
+
typing: async (messages, status) => (await server()).typing(messages, status),
|
|
3163
|
+
accessNow: (principal) => policy.accessNow(principal),
|
|
3164
|
+
project: () => policy.project(),
|
|
3165
|
+
handle: (caller) => handleOf(caller, null),
|
|
3166
|
+
url: ownUrl
|
|
3167
|
+
};
|
|
3168
|
+
backend.bind(binding);
|
|
3169
|
+
return handleOf({
|
|
3170
|
+
self: null,
|
|
3171
|
+
origin: { via: {
|
|
3172
|
+
kind: "client",
|
|
3173
|
+
name: null
|
|
3174
|
+
} }
|
|
3175
|
+
}, null);
|
|
3176
|
+
}
|
|
3177
|
+
/**
|
|
3178
|
+
* Live events for a handle, from the backend's long-poll: each page from the last cursor it saw,
|
|
3179
|
+
* waiting for the next. It backs off after a failure, up to 30 seconds; a 4xx throws.
|
|
3180
|
+
*/
|
|
3181
|
+
async function* events(client, query = {}, opts = {}) {
|
|
3182
|
+
let after = query.after;
|
|
3183
|
+
let failures = 0;
|
|
3184
|
+
while (!opts.signal?.aborted) {
|
|
3185
|
+
let page;
|
|
3186
|
+
try {
|
|
3187
|
+
page = await client.poll({
|
|
3188
|
+
...query,
|
|
3189
|
+
...after !== void 0 ? { after } : {},
|
|
3190
|
+
wait: EVENTS_WAIT_S
|
|
3191
|
+
}, opts.signal);
|
|
3192
|
+
} catch (error) {
|
|
3193
|
+
if (opts.signal?.aborted) return;
|
|
3194
|
+
if (error instanceof BoardError && error.status >= 400 && error.status < 500) throw error;
|
|
3195
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(3e4, 500 * 2 ** failures++)));
|
|
3196
|
+
continue;
|
|
3197
|
+
}
|
|
3198
|
+
failures = 0;
|
|
3199
|
+
for (const event of page.events) {
|
|
3200
|
+
yield event;
|
|
3201
|
+
if (opts.signal?.aborted) return;
|
|
3202
|
+
}
|
|
3203
|
+
after = page.cursor;
|
|
3204
|
+
}
|
|
3205
|
+
}
|
|
3206
|
+
//#endregion
|
|
3207
|
+
export { registrant as a, isApiMessageId as i, isBoardName as n, wakePath as o, createVercel as r, createBoard as t };
|