@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
|
@@ -1,1656 +0,0 @@
|
|
|
1
|
-
import { r as IMPORT_BYTES_MAX } from "./files-SniSmeEr.mjs";
|
|
2
|
-
import { _ as RemoteWatcherId } from "./schemas-DBmUO6pr.mjs";
|
|
3
|
-
import { A as RegisterBody, a as METHODS, d as VERSION, n as compileWatcher, t as canonicalWatchers } from "./watchers-hash-BjwlnGD9.mjs";
|
|
4
|
-
import { a as forbidden, f as duration, o as json, r as badRequest, s as notFound, t as HttpError } from "./errors-CJXhhzvT.mjs";
|
|
5
|
-
import { o as sha256, r as derivedId } from "./wait-until-Dw4XrIDQ.mjs";
|
|
6
|
-
import { a as wakePath, i as registrant, n as callerProfile, t as PROJECTS_OWN } from "./backend-http-CvUKOn-m.mjs";
|
|
7
|
-
import { o as mediaType, r as fileName } from "./blob-WbB2DJKn.mjs";
|
|
8
|
-
//#region src/server/backend-vercel.ts
|
|
9
|
-
const PROFILE = /^[A-Za-z][A-Za-z0-9-]{0,31}$/;
|
|
10
|
-
const SESSION = /^[A-Za-z0-9_.:-]{1,128}$/;
|
|
11
|
-
const CLIENT_ID = /^[A-Za-z0-9_.:-]{1,128}$/;
|
|
12
|
-
const MESSAGE_ID = /^msg_([0-9a-f-]{36})_([1-9]\d*)$/;
|
|
13
|
-
/** A cursor this backend made: a time, then the position it names, in base 36. */
|
|
14
|
-
const CURSOR = /^([0-9a-z]+)(?:\.([0-9a-z]+))?$/;
|
|
15
|
-
/** The API's own cursor for one channel, which its message list and feed share, and any process resumes. */
|
|
16
|
-
const API_CURSOR = /^c1\./;
|
|
17
|
-
/** The API's longest page of a channel's messages, and longest long-poll, in seconds. */
|
|
18
|
-
const PAGE_MAX = 100;
|
|
19
|
-
const WAIT_MAX_S = 25;
|
|
20
|
-
/** Pages a filtered read of one channel scans for matches before it answers with what it found. */
|
|
21
|
-
const SCAN_PAGES = 10;
|
|
22
|
-
/** A file as the board names it. */
|
|
23
|
-
const fileOf = ({ id, name, type, size }) => ({
|
|
24
|
-
id,
|
|
25
|
-
name,
|
|
26
|
-
type,
|
|
27
|
-
size
|
|
28
|
-
});
|
|
29
|
-
const notSupported = (what) => new HttpError(501, "not_supported", `Vercel's boards don't support ${what} yet`);
|
|
30
|
-
/** What a caller board() verified may do. Null for this deployment's own code, which may do what its credentials may. */
|
|
31
|
-
const accessOf = (caller) => "identity" in caller ? caller.identity.principal.access : null;
|
|
32
|
-
/** A verified caller's grant, which the API can't check: it sees this deployment's credentials. */
|
|
33
|
-
function need(access, permission, channel) {
|
|
34
|
-
if (access && !access.can(permission, channel)) throw forbidden(`this token can't ${permission} in ${channel}`);
|
|
35
|
-
}
|
|
36
|
-
const apiKind = (kind) => kind === "app" ? "workflow" : kind;
|
|
37
|
-
/** A UUIDv7, which the API takes as an operation ID. */
|
|
38
|
-
function operationId() {
|
|
39
|
-
const bytes = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16));
|
|
40
|
-
const now = BigInt(Date.now());
|
|
41
|
-
for (let i = 0; i < 6; i++) bytes[i] = Number(now >> BigInt(8 * (5 - i)) & 255n);
|
|
42
|
-
bytes[6] = bytes[6] & 15 | 112;
|
|
43
|
-
bytes[8] = bytes[8] & 63 | 128;
|
|
44
|
-
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
45
|
-
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
46
|
-
}
|
|
47
|
-
const iso = (ms) => new Date(ms).toISOString();
|
|
48
|
-
const idAt = (threadId, sequence) => `msg_${threadId.slice(4)}_${sequence}`;
|
|
49
|
-
/** Where a message ID points: its thread and its place in it. Null for one that isn't a message's. */
|
|
50
|
-
function locate(id) {
|
|
51
|
-
const found = MESSAGE_ID.exec(id);
|
|
52
|
-
return found ? {
|
|
53
|
-
threadId: `thr_${found[1]}`,
|
|
54
|
-
sequence: Number(found[2])
|
|
55
|
-
} : null;
|
|
56
|
-
}
|
|
57
|
-
/** A principal as board names it: `vercel:user:<id>`, `vercel:app:<id>`, `vercel:project:<id>:<env>`. */
|
|
58
|
-
function principalId(principal) {
|
|
59
|
-
if (principal.type === "user") return `vercel:user:${principal.userId}`;
|
|
60
|
-
if (principal.type === "app") return `vercel:app:${principal.clientId}`;
|
|
61
|
-
return `vercel:project:${principal.projectId}:${principal.environment}`;
|
|
62
|
-
}
|
|
63
|
-
const authorOf = (actor) => ({
|
|
64
|
-
actor: actor.id,
|
|
65
|
-
principal: principalId(actor.principal),
|
|
66
|
-
profile: actor.profile?.name ?? null,
|
|
67
|
-
session: actor.session ?? null
|
|
68
|
-
});
|
|
69
|
-
/** Who cancels a schedule when no one did: the API, once its creator can no longer post it, as a2()'s scheduler. */
|
|
70
|
-
const SCHEDULER = {
|
|
71
|
-
actor: "board:schedule",
|
|
72
|
-
principal: "board:schedule",
|
|
73
|
-
profile: null,
|
|
74
|
-
session: null
|
|
75
|
-
};
|
|
76
|
-
/** The API names nobody, so an actor's handle is its profile, or a short form of its principal. */
|
|
77
|
-
function actorView(actor) {
|
|
78
|
-
const { principal } = actor;
|
|
79
|
-
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}`;
|
|
80
|
-
const handle = actor.profile?.name ?? base;
|
|
81
|
-
const kind = actor.profile ? "agent" : principal.type === "user" ? "person" : principal.type === "project" ? "deployment" : "workflow";
|
|
82
|
-
return {
|
|
83
|
-
id: actor.id,
|
|
84
|
-
kind,
|
|
85
|
-
handle,
|
|
86
|
-
name: handle,
|
|
87
|
-
avatar: actor.profile?.avatar ?? null
|
|
88
|
-
};
|
|
89
|
-
}
|
|
90
|
-
/**
|
|
91
|
-
* Vercel's board for your team, in Vercel's API: this deployment keeps nothing and reads and writes
|
|
92
|
-
* it as itself, its people as themselves. Messages, threads, reactions, labels, a channel's
|
|
93
|
-
* changes, schedules, files, and watchers work; what the API keeps none of yet (sync) answers 501.
|
|
94
|
-
*/
|
|
95
|
-
function createVercel(options, environment) {
|
|
96
|
-
const origin = (options.api ?? "https://api.vercel.com").replace(/\/+$/, "");
|
|
97
|
-
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`);
|
|
98
|
-
if (!options.fetch && !environment) throw new Error("vercel: pass a fetch that sends credentials: outside Node there's no environment to find them in");
|
|
99
|
-
const doFetch = options.fetch ?? environment.fetch();
|
|
100
|
-
const filesFetch = options.files ?? fetch;
|
|
101
|
-
let binding = null;
|
|
102
|
-
/** This board's own code's names, which a caller here never takes as its profile. */
|
|
103
|
-
const own = /* @__PURE__ */ new Set();
|
|
104
|
-
let team = null;
|
|
105
|
-
const teamId = () => team ??= options.team ? Promise.resolve(options.team) : environment?.team() ?? Promise.resolve(null);
|
|
106
|
-
/** One request to the API, as `who`. Its errors are the API's own, with its status and code. */
|
|
107
|
-
async function api(who, method, path, init = {}) {
|
|
108
|
-
const url = new URL(`${origin}/v1/messageboard${path}`);
|
|
109
|
-
const id = await teamId();
|
|
110
|
-
if (id) url.searchParams.set(id.startsWith("team_") ? "teamId" : "slug", id);
|
|
111
|
-
for (const [name, value] of Object.entries(init.query ?? {})) if (value !== void 0) url.searchParams.set(name, value);
|
|
112
|
-
const headers = { "content-type": "application/json" };
|
|
113
|
-
if (who.profile) headers["x-board-profile"] = who.profile.name;
|
|
114
|
-
if (who.profile?.avatar?.startsWith("https://")) headers["x-board-avatar"] = who.profile.avatar;
|
|
115
|
-
if (who.session && SESSION.test(who.session)) headers["x-board-session"] = who.session;
|
|
116
|
-
let response;
|
|
117
|
-
try {
|
|
118
|
-
response = await doFetch(url, {
|
|
119
|
-
method,
|
|
120
|
-
headers,
|
|
121
|
-
redirect: "error",
|
|
122
|
-
...init.body !== void 0 ? { body: JSON.stringify(init.body) } : {},
|
|
123
|
-
...init.signal ? { signal: init.signal } : {}
|
|
124
|
-
});
|
|
125
|
-
} catch (error) {
|
|
126
|
-
if (error instanceof HttpError || error instanceof Error && error.name === "AbortError") throw error;
|
|
127
|
-
throw new HttpError(502, "unreachable", `Vercel's API didn't answer: ${error instanceof Error ? error.message : String(error)}`);
|
|
128
|
-
}
|
|
129
|
-
const text = await response.text();
|
|
130
|
-
let body;
|
|
131
|
-
try {
|
|
132
|
-
body = text ? JSON.parse(text) : void 0;
|
|
133
|
-
} catch {}
|
|
134
|
-
if (response.ok) return body;
|
|
135
|
-
const error = body?.error;
|
|
136
|
-
throw new HttpError(response.status, error?.code ?? "remote_error", error?.message ?? `Vercel's API answered ${response.status}`);
|
|
137
|
-
}
|
|
138
|
-
/** Every page of a list, in order. */
|
|
139
|
-
async function all(who, path, key, query = {}, signal) {
|
|
140
|
-
const out = [];
|
|
141
|
-
let cursor;
|
|
142
|
-
do {
|
|
143
|
-
const page = await api(who, "GET", path, {
|
|
144
|
-
query: {
|
|
145
|
-
...query,
|
|
146
|
-
cursor
|
|
147
|
-
},
|
|
148
|
-
...signal ? { signal } : {}
|
|
149
|
-
});
|
|
150
|
-
out.push(...page[key]);
|
|
151
|
-
cursor = page.cursor ?? void 0;
|
|
152
|
-
} while (cursor);
|
|
153
|
-
return out;
|
|
154
|
-
}
|
|
155
|
-
let board = null;
|
|
156
|
-
/**
|
|
157
|
-
* The board's ID: the one given, or the team's, which the API names only to those it lets in. A
|
|
158
|
-
* team with none gets one the first time a person uses it, as the API asks of its clients; a
|
|
159
|
-
* project can't make it, and needs a person to grant it the board anyway.
|
|
160
|
-
*/
|
|
161
|
-
const boardId = (who) => (board ??= options.board ? Promise.resolve(options.board) : api(who, "GET", "/boards").then(async ({ defaultBoardId }) => {
|
|
162
|
-
if (defaultBoardId) return defaultBoardId;
|
|
163
|
-
if ((await self(who)).actor.principal.type === "project") throw new HttpError(404, "no_board", "Vercel's API names no board this project may use: ask someone on the team to grant it the team's board, or pass `board`");
|
|
164
|
-
const { board: made } = await api(who, "POST", "/boards/default", { body: { operationId: operationId() } });
|
|
165
|
-
return made.id;
|
|
166
|
-
})).catch((error) => {
|
|
167
|
-
board = null;
|
|
168
|
-
throw error;
|
|
169
|
-
});
|
|
170
|
-
const onBoard = async (who, path = "") => `/boards/${encodeURIComponent(await boardId(who))}${path}`;
|
|
171
|
-
let channels = null;
|
|
172
|
-
const loadChannels = async (who, fresh = false) => {
|
|
173
|
-
if (fresh) channels = null;
|
|
174
|
-
channels ??= onBoard(who, "/channels").then((path) => all(who, path, "channels"));
|
|
175
|
-
return channels.catch((error) => {
|
|
176
|
-
channels = null;
|
|
177
|
-
throw error;
|
|
178
|
-
});
|
|
179
|
-
};
|
|
180
|
-
/** The channel by `name`, which the API finds without listing the board's. */
|
|
181
|
-
const named = /* @__PURE__ */ new Map();
|
|
182
|
-
async function channelNamed(who, name) {
|
|
183
|
-
const known = named.get(name);
|
|
184
|
-
if (known) return known;
|
|
185
|
-
const { channels: [found] } = await api(who, "GET", await onBoard(who, "/channels"), { query: { name } });
|
|
186
|
-
if (found) named.set(name, found);
|
|
187
|
-
return found ?? null;
|
|
188
|
-
}
|
|
189
|
-
async function channelById(who, id) {
|
|
190
|
-
const found = (await loadChannels(who)).find((channel) => channel.id === id) ?? (await loadChannels(who, true)).find((channel) => channel.id === id);
|
|
191
|
-
if (!found) throw new HttpError(502, "remote_error", `Vercel's API names a channel it doesn't list: ${id}`);
|
|
192
|
-
return found;
|
|
193
|
-
}
|
|
194
|
-
/** The channel by `name`, made if it isn't there: `created` says whether this made it. */
|
|
195
|
-
async function ensureChannel(who, name) {
|
|
196
|
-
const found = await channelNamed(who, name);
|
|
197
|
-
if (found) return {
|
|
198
|
-
channel: found,
|
|
199
|
-
created: false
|
|
200
|
-
};
|
|
201
|
-
try {
|
|
202
|
-
const { channel } = await api(who, "POST", await onBoard(who, "/channels"), { body: {
|
|
203
|
-
operationId: operationId(),
|
|
204
|
-
name
|
|
205
|
-
} });
|
|
206
|
-
channels = null;
|
|
207
|
-
named.set(name, channel);
|
|
208
|
-
return {
|
|
209
|
-
channel,
|
|
210
|
-
created: true
|
|
211
|
-
};
|
|
212
|
-
} catch (error) {
|
|
213
|
-
if (error instanceof HttpError && error.code === "channel_name_taken") {
|
|
214
|
-
const made = await channelNamed(who, name);
|
|
215
|
-
if (made) return {
|
|
216
|
-
channel: made,
|
|
217
|
-
created: false
|
|
218
|
-
};
|
|
219
|
-
}
|
|
220
|
-
throw error;
|
|
221
|
-
}
|
|
222
|
-
}
|
|
223
|
-
/** A channel to post in, made the first time something posts to it, as on any board. */
|
|
224
|
-
const channelToPost = async (who, name) => (await ensureChannel(who, name)).channel;
|
|
225
|
-
/** The channels a filter names that `access` reads: one, a channel and those under it (`dev/`), or every one. */
|
|
226
|
-
async function channelsFor(who, filter, access) {
|
|
227
|
-
const readable = (channel) => access === null || access.readable(channel.name);
|
|
228
|
-
if (filter !== void 0 && !filter.endsWith("/")) {
|
|
229
|
-
const found = await channelNamed(who, filter);
|
|
230
|
-
return found && readable(found) ? [found] : [];
|
|
231
|
-
}
|
|
232
|
-
const listed = (await loadChannels(who, true)).filter(readable);
|
|
233
|
-
if (filter === void 0) return listed;
|
|
234
|
-
const path = filter.slice(0, -1);
|
|
235
|
-
return listed.filter((channel) => channel.name === path || channel.name.startsWith(filter));
|
|
236
|
-
}
|
|
237
|
-
async function messageById(who, id, signal) {
|
|
238
|
-
if (!locate(id)) throw notFound(`message not found: ${id}`, "message_not_found");
|
|
239
|
-
try {
|
|
240
|
-
return await api(who, "GET", await onBoard(who, `/messages/${encodeURIComponent(id)}`), signal ? { signal } : {});
|
|
241
|
-
} catch (error) {
|
|
242
|
-
if (error instanceof HttpError && error.code === "thread_not_found") throw notFound(`message not found: ${id}`, "message_not_found");
|
|
243
|
-
throw error;
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
/** A message `access` may read, and its channel: one it can't is as missing as one that isn't there. */
|
|
247
|
-
async function readableMessage(who, access, id, signal) {
|
|
248
|
-
const found = await messageById(who, id, signal);
|
|
249
|
-
const channel = await channelById(who, found.thread.channelId);
|
|
250
|
-
if (access && !access.readable(channel.name)) throw notFound(`message not found: ${id}`, "message_not_found");
|
|
251
|
-
return {
|
|
252
|
-
...found,
|
|
253
|
-
channel
|
|
254
|
-
};
|
|
255
|
-
}
|
|
256
|
-
/** Each thread a read needs, read once: a label matches on its root's, which the API keeps on the thread. */
|
|
257
|
-
function threadReader(who, signal) {
|
|
258
|
-
const read = /* @__PURE__ */ new Map();
|
|
259
|
-
return (id) => {
|
|
260
|
-
let thread = read.get(id);
|
|
261
|
-
if (!thread) read.set(id, thread = onBoard(who, `/threads/${encodeURIComponent(id)}`).then((path) => api(who, "GET", path, signal ? { signal } : {})).then((found) => found.thread));
|
|
262
|
-
return thread;
|
|
263
|
-
};
|
|
264
|
-
}
|
|
265
|
-
const threadMessages = async (who, threadId, signal) => all(who, await onBoard(who, `/threads/${encodeURIComponent(threadId)}/messages`), "messages", {}, signal);
|
|
266
|
-
/** Who reacted with each emoji. The API counts them on the message and lists them apart. */
|
|
267
|
-
async function reactors(who, message) {
|
|
268
|
-
if (!message.reactions || Object.keys(message.reactions).length === 0) return {};
|
|
269
|
-
const named = message.reactors ?? {};
|
|
270
|
-
if (Object.entries(message.reactions).every(([emoji, count]) => (named[emoji]?.length ?? 0) >= count)) return Object.fromEntries(Object.entries(named).map(([emoji, actors]) => [emoji, [...actors]]));
|
|
271
|
-
const path = await onBoard(who, `/threads/${encodeURIComponent(message.threadId)}/messages/${message.sequence}/reactions`);
|
|
272
|
-
const out = {};
|
|
273
|
-
for (const reaction of await all(who, path, "reactions")) (out[reaction.emoji] ??= []).push(reaction.actor.id);
|
|
274
|
-
return out;
|
|
275
|
-
}
|
|
276
|
-
/** Who's written here, by actor ID, as the API names them: messages carry only the actor. */
|
|
277
|
-
let actorNames = null;
|
|
278
|
-
/** How long names are kept before they're read again: someone renamed shows by their new name after this. */
|
|
279
|
-
const NAMES_FRESH_MS = 3e5;
|
|
280
|
-
/** Actors a list read again for them didn't have: it isn't read again for them. */
|
|
281
|
-
const unlisted = /* @__PURE__ */ new Set();
|
|
282
|
-
/** Reads the list, kept as the current one; a read that fails isn't kept, so the next name tries again. */
|
|
283
|
-
const readNames = (who) => {
|
|
284
|
-
const views = (async () => new Map((await all(who, await onBoard(who, "/actors"), "actors")).map((view) => [view.id, view])))();
|
|
285
|
-
const read = {
|
|
286
|
-
at: Date.now(),
|
|
287
|
-
views
|
|
288
|
-
};
|
|
289
|
-
actorNames = read;
|
|
290
|
-
views.catch(() => {
|
|
291
|
-
if (actorNames === read) actorNames = null;
|
|
292
|
-
});
|
|
293
|
-
return read;
|
|
294
|
-
};
|
|
295
|
-
/** The actor in a read of the list, or undefined when it doesn't have them or failed. */
|
|
296
|
-
const inList = (read, id) => read.views.then((views) => views.get(id), () => void 0);
|
|
297
|
-
/**
|
|
298
|
-
* An actor as board shows them: a person by their Vercel username and name, and an agent acting
|
|
299
|
-
* for a person by its profile under them, as the API names them; anyone else (a project, an app,
|
|
300
|
-
* an agent of one), or someone the API doesn't list, by their principal. The list is read again
|
|
301
|
-
* every few minutes, and at once for someone who wrote since it was.
|
|
302
|
-
*/
|
|
303
|
-
async function nameOf(who, actor) {
|
|
304
|
-
const current = !actorNames || Date.now() - actorNames.at > NAMES_FRESH_MS ? readNames(who) : actorNames;
|
|
305
|
-
let found = await inList(current, actor.id);
|
|
306
|
-
if (!found && !unlisted.has(actor.id)) {
|
|
307
|
-
const again = actorNames && actorNames !== current ? actorNames : readNames(who);
|
|
308
|
-
found = await inList(again, actor.id);
|
|
309
|
-
if (!found && await again.views.then(() => true, () => false)) unlisted.add(actor.id);
|
|
310
|
-
}
|
|
311
|
-
const kind = found && apiKind(found.kind);
|
|
312
|
-
if (!found || !(kind === "person" || kind === "agent" && actor.principal.type === "user")) return actorView(actor);
|
|
313
|
-
return {
|
|
314
|
-
id: actor.id,
|
|
315
|
-
kind,
|
|
316
|
-
handle: found.handle,
|
|
317
|
-
name: found.name ?? found.handle,
|
|
318
|
-
avatar: found.avatar ?? null
|
|
319
|
-
};
|
|
320
|
-
}
|
|
321
|
-
async function view(who, message, channel) {
|
|
322
|
-
const root = message.sequence === 1;
|
|
323
|
-
return {
|
|
324
|
-
id: message.id,
|
|
325
|
-
channel,
|
|
326
|
-
text: message.text,
|
|
327
|
-
re: root ? null : idAt(message.threadId, 1),
|
|
328
|
-
replyTo: message.replyTo !== void 0 && message.replyTo !== 1 ? idAt(message.threadId, message.replyTo) : null,
|
|
329
|
-
thread: message.threadId,
|
|
330
|
-
labels: { ...message.labels },
|
|
331
|
-
reactions: message.deletedAt === void 0 ? await reactors(who, message) : {},
|
|
332
|
-
mentions: [],
|
|
333
|
-
by: authorOf(message.createdBy),
|
|
334
|
-
noSync: false,
|
|
335
|
-
origin: null,
|
|
336
|
-
from: null,
|
|
337
|
-
createdAt: iso(message.createdAt),
|
|
338
|
-
editedAt: message.editedAt === void 0 ? null : iso(message.editedAt),
|
|
339
|
-
deleted: message.deletedAt !== void 0,
|
|
340
|
-
undelivered: {},
|
|
341
|
-
attachments: message.attachments ?? [],
|
|
342
|
-
links: [],
|
|
343
|
-
version: message.version,
|
|
344
|
-
revision: message.revision,
|
|
345
|
-
author: await nameOf(who, message.createdBy),
|
|
346
|
-
...message.schedule ? { schedule: {
|
|
347
|
-
id: message.schedule.id,
|
|
348
|
-
n: message.schedule.n
|
|
349
|
-
} } : {}
|
|
350
|
-
};
|
|
351
|
-
}
|
|
352
|
-
async function scheduleView(who, schedule) {
|
|
353
|
-
const { canceled } = schedule;
|
|
354
|
-
return {
|
|
355
|
-
id: schedule.id,
|
|
356
|
-
channel: (await channelById(who, schedule.channelId)).name,
|
|
357
|
-
re: schedule.threadId === void 0 ? null : idAt(schedule.threadId, 1),
|
|
358
|
-
text: schedule.text,
|
|
359
|
-
labels: { ...schedule.labels },
|
|
360
|
-
noSync: false,
|
|
361
|
-
attachments: [],
|
|
362
|
-
first: iso(schedule.firstAt),
|
|
363
|
-
every: schedule.every ?? null,
|
|
364
|
-
until: schedule.until === void 0 ? null : iso(schedule.until),
|
|
365
|
-
times: schedule.times ?? null,
|
|
366
|
-
sent: schedule.sent,
|
|
367
|
-
next: schedule.nextAt === null ? null : iso(schedule.nextAt),
|
|
368
|
-
last: schedule.lastMessageId ?? null,
|
|
369
|
-
state: schedule.state,
|
|
370
|
-
canceled: canceled ? {
|
|
371
|
-
by: canceled.by ? authorOf(canceled.by) : SCHEDULER,
|
|
372
|
-
reason: canceled.reason === "disabled" ? "revoked" : canceled.reason
|
|
373
|
-
} : null,
|
|
374
|
-
by: authorOf(schedule.createdBy),
|
|
375
|
-
author: await nameOf(who, schedule.createdBy),
|
|
376
|
-
createdAt: iso(schedule.createdAt)
|
|
377
|
-
};
|
|
378
|
-
}
|
|
379
|
-
const positions = /* @__PURE__ */ new Map();
|
|
380
|
-
function cursorOf(position) {
|
|
381
|
-
const key = `${position.t.toString(36)}.${Math.floor(Math.random() * 36 ** 8).toString(36)}`;
|
|
382
|
-
positions.set(key, position);
|
|
383
|
-
if (positions.size > 1e4) positions.delete(positions.keys().next().value);
|
|
384
|
-
return key;
|
|
385
|
-
}
|
|
386
|
-
function positionOf(cursor) {
|
|
387
|
-
const kept = positions.get(cursor);
|
|
388
|
-
if (kept) return kept;
|
|
389
|
-
const found = CURSOR.exec(cursor);
|
|
390
|
-
if (!found) throw new HttpError(400, "invalid_cursor", `after: ${cursor} isn't a cursor here or a message's ID`);
|
|
391
|
-
return {
|
|
392
|
-
t: parseInt(found[1], 36),
|
|
393
|
-
feeds: {}
|
|
394
|
-
};
|
|
395
|
-
}
|
|
396
|
-
/** A time a read goes on from: a cursor's, or a message's own. */
|
|
397
|
-
async function timeOf(who, after) {
|
|
398
|
-
return locate(after) ? (await messageById(who, after)).message.createdAt : positionOf(after).t;
|
|
399
|
-
}
|
|
400
|
-
/** Each channel's feed now, taken before a read, so what's posted while it reads comes after. */
|
|
401
|
-
async function heads(who, listed) {
|
|
402
|
-
const path = await onBoard(who, "/changes");
|
|
403
|
-
const found = await Promise.all(listed.map((channel) => api(who, "GET", path, { query: {
|
|
404
|
-
channelId: channel.id,
|
|
405
|
-
from: "latest"
|
|
406
|
-
} })));
|
|
407
|
-
return Object.fromEntries(listed.map((channel, i) => [channel.id, {
|
|
408
|
-
at: found[i].cursor,
|
|
409
|
-
skip: 0
|
|
410
|
-
}]));
|
|
411
|
-
}
|
|
412
|
-
/** Whether a message matches a read's filters. A label matches on the message or its thread's root. */
|
|
413
|
-
function matches(filters, message, thread, me) {
|
|
414
|
-
if (filters.re !== void 0 && filters.re !== message.id && filters.re !== idAt(thread.id, 1)) return false;
|
|
415
|
-
if (filters.by !== void 0) {
|
|
416
|
-
const { createdBy } = message;
|
|
417
|
-
const names = [
|
|
418
|
-
createdBy.id,
|
|
419
|
-
principalId(createdBy.principal),
|
|
420
|
-
createdBy.profile?.name
|
|
421
|
-
];
|
|
422
|
-
if (!(filters.by === "me" ? createdBy.id === me : names.includes(filters.by))) return false;
|
|
423
|
-
}
|
|
424
|
-
if (filters.mentions !== void 0) return false;
|
|
425
|
-
if (filters.from !== void 0 && filters.from !== "board") return false;
|
|
426
|
-
if (filters.text !== void 0 && !message.text.toLowerCase().includes(filters.text.toLowerCase())) return false;
|
|
427
|
-
for (const [key, values] of filters.label ?? []) {
|
|
428
|
-
const on = (labels) => labels !== void 0 && Object.hasOwn(labels, key) && (values === null || values.includes(labels[key]));
|
|
429
|
-
if (!on(message.labels) && !on(thread.labels)) return false;
|
|
430
|
-
}
|
|
431
|
-
return true;
|
|
432
|
-
}
|
|
433
|
-
/** The label the API's index can narrow a channel's threads by: a root's `key` or `key=value`. */
|
|
434
|
-
function indexed(filters) {
|
|
435
|
-
const first = filters.label?.find(([, values]) => values === null || values.length === 1);
|
|
436
|
-
return first && (first[1] === null ? first[0] : `${first[0]}=${first[1][0]}`);
|
|
437
|
-
}
|
|
438
|
-
async function threadsOf(who, channel, filters, signal) {
|
|
439
|
-
const label = indexed(filters);
|
|
440
|
-
return all(who, await onBoard(who, "/threads"), "threads", {
|
|
441
|
-
channelId: channel.id,
|
|
442
|
-
label
|
|
443
|
-
}, signal);
|
|
444
|
-
}
|
|
445
|
-
/**
|
|
446
|
-
* A channel's threads, as far as a read needs: the API lists them most recently active first, so
|
|
447
|
-
* it stops at the first not active since `after`, or at the `limit` newest when it's given one
|
|
448
|
-
* (not when the read filters what's listed). One it lists by a label comes oldest first, so it
|
|
449
|
-
* reads every page.
|
|
450
|
-
*/
|
|
451
|
-
async function latestThreads(who, channel, label, page, signal) {
|
|
452
|
-
const path = await onBoard(who, "/threads");
|
|
453
|
-
const out = [];
|
|
454
|
-
let cursor;
|
|
455
|
-
do {
|
|
456
|
-
const found = await api(who, "GET", path, {
|
|
457
|
-
query: {
|
|
458
|
-
channelId: channel.id,
|
|
459
|
-
label,
|
|
460
|
-
cursor
|
|
461
|
-
},
|
|
462
|
-
signal
|
|
463
|
-
});
|
|
464
|
-
out.push(...found.threads);
|
|
465
|
-
cursor = found.cursor ?? void 0;
|
|
466
|
-
const last = out.at(-1);
|
|
467
|
-
if (label === void 0 && (page.after !== void 0 ? last !== void 0 && last.lastActivityAt <= page.after : page.limit !== void 0 && out.length >= page.limit)) break;
|
|
468
|
-
} while (cursor);
|
|
469
|
-
return out;
|
|
470
|
-
}
|
|
471
|
-
/** A thread at a glance: its root, its reply count, and its latest reply, read by reference. */
|
|
472
|
-
async function summary(who, thread, channel, signal) {
|
|
473
|
-
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]);
|
|
474
|
-
return {
|
|
475
|
-
message: await view(who, root.message, channel.name),
|
|
476
|
-
replies: thread.messageCount - 1,
|
|
477
|
-
last: last && await view(who, last.message, channel.name)
|
|
478
|
-
};
|
|
479
|
-
}
|
|
480
|
-
let me = null;
|
|
481
|
-
/** Who these credentials are, asked once. */
|
|
482
|
-
const self = (who) => (me ??= api(who, "GET", "/me")).catch((error) => {
|
|
483
|
-
me = null;
|
|
484
|
-
throw error;
|
|
485
|
-
});
|
|
486
|
-
/** The actor `who` writes as: the credentials' principal, and its profile, as the API names it. */
|
|
487
|
-
const actorOf = async (who) => `${principalId((await self(who)).actor.principal)}${who.profile ? `+${who.profile.name.toLowerCase()}` : ""}`;
|
|
488
|
-
/** Who a caller acts as there: its profile and session, beside this deployment's credentials. */
|
|
489
|
-
function whoOf(caller) {
|
|
490
|
-
if ("identity" in caller) {
|
|
491
|
-
const avatar = caller.identity.actor.avatar?.startsWith("https://") ? caller.identity.actor.avatar : void 0;
|
|
492
|
-
return {
|
|
493
|
-
profile: {
|
|
494
|
-
name: callerProfile(caller.identity.actor.handle, own),
|
|
495
|
-
...avatar ? { avatar } : {}
|
|
496
|
-
},
|
|
497
|
-
session: null
|
|
498
|
-
};
|
|
499
|
-
}
|
|
500
|
-
const named = (profile) => {
|
|
501
|
-
if (profile === null) return null;
|
|
502
|
-
const name = typeof profile === "string" ? profile : profile.name;
|
|
503
|
-
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`);
|
|
504
|
-
return typeof profile === "string" || !profile.avatar ? { name } : {
|
|
505
|
-
name,
|
|
506
|
-
avatar: profile.avatar
|
|
507
|
-
};
|
|
508
|
-
};
|
|
509
|
-
if (caller.origin.via?.kind === "client") {
|
|
510
|
-
const asked = "profile" in caller ? caller.profile : caller.self ?? void 0;
|
|
511
|
-
const found = environment?.profile() ?? {
|
|
512
|
-
profile: null,
|
|
513
|
-
session: null
|
|
514
|
-
};
|
|
515
|
-
if (asked === void 0) return {
|
|
516
|
-
profile: named(found.profile),
|
|
517
|
-
session: found.session
|
|
518
|
-
};
|
|
519
|
-
return {
|
|
520
|
-
profile: named(asked),
|
|
521
|
-
session: asked === null ? null : found.session
|
|
522
|
-
};
|
|
523
|
-
}
|
|
524
|
-
return {
|
|
525
|
-
profile: named(caller.self ?? "client"),
|
|
526
|
-
session: null
|
|
527
|
-
};
|
|
528
|
-
}
|
|
529
|
-
/** A post's client ID, as the API takes one: its own when it fits, a hash of it when it doesn't. */
|
|
530
|
-
const clientIdOf = async (id) => CLIENT_ID.test(id) ? id : `h.${(await sha256(id)).slice(0, 64)}`;
|
|
531
|
-
/** A gateway caller's post IDs are its own, derived under who it is here, since the API sees this deployment. */
|
|
532
|
-
const postId = async (caller, id) => clientIdOf("identity" in caller ? await derivedId("board-gateway", caller.identity.principal.id, id) : id);
|
|
533
|
-
/** Messages a read covers, newest last: every thread's in the channels it names, or one thread's. */
|
|
534
|
-
async function collect(who, access, filters, signal) {
|
|
535
|
-
let listed;
|
|
536
|
-
let threads;
|
|
537
|
-
if (filters.re !== void 0) {
|
|
538
|
-
const found = await readableMessage(who, access, filters.re, signal).catch((error) => {
|
|
539
|
-
if (error instanceof HttpError && error.status === 404) return null;
|
|
540
|
-
throw error;
|
|
541
|
-
});
|
|
542
|
-
if (!found) return {
|
|
543
|
-
messages: [],
|
|
544
|
-
feeds: {},
|
|
545
|
-
newest: 0
|
|
546
|
-
};
|
|
547
|
-
const { channel } = found;
|
|
548
|
-
if (filters.channel !== void 0 && !(await channelsFor(who, filters.channel, access)).some((c) => c.id === channel.id)) return {
|
|
549
|
-
messages: [],
|
|
550
|
-
feeds: {},
|
|
551
|
-
newest: 0
|
|
552
|
-
};
|
|
553
|
-
listed = [channel];
|
|
554
|
-
threads = [{
|
|
555
|
-
thread: found.thread,
|
|
556
|
-
channel
|
|
557
|
-
}];
|
|
558
|
-
} else {
|
|
559
|
-
listed = await channelsFor(who, filters.channel, access);
|
|
560
|
-
threads = (await Promise.all(listed.map(async (channel) => (await threadsOf(who, channel, filters, signal)).map((thread) => ({
|
|
561
|
-
thread,
|
|
562
|
-
channel
|
|
563
|
-
}))))).flat();
|
|
564
|
-
}
|
|
565
|
-
const feeds = await heads(who, listed);
|
|
566
|
-
const mine = await actorOf(who);
|
|
567
|
-
let newest = 0;
|
|
568
|
-
const messages = [];
|
|
569
|
-
for (const { thread, channel } of threads) for (const message of await threadMessages(who, thread.id, signal)) {
|
|
570
|
-
newest = Math.max(newest, message.createdAt);
|
|
571
|
-
if (matches(filters, message, thread, mine)) messages.push({
|
|
572
|
-
message,
|
|
573
|
-
thread,
|
|
574
|
-
channel
|
|
575
|
-
});
|
|
576
|
-
}
|
|
577
|
-
messages.sort((a, b) => a.message.createdAt - b.message.createdAt || a.thread.id.localeCompare(b.thread.id) || a.message.sequence - b.message.sequence);
|
|
578
|
-
return {
|
|
579
|
-
messages,
|
|
580
|
-
feeds,
|
|
581
|
-
newest
|
|
582
|
-
};
|
|
583
|
-
}
|
|
584
|
-
/** 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. */
|
|
585
|
-
async function eventOf(who, change, channel, cursor, filters, me, given) {
|
|
586
|
-
if (!change.messageId || !change.type.startsWith("message.")) return null;
|
|
587
|
-
const found = given ?? await messageById(who, change.messageId).catch((error) => {
|
|
588
|
-
if (error instanceof HttpError && error.status === 404) return null;
|
|
589
|
-
throw error;
|
|
590
|
-
});
|
|
591
|
-
if (!found || !matches(filters, found.message, found.thread, me)) return null;
|
|
592
|
-
const message = await view(who, found.message, channel);
|
|
593
|
-
const by = authorOf(change.actor);
|
|
594
|
-
const base = {
|
|
595
|
-
id: message.id,
|
|
596
|
-
thread: message.thread
|
|
597
|
-
};
|
|
598
|
-
let type;
|
|
599
|
-
let payload;
|
|
600
|
-
switch (change.type) {
|
|
601
|
-
case "message.posted":
|
|
602
|
-
type = "message.posted";
|
|
603
|
-
payload = {
|
|
604
|
-
channel,
|
|
605
|
-
text: message.text,
|
|
606
|
-
re: message.re,
|
|
607
|
-
replyTo: message.replyTo,
|
|
608
|
-
thread: message.thread,
|
|
609
|
-
labels: message.labels,
|
|
610
|
-
noSync: false,
|
|
611
|
-
mentions: [],
|
|
612
|
-
by,
|
|
613
|
-
origin: null,
|
|
614
|
-
from: null,
|
|
615
|
-
attachments: message.attachments,
|
|
616
|
-
links: []
|
|
617
|
-
};
|
|
618
|
-
break;
|
|
619
|
-
case "message.edited":
|
|
620
|
-
type = "message.edited";
|
|
621
|
-
payload = {
|
|
622
|
-
...base,
|
|
623
|
-
text: message.text,
|
|
624
|
-
mentions: [],
|
|
625
|
-
by,
|
|
626
|
-
from: null
|
|
627
|
-
};
|
|
628
|
-
break;
|
|
629
|
-
case "message.deleted":
|
|
630
|
-
type = "message.deleted";
|
|
631
|
-
payload = {
|
|
632
|
-
...base,
|
|
633
|
-
by,
|
|
634
|
-
from: null
|
|
635
|
-
};
|
|
636
|
-
break;
|
|
637
|
-
case "message.reaction_added":
|
|
638
|
-
case "message.reaction_removed":
|
|
639
|
-
type = change.type === "message.reaction_added" ? "reaction.added" : "reaction.removed";
|
|
640
|
-
payload = {
|
|
641
|
-
...base,
|
|
642
|
-
emoji: change.emoji,
|
|
643
|
-
by,
|
|
644
|
-
from: null
|
|
645
|
-
};
|
|
646
|
-
break;
|
|
647
|
-
case "message.labeled": {
|
|
648
|
-
const changed = Object.entries(change.labels ?? {});
|
|
649
|
-
type = "labels.changed";
|
|
650
|
-
payload = {
|
|
651
|
-
...base,
|
|
652
|
-
set: Object.fromEntries(changed.flatMap(([key, { to }]) => to === void 0 ? [] : [[key, to]])),
|
|
653
|
-
unset: changed.flatMap(([key, { to }]) => to === void 0 ? [key] : []),
|
|
654
|
-
by
|
|
655
|
-
};
|
|
656
|
-
break;
|
|
657
|
-
}
|
|
658
|
-
default: return null;
|
|
659
|
-
}
|
|
660
|
-
return {
|
|
661
|
-
cursor,
|
|
662
|
-
type,
|
|
663
|
-
createdAt: iso(change.createdAt),
|
|
664
|
-
payload,
|
|
665
|
-
message,
|
|
666
|
-
actor: await nameOf(who, change.actor)
|
|
667
|
-
};
|
|
668
|
-
}
|
|
669
|
-
/**
|
|
670
|
-
* One read of every channel's feed from `position`: its events, merged by time, each with the
|
|
671
|
-
* position right after it, and the position after them all.
|
|
672
|
-
*/
|
|
673
|
-
async function read(who, listed, position, filters, signal) {
|
|
674
|
-
const path = await onBoard(who, "/changes");
|
|
675
|
-
const pages = await Promise.all(listed.map(async (channel) => {
|
|
676
|
-
const from = position.feeds[channel.id];
|
|
677
|
-
const page = await api(who, "GET", path, {
|
|
678
|
-
query: {
|
|
679
|
-
channelId: channel.id,
|
|
680
|
-
...from?.at ? { cursor: from.at } : {}
|
|
681
|
-
},
|
|
682
|
-
signal
|
|
683
|
-
});
|
|
684
|
-
const skip = from?.skip ?? 0;
|
|
685
|
-
const events = page.events.map((change, i) => ({
|
|
686
|
-
change,
|
|
687
|
-
i
|
|
688
|
-
})).slice(skip).filter(({ change }) => from || change.createdAt > position.t);
|
|
689
|
-
return {
|
|
690
|
-
channel,
|
|
691
|
-
at: from?.at ?? null,
|
|
692
|
-
next: page.cursor,
|
|
693
|
-
events
|
|
694
|
-
};
|
|
695
|
-
}));
|
|
696
|
-
const mine = await actorOf(who);
|
|
697
|
-
const running = { ...position.feeds };
|
|
698
|
-
const merged = pages.flatMap((page) => page.events.map((event) => ({
|
|
699
|
-
...event,
|
|
700
|
-
page
|
|
701
|
-
}))).sort((a, b) => a.change.createdAt - b.change.createdAt);
|
|
702
|
-
const events = [];
|
|
703
|
-
for (const { change, i, page } of merged) {
|
|
704
|
-
running[page.channel.id] = {
|
|
705
|
-
at: page.at,
|
|
706
|
-
skip: i + 1
|
|
707
|
-
};
|
|
708
|
-
const event = await eventOf(who, change, page.channel.name, cursorOf({
|
|
709
|
-
t: change.createdAt,
|
|
710
|
-
feeds: { ...running }
|
|
711
|
-
}), filters, mine);
|
|
712
|
-
if (event) events.push(event);
|
|
713
|
-
}
|
|
714
|
-
const after = { ...position.feeds };
|
|
715
|
-
for (const page of pages) after[page.channel.id] = {
|
|
716
|
-
at: page.next,
|
|
717
|
-
skip: 0
|
|
718
|
-
};
|
|
719
|
-
return {
|
|
720
|
-
events,
|
|
721
|
-
position: {
|
|
722
|
-
t: Math.max(position.t, ...merged.map(({ change }) => change.createdAt)),
|
|
723
|
-
feeds: after
|
|
724
|
-
}
|
|
725
|
-
};
|
|
726
|
-
}
|
|
727
|
-
/** Whether a read filters on what messages say, who wrote them, or their labels: what the API can't narrow by. */
|
|
728
|
-
const filtered = (filters) => filters.by !== void 0 || filters.mentions !== void 0 || filters.text !== void 0 || filters.from !== void 0 || (filters.label?.length ?? 0) > 0;
|
|
729
|
-
/**
|
|
730
|
-
* One channel's messages, from the API's message list: the latest `limit`, or those after one of
|
|
731
|
-
* its cursors. A filtered read checks each page here, and asks only for as many as it still needs,
|
|
732
|
-
* so the cursor it answers with never passes a match it left out.
|
|
733
|
-
*/
|
|
734
|
-
async function channelMessages(who, channel, query, signal) {
|
|
735
|
-
const path = await onBoard(who, "/messages");
|
|
736
|
-
const limit = query.limit ?? 50;
|
|
737
|
-
const thread = threadReader(who, signal);
|
|
738
|
-
const narrowed = filtered(query);
|
|
739
|
-
const me = narrowed ? await actorOf(who) : null;
|
|
740
|
-
const keep = async (message) => !narrowed || matches(query, message, query.label?.length ? await thread(message.threadId) : { id: message.threadId }, me);
|
|
741
|
-
const kept = [];
|
|
742
|
-
if (query.after === void 0) {
|
|
743
|
-
const page = await api(who, "GET", path, {
|
|
744
|
-
query: {
|
|
745
|
-
channelId: channel.id,
|
|
746
|
-
limit: String(narrowed ? PAGE_MAX : Math.min(limit, PAGE_MAX))
|
|
747
|
-
},
|
|
748
|
-
signal
|
|
749
|
-
});
|
|
750
|
-
for (const message of page.messages) if (await keep(message)) kept.push(message);
|
|
751
|
-
return {
|
|
752
|
-
messages: kept.slice(-limit),
|
|
753
|
-
cursor: page.cursor
|
|
754
|
-
};
|
|
755
|
-
}
|
|
756
|
-
let cursor = query.after;
|
|
757
|
-
for (let pages = 0; pages < SCAN_PAGES && kept.length < limit; pages++) {
|
|
758
|
-
const page = await api(who, "GET", path, {
|
|
759
|
-
query: {
|
|
760
|
-
channelId: channel.id,
|
|
761
|
-
after: cursor,
|
|
762
|
-
limit: String(Math.min(limit - kept.length, PAGE_MAX))
|
|
763
|
-
},
|
|
764
|
-
signal
|
|
765
|
-
});
|
|
766
|
-
cursor = page.cursor;
|
|
767
|
-
for (const message of page.messages) if (await keep(message)) kept.push(message);
|
|
768
|
-
if (page.messages.length === 0) break;
|
|
769
|
-
}
|
|
770
|
-
return {
|
|
771
|
-
messages: kept,
|
|
772
|
-
cursor
|
|
773
|
-
};
|
|
774
|
-
}
|
|
775
|
-
/** One channel's events, from the API's feed after one of its cursors, or from now: a long-poll holds there, not here. */
|
|
776
|
-
async function channelEvents(who, channel, query, signal) {
|
|
777
|
-
const path = await onBoard(who, "/changes");
|
|
778
|
-
const thread = threadReader(who, signal);
|
|
779
|
-
const me = await actorOf(who);
|
|
780
|
-
const until = Date.now() + (query.wait ?? 0) * 1e3;
|
|
781
|
-
let cursor = query.after;
|
|
782
|
-
for (;;) {
|
|
783
|
-
const wait = Math.min(WAIT_MAX_S, Math.max(0, Math.ceil((until - Date.now()) / 1e3)));
|
|
784
|
-
const page = await api(who, "GET", path, {
|
|
785
|
-
query: {
|
|
786
|
-
channelId: channel.id,
|
|
787
|
-
include: "message",
|
|
788
|
-
...cursor === void 0 ? { from: "latest" } : { cursor },
|
|
789
|
-
...wait > 0 ? { wait: String(wait) } : {}
|
|
790
|
-
},
|
|
791
|
-
signal
|
|
792
|
-
});
|
|
793
|
-
cursor = page.cursor;
|
|
794
|
-
const events = [];
|
|
795
|
-
for (const change of page.events) {
|
|
796
|
-
const message = change.currentMessage;
|
|
797
|
-
const found = message && change.threadId ? {
|
|
798
|
-
message,
|
|
799
|
-
thread: query.label?.length ? await thread(change.threadId) : { id: change.threadId }
|
|
800
|
-
} : null;
|
|
801
|
-
if (!found) continue;
|
|
802
|
-
const event = await eventOf(who, change, channel.name, change.cursor ?? page.cursor, query, me, found);
|
|
803
|
-
if (event) events.push(event);
|
|
804
|
-
}
|
|
805
|
-
if (events.length > 0 || Date.now() >= until || signal.aborted) return {
|
|
806
|
-
events,
|
|
807
|
-
cursor
|
|
808
|
-
};
|
|
809
|
-
}
|
|
810
|
-
}
|
|
811
|
-
/** The one channel a read names, when the API can read it directly: not a subtree, and from one of its cursors or now. */
|
|
812
|
-
async function oneChannel(who, access, query) {
|
|
813
|
-
if (query.channel === void 0 || query.channel.endsWith("/") || query.re !== void 0) return null;
|
|
814
|
-
if (query.after !== void 0 && !API_CURSOR.test(query.after)) return null;
|
|
815
|
-
const [channel] = await channelsFor(who, query.channel, access);
|
|
816
|
-
return channel ?? null;
|
|
817
|
-
}
|
|
818
|
-
/** Who wrote or reacted in the latest messages of each channel `access` reads. */
|
|
819
|
-
async function actorsSeen(who, access, signal) {
|
|
820
|
-
const path = await onBoard(who, "/messages");
|
|
821
|
-
const seen = /* @__PURE__ */ new Set();
|
|
822
|
-
for (const channel of await channelsFor(who, void 0, access)) {
|
|
823
|
-
const { messages } = await api(who, "GET", path, {
|
|
824
|
-
query: {
|
|
825
|
-
channelId: channel.id,
|
|
826
|
-
limit: String(PAGE_MAX)
|
|
827
|
-
},
|
|
828
|
-
signal
|
|
829
|
-
});
|
|
830
|
-
for (const message of messages) {
|
|
831
|
-
seen.add(message.createdBy.id);
|
|
832
|
-
for (const actors of Object.values(message.reactors ?? {})) for (const actor of actors) seen.add(actor);
|
|
833
|
-
}
|
|
834
|
-
}
|
|
835
|
-
return seen;
|
|
836
|
-
}
|
|
837
|
-
/** What a gateway caller does here, as this deployment: never what's the project's own. */
|
|
838
|
-
function checkCaller(method, caller) {
|
|
839
|
-
if ("identity" in caller && PROJECTS_OWN.has(method)) throw forbidden(`this board's callers act as its project on Vercel's board, which can't tell them apart: ${method} is the project's own to do there`);
|
|
840
|
-
}
|
|
841
|
-
/**
|
|
842
|
-
* The API owns messages and schedules by principal, and sees every caller here as this project:
|
|
843
|
-
* a caller that is the project (its own deployment's token) changes what it wrote, as on any
|
|
844
|
-
* board, and anyone else would be changing what the project wrote for others.
|
|
845
|
-
*/
|
|
846
|
-
/** Whether a caller is this project: the deployment's own code, or a caller verified as its principal. */
|
|
847
|
-
const isProject = async (caller, who) => !("identity" in caller) || caller.identity.principal.id === principalId((await self(who)).actor.principal);
|
|
848
|
-
async function checkOwner(what, caller, who) {
|
|
849
|
-
if (!await isProject(caller, who)) throw forbidden(`this board's callers act as its project on Vercel's board, which owns what any of them wrote: only the project itself may ${what} there`);
|
|
850
|
-
}
|
|
851
|
-
/** A file is no use until a post or an import carries it, so uploading takes `post` or `sync` somewhere, as on a2(). */
|
|
852
|
-
async function checkUploader(caller, who) {
|
|
853
|
-
await checkOwner("upload", caller, who);
|
|
854
|
-
const access = accessOf(caller);
|
|
855
|
-
if (access && !access.anywhere("post") && !access.anywhere("sync")) throw forbidden("this token can't post anywhere, so it can't upload");
|
|
856
|
-
}
|
|
857
|
-
const meOf = (identity) => {
|
|
858
|
-
const { principal, author, actor } = identity;
|
|
859
|
-
return {
|
|
860
|
-
actor: actor.id,
|
|
861
|
-
principal: principal.id,
|
|
862
|
-
kind: actor.kind,
|
|
863
|
-
handle: actor.handle,
|
|
864
|
-
name: actor.name,
|
|
865
|
-
avatar: actor.avatar,
|
|
866
|
-
profile: author.profile,
|
|
867
|
-
session: author.session,
|
|
868
|
-
expiresAt: principal.expiresAt?.toISOString() ?? null,
|
|
869
|
-
can: principal.access.summary()
|
|
870
|
-
};
|
|
871
|
-
};
|
|
872
|
-
/** A watcher's tail registers with the API as its own: an API watcher, so a match is the API's to make. */
|
|
873
|
-
const tagOf = async (watch) => (await sha256(canonicalWatchers(watch))).slice(0, 32);
|
|
874
|
-
/** Who `--by` names, as the API's authors: an actor, a principal, or everyone here with that handle or profile, as of now. */
|
|
875
|
-
async function authorsOf(who, by) {
|
|
876
|
-
if (by === "me") return [await actorOf(who)];
|
|
877
|
-
if (by.startsWith("vercel:")) return [by];
|
|
878
|
-
const named = (await all(who, await onBoard(who, "/actors"), "actors")).filter((actor) => actor.handle === by || actor.id.endsWith(`+${by.toLowerCase()}`)).map((actor) => actor.id);
|
|
879
|
-
if (named.length === 0) throw new HttpError(400, "bad_watcher", `--by ${by}: nobody here goes by that yet: name them by their actor ID`);
|
|
880
|
-
return named;
|
|
881
|
-
}
|
|
882
|
-
/**
|
|
883
|
-
* A tail as the filter the API matches. The API reads no tails: channels, people, and threads are
|
|
884
|
-
* looked up here, now, and what it can't match (mentions, other sources) is refused rather than
|
|
885
|
-
* left to match nothing.
|
|
886
|
-
*/
|
|
887
|
-
async function filterOf(who, id, spec) {
|
|
888
|
-
const bad = (message) => new HttpError(400, "bad_watcher", `watch ${id}: ${message}`);
|
|
889
|
-
if (!RemoteWatcherId.safeParse(id).success) throw bad("ids start with a letter and use up to 32 letters, numbers, and hyphens");
|
|
890
|
-
let filters;
|
|
891
|
-
try {
|
|
892
|
-
({filters} = compileWatcher(id, spec));
|
|
893
|
-
} catch (error) {
|
|
894
|
-
throw new HttpError(400, "bad_watcher", error.message);
|
|
895
|
-
}
|
|
896
|
-
if (filters.mentions !== void 0) throw bad("Vercel's boards can't match mentions yet");
|
|
897
|
-
if (filters.from !== void 0 && filters.from !== "board") throw bad(`nothing comes from ${filters.from} here: every message is written on the board`);
|
|
898
|
-
const filter = {};
|
|
899
|
-
if (filters.channel !== void 0) {
|
|
900
|
-
if (filters.channel.endsWith("/")) filter.channelTree = filters.channel.slice(0, -1);
|
|
901
|
-
else {
|
|
902
|
-
const found = await channelNamed(who, filters.channel);
|
|
903
|
-
if (found) filter.channelIds = [found.id];
|
|
904
|
-
else filter.channelTree = filters.channel;
|
|
905
|
-
}
|
|
906
|
-
}
|
|
907
|
-
if (filters.re !== void 0) {
|
|
908
|
-
const at = locate(filters.re);
|
|
909
|
-
if (!at) throw bad(`--re ${filters.re} names no message here`);
|
|
910
|
-
filter.threadId = at.threadId;
|
|
911
|
-
}
|
|
912
|
-
if (filters.by !== void 0) filter.authors = await authorsOf(who, filters.by);
|
|
913
|
-
if (filters.text !== void 0) filter.text = filters.text;
|
|
914
|
-
if (filters.label?.length) filter.labels = filters.label.map(([key, values]) => values === null ? { key } : {
|
|
915
|
-
key,
|
|
916
|
-
values: [...values]
|
|
917
|
-
});
|
|
918
|
-
return {
|
|
919
|
-
filter,
|
|
920
|
-
when: spec.when ?? "matches"
|
|
921
|
-
};
|
|
922
|
-
}
|
|
923
|
-
/** A filter shown as a tail again, for listing: what it matches, if not always as it was written. */
|
|
924
|
-
async function tailOf(who, { filter }) {
|
|
925
|
-
const parts = [];
|
|
926
|
-
if (filter.channelIds?.[0]) parts.push((await channelById(who, filter.channelIds[0])).name);
|
|
927
|
-
else if (filter.channelTree !== void 0) parts.push(`${filter.channelTree}/`);
|
|
928
|
-
if (filter.threadId !== void 0) parts.push(`--re ${idAt(filter.threadId, 1)}`);
|
|
929
|
-
if (filter.authors?.[0]) parts.push(`--by ${filter.authors[0]}`);
|
|
930
|
-
if (filter.text !== void 0) parts.push(`--text ${JSON.stringify(filter.text)}`);
|
|
931
|
-
for (const { key, values } of filter.labels ?? []) parts.push(`--label ${values ? `${key}=${values.join("|")}` : key}`);
|
|
932
|
-
return parts.join(" ");
|
|
933
|
-
}
|
|
934
|
-
/** Where a registration is woken, as board shows it: its URL, or a path on its project (and a preview's branch). */
|
|
935
|
-
const whereOf = (found) => found.path ? {
|
|
936
|
-
url: null,
|
|
937
|
-
path: found.path,
|
|
938
|
-
...found.branch ? { branch: found.branch } : {}
|
|
939
|
-
} : { url: found.url };
|
|
940
|
-
async function registerAs(who, where, watch) {
|
|
941
|
-
const specs = Object.fromEntries(Object.entries(watch).map(([id, spec]) => [id, {
|
|
942
|
-
tail: spec.tail,
|
|
943
|
-
when: spec.when ?? "matches"
|
|
944
|
-
}]));
|
|
945
|
-
const filters = Object.fromEntries(await Promise.all(Object.entries(specs).map(async ([id, spec]) => [id, await filterOf(who, id, spec)])));
|
|
946
|
-
const made = await api(who, "PUT", await onBoard(who, "/watchers"), { body: {
|
|
947
|
-
...where,
|
|
948
|
-
watch: filters,
|
|
949
|
-
tag: await tagOf(specs)
|
|
950
|
-
} });
|
|
951
|
-
return {
|
|
952
|
-
owner: made.owner,
|
|
953
|
-
...whereOf(made),
|
|
954
|
-
watch: specs,
|
|
955
|
-
sync: [],
|
|
956
|
-
hash: made.hash
|
|
957
|
-
};
|
|
958
|
-
}
|
|
959
|
-
/** A match as vboard hands it out: its event as `vb tail --json` prints it, with its message as it is now. */
|
|
960
|
-
async function matchOf(who, match, me) {
|
|
961
|
-
const found = await messageById(who, match.event.messageId).catch((error) => {
|
|
962
|
-
if (error instanceof HttpError && error.status === 404) return null;
|
|
963
|
-
throw error;
|
|
964
|
-
});
|
|
965
|
-
const channel = found && await channelById(who, found.thread.channelId);
|
|
966
|
-
const event = found && channel && await eventOf(who, match.event, channel.name, match.id, {}, me, found);
|
|
967
|
-
if (!event?.message) return null;
|
|
968
|
-
return {
|
|
969
|
-
id: match.id,
|
|
970
|
-
watcher: match.watcher,
|
|
971
|
-
thread: event.message.thread,
|
|
972
|
-
lease: match.lease,
|
|
973
|
-
attempt: match.attempt,
|
|
974
|
-
event
|
|
975
|
-
};
|
|
976
|
-
}
|
|
977
|
-
async function pullAs(who, query, signal) {
|
|
978
|
-
const { matches } = await api(who, "GET", await onBoard(who, "/watchers/matches"), {
|
|
979
|
-
query: {
|
|
980
|
-
limit: query.limit?.toString(),
|
|
981
|
-
wait: query.wait?.toString()
|
|
982
|
-
},
|
|
983
|
-
...signal ? { signal } : {}
|
|
984
|
-
});
|
|
985
|
-
const me = await actorOf(who);
|
|
986
|
-
const shown = await Promise.all(matches.map((match) => matchOf(who, match, me)));
|
|
987
|
-
await Promise.all(matches.map((match, i) => shown[i] ? null : ackAs(who, match.id, {
|
|
988
|
-
lease: match.lease,
|
|
989
|
-
skip: true
|
|
990
|
-
}).catch(() => {})));
|
|
991
|
-
return shown.filter((match) => match !== null);
|
|
992
|
-
}
|
|
993
|
-
async function ackAs(who, id, body) {
|
|
994
|
-
await api(who, "POST", await onBoard(who, `/watchers/matches/${encodeURIComponent(id)}/ack`), { body: {
|
|
995
|
-
lease: body.lease,
|
|
996
|
-
...body.error !== void 0 ? { error: body.error } : {},
|
|
997
|
-
...body.skip ? { skip: true } : {}
|
|
998
|
-
} });
|
|
999
|
-
}
|
|
1000
|
-
/**
|
|
1001
|
-
* The API keeps one registration per principal, and this board reaches it as its own deployment:
|
|
1002
|
-
* one a caller registered through it would replace the deployment's, and every other caller's.
|
|
1003
|
-
*/
|
|
1004
|
-
function ownWatchers(caller, what) {
|
|
1005
|
-
if ("identity" in caller) throw forbidden(`this board registers watchers as its own deployment, so it can't ${what} for you: run them in its config, or register with Vercel's API as yourself`);
|
|
1006
|
-
}
|
|
1007
|
-
/** This deployment's own: what its config's watchers run as. */
|
|
1008
|
-
const deployment = {
|
|
1009
|
-
profile: null,
|
|
1010
|
-
session: null
|
|
1011
|
-
};
|
|
1012
|
-
/** This board's config's watchers, which run here when the API wakes it. */
|
|
1013
|
-
let tails = {};
|
|
1014
|
-
const bound = () => {
|
|
1015
|
-
if (!binding) throw new Error("vercel: used before board() bound it");
|
|
1016
|
-
return binding;
|
|
1017
|
-
};
|
|
1018
|
-
const runner = registrant({
|
|
1019
|
-
remote: "Vercel's API",
|
|
1020
|
-
registry: {
|
|
1021
|
-
register: (where) => registerAs(deployment, where, tails),
|
|
1022
|
-
matches: ({ signal, ...query }) => pullAs(deployment, query, signal),
|
|
1023
|
-
ack: (id, body) => ackAs(deployment, id, body)
|
|
1024
|
-
},
|
|
1025
|
-
wakeAt: async (here) => wakePath(here) ?? { url: here },
|
|
1026
|
-
binding: bound,
|
|
1027
|
-
hash: () => tagOf(tails),
|
|
1028
|
-
hasWork: () => Object.keys(tails).length > 0,
|
|
1029
|
-
rethrow: (error) => {
|
|
1030
|
-
throw error;
|
|
1031
|
-
},
|
|
1032
|
-
registerFor: async (caller, request) => json(await methods.register(caller, RegisterBody.parse(await request.json()), request.signal))
|
|
1033
|
-
});
|
|
1034
|
-
const methods = {
|
|
1035
|
-
...Object.fromEntries(METHODS.map((method) => [method, async () => {
|
|
1036
|
-
throw notSupported(method === "register" || method === "watchers" || method === "matches" || method === "ack" ? "watchers" : method);
|
|
1037
|
-
}])),
|
|
1038
|
-
async discovery() {
|
|
1039
|
-
const who = {
|
|
1040
|
-
profile: null,
|
|
1041
|
-
session: null
|
|
1042
|
-
};
|
|
1043
|
-
const team = await teamId();
|
|
1044
|
-
if (options.board) await api(who, "GET", await onBoard(who));
|
|
1045
|
-
const id = team?.startsWith("team_") ? team : (await self(who)).teamId;
|
|
1046
|
-
return {
|
|
1047
|
-
version: VERSION,
|
|
1048
|
-
url: `${origin}/v1/messageboard${await onBoard(who)}?teamId=${encodeURIComponent(id)}`,
|
|
1049
|
-
audience: origin,
|
|
1050
|
-
team_id: id,
|
|
1051
|
-
project_id: null,
|
|
1052
|
-
sync: [],
|
|
1053
|
-
wake_by_path: true
|
|
1054
|
-
};
|
|
1055
|
-
},
|
|
1056
|
-
async me(caller) {
|
|
1057
|
-
if ("identity" in caller) return meOf(caller.identity);
|
|
1058
|
-
const found = await api(whoOf(caller), "GET", "/me");
|
|
1059
|
-
const { view: named } = found;
|
|
1060
|
-
const shown = named ? {
|
|
1061
|
-
kind: apiKind(named.kind),
|
|
1062
|
-
handle: named.handle,
|
|
1063
|
-
name: named.name ?? named.handle,
|
|
1064
|
-
avatar: named.avatar ?? null
|
|
1065
|
-
} : actorView(found.actor);
|
|
1066
|
-
return {
|
|
1067
|
-
actor: found.actor.id,
|
|
1068
|
-
principal: principalId(found.actor.principal),
|
|
1069
|
-
kind: shown.kind,
|
|
1070
|
-
handle: shown.handle,
|
|
1071
|
-
name: shown.name,
|
|
1072
|
-
avatar: shown.avatar,
|
|
1073
|
-
profile: found.actor.profile?.name ?? null,
|
|
1074
|
-
session: found.actor.session ?? null,
|
|
1075
|
-
expiresAt: null,
|
|
1076
|
-
can: { "*": [
|
|
1077
|
-
"read",
|
|
1078
|
-
"post",
|
|
1079
|
-
"react",
|
|
1080
|
-
"label"
|
|
1081
|
-
] }
|
|
1082
|
-
};
|
|
1083
|
-
},
|
|
1084
|
-
async channels(caller) {
|
|
1085
|
-
return {
|
|
1086
|
-
channels: (await channelsFor(whoOf(caller), void 0, accessOf(caller))).map((channel) => ({ path: channel.name })).sort((a, b) => a.path.localeCompare(b.path)),
|
|
1087
|
-
cursor: cursorOf({
|
|
1088
|
-
t: Date.now(),
|
|
1089
|
-
feeds: {}
|
|
1090
|
-
})
|
|
1091
|
-
};
|
|
1092
|
-
},
|
|
1093
|
-
async createChannel(caller, { path }) {
|
|
1094
|
-
checkCaller("createChannel", caller);
|
|
1095
|
-
const access = accessOf(caller);
|
|
1096
|
-
need(access, "read", path);
|
|
1097
|
-
need(access, "post", path);
|
|
1098
|
-
const { created } = await ensureChannel(whoOf(caller), path);
|
|
1099
|
-
return {
|
|
1100
|
-
channel: { path },
|
|
1101
|
-
created
|
|
1102
|
-
};
|
|
1103
|
-
},
|
|
1104
|
-
async actors(caller, _input, signal) {
|
|
1105
|
-
const who = whoOf(caller);
|
|
1106
|
-
const listed = (await all(who, await onBoard(who, "/actors"), "actors", {}, signal)).map((actor) => ({
|
|
1107
|
-
id: actor.id,
|
|
1108
|
-
kind: apiKind(actor.kind),
|
|
1109
|
-
handle: actor.handle,
|
|
1110
|
-
name: actor.name ?? actor.handle,
|
|
1111
|
-
avatar: actor.avatar ?? null
|
|
1112
|
-
}));
|
|
1113
|
-
const cursor = cursorOf({
|
|
1114
|
-
t: Date.now(),
|
|
1115
|
-
feeds: {}
|
|
1116
|
-
});
|
|
1117
|
-
if (!("identity" in caller) || caller.identity.principal.access.readsAll) return {
|
|
1118
|
-
actors: listed,
|
|
1119
|
-
cursor
|
|
1120
|
-
};
|
|
1121
|
-
const { actor: self, principal } = caller.identity;
|
|
1122
|
-
const seen = await actorsSeen(who, principal.access, signal);
|
|
1123
|
-
return {
|
|
1124
|
-
actors: [...listed.filter((actor) => seen.has(actor.id) && actor.id !== self.id), {
|
|
1125
|
-
id: self.id,
|
|
1126
|
-
kind: self.kind,
|
|
1127
|
-
handle: self.handle,
|
|
1128
|
-
name: self.name,
|
|
1129
|
-
avatar: self.avatar
|
|
1130
|
-
}],
|
|
1131
|
-
cursor
|
|
1132
|
-
};
|
|
1133
|
-
},
|
|
1134
|
-
async messages(caller, query, signal) {
|
|
1135
|
-
const who = whoOf(caller);
|
|
1136
|
-
const access = accessOf(caller);
|
|
1137
|
-
const channel = query.before === void 0 ? await oneChannel(who, access, query) : null;
|
|
1138
|
-
if (channel) {
|
|
1139
|
-
const page = await channelMessages(who, channel, query, signal);
|
|
1140
|
-
return {
|
|
1141
|
-
messages: await Promise.all(page.messages.map((message) => view(who, message, channel.name))),
|
|
1142
|
-
cursor: page.cursor
|
|
1143
|
-
};
|
|
1144
|
-
}
|
|
1145
|
-
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`);
|
|
1146
|
-
const { messages, feeds, newest } = await collect(who, access, query, signal);
|
|
1147
|
-
const after = query.after !== void 0 ? await timeOf(who, query.after) : void 0;
|
|
1148
|
-
const before = query.before !== void 0 ? await timeOf(who, query.before) : void 0;
|
|
1149
|
-
const limit = query.limit ?? 50;
|
|
1150
|
-
const bounded = messages.filter(({ message }) => (after === void 0 || message.createdAt > after) && (before === void 0 || message.createdAt < before));
|
|
1151
|
-
const page = after !== void 0 ? bounded.slice(0, limit) : bounded.slice(-limit);
|
|
1152
|
-
return {
|
|
1153
|
-
messages: await Promise.all(page.map(({ message, channel }) => view(who, message, channel.name))),
|
|
1154
|
-
cursor: cursorOf({
|
|
1155
|
-
t: newest,
|
|
1156
|
-
feeds
|
|
1157
|
-
})
|
|
1158
|
-
};
|
|
1159
|
-
},
|
|
1160
|
-
async threads(caller, query, signal) {
|
|
1161
|
-
const who = whoOf(caller);
|
|
1162
|
-
const after = query.after !== void 0 ? await timeOf(who, query.after) : void 0;
|
|
1163
|
-
const limit = query.limit ?? 50;
|
|
1164
|
-
const pick = (found) => {
|
|
1165
|
-
const ordered = found.filter(({ at }) => after === void 0 || at > after).sort((a, b) => a.at - b.at);
|
|
1166
|
-
return after !== void 0 ? ordered.slice(0, limit) : ordered.slice(-limit);
|
|
1167
|
-
};
|
|
1168
|
-
if (query.re !== void 0 || query.by !== void 0 || query.mentions !== void 0 || query.text !== void 0 || query.from !== void 0 && query.from !== "board") {
|
|
1169
|
-
const { messages, feeds, newest } = await collect(who, accessOf(caller), query, signal);
|
|
1170
|
-
const latest = /* @__PURE__ */ new Map();
|
|
1171
|
-
for (const { message, thread, channel } of messages) latest.set(thread.id, {
|
|
1172
|
-
thread,
|
|
1173
|
-
channel,
|
|
1174
|
-
at: Math.max(latest.get(thread.id)?.at ?? 0, message.createdAt)
|
|
1175
|
-
});
|
|
1176
|
-
return {
|
|
1177
|
-
threads: await Promise.all(pick([...latest.values()]).map(({ thread, channel }) => summary(who, thread, channel, signal))),
|
|
1178
|
-
cursor: cursorOf({
|
|
1179
|
-
t: newest,
|
|
1180
|
-
feeds
|
|
1181
|
-
})
|
|
1182
|
-
};
|
|
1183
|
-
}
|
|
1184
|
-
const listed = await channelsFor(who, query.channel, accessOf(caller));
|
|
1185
|
-
const feeds = await heads(who, listed);
|
|
1186
|
-
const label = indexed(query);
|
|
1187
|
-
const found = (await Promise.all(listed.map(async (channel) => (await latestThreads(who, channel, label, {
|
|
1188
|
-
...after !== void 0 ? { after } : {},
|
|
1189
|
-
...query.label?.length ? {} : { limit }
|
|
1190
|
-
}, signal)).map((thread) => ({
|
|
1191
|
-
thread,
|
|
1192
|
-
channel,
|
|
1193
|
-
at: thread.lastActivityAt
|
|
1194
|
-
}))))).flat();
|
|
1195
|
-
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]))));
|
|
1196
|
-
const newest = found.reduce((max, { at }) => Math.max(max, at), 0);
|
|
1197
|
-
return {
|
|
1198
|
-
threads: await Promise.all(pick(rooted).map(({ thread, channel }) => summary(who, thread, channel, signal))),
|
|
1199
|
-
cursor: cursorOf({
|
|
1200
|
-
t: newest,
|
|
1201
|
-
feeds
|
|
1202
|
-
})
|
|
1203
|
-
};
|
|
1204
|
-
},
|
|
1205
|
-
async message(caller, { id }, signal) {
|
|
1206
|
-
const who = whoOf(caller);
|
|
1207
|
-
const { thread, channel } = await readableMessage(who, accessOf(caller), id, signal);
|
|
1208
|
-
const [root, ...replies] = await threadMessages(who, thread.id, signal);
|
|
1209
|
-
if (!root) throw notFound(`message not found: ${id}`, "message_not_found");
|
|
1210
|
-
return {
|
|
1211
|
-
message: await view(who, root, channel.name),
|
|
1212
|
-
replies: await Promise.all(replies.map((reply) => view(who, reply, channel.name))),
|
|
1213
|
-
cursor: cursorOf({
|
|
1214
|
-
t: Math.max(root.createdAt, ...replies.map((reply) => reply.createdAt)),
|
|
1215
|
-
feeds: {}
|
|
1216
|
-
})
|
|
1217
|
-
};
|
|
1218
|
-
},
|
|
1219
|
-
async upload(caller, { data, name, type }) {
|
|
1220
|
-
const who = whoOf(caller);
|
|
1221
|
-
await checkUploader(caller, who);
|
|
1222
|
-
if (data.byteLength === 0) throw new HttpError(400, "bad_request", "the file is empty");
|
|
1223
|
-
if (data.byteLength > 26214400) throw new HttpError(413, "too_large", `attachments are at most ${IMPORT_BYTES_MAX / 1024 / 1024} MB`);
|
|
1224
|
-
const bytes = new Uint8Array(data);
|
|
1225
|
-
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
|
|
1226
|
-
const started = await api(who, "POST", await onBoard(who, "/attachments"), { body: {
|
|
1227
|
-
operationId: operationId(),
|
|
1228
|
-
name: fileName(name),
|
|
1229
|
-
type: mediaType(type),
|
|
1230
|
-
size: data.byteLength,
|
|
1231
|
-
sha256: btoa(String.fromCharCode(...digest))
|
|
1232
|
-
} });
|
|
1233
|
-
const put = await filesFetch(started.upload.url, {
|
|
1234
|
-
method: started.upload.method,
|
|
1235
|
-
headers: started.upload.headers,
|
|
1236
|
-
body: bytes,
|
|
1237
|
-
redirect: "error"
|
|
1238
|
-
});
|
|
1239
|
-
if (!put.ok) throw new HttpError(502, "upload_failed", `the upload to Vercel's storage answered ${put.status}`);
|
|
1240
|
-
const { attachment } = await api(who, "POST", await onBoard(who, `/attachments/${encodeURIComponent(started.attachment.id)}/complete`));
|
|
1241
|
-
return { attachment: fileOf(attachment) };
|
|
1242
|
-
},
|
|
1243
|
-
async uploadStart(caller, { name, type, size, sha256 }) {
|
|
1244
|
-
const who = whoOf(caller);
|
|
1245
|
-
await checkUploader(caller, who);
|
|
1246
|
-
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");
|
|
1247
|
-
const started = await api(who, "POST", await onBoard(who, "/attachments"), { body: {
|
|
1248
|
-
operationId: operationId(),
|
|
1249
|
-
name: fileName(name ?? null),
|
|
1250
|
-
type: mediaType(type ?? null),
|
|
1251
|
-
size,
|
|
1252
|
-
sha256
|
|
1253
|
-
} });
|
|
1254
|
-
return {
|
|
1255
|
-
id: started.attachment.id,
|
|
1256
|
-
url: started.upload.url,
|
|
1257
|
-
headers: started.upload.headers,
|
|
1258
|
-
expiresAt: iso(started.upload.expiresAt)
|
|
1259
|
-
};
|
|
1260
|
-
},
|
|
1261
|
-
async uploadFinish(caller, { id }) {
|
|
1262
|
-
const who = whoOf(caller);
|
|
1263
|
-
await checkUploader(caller, who);
|
|
1264
|
-
const { attachment } = await api(who, "POST", await onBoard(who, `/attachments/${encodeURIComponent(id)}/complete`));
|
|
1265
|
-
return { attachment: fileOf(attachment) };
|
|
1266
|
-
},
|
|
1267
|
-
async attachment(caller, { id }, signal) {
|
|
1268
|
-
const who = whoOf(caller);
|
|
1269
|
-
const access = accessOf(caller);
|
|
1270
|
-
const found = await api(who, "GET", await onBoard(who, `/attachments/${encodeURIComponent(id)}`), signal ? { signal } : {});
|
|
1271
|
-
if (access && !found.attachment.messageId) {
|
|
1272
|
-
if (!await isProject(caller, who)) throw notFound(`no attachment: ${id}`, "attachment_not_found");
|
|
1273
|
-
} else if (access) {
|
|
1274
|
-
const { message } = await readableMessage(who, access, found.attachment.messageId, signal).catch((error) => {
|
|
1275
|
-
if (error instanceof HttpError && error.status === 404) throw notFound(`no attachment: ${id}`, "attachment_not_found");
|
|
1276
|
-
throw error;
|
|
1277
|
-
});
|
|
1278
|
-
if (message.deletedAt !== void 0) throw notFound(`no attachment: ${id}`, "attachment_not_found");
|
|
1279
|
-
}
|
|
1280
|
-
const response = await filesFetch(found.url, {
|
|
1281
|
-
redirect: "error",
|
|
1282
|
-
...signal ? { signal } : {}
|
|
1283
|
-
});
|
|
1284
|
-
if (!response.ok || !response.body) throw new HttpError(502, "download_failed", `Vercel's storage answered ${response.status}`);
|
|
1285
|
-
return {
|
|
1286
|
-
attachment: fileOf(found.attachment),
|
|
1287
|
-
data: response.body
|
|
1288
|
-
};
|
|
1289
|
-
},
|
|
1290
|
-
async post(caller, input, signal) {
|
|
1291
|
-
checkCaller("post", caller);
|
|
1292
|
-
if (input.sync?.length) throw notSupported("sync");
|
|
1293
|
-
const who = whoOf(caller);
|
|
1294
|
-
const access = accessOf(caller);
|
|
1295
|
-
if (input.attachments?.length) await checkOwner("post files", caller, who);
|
|
1296
|
-
const labeled = Object.keys(input.labels ?? {}).length > 0;
|
|
1297
|
-
const clientId = input.id !== void 0 ? await postId(caller, input.id) : void 0;
|
|
1298
|
-
let made;
|
|
1299
|
-
if (input.channel !== void 0) {
|
|
1300
|
-
need(access, "post", input.channel);
|
|
1301
|
-
if (labeled) need(access, "label", input.channel);
|
|
1302
|
-
const channel = await channelToPost(who, input.channel);
|
|
1303
|
-
made = await api(who, "POST", await onBoard(who, "/threads"), {
|
|
1304
|
-
body: {
|
|
1305
|
-
operationId: operationId(),
|
|
1306
|
-
channelId: channel.id,
|
|
1307
|
-
text: input.text,
|
|
1308
|
-
...input.labels && Object.keys(input.labels).length ? { labels: input.labels } : {},
|
|
1309
|
-
...clientId ? { clientId } : {},
|
|
1310
|
-
...input.attachments?.length ? { attachments: input.attachments } : {}
|
|
1311
|
-
},
|
|
1312
|
-
signal
|
|
1313
|
-
});
|
|
1314
|
-
} else {
|
|
1315
|
-
const { thread, message: to, channel } = await readableMessage(who, access, input.re, signal);
|
|
1316
|
-
need(access, "post", channel.name);
|
|
1317
|
-
if (labeled) need(access, "label", channel.name);
|
|
1318
|
-
const after = input.after === void 0 ? void 0 : locate(input.after);
|
|
1319
|
-
if (after !== void 0 && after?.threadId !== thread.id) {
|
|
1320
|
-
const landed = clientId ? await api(who, "GET", await onBoard(who, `/posts/${encodeURIComponent(clientId)}`), { signal }).catch(() => null) : null;
|
|
1321
|
-
if (landed?.thread.id === thread.id) return { message: await view(who, landed.message, channel.name) };
|
|
1322
|
-
throw badRequest(`after: ${input.after} isn't in ${input.re}'s thread`, "invalid_after");
|
|
1323
|
-
}
|
|
1324
|
-
made = await api(who, "POST", await onBoard(who, `/threads/${encodeURIComponent(thread.id)}/messages`), {
|
|
1325
|
-
body: {
|
|
1326
|
-
operationId: operationId(),
|
|
1327
|
-
text: input.text,
|
|
1328
|
-
...to.sequence > 1 ? { replyTo: to.sequence } : {},
|
|
1329
|
-
...clientId ? { clientId } : {},
|
|
1330
|
-
...input.attachments?.length ? { attachments: input.attachments } : {},
|
|
1331
|
-
...after ? { after: after.sequence } : {}
|
|
1332
|
-
},
|
|
1333
|
-
signal
|
|
1334
|
-
}).catch((error) => {
|
|
1335
|
-
if (error instanceof HttpError && error.code === "newer_message") throw new HttpError(409, "newer_message", `a message came after ${input.after}`);
|
|
1336
|
-
throw error;
|
|
1337
|
-
});
|
|
1338
|
-
if (input.labels && Object.keys(input.labels).length) {
|
|
1339
|
-
const labeled = await api(who, "POST", await onBoard(who, `/threads/${encodeURIComponent(thread.id)}/messages/${made.message.sequence}/labels`), {
|
|
1340
|
-
body: {
|
|
1341
|
-
operationId: operationId(),
|
|
1342
|
-
set: input.labels
|
|
1343
|
-
},
|
|
1344
|
-
signal
|
|
1345
|
-
});
|
|
1346
|
-
made = {
|
|
1347
|
-
...made,
|
|
1348
|
-
message: {
|
|
1349
|
-
...made.message,
|
|
1350
|
-
...labeled.meta.labels ? { labels: labeled.meta.labels } : {},
|
|
1351
|
-
version: labeled.meta.version
|
|
1352
|
-
}
|
|
1353
|
-
};
|
|
1354
|
-
}
|
|
1355
|
-
}
|
|
1356
|
-
const channel = await channelById(who, made.thread.channelId);
|
|
1357
|
-
return { message: await view(who, made.message, channel.name) };
|
|
1358
|
-
},
|
|
1359
|
-
async posted(caller, { id }, signal) {
|
|
1360
|
-
checkCaller("posted", caller);
|
|
1361
|
-
const who = whoOf(caller);
|
|
1362
|
-
const found = await api(who, "GET", await onBoard(who, `/posts/${encodeURIComponent(await postId(caller, id))}`), { signal });
|
|
1363
|
-
const channel = await channelById(who, found.thread.channelId);
|
|
1364
|
-
const access = accessOf(caller);
|
|
1365
|
-
if (access && !access.readable(channel.name)) throw notFound(`no post of yours has id ${id}`, "post_not_found");
|
|
1366
|
-
return { message: await view(who, found.message, channel.name) };
|
|
1367
|
-
},
|
|
1368
|
-
async edit(caller, { id, text, revision }, signal) {
|
|
1369
|
-
const who = whoOf(caller);
|
|
1370
|
-
await checkOwner("edit", caller, who);
|
|
1371
|
-
const at = locate(id);
|
|
1372
|
-
if (!at) throw notFound(`message not found: ${id}`, "message_not_found");
|
|
1373
|
-
const access = accessOf(caller);
|
|
1374
|
-
if (access) need(access, "post", (await readableMessage(who, access, id, signal)).channel.name);
|
|
1375
|
-
await api(who, "PATCH", await onBoard(who, `/threads/${encodeURIComponent(at.threadId)}/messages/${at.sequence}`), {
|
|
1376
|
-
body: {
|
|
1377
|
-
operationId: operationId(),
|
|
1378
|
-
text,
|
|
1379
|
-
...revision !== void 0 ? { revision } : {}
|
|
1380
|
-
},
|
|
1381
|
-
signal
|
|
1382
|
-
});
|
|
1383
|
-
return { ok: true };
|
|
1384
|
-
},
|
|
1385
|
-
async delete(caller, { id, revision }, signal) {
|
|
1386
|
-
const who = whoOf(caller);
|
|
1387
|
-
await checkOwner("delete", caller, who);
|
|
1388
|
-
const at = locate(id);
|
|
1389
|
-
if (!at) throw notFound(`message not found: ${id}`, "message_not_found");
|
|
1390
|
-
const access = accessOf(caller);
|
|
1391
|
-
if (access) need(access, "post", (await readableMessage(who, access, id, signal)).channel.name);
|
|
1392
|
-
await api(who, "POST", await onBoard(who, `/threads/${encodeURIComponent(at.threadId)}/messages/${at.sequence}/delete`), {
|
|
1393
|
-
body: {
|
|
1394
|
-
operationId: operationId(),
|
|
1395
|
-
...revision !== void 0 ? { revision } : {}
|
|
1396
|
-
},
|
|
1397
|
-
signal
|
|
1398
|
-
});
|
|
1399
|
-
return { ok: true };
|
|
1400
|
-
},
|
|
1401
|
-
async react(caller, { id, emoji, remove }, signal) {
|
|
1402
|
-
checkCaller("react", caller);
|
|
1403
|
-
const who = whoOf(caller);
|
|
1404
|
-
const at = locate(id);
|
|
1405
|
-
if (!at) throw notFound(`message not found: ${id}`, "message_not_found");
|
|
1406
|
-
const access = accessOf(caller);
|
|
1407
|
-
if (access) need(access, "react", (await readableMessage(who, access, id, signal)).channel.name);
|
|
1408
|
-
await api(who, "POST", await onBoard(who, `/threads/${encodeURIComponent(at.threadId)}/messages/${at.sequence}/reactions`), {
|
|
1409
|
-
body: {
|
|
1410
|
-
operationId: operationId(),
|
|
1411
|
-
emoji,
|
|
1412
|
-
...remove ? { remove: true } : {}
|
|
1413
|
-
},
|
|
1414
|
-
signal
|
|
1415
|
-
});
|
|
1416
|
-
return { ok: true };
|
|
1417
|
-
},
|
|
1418
|
-
async label(caller, { id, set, unset, if: expected }, signal) {
|
|
1419
|
-
checkCaller("label", caller);
|
|
1420
|
-
const who = whoOf(caller);
|
|
1421
|
-
const at = locate(id);
|
|
1422
|
-
if (!at) throw notFound(`message not found: ${id}`, "message_not_found");
|
|
1423
|
-
const access = accessOf(caller);
|
|
1424
|
-
if (access) need(access, "label", (await readableMessage(who, access, id, signal)).channel.name);
|
|
1425
|
-
await api(who, "POST", await onBoard(who, `/threads/${encodeURIComponent(at.threadId)}/messages/${at.sequence}/labels`), {
|
|
1426
|
-
body: {
|
|
1427
|
-
operationId: operationId(),
|
|
1428
|
-
...set ? { set } : {},
|
|
1429
|
-
...unset ? { unset } : {},
|
|
1430
|
-
...expected && Object.keys(expected).length ? { if: expected } : {}
|
|
1431
|
-
},
|
|
1432
|
-
signal
|
|
1433
|
-
});
|
|
1434
|
-
return { ok: true };
|
|
1435
|
-
},
|
|
1436
|
-
async grants(caller, _input, signal) {
|
|
1437
|
-
checkCaller("grants", caller);
|
|
1438
|
-
const who = whoOf(caller);
|
|
1439
|
-
return api(who, "GET", await onBoard(who, "/grants"), signal ? { signal } : {});
|
|
1440
|
-
},
|
|
1441
|
-
async createGrant(caller, input, signal) {
|
|
1442
|
-
checkCaller("createGrant", caller);
|
|
1443
|
-
const who = whoOf(caller);
|
|
1444
|
-
return api(who, "POST", await onBoard(who, "/grants"), {
|
|
1445
|
-
body: {
|
|
1446
|
-
operationId: operationId(),
|
|
1447
|
-
...input
|
|
1448
|
-
},
|
|
1449
|
-
...signal ? { signal } : {}
|
|
1450
|
-
});
|
|
1451
|
-
},
|
|
1452
|
-
async revokeGrant(caller, { id }, signal) {
|
|
1453
|
-
checkCaller("revokeGrant", caller);
|
|
1454
|
-
const who = whoOf(caller);
|
|
1455
|
-
return api(who, "POST", await onBoard(who, `/grants/${encodeURIComponent(id)}/revoke`), {
|
|
1456
|
-
body: { operationId: operationId() },
|
|
1457
|
-
...signal ? { signal } : {}
|
|
1458
|
-
});
|
|
1459
|
-
},
|
|
1460
|
-
async tokens(caller, _input, signal) {
|
|
1461
|
-
checkCaller("tokens", caller);
|
|
1462
|
-
const who = whoOf(caller);
|
|
1463
|
-
return api(who, "GET", await onBoard(who, "/tokens"), signal ? { signal } : {});
|
|
1464
|
-
},
|
|
1465
|
-
async createToken(caller, input, signal) {
|
|
1466
|
-
checkCaller("createToken", caller);
|
|
1467
|
-
const who = whoOf(caller);
|
|
1468
|
-
return api(who, "POST", await onBoard(who, "/tokens"), {
|
|
1469
|
-
body: {
|
|
1470
|
-
operationId: operationId(),
|
|
1471
|
-
...input
|
|
1472
|
-
},
|
|
1473
|
-
...signal ? { signal } : {}
|
|
1474
|
-
});
|
|
1475
|
-
},
|
|
1476
|
-
async revokeToken(caller, { id }, signal) {
|
|
1477
|
-
checkCaller("revokeToken", caller);
|
|
1478
|
-
const who = whoOf(caller);
|
|
1479
|
-
return api(who, "POST", await onBoard(who, `/tokens/${encodeURIComponent(id)}/revoke`), {
|
|
1480
|
-
body: { operationId: operationId() },
|
|
1481
|
-
...signal ? { signal } : {}
|
|
1482
|
-
});
|
|
1483
|
-
},
|
|
1484
|
-
async schedule(caller, input, signal) {
|
|
1485
|
-
if (input.attachments?.length) throw notSupported("files on scheduled messages");
|
|
1486
|
-
const who = whoOf(caller);
|
|
1487
|
-
await checkOwner("schedule", caller, who);
|
|
1488
|
-
const access = accessOf(caller);
|
|
1489
|
-
const labels = input.labels && Object.keys(input.labels).length ? input.labels : void 0;
|
|
1490
|
-
let target;
|
|
1491
|
-
if (input.channel !== void 0) {
|
|
1492
|
-
need(access, "post", input.channel);
|
|
1493
|
-
if (labels) need(access, "label", input.channel);
|
|
1494
|
-
target = { channelId: (await channelToPost(who, input.channel)).id };
|
|
1495
|
-
} else {
|
|
1496
|
-
if (labels) throw notSupported("labels on a scheduled reply");
|
|
1497
|
-
const { thread, channel } = await readableMessage(who, access, input.re, signal);
|
|
1498
|
-
need(access, "post", channel.name);
|
|
1499
|
-
target = { threadId: thread.id };
|
|
1500
|
-
}
|
|
1501
|
-
const ms = (value) => Math.round(duration(value));
|
|
1502
|
-
const firstAt = input.at !== void 0 ? Date.parse(input.at) : Date.now() + ms(input.in ?? input.every);
|
|
1503
|
-
const until = input.until !== void 0 ? Date.parse(input.until) : input.for !== void 0 ? firstAt + ms(input.for) : void 0;
|
|
1504
|
-
const { schedule } = await api(who, "POST", await onBoard(who, "/schedules"), {
|
|
1505
|
-
body: {
|
|
1506
|
-
operationId: operationId(),
|
|
1507
|
-
...target,
|
|
1508
|
-
text: input.text,
|
|
1509
|
-
...labels ? { labels } : {},
|
|
1510
|
-
firstAt,
|
|
1511
|
-
...input.every !== void 0 ? { every: ms(input.every) } : {},
|
|
1512
|
-
...until !== void 0 ? { until } : {},
|
|
1513
|
-
...input.times !== void 0 ? { times: input.times } : {}
|
|
1514
|
-
},
|
|
1515
|
-
signal
|
|
1516
|
-
});
|
|
1517
|
-
return { schedule: await scheduleView(who, schedule) };
|
|
1518
|
-
},
|
|
1519
|
-
async schedules(caller, query, signal) {
|
|
1520
|
-
const who = whoOf(caller);
|
|
1521
|
-
const access = accessOf(caller);
|
|
1522
|
-
const filter = { state: query.all ? void 0 : "pending" };
|
|
1523
|
-
if (query.re !== void 0) {
|
|
1524
|
-
const found = await readableMessage(who, access, query.re, signal).catch((error) => {
|
|
1525
|
-
if (error instanceof HttpError && error.status === 404) return null;
|
|
1526
|
-
throw error;
|
|
1527
|
-
});
|
|
1528
|
-
if (!found) return { schedules: [] };
|
|
1529
|
-
filter.threadId = found.thread.id;
|
|
1530
|
-
}
|
|
1531
|
-
if (query.channel !== void 0) {
|
|
1532
|
-
const channel = await channelNamed(who, query.channel);
|
|
1533
|
-
if (!channel) return { schedules: [] };
|
|
1534
|
-
filter.channelId = channel.id;
|
|
1535
|
-
}
|
|
1536
|
-
const me = query.by === "me" ? await actorOf(who) : void 0;
|
|
1537
|
-
const by = me ?? query.by;
|
|
1538
|
-
if (by?.startsWith("vercel:")) filter.createdBy = by;
|
|
1539
|
-
const created = (actor) => by === void 0 || (me ? actor.id === me : [
|
|
1540
|
-
actor.id,
|
|
1541
|
-
principalId(actor.principal),
|
|
1542
|
-
actor.profile?.name
|
|
1543
|
-
].includes(by));
|
|
1544
|
-
const listed = await all(who, await onBoard(who, "/schedules"), "schedules", filter, signal);
|
|
1545
|
-
return { schedules: (await Promise.all(listed.filter((schedule) => created(schedule.createdBy)).map((schedule) => scheduleView(who, schedule)))).filter((schedule) => access === null || access.readable(schedule.channel)) };
|
|
1546
|
-
},
|
|
1547
|
-
async cancelSchedule(caller, { id }, signal) {
|
|
1548
|
-
const who = whoOf(caller);
|
|
1549
|
-
await checkOwner("cancelSchedule", caller, who);
|
|
1550
|
-
const access = accessOf(caller);
|
|
1551
|
-
if (access) {
|
|
1552
|
-
const found = (await all(who, await onBoard(who, "/schedules"), "schedules", {}, signal)).find((schedule) => schedule.id === id);
|
|
1553
|
-
const channel = found && await channelById(who, found.channelId);
|
|
1554
|
-
if (!channel || !access.readable(channel.name)) throw notFound(`no schedule: ${id}`, "schedule_not_found");
|
|
1555
|
-
need(access, "post", channel.name);
|
|
1556
|
-
}
|
|
1557
|
-
const { schedule, canceled } = await api(who, "POST", await onBoard(who, `/schedules/${encodeURIComponent(id)}/cancel`), {
|
|
1558
|
-
body: { operationId: operationId() },
|
|
1559
|
-
signal
|
|
1560
|
-
});
|
|
1561
|
-
return {
|
|
1562
|
-
schedule: await scheduleView(who, schedule),
|
|
1563
|
-
canceled
|
|
1564
|
-
};
|
|
1565
|
-
},
|
|
1566
|
-
async events(caller, query, signal) {
|
|
1567
|
-
checkCaller("events", caller);
|
|
1568
|
-
const who = whoOf(caller);
|
|
1569
|
-
const access = accessOf(caller);
|
|
1570
|
-
const channel = await oneChannel(who, access, query);
|
|
1571
|
-
if (channel) return channelEvents(who, channel, query, signal);
|
|
1572
|
-
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`);
|
|
1573
|
-
const listed = await channelsFor(who, query.channel, access);
|
|
1574
|
-
let position = query.after === void 0 ? {
|
|
1575
|
-
t: Date.now(),
|
|
1576
|
-
feeds: await heads(who, listed)
|
|
1577
|
-
} : locate(query.after) ? {
|
|
1578
|
-
t: await timeOf(who, query.after),
|
|
1579
|
-
feeds: {}
|
|
1580
|
-
} : positionOf(query.after);
|
|
1581
|
-
const until = Date.now() + (query.wait ?? 0) * 1e3;
|
|
1582
|
-
for (;;) {
|
|
1583
|
-
const page = await read(who, listed, position, query, signal);
|
|
1584
|
-
position = page.position;
|
|
1585
|
-
if (page.events.length > 0 || Date.now() >= until || signal.aborted) return {
|
|
1586
|
-
events: page.events,
|
|
1587
|
-
cursor: cursorOf(position)
|
|
1588
|
-
};
|
|
1589
|
-
await new Promise((resolve) => setTimeout(resolve, Math.min(1e3, until - Date.now())));
|
|
1590
|
-
}
|
|
1591
|
-
},
|
|
1592
|
-
async typing() {
|
|
1593
|
-
return { targets: [] };
|
|
1594
|
-
},
|
|
1595
|
-
async readSource(_caller, { key }) {
|
|
1596
|
-
throw notFound(`this board doesn't run sync entry ${key}`, "not_synced_here");
|
|
1597
|
-
},
|
|
1598
|
-
async watchers(caller) {
|
|
1599
|
-
ownWatchers(caller, "list watchers");
|
|
1600
|
-
const who = whoOf(caller);
|
|
1601
|
-
const { watchers } = await api(who, "GET", await onBoard(who, "/watchers"));
|
|
1602
|
-
return { watchers: await Promise.all(watchers.map(async (found) => ({
|
|
1603
|
-
owner: found.owner,
|
|
1604
|
-
...whereOf(found),
|
|
1605
|
-
watch: Object.fromEntries(await Promise.all(Object.entries(found.watch).map(async ([id, spec]) => [id, {
|
|
1606
|
-
tail: await tailOf(who, spec),
|
|
1607
|
-
when: spec.when
|
|
1608
|
-
}]))),
|
|
1609
|
-
sync: [],
|
|
1610
|
-
hash: found.hash
|
|
1611
|
-
}))) };
|
|
1612
|
-
},
|
|
1613
|
-
async register(caller, body) {
|
|
1614
|
-
ownWatchers(caller, "register watchers");
|
|
1615
|
-
if ((body.sync?.length ?? 0) > 0) throw notSupported("sync");
|
|
1616
|
-
return registerAs(whoOf(caller), typeof body.path === "string" ? {
|
|
1617
|
-
path: body.path,
|
|
1618
|
-
...body.branch ? { branch: body.branch } : {}
|
|
1619
|
-
} : { url: body.url ?? null }, body.watch);
|
|
1620
|
-
},
|
|
1621
|
-
async matches(caller, query, signal) {
|
|
1622
|
-
ownWatchers(caller, "pull matches");
|
|
1623
|
-
return { matches: await pullAs(whoOf(caller), query, signal) };
|
|
1624
|
-
},
|
|
1625
|
-
async ack(caller, { id, ...body }) {
|
|
1626
|
-
ownWatchers(caller, "ack matches");
|
|
1627
|
-
await ackAs(whoOf(caller), id, body);
|
|
1628
|
-
return { ok: true };
|
|
1629
|
-
}
|
|
1630
|
-
};
|
|
1631
|
-
return {
|
|
1632
|
-
...Object.fromEntries(Object.entries(methods).map(([name, method]) => [name, (...args) => {
|
|
1633
|
-
if (binding) runner.start();
|
|
1634
|
-
return method(...args);
|
|
1635
|
-
}])),
|
|
1636
|
-
routes: runner.routes,
|
|
1637
|
-
keeps: false,
|
|
1638
|
-
sendsSchedulesHere: false,
|
|
1639
|
-
bind(next) {
|
|
1640
|
-
if (binding) throw new Error("vercel: this backend already serves a board: create one vercel() per board()");
|
|
1641
|
-
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");
|
|
1642
|
-
for (const id of Object.keys(next.subscriptions)) own.add(id);
|
|
1643
|
-
tails = Object.fromEntries(Object.entries(next.subscriptions).flatMap(([id, subscription]) => subscription.kind === "tail" ? [[id, {
|
|
1644
|
-
tail: subscription.tail,
|
|
1645
|
-
when: subscription.when
|
|
1646
|
-
}]] : []));
|
|
1647
|
-
binding = next;
|
|
1648
|
-
},
|
|
1649
|
-
/** Registers this board's watchers with Vercel's API now, as `POST /watchers` does. */
|
|
1650
|
-
registerWatchers: runner.registerNow,
|
|
1651
|
-
/** Stops pulling, for a board that pulls on its own. */
|
|
1652
|
-
close: runner.close
|
|
1653
|
-
};
|
|
1654
|
-
}
|
|
1655
|
-
//#endregion
|
|
1656
|
-
export { createVercel as t };
|