@vercel/board 0.42.0 → 0.42.1
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/dist/backend-local.mjs +1 -1
- package/dist/cli-commands.d.mts +1 -1
- package/dist/cli-commands.mjs +1 -1
- package/dist/cli-embedded.mjs +4 -4
- package/dist/cli.mjs +5 -5
- package/dist/{commands-CrEVjASe.d.mts → commands-BlM-ckFS.d.mts} +3 -3
- package/dist/{commands-QRD0U9AQ.mjs → commands-DeEJJw3i.mjs} +3 -3
- package/dist/digest-dm54M2k8.mjs +4 -0
- package/dist/{exports-BfNXPHN_.mjs → exports-kDMIgZVu.mjs} +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.node.mjs +1 -1
- package/dist/inspect/app.js +1 -1
- package/dist/inspect-CNW1rLWB.mjs +2 -0
- package/dist/{inspect-CniRRiJ2.mjs → inspect-CqCXjtPI.mjs} +5 -5
- package/dist/{local-CWLPYoiY.mjs → local-DsJ14yqg.mjs} +1 -1
- package/dist/{main-aVEEoc60.mjs → main-C4HVA8cc.mjs} +41 -9
- package/dist/{origin-DAyYeDuW.mjs → origin-Cuu8lW8n.mjs} +2 -2
- package/dist/page-BPTzCBeW.mjs +2 -0
- package/dist/{page-BD6ygU49.mjs → page-CnjVt5w2.mjs} +2 -2
- package/dist/{serve-BnBqi0sw.mjs → serve-BmabgHV-.mjs} +2 -2
- package/dist/{server-Bcpkt6TS.mjs → server-CKbE7eMT.mjs} +2 -3
- package/docs/04-reference/01-cli.md +0 -2
- package/docs/04-reference/02-board.md +0 -1
- package/package.json +1 -1
- package/dist/digest-CKC0Rmy1.mjs +0 -4
- package/dist/inspect-HlHh7OXa.mjs +0 -2
- package/dist/page-BiJVe-7R.mjs +0 -2
package/dist/backend-local.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as local } from "./local-
|
|
1
|
+
import { t as local } from "./local-DsJ14yqg.mjs";
|
|
2
2
|
export { local };
|
package/dist/cli-commands.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as OptionName, c as globalOptions, d as options, f as usage, i as CliOption, l as groups, n as CliCommand, o as commands, r as CliExample, s as filters, t as CliArgument, u as option } from "./commands-
|
|
1
|
+
import { a as OptionName, c as globalOptions, d as options, f as usage, i as CliOption, l as groups, n as CliCommand, o as commands, r as CliExample, s as filters, t as CliArgument, u as option } from "./commands-BlM-ckFS.mjs";
|
|
2
2
|
export { CliArgument, CliCommand, CliExample, CliOption, OptionName, commands, filters, globalOptions, groups, option, options, usage };
|
package/dist/cli-commands.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as option, i as groups, n as filters, o as options, r as globalOptions, s as usage, t as commands } from "./commands-
|
|
1
|
+
import { a as option, i as groups, n as filters, o as options, r as globalOptions, s as usage, t as commands } from "./commands-DeEJJw3i.mjs";
|
|
2
2
|
export { commands, filters, globalOptions, groups, option, options, usage };
|
package/dist/cli-embedded.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { h as VERSION } from "./origin-
|
|
2
|
-
import { r as stoppedBy } from "./exports-
|
|
3
|
-
import { a as commandLine, c as failureLines, i as mainWith, l as formatFailure, n as commandWord, o as exitCode, r as main, s as failureDocument, t as Failed } from "./main-
|
|
4
|
-
import { t as PAGE_SHA256 } from "./digest-
|
|
1
|
+
import { h as VERSION } from "./origin-Cuu8lW8n.mjs";
|
|
2
|
+
import { r as stoppedBy } from "./exports-kDMIgZVu.mjs";
|
|
3
|
+
import { a as commandLine, c as failureLines, i as mainWith, l as formatFailure, n as commandWord, o as exitCode, r as main, s as failureDocument, t as Failed } from "./main-C4HVA8cc.mjs";
|
|
4
|
+
import { t as PAGE_SHA256 } from "./digest-dm54M2k8.mjs";
|
|
5
5
|
//#region src/cli/embedded.ts
|
|
6
6
|
/**
|
|
7
7
|
* The inspector's page as this version of board's npm package has it, for an app that bundles
|
package/dist/cli.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { a as option } from "./commands-
|
|
3
|
-
import { f as projectDir } from "./server-
|
|
4
|
-
import { r as main } from "./main-
|
|
5
|
-
import { n as stopped, r as startInspector } from "./inspect-
|
|
2
|
+
import { a as option } from "./commands-DeEJJw3i.mjs";
|
|
3
|
+
import { f as projectDir } from "./server-CKbE7eMT.mjs";
|
|
4
|
+
import { r as main } from "./main-C4HVA8cc.mjs";
|
|
5
|
+
import { n as stopped, r as startInspector } from "./inspect-CqCXjtPI.mjs";
|
|
6
6
|
import { appendFile, readFile } from "node:fs/promises";
|
|
7
7
|
import { join } from "node:path";
|
|
8
8
|
//#region src/cli/local.ts
|
|
@@ -36,7 +36,7 @@ const local = { serve: {
|
|
|
36
36
|
if (args.length > 0) throw usage("serve takes no arguments: pass its port with --port, and its directory with --dir.");
|
|
37
37
|
const port = portFlag();
|
|
38
38
|
const root = projectDir();
|
|
39
|
-
const { serveLocal } = await import("./serve-
|
|
39
|
+
const { serveLocal } = await import("./serve-BmabgHV-.mjs");
|
|
40
40
|
const local = await serveLocal({
|
|
41
41
|
dir: flags.dir ?? join(root, ".board"),
|
|
42
42
|
...port !== void 0 ? { port } : {}
|
|
@@ -288,7 +288,7 @@ declare const options: {
|
|
|
288
288
|
readonly app: {
|
|
289
289
|
readonly type: 'string';
|
|
290
290
|
readonly multiple: true;
|
|
291
|
-
readonly value: '
|
|
291
|
+
readonly value: 'app';
|
|
292
292
|
readonly description: 'an app installed on the team';
|
|
293
293
|
};
|
|
294
294
|
readonly 'all-apps': {
|
|
@@ -365,7 +365,7 @@ declare const options: {
|
|
|
365
365
|
readonly 'add-app': {
|
|
366
366
|
readonly type: 'string';
|
|
367
367
|
readonly multiple: true;
|
|
368
|
-
readonly value: '
|
|
368
|
+
readonly value: 'app';
|
|
369
369
|
readonly description: 'add an app';
|
|
370
370
|
};
|
|
371
371
|
readonly 'add-all-apps': {
|
|
@@ -411,7 +411,7 @@ declare const options: {
|
|
|
411
411
|
readonly 'remove-app': {
|
|
412
412
|
readonly type: 'string';
|
|
413
413
|
readonly multiple: true;
|
|
414
|
-
readonly value: '
|
|
414
|
+
readonly value: 'app';
|
|
415
415
|
readonly description: 'remove an app';
|
|
416
416
|
};
|
|
417
417
|
readonly 'remove-all-apps': {
|
|
@@ -238,7 +238,7 @@ const options = {
|
|
|
238
238
|
app: {
|
|
239
239
|
type: "string",
|
|
240
240
|
multiple: true,
|
|
241
|
-
value: "
|
|
241
|
+
value: "app",
|
|
242
242
|
description: "an app installed on the team"
|
|
243
243
|
},
|
|
244
244
|
"all-apps": {
|
|
@@ -315,7 +315,7 @@ const options = {
|
|
|
315
315
|
"add-app": {
|
|
316
316
|
type: "string",
|
|
317
317
|
multiple: true,
|
|
318
|
-
value: "
|
|
318
|
+
value: "app",
|
|
319
319
|
description: "add an app"
|
|
320
320
|
},
|
|
321
321
|
"add-all-apps": {
|
|
@@ -361,7 +361,7 @@ const options = {
|
|
|
361
361
|
"remove-app": {
|
|
362
362
|
type: "string",
|
|
363
363
|
multiple: true,
|
|
364
|
-
value: "
|
|
364
|
+
value: "app",
|
|
365
365
|
description: "remove an app"
|
|
366
366
|
},
|
|
367
367
|
"remove-all-apps": {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { _ as IMPORT_BYTES_MAX, a as forbidden, b as mediaType, c as toErrorResponse, d as createBoardClient, f as duration, h as ATTACHMENT_BYTES_MAX, l as unauthorized, n as RejectedError, o as json, p as formatProfileHeader, r as badRequest, s as notFound, t as HttpError, u as BoardError, v as fileName } from "./errors-DUzpDSrJ.mjs";
|
|
2
2
|
import { h as RemoteWatcherId } from "./schemas-DAzSsgWk.mjs";
|
|
3
3
|
import { f as schemaId, n as blocksIn, r as findBlocks } from "./blocks-CVoBC7ur.mjs";
|
|
4
|
-
import { A as MessagesQuery, B as SyncBody, C as InboxAckBody, D as LabelBody, E as InboxQuery, F as ScheduleBody, G as ThreadsQuery, H as SyncFindQuery, I as SchedulesQuery, J as UploadStartBody, K as TypingBody, L as SchemaBody, M as ReactBody, N as Ref, O as LinkedQuery, P as RegisterBody, R as SourceJoinBody, S as GrantBody, T as InboxPushBody, U as SyncImportBody, V as SyncCopiesQuery, W as SyncReceiptBody, Y as routes, _ as CreateChannelBody, a as compileWatcher, b as EventsQuery, c as METHODS, d as queryObject, f as readCapped, g as AckBody, h as VERSION, i as runMatch, j as PostBody, k as MatchesQuery, l as createRouter, m as SYNC, n as syncTarget, p as readJson, q as UpdateGrantBody, r as canonicalWatchers, t as SYNC_ACTOR, u as openapi, v as DeleteBody, w as InboxNextQuery, x as ExplainQuery, y as EditBody, z as SourceReadQuery } from "./origin-
|
|
4
|
+
import { A as MessagesQuery, B as SyncBody, C as InboxAckBody, D as LabelBody, E as InboxQuery, F as ScheduleBody, G as ThreadsQuery, H as SyncFindQuery, I as SchedulesQuery, J as UploadStartBody, K as TypingBody, L as SchemaBody, M as ReactBody, N as Ref, O as LinkedQuery, P as RegisterBody, R as SourceJoinBody, S as GrantBody, T as InboxPushBody, U as SyncImportBody, V as SyncCopiesQuery, W as SyncReceiptBody, Y as routes, _ as CreateChannelBody, a as compileWatcher, b as EventsQuery, c as METHODS, d as queryObject, f as readCapped, g as AckBody, h as VERSION, i as runMatch, j as PostBody, k as MatchesQuery, l as createRouter, m as SYNC, n as syncTarget, p as readJson, q as UpdateGrantBody, r as canonicalWatchers, t as SYNC_ACTOR, u as openapi, v as DeleteBody, w as InboxNextQuery, x as ExplainQuery, y as EditBody, z as SourceReadQuery } from "./origin-Cuu8lW8n.mjs";
|
|
5
5
|
import { _ as sha256, a as waitUntil, c as platformProfile, d as userIdOf, m as derivedId, o as actorParts, r as runMiddleware, s as importedHandle, t as DroppedError, u as underPrincipal } from "./middleware-0DUFrav-.mjs";
|
|
6
6
|
import { a as canText, c as compileAccess, d as parsePattern, n as InvalidCan, r as PERMISSIONS, t as FULL_ACCESS, u as parseCan } from "./access-BgBiaCyx.mjs";
|
|
7
7
|
import { C as explainGrants, b as verifiesTokens, d as grantIssuers, f as hostPrincipal, i as VERCEL_ISSUER, l as createAuthority, t as DEFAULT_CAN$1, u as fromTokens, y as verifiedIssuers } from "./auth-Ft4AJptx.mjs";
|
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { f as duration, t as HttpError, u as BoardError } from "./errors-DUzpDSrJ.mjs";
|
|
2
2
|
import { t as block } from "./blocks-CVoBC7ur.mjs";
|
|
3
3
|
import { t as DroppedError } from "./middleware-0DUFrav-.mjs";
|
|
4
|
-
import { i as createVercel, t as createBoard } from "./exports-
|
|
4
|
+
import { i as createVercel, t as createBoard } from "./exports-kDMIgZVu.mjs";
|
|
5
5
|
//#region src/backend-vercel/index.default.ts
|
|
6
6
|
/**
|
|
7
7
|
* Your team's board, in Vercel's API. Outside Node there's no environment to find credentials or
|
package/dist/index.node.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { f as duration, t as HttpError, u as BoardError } from "./errors-DUzpDSrJ.mjs";
|
|
2
2
|
import { t as block } from "./blocks-CVoBC7ur.mjs";
|
|
3
3
|
import { t as DroppedError } from "./middleware-0DUFrav-.mjs";
|
|
4
|
-
import { t as board } from "./server-
|
|
4
|
+
import { t as board } from "./server-CKbE7eMT.mjs";
|
|
5
5
|
export { BoardError, DroppedError, HttpError, block, board, duration };
|
package/dist/inspect/app.js
CHANGED
|
@@ -342,7 +342,7 @@ function as(e,t){let n=/* @__PURE__ */ os(t=>(t.addIssue=e=>{if(typeof e==`strin
|
|
|
342
342
|
function os(e,t){let n=new Ir({check:`custom`,...U(t)});return n._zod.check=e,n}function ss(e,...t){for(let n of t)for(let t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&yt(e,t,n[t]);return e}function cs(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??$a,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:/* @__PURE__ */ new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,intersections:[],deferred:[],external:e?.external??void 0}}function ls(e,t,n,r,i){let a=typeof t.unrepresentable==`function`?t.unrepresentable({zodSchema:e,path:r.path,message:i}):t.unrepresentable;if(a===`any`)return!1;if(a===void 0||a===`throw`)throw Error(i);return Object.assign(n,a),!0}function us(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,us(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&ss(o.schema,c),t.io===`input`&&bs(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function ds(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function fs(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=/* @__PURE__ */ new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${ds(a)}`}}let i=`#/${r}/`;if(t[1]===n&&!t[1].schema.id)return{ref:`#`};let a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+ds(a)}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
|
|
343
343
|
|
|
344
344
|
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}r.count>1&&e.reused===`ref`&&a(n)}e.external&&(e.sharedDefsExtractedFor=e.external)}function ps(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let e of t){if(!e||typeof e!=`object`)return;ps(e);let t=Object.keys(e);if(t.length!==1||t[0]!==`type`)return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if(typeof e!=`string`)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=n.length===1?n[0]:n}const ms=/* @__PURE__ */ new Set([`type`,`properties`,`required`,`additionalProperties`]),hs=[`oneOf`,`anyOf`];function gs(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function _s(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!ms.has(e))return null;t.push(n)}let n={},r=/* @__PURE__ */ new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??gs(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}yt(n,r,e.length===1?e[0]:_s(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:`object`,properties:n};if(r.size&&(i.required=[...r]),t.every(e=>e.additionalProperties===!1))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=gs(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}e.length===1?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function vs(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of ms)if(t in e)return;let n=t.filter(e=>hs.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=_s(t);else{let e=n[0],i=hs.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;let a=t.filter(t=>t!==e),o=e[i].map(e=>_s([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,ss(e,r))}function ys(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):ss(i,s),ss(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())r(t[0]);if(e.target!==`openapi-3.0`)for(let t of e.seen.entries())ps(t[1].def??t[1].schema);for(let t of e.deferred)t();if(e.intersections.length){let t=/* @__PURE__ */ new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])vs(e)}}let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}ss(i,n.defId?n.schema:n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,yt(o,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:Ss(t,`input`,e.processors),output:Ss(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function bs(e,t){let n=t??{seen:/* @__PURE__ */ new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return bs(r.element,n);if(r.type===`set`)return bs(r.valueType,n);if(r.type===`lazy`)return bs(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`||r.type===`catch`)return bs(r.innerType,n);if(r.type===`intersection`)return bs(r.left,n)||bs(r.right,n);if(r.type===`record`||r.type===`map`)return bs(r.keyType,n)||bs(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:bs(r.in,n)||bs(r.out,n);if(r.type===`object`){for(let e in r.shape)if(bs(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(bs(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(bs(e,n))return!0;return!!(r.rest&&bs(r.rest,n))}return!1}const xs=(e,t={})=>n=>{let r=cs({...n,processors:t});return us(e,r),fs(r,e),ys(r,e)},Ss=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=cs({...i??{},target:a,io:t,processors:n});return us(e,o),fs(o,e),ys(o,e)},Cs=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},ws=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},Ts=(e,t)=>{Cs(e,`minimum`,t),ws(e,`maximum`,t)},Es=(e,t)=>{e.multipleOf??=[],e.multipleOf.includes(t)||e.multipleOf.push(t)},Ds=(e,t)=>{e.patterns??=/* @__PURE__ */ new Set,e.patterns.add(t)},Os=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},ks=(e,t)=>{e.format=t,t.includes(`int`)&&(e.isInt=!0)},As=(e,t)=>Cs(e,`minimum`,t.minimum),js=(e,t)=>ws(e,`maximum`,t.maximum),Ms=e=>(t,n)=>{ks(t,n.format);let[r,i]=e[n.format];Cs(t,`minimum`,r),ws(t,`maximum`,i)},Ns={greater_than:(e,t)=>Cs(e,t.inclusive?`minimum`:`exclusiveMinimum`,t.value),less_than:(e,t)=>ws(e,t.inclusive?`maximum`:`exclusiveMaximum`,t.value),multiple_of:(e,t)=>Es(e,t.value),number_format:Ms(zt),bigint_format:Ms(Bt),min_length:As,max_length:js,length_equals:(e,t)=>Ts(e,t.length),min_size:As,max_size:js,size_equals:(e,t)=>Ts(e,t.size),string_format:(e,t)=>{ks(e,t.format),t.pattern&&Ds(e,t.pattern),(t.format===`base64`||t.format===`base64url`)&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>Os(e,t.mime)};function Ps(e){let t={},n=e._zod.def,r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(let e of r)Ns[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;i.minimum!==void 0&&Cs(t,`minimum`,i.minimum),i.exclusiveMinimum!==void 0&&Cs(t,`exclusiveMinimum`,i.exclusiveMinimum),i.maximum!==void 0&&ws(t,`maximum`,i.maximum),i.exclusiveMaximum!==void 0&&ws(t,`exclusiveMaximum`,i.exclusiveMaximum),i.multipleOf!==void 0&&Es(t,i.multipleOf),i.format!==void 0&&(t.format??=i.format,i.format.includes(`int`)&&(t.isInt=!0)),i.mime&&Os(t,i.mime);for(let e of i.patterns??[])Ds(t,e);return t}const Fs={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Is=/* @__PURE__ */ new Map([[Ri,yr],[Bi,br]]),Ls=e=>Is.get(e)??e,Rs=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=Ps(e);if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Fs[s]??s,i.format===``&&delete i.format,(s===`time`||u)&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c].map(Ls);e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},zs=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=Ps(e);i.type=u?`integer`:`number`;let d=typeof l==`number`&&l>=(a??-1/0),f=typeof c==`number`&&c<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;if(d?p?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:typeof o==`number`&&(i.maximum=o),s){let n=/* @__PURE__ */ new Set;for(let a of s)Number.isFinite(a)&&a!==0?n.add(Math.abs(a)):ls(e,t,i,r,`A multipleOf divisor of ${a} cannot be represented in JSON Schema`);let[a,...o]=n;a!==void 0&&(i.multipleOf=a),o.length&&(i.allOf=[...i.allOf??[],...o.map(e=>({multipleOf:e}))])}},Bs=(e,t,n,r)=>{n.type=`boolean`},Vs=(e,t,n,r)=>{ls(e,t,n,r,`BigInt cannot be represented in JSON Schema`)},Hs=(e,t,n,r)=>{ls(e,t,n,r,`Symbols cannot be represented in JSON Schema`)},Us=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},Ws=(e,t,n,r)=>{ls(e,t,n,r,`Undefined cannot be represented in JSON Schema`)},Gs=(e,t,n,r)=>{ls(e,t,n,r,`Void cannot be represented in JSON Schema`)},Ks=(e,t,n,r)=>{n.not={}},qs=(e,t,n,r)=>{},Js=(e,t,n,r)=>{},Ys=(e,t,n,r)=>{ls(e,t,n,r,`Date cannot be represented in JSON Schema`)},Xs=(e,t,n,r)=>{let i=e._zod.def,a=H(i.entries);if(a.length===0){n.not={};return}a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},Zs=(e,t,n,r)=>{let i=e._zod.def;if(i.values.length===0){n.not={};return}let a=[];for(let o of i.values)if(o===void 0){if(ls(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o==`bigint`){if(ls(e,t,n,r,`BigInt literals cannot be represented in JSON Schema`))return;a.push(Number(o))}else a.push(o);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},Qs=(e,t,n,r)=>{ls(e,t,n,r,`NaN cannot be represented in JSON Schema`)},$s=(e,t,n,r)=>{let i=n,a=e._zod.pattern;if(!a)throw Error(`Pattern not found in template literal`);i.type=`string`,i.pattern=a.source},ec=(e,t,n,r)=>{let i=n;i.type=`string`,i.format=`binary`,i.contentEncoding=`binary`;let{minimum:a,maximum:o,mime:s}=Ps(e);a!==void 0&&(i.minLength=a),o!==void 0&&(i.maxLength=o),s&&(s.length===0?i.not={}:s.length===1?i.contentMediaType=s[0]:i.anyOf=s.map(e=>({contentMediaType:e})))},tc=(e,t,n,r)=>{n.type=`boolean`},nc=(e,t,n,r)=>{ls(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},rc=(e,t,n,r)=>{ls(e,t,n,r,`Function types cannot be represented in JSON Schema`)},ic=(e,t,n,r)=>{ls(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},ac=(e,t,n,r)=>{ls(e,t,n,r,`Map cannot be represented in JSON Schema`)},oc=(e,t,n,r)=>{ls(e,t,n,r,`Set cannot be represented in JSON Schema`)},sc=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=Ps(e);typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=us(a.element,t,{...r,path:[...r.path,`items`]})};function cc(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?cc(t.out):t.type===`catch`?cc(t.innerType):e._zod.optin}const lc=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&ls(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)yt(i.properties,e,us(o[e],t,{...r,path:[...r.path,`properties`,e]}));let s=[];for(let e of Object.keys(o)){let n=a.shape[e];(t.io===`input`?cc(n)===void 0:n._zod.optout===void 0)&&s.push(e)}s.length>0&&(i.required=s),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=us(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},uc=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>us(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},dc=(e,t,n,r)=>{let i=e._zod.def,a=us(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=us(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];n.allOf=c,t.intersections.push(c)},fc=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>us(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?us(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null,u=a.items.length;for(;u>0;){let e=a.items[u-1];if(!(t.io===`input`?cc(e)!==void 0:e._zod.optout===`optional`))break;u--}let d=a.items.length,f=!a.rest;t.target===`draft-2020-12`?(i.prefixItems=c,f?i.items=!1:l&&(i.items=l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):(i.items=c,f?i.additionalItems=!1:l&&(i.additionalItems=l),u>0&&(i.minItems=u),f&&(i.maxItems=d));let{minimum:p,maximum:m}=Ps(e);typeof p==`number`&&(i.minItems=p),typeof m==`number`&&(i.maxItems=m)};function pc(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let r=e.get(t)?.def;if(!r)return t;let i=pc(e,r,n);return i===r?t:i}for(let r of[`anyOf`,`oneOf`]){let i=t[r];if(!Array.isArray(i))continue;let a=i.map(t=>pc(e,t,n));a.some((e,t)=>e!==i[t])&&(t={...t,[r]:a})}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes(`string`)&&r.some(e=>e===`number`||e===`integer`),a=t.enum??(t.const===void 0?void 0:[t.const]);if(!i&&!a?.some(e=>typeof e==`number`))return t;let{minimum:o,maximum:s,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:f,...p}=t;return p.enum?p.enum=p.enum.map(e=>typeof e==`number`?String(e):e):typeof p.const==`number`&&(p.const=String(p.const)),i?(p.type=`string`,a||(p.pattern=(r.includes(`number`)?jr:Ar).source),p):p}const mc=/* @__PURE__ */ new WeakMap;function hc(e){let t=/* @__PURE__ */ new Map;for(let n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);let n=/* @__PURE__ */ new Map;for(let r of mc.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let o=pc(t,a,/* @__PURE__ */ new Set);o!==a&&n.set(a,o)}if(n.size)for(let t of e.seen.values())for(let e of[t.schema,t.def]){let t=e&&n.get(e.propertyNames);t&&(e.propertyNames=t)}}const gc=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=Ps(o).patterns;if(a.mode===`loose`&&s&&s.size>0){let e=us(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)yt(i.patternProperties,Ls(t).source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=us(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=mc.get(t);n||(n=[],mc.set(t,n),t.deferred.push(()=>hc(t))),n.push(e)}i.additionalProperties=us(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let c=o._zod.values,l=t.io===`input`&&cc(a.valueType)!==void 0;if(c&&!a.partial&&!l){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e.map(String))}},_c=(e,t,n,r)=>{let i=e._zod.def,a=us(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},vc=(e,t,n,r)=>{let i=e._zod.def;us(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},yc=Symbol();function bc(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(ls(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),yc):JSON.parse(o)}const xc=(e,t,n,r)=>{let i=e._zod.def;us(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=bc(i.defaultValue,e,t,n,r);o!==yc&&(n.default=o)},Sc=(e,t,n,r)=>{let i=e._zod.def;us(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=bc(i.defaultValue,e,t,n,r);o!==yc&&(n._prefault=o)},Cc=(e,t,n,r)=>{let i=e._zod.def;us(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{ls(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},wc=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;us(o,t,r);let s=t.seen.get(e);s.ref=o},Tc=(e,t,n,r)=>{let i=e._zod.def;us(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},Ec=(e,t,n,r)=>{let i=e._zod.def;us(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Dc=(e,t,n,r)=>{let i=e._zod.def;us(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Oc={string:Rs,number:zs,boolean:Bs,bigint:Vs,symbol:Hs,null:Us,undefined:Ws,void:Gs,never:Ks,any:qs,unknown:Js,date:Ys,enum:Xs,literal:Zs,nan:Qs,template_literal:$s,file:ec,success:tc,custom:nc,function:rc,transform:ic,map:ac,set:oc,array:sc,object:lc,union:uc,intersection:dc,tuple:fc,record:gc,nullable:_c,nonoptional:vc,default:xc,prefault:Sc,catch:Cc,pipe:wc,readonly:Tc,promise:Ec,optional:Dc,lazy:(e,t,n,r)=>{let i=e._zod.innerType;us(i,t,r);let a=t.seen.get(e);a.ref=i}};function kc(e,t){if(`_idmap`in e){let n=e,r=cs({...t,processors:Oc}),i={};for(let e of n._idmap.entries()){let[t,n]=e;us(n,r)}let a={};r.external={registry:n,uri:t?.uri,defs:i};for(let e of n._idmap.entries()){let[t,n]=e;fs(r,n),yt(a,t,ys(r,n))}return Object.keys(i).length>0&&(a.__shared={[r.target===`draft-2020-12`?`$defs`:`definitions`]:i}),{schemas:a}}let n=cs({...t,processors:Oc});return us(e,n),fs(n,e),ys(n,e)}const Ac=/* @__PURE__ */ new WeakSet([Object.prototype,Error.prototype]);function jc(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}const Mc=(e,t)=>{Pn.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);Ac.has(n)||(Ac.add(n),jc(n,`format`,e=>t=>Ln(e,t)),jc(n,`flatten`,e=>t=>In(e,t)),jc(n,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,pt,2)}),jc(n,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,pt,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},Nc=/*@__PURE__*/ W(`ZodError`,Mc),Pc=/*@__PURE__*/ W(`ZodError`,Mc,void 0,{Parent:Error}),Fc=/* @__PURE__ */ zn(Pc),Ic=/* @__PURE__ */ Bn(Pc),Lc=/* @__PURE__ */ Vn(Pc),Rc=/* @__PURE__ */ Un(Pc),zc=/* @__PURE__ */ Yn(Pc),Bc=/* @__PURE__ */ Xn(Pc),Vc=/* @__PURE__ */ Zn(Pc),Hc=/* @__PURE__ */ Qn(Pc),Uc=/* @__PURE__ */ $n(Pc),Wc=/* @__PURE__ */ er(Pc),Gc=/* @__PURE__ */ tr(Pc),Kc=/* @__PURE__ */ nr(Pc);function qc(){En.localeError||Dn(Ya())}function Jc(){En.memoizer||Dn({memoizer:Ka()})}const Yc=/*@__PURE__*/ W(`ZodType`,(e,t)=>(qc(),ni.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(Et(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return It(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(vu(e,t))},superRefine(e,t){return this.check(yu(e,t))},overwrite(e){return this.check(/* @__PURE__ */ Xo(e))},optional(){return $l(this)},exactOptional(){return tu(this)},nullable(){return ru(this)},nullish(){return $l(ru(this))},nonoptional(e){return lu(this,e)},array(){return Fl(this)},or(e){return zl([this,e])},and(e){return Ul(this,e)},transform(e){return pu(this,Zl(e))},default(e){return au(this,e)},prefault(e){return su(this,e)},catch(e){return du(this,e)},pipe(e){return pu(this,e)},readonly(){return hu(this)},describe(e){let t=this.clone();return $a.add(t,{description:e}),t},meta(...e){if(e.length===0)return $a.get(this);let t=this.clone();return $a.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return un(this,`~standard`,{...ai(this),jsonSchema:{input:Ss(this,`input`),output:Ss(this,`output`)}})},set"~standard"(e){ln(this,`~standard`,e)},parse:function e(t,n){return Fc(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await Ic(this,t,n,{callee:e})},safeParse(e,t){return Lc(this,e,t)},async safeParseAsync(e,t){return Rc(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){ln(this,`spa`,e)},validate(e,t){return Kn(this,e,t)},validateAsync(e,t){return Jn(this,e,t)},encode:function e(t,n){return zc(this,t,n,{callee:e})},decode:function e(t,n){return Bc(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await Vc(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await Hc(this,t,n,{callee:e})},safeEncode(e,t){return Uc(this,e,t)},safeDecode(e,t){return Wc(this,e,t)},async safeEncodeAsync(e,t){return Gc(this,e,t)},async safeDecodeAsync(e,t){return Kc(this,e,t)},toJSONSchema(e){return xs(this,{})(e)},get description(){return $a.get(this)?.description},get _def(){return this._zod.def}}),Xc=/*@__PURE__*/ W(`_ZodString`,(e,t)=>{oi.init(e,t),Yc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Rs(e,t,n,r)},/*@__PURE__*/ dn({format:e=>Ps(e).format??null,minLength:e=>Ps(e).minimum??null,maxLength:e=>Ps(e).maximum??null},{regex(...e){return this.check(/* @__PURE__ */ Wo(...e))},includes(...e){return this.check(/* @__PURE__ */ qo(...e))},startsWith(...e){return this.check(/* @__PURE__ */ Jo(...e))},endsWith(...e){return this.check(/* @__PURE__ */ Yo(...e))},min(...e){return this.check(/* @__PURE__ */ Ho(...e))},max(...e){return this.check(/* @__PURE__ */ Vo(...e))},length(...e){return this.check(/* @__PURE__ */ Uo(...e))},nonempty(...e){return this.check(/* @__PURE__ */ Ho(1,...e))},lowercase(e){return this.check(/* @__PURE__ */ Go(e))},uppercase(e){return this.check(/* @__PURE__ */ Ko(e))},trim(){return this.check(/* @__PURE__ */ Qo())},normalize(...e){return this.check(/* @__PURE__ */ Zo(...e))},toLowerCase(){return this.check(/* @__PURE__ */ $o())},toUpperCase(){return this.check(/* @__PURE__ */ es())},slugify(){return this.check(/* @__PURE__ */ ts())}})),Zc=/*@__PURE__*/ W(`ZodString`,(e,t)=>{oi.init(e,t),Xc.init(e,t)},{email(e){return this.check(/* @__PURE__ */ no(rl,e))},url(e){return this.check(/* @__PURE__ */ co(ol,e))},jwt(e){return this.check(/* @__PURE__ */ wo(xl,e))},emoji(e){return this.check(/* @__PURE__ */ lo(sl,e))},guid(e){return this.check(/* @__PURE__ */ ro(il,e))},uuid(e){return this.check(/* @__PURE__ */ io(al,e))},uuidv4(e){return this.check(/* @__PURE__ */ ao(al,e))},uuidv6(e){return this.check(/* @__PURE__ */ oo(al,e))},uuidv7(e){return this.check(/* @__PURE__ */ so(al,e))},nanoid(e){return this.check(/* @__PURE__ */ uo(cl,e))},cuid(e){return this.check(/* @__PURE__ */ fo(ll,e))},cuid2(e){return this.check(/* @__PURE__ */ po(ul,e))},ulid(e){return this.check(/* @__PURE__ */ mo(dl,e))},base64(e){return this.check(/* @__PURE__ */ xo(vl,e))},base64url(e){return this.check(/* @__PURE__ */ So(yl,e))},xid(e){return this.check(/* @__PURE__ */ ho(fl,e))},ksuid(e){return this.check(/* @__PURE__ */ go(pl,e))},ipv4(e){return this.check(/* @__PURE__ */ _o(ml,e))},ipv6(e){return this.check(/* @__PURE__ */ vo(hl,e))},cidrv4(e){return this.check(/* @__PURE__ */ yo(gl,e))},cidrv6(e){return this.check(/* @__PURE__ */ bo(_l,e))},e164(e){return this.check(/* @__PURE__ */ Co(bl,e))},datetime(e){return this.check(/* @__PURE__ */ To($c,e))},date(e){return this.check(/* @__PURE__ */ Eo(el,e))},time(e){return this.check(/* @__PURE__ */ Do(tl,e))},duration(e){return this.check(/* @__PURE__ */ Oo(nl,e))}});function G(e){return/* @__PURE__ */ to(Zc,e)}const Qc=/*@__PURE__*/ W(`ZodStringFormat`,(e,t)=>{si.init(e,t),Xc.init(e,t)}),$c=/*@__PURE__*/ W(`ZodISODateTime`,(e,t)=>{Ei.init(e,t),Qc.init(e,t)}),el=/*@__PURE__*/ W(`ZodISODate`,(e,t)=>{Di.init(e,t),Qc.init(e,t)}),tl=/*@__PURE__*/ W(`ZodISOTime`,(e,t)=>{Oi.init(e,t),Qc.init(e,t)}),nl=/*@__PURE__*/ W(`ZodISODuration`,(e,t)=>{ki.init(e,t),Qc.init(e,t)}),rl=/*@__PURE__*/ W(`ZodEmail`,(e,t)=>{ui.init(e,t),Qc.init(e,t)}),il=/*@__PURE__*/ W(`ZodGUID`,(e,t)=>{ci.init(e,t),Qc.init(e,t)}),al=/*@__PURE__*/ W(`ZodUUID`,(e,t)=>{li.init(e,t),Qc.init(e,t)}),ol=/*@__PURE__*/ W(`ZodURL`,(e,t)=>{vi.init(e,t),Qc.init(e,t)}),sl=/*@__PURE__*/ W(`ZodEmoji`,(e,t)=>{yi.init(e,t),Qc.init(e,t)}),cl=/*@__PURE__*/ W(`ZodNanoID`,(e,t)=>{bi.init(e,t),Qc.init(e,t)}),ll=/*@__PURE__*/ W(`ZodCUID`,(e,t)=>{xi.init(e,t),Qc.init(e,t)}),ul=/*@__PURE__*/ W(`ZodCUID2`,(e,t)=>{Si.init(e,t),Qc.init(e,t)}),dl=/*@__PURE__*/ W(`ZodULID`,(e,t)=>{Ci.init(e,t),Qc.init(e,t)}),fl=/*@__PURE__*/ W(`ZodXID`,(e,t)=>{wi.init(e,t),Qc.init(e,t)}),pl=/*@__PURE__*/ W(`ZodKSUID`,(e,t)=>{Ti.init(e,t),Qc.init(e,t)}),ml=/*@__PURE__*/ W(`ZodIPv4`,(e,t)=>{Ai.init(e,t),Qc.init(e,t)}),hl=/*@__PURE__*/ W(`ZodIPv6`,(e,t)=>{Ni.init(e,t),Qc.init(e,t)}),gl=/*@__PURE__*/ W(`ZodCIDRv4`,(e,t)=>{Pi.init(e,t),Qc.init(e,t)}),_l=/*@__PURE__*/ W(`ZodCIDRv6`,(e,t)=>{Ii.init(e,t),Qc.init(e,t)}),vl=/*@__PURE__*/ W(`ZodBase64`,(e,t)=>{zi.init(e,t),Qc.init(e,t)}),yl=/*@__PURE__*/ W(`ZodBase64URL`,(e,t)=>{Hi.init(e,t),Qc.init(e,t)}),bl=/*@__PURE__*/ W(`ZodE164`,(e,t)=>{Ui.init(e,t),Qc.init(e,t)}),xl=/*@__PURE__*/ W(`ZodJWT`,(e,t)=>{Gi.init(e,t),Qc.init(e,t)}),Sl=/*@__PURE__*/ W(`ZodNumber`,(e,t)=>{Ki.init(e,t),Yc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zs(e,t,n,r),e.isFinite=!0},/*@__PURE__*/ dn({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=Ps(e);return Math.max(t??-1/0,n??-1/0)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=Ps(e);return Math.min(t??1/0,n??1/0)},isInt:e=>{let{isInt:t,multipleOf:n}=Ps(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>Ps(e).format??null},{gt(e,t){return this.check(/* @__PURE__ */ Ro(e,t))},gte(e,t){return this.check(/* @__PURE__ */ zo(e,t))},min(e,t){return this.check(/* @__PURE__ */ zo(e,t))},lt(e,t){return this.check(/* @__PURE__ */ Io(e,t))},lte(e,t){return this.check(/* @__PURE__ */ Lo(e,t))},max(e,t){return this.check(/* @__PURE__ */ Lo(e,t))},int(e){return this.check(Tl(e))},safe(e){return this.check(Tl(e))},positive(e){return this.check(/* @__PURE__ */ Ro(0,e))},nonnegative(e){return this.check(/* @__PURE__ */ zo(0,e))},negative(e){return this.check(/* @__PURE__ */ Io(0,e))},nonpositive(e){return this.check(/* @__PURE__ */ Lo(0,e))},multipleOf(e,t){return this.check(/* @__PURE__ */ Bo(e,t))},step(e,t){return this.check(/* @__PURE__ */ Bo(e,t))},finite(){return this}}));function Cl(e){return/* @__PURE__ */ ko(Sl,e)}const wl=/*@__PURE__*/ W(`ZodNumberFormat`,(e,t)=>{qi.init(e,t),Sl.init(e,t)});function Tl(e){return/* @__PURE__ */ jo(wl,e)}const El=/*@__PURE__*/ W(`ZodBoolean`,(e,t)=>{Ji.init(e,t),Yc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Bs(e,t,n,r)});function Dl(e){return/* @__PURE__ */ Mo(El,e)}const Ol=/*@__PURE__*/ W(`ZodNull`,(e,t)=>{Yi.init(e,t),Yc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Us(e,t,n,r)});function kl(e){return/* @__PURE__ */ No(Ol,e)}const Al=/*@__PURE__*/ W(`ZodUnknown`,(e,t)=>{Xi.init(e,t),Yc.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function jl(){return/* @__PURE__ */ Po(Al)}const Ml=/*@__PURE__*/ W(`ZodNever`,(e,t)=>{Zi.init(e,t),Yc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ks(e,t,n,r)});function Nl(e){return/* @__PURE__ */ Fo(Ml,e)}const Pl=/*@__PURE__*/ W(`ZodArray`,(e,t)=>{Jc(),$i.init(e,t),Yc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>sc(e,t,n,r),e.element=t.element},{min(e,t){return this.check(/* @__PURE__ */ Ho(e,t))},nonempty(e){return this.check(/* @__PURE__ */ Ho(1,e))},max(e,t){return this.check(/* @__PURE__ */ Vo(e,t))},length(e,t){return this.check(/* @__PURE__ */ Uo(e,t))},unwrap(){return this.element}});function Fl(e,t){return/* @__PURE__ */ ns(Pl,e,t)}const Il=/*@__PURE__*/ W(`ZodObject`,(e,t)=>{Jc(),aa.init(e,t),Yc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>lc(e,t,n,r),vn(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return ql(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(Et(this._zod.def,{catchall:e}))},passthrough(){return this.clone(Et(this._zod.def,{catchall:jl()}))},loose(){return this.clone(Et(this._zod.def,{catchall:jl()}))},strict(){return this.clone(Et(this._zod.def,{catchall:Nl()}))},strip(){return this.clone(Et(this._zod.def,{catchall:void 0}))},extend(e){return Wt(this,e)},safeExtend(e){return Kt(this,e)},merge(e){return qt(this,e)},pick(e){return Vt(this,e)},omit(e){return Ut(this,e)},partial(...e){return Jt(Ql,this,e[0])},exactPartial(...e){return Jt(eu,this,e[0],`exactPartial`)},required(...e){return Yt(cu,this,e[0])}});function K(e,t){let n={type:`object`,shape:e??{},...U(t)};return new Il(n)}function Ll(e,t){return new Il({type:`object`,shape:e,catchall:Nl(),...U(t)})}const Rl=/*@__PURE__*/ W(`ZodUnion`,(e,t)=>{sa.init(e,t),Yc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>uc(e,t,n,r),e.options=t.options});function zl(e,t){return new Rl({type:`union`,options:e,...U(t)})}const Bl=/*@__PURE__*/ W(`ZodDiscriminatedUnion`,(e,t)=>{Rl.init(e,t),la.init(e,t)});function Vl(e,t,n){return new Bl({type:`union`,options:t,discriminator:e,...U(n)})}const Hl=/*@__PURE__*/ W(`ZodIntersection`,(e,t)=>{ua.init(e,t),Yc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>dc(e,t,n,r)});function Ul(e,t){return new Hl({type:`intersection`,left:e,right:t})}const Wl=/*@__PURE__*/ W(`ZodRecord`,(e,t)=>{Jc(),pa.init(e,t),Yc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>gc(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function Gl(e,t,n){return!t||!t._zod?new Wl({type:`record`,keyType:G(),valueType:e,...U(t)}):new Wl({type:`record`,keyType:e,valueType:t,...U(n)})}const Kl=/*@__PURE__*/ W(`ZodEnum`,(e,t)=>{ma.init(e,t),Yc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xs(e,t,n,r),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new Kl({...t,checks:[],...U(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new Kl({...t,checks:[],...U(r),entries:i})}});function ql(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new Kl({type:`enum`,entries:n,...U(t)})}const Jl=/*@__PURE__*/ W(`ZodLiteral`,(e,t)=>{ha.init(e,t),Yc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zs(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Yl(e,t){return new Jl({type:`literal`,values:Array.isArray(e)?e:[e],...U(t)})}const Xl=/*@__PURE__*/ W(`ZodTransform`,(e,t)=>{Jc(),ga.init(e,t),Yc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ic(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Tn(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(sn(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,`input`in t||(t.input=n.value),t.inst??=e,n.issues.push(sn(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function Zl(e){return new Xl({type:`transform`,transform:e})}const Ql=/*@__PURE__*/ W(`ZodOptional`,(e,t)=>{va.init(e,t),Yc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Dc(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function $l(e){return new Ql({type:`optional`,innerType:e})}const eu=/*@__PURE__*/ W(`ZodExactOptional`,(e,t)=>{ya.init(e,t),Yc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Dc(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function tu(e){return new eu({type:`optional`,innerType:e})}const nu=/*@__PURE__*/ W(`ZodNullable`,(e,t)=>{ba.init(e,t),Yc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_c(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function ru(e){return new nu({type:`nullable`,innerType:e})}const iu=/*@__PURE__*/ W(`ZodDefault`,(e,t)=>{xa.init(e,t),Yc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xc(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function au(e,t){return new iu({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():Nt(t)}})}const ou=/*@__PURE__*/ W(`ZodPrefault`,(e,t)=>{Ca.init(e,t),Yc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Sc(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function su(e,t){return new ou({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():Nt(t)}})}const cu=/*@__PURE__*/ W(`ZodNonOptional`,(e,t)=>{wa.init(e,t),Yc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vc(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function lu(e,t){return new cu({type:`nonoptional`,innerType:e,...U(t)})}const uu=/*@__PURE__*/ W(`ZodCatch`,(e,t)=>{Da.init(e,t),Yc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Cc(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function du(e,t){return new uu({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:yn(t)})}const fu=/*@__PURE__*/ W(`ZodPipe`,(e,t)=>{Oa.init(e,t),Yc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>wc(e,t,n,r),e.in=t.in,e.out=t.out});function pu(e,t){return new fu({type:`pipe`,in:e,out:t})}const mu=/*@__PURE__*/ W(`ZodReadonly`,(e,t)=>{Aa.init(e,t),Yc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Tc(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function hu(e){return new mu({type:`readonly`,innerType:e})}const gu=/*@__PURE__*/ W(`ZodCustom`,(e,t)=>{Ma.init(e,t),Yc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nc(e,t,n,r)});function _u(e,t){return/* @__PURE__ */ rs(gu,e??(()=>!0),t)}function vu(e,t={}){return/* @__PURE__ */ is(gu,e,t)}function yu(e,t){return/* @__PURE__ */ as(e,t)}function bu(e){return/* @__PURE__ */ Ao(Sl,e)}const xu=1e4,Su=`[a-z0-9][a-z0-9_-]*`,Cu=G().max(80).regex(RegExp(`^${Su}(?:/${Su})*$`),`invalid channel path`),wu=e=>!e.includes(`\0`)&&e.isWellFormed(),Tu=e=>e.replaceAll(`\0`,``).toWellFormed(),Eu=G().max(xu).refine(e=>e.trim().length>0,`message text is empty`).refine(wu,`message text has a NUL character or a lone surrogate`),Du=Cl().int().positive(),Ou=/* @__PURE__ */ new Set([...Object.getOwnPropertyNames(Object.prototype),`prototype`]),ku=e=>!Ou.has(e),Au=G().max(64).regex(/^[a-z0-9][a-z0-9_.-]*$/,`invalid label key`).refine(ku,`label key is a reserved name`),ju=G().max(256).refine(wu,`label value has a NUL character or a lone surrogate`),Mu=Gl(Au,ju),Nu=G().max(64).regex(/^[a-z0-9_+-]+$/,`invalid emoji name`).refine(ku,`emoji name is a reserved name`),Pu=G().min(1).max(256);zl([ql([`person`,`agent`,`deployment`,`workflow`,`external`]),Yl(`profile`)]);const Fu=e=>e===`profile`?`agent`:e;G().min(1).max(128).refine(wu,`handle has a NUL character or a lone surrogate`);function Iu(e){if(e===null)return null;try{return new URL(e).protocol===`https:`?e:null}catch{return null}}K({actor:Pu,principal:G().min(1),profile:G().nullable()});const Lu=G().regex(/^(?:[A-Za-z0-9_-]{22}|att_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/,`invalid attachment id`);K({id:Lu,name:G().min(1).max(255),type:G().min(1).max(255),size:Cl().int().nonnegative()});const Ru=G().regex(/^[A-Za-z][A-Za-z0-9-]{0,31}$/,`ids start with a letter and use up to 32 letters, numbers, and hyphens`),zu=G().min(3).max(300),Bu=K({channel:zu.optional(),thread:zu,subthread:zu.nullable(),message:G().min(1).max(300),context:G().max(300).nullable()}),Vu=K({author:G().min(1).max(256),text:G().max(xu),createdAt:G().max(64).nullable(),files:Fl(K({name:G().min(1).max(1e3),url:G().max(4e3).nullable()})).max(20)}),Hu=K({url:G().min(1).max(4e3),message:Du.nullable(),snapshot:Vu.nullable(),unavailable:G().max(300).nullable()}),Uu=K({id:G().min(1),handle:G().min(1),name:G().min(1),avatar:G().nullable(),isBot:Dl()}),Wu=K({type:ql([`image`,`file`,`video`,`audio`]),name:G().max(1e3).optional(),mimeType:G().max(255).optional(),size:Cl().int().nonnegative().optional(),url:G().max(4e3).optional(),fetchMetadata:Gl(G(),G().max(4e3)).optional()}),Gu=K({url:G().min(1).max(4e3),thread:zu,message:G().min(1).max(300),snapshot:Vu.nullable()}),Ku=K({channel:zu,thread:zu,subthread:zu.nullable()}),qu=Vl(`kind`,[K({kind:Yl(`message`),...Ku.shape,message:G(),isRoot:Dl(),text:G(),context:G().nullable(),author:Uu,files:Fl(Wu).max(20).optional(),links:Fl(Gu).max(10).optional()}),K({kind:Yl(`edited`),...Ku.shape,message:G(),text:G(),author:Uu,links:Fl(Gu).max(10).optional(),linksOnly:Dl().optional()}),K({kind:Yl(`deleted`),...Ku.shape,message:G()}),K({kind:Yl(`reaction`),...Ku.shape,message:G(),emoji:G(),added:Dl(),author:Uu}),K({kind:Yl(`lifecycle`),...Ku.omit({subthread:!0}).shape,type:G(),title:G(),url:G().nullable(),body:G().nullable().optional(),labels:Gl(G(),G()),unset:Fl(G()),owns:Fl(G()).optional(),reply:G().nullable(),createRoot:Dl(),retitled:Dl().optional(),author:Uu})]),Ju=e=>e.slice(e.indexOf(`:`)+1).includes(`:`),Yu=e=>{let t=e.indexOf(`:`),n=e.slice(t+1).indexOf(`:`);return n===-1?e:e.slice(0,t+1+n)},Xu=G().min(1).max(128),Zu=Cl().int().positive(),Qu=Xu,$u=ql([`true`,`false`,`1`,`0`]).transform(e=>e===`true`||e===`1`),ed=zl([G(),Fl(G())]).transform(e=>Array.isArray(e)?e:[e]),td=G().regex(/^[a-z0-9][a-z0-9_.-]*(=.*)?$/,`label filters look like key, key=value, or key=a|b`).transform(e=>{let t=e.indexOf(`=`);return t===-1?[e,null]:[e.slice(0,t),e.slice(t+1).split(`|`)]}),nd=K({target:zu,kind:ql([`channel`,`thread`])}),rd=K({channel:G().optional(),re:Qu.optional(),by:G().optional(),mentions:G().optional(),label:ed.pipe(Fl(td)).optional(),from:G().min(1).max(165).optional(),text:G().min(1).max(200).optional()}),id=rd.extend({after:Xu.optional(),before:Qu.optional(),limit:bu().int().min(1).max(500).optional()}),ad=rd.extend({after:Xu.optional(),limit:bu().int().min(1).max(500).optional()}),od=rd.extend({after:Xu.optional(),wait:bu().min(0).max(300).optional(),all:$u.optional()}),sd=K({channel:Cu.optional(),re:Xu.optional(),text:G().max(xu).default(``),labels:Mu.optional(),noSync:Dl().optional(),sync:Fl(zl([G().min(3).max(300),nd])).max(10).optional(),id:G().min(1).max(200).refine(wu,`id has a NUL character or a lone surrogate`).optional(),attachments:Fl(Lu).max(10).optional(),after:Xu.optional()}).refine(e=>e.text.trim().length>0||(e.attachments?.length??0)>0,{message:`message text is empty`,path:[`text`]}).refine(e=>e.channel===void 0!=(e.re===void 0),{message:"a post needs `channel`; a reply needs `re`"}).refine(e=>!(e.noSync&&e.sync?.length),{message:"`noSync` and `sync` contradict each other"}).refine(e=>e.after===void 0||e.re!==void 0,{message:"`after` is for replies: it names the newest message in `re`'s thread",path:[`after`]}),cd=G().regex(/^\d+(\.\d+)?(s|m|h|d)$/,`durations look like 30s, 30m, 12h, or 1d`),ld=G().datetime({offset:!0}),ud=K({channel:Cu.optional(),re:Xu.optional(),text:G().max(xu).default(``),labels:Mu.optional(),noSync:Dl().optional(),attachments:Fl(Lu).max(10).optional(),in:cd.optional(),at:ld.optional(),every:cd.optional(),until:ld.optional(),for:cd.optional(),times:Cl().int().positive().optional()}).refine(e=>e.text.trim().length>0||(e.attachments?.length??0)>0,{message:`message text is empty`,path:[`text`]}).refine(e=>e.channel===void 0!=(e.re===void 0),{message:"a schedule needs `channel` for a new thread, or `re` for a reply"}).refine(e=>e.in!==void 0||e.at!==void 0||e.every!==void 0,{message:"say when: `in`, `at`, or `every`"}).refine(e=>e.in===void 0||e.at===void 0,{message:"`in` and `at` contradict each other"}).refine(e=>[e.until,e.for,e.times].filter(e=>e!==void 0).length<=1,{message:"pick one stop: `until`, `for`, or `times`"}).refine(e=>e.every!==void 0||e.until===void 0&&e.for===void 0&&e.times===void 0,{message:"`until`, `for`, and `times` stop a repeat: add `every`"}),dd=K({re:Qu.optional(),channel:G().optional(),by:G().optional(),all:$u.optional()}),fd=zl([Yl(`all`),Fl(G().min(1).max(16)).max(8)]),pd=G().min(1).max(1e3),md=Fl(G().min(1).max(100)).min(1).max(16),hd=Vl(`kind`,[Ll({kind:Yl(`user`),email:G().min(3).max(320).optional(),userId:G().min(1).max(200).optional()}),Ll({kind:Yl(`project`),project:G().min(1).max(200),environments:md.optional()}),Ll({kind:Yl(`github`),repository:G().min(3).max(200),workflow:G().min(1).max(300).optional(),branch:G().min(1).max(255).optional(),event:G().min(1).max(64).optional()}),Ll({kind:Yl(`oidc`),issuer:G().min(1).max(1e3),claims:Gl(G().min(1).max(200),zl([pd,Fl(pd).min(1).max(32)]))}),Ll({kind:Yl(`all-users`)}),Ll({kind:Yl(`all-projects`),environments:md.optional()}),Ll({kind:Yl(`app`),app:G().min(1).max(200)}),Ll({kind:Yl(`all-apps`)}),Ll({kind:Yl(`everyone`)})]),gd=Gl(G().min(1).max(300),fd),_d=Ll({principals:Fl(hd).min(1).max(32),can:gd}),vd=K({channel:Cu,user:G().min(1).max(320).optional(),project:G().min(1).max(200).optional(),environment:G().min(1).max(100).optional(),github:G().min(3).max(200).optional(),workflow:G().min(1).max(300).optional(),branch:G().min(1).max(255).optional(),event:G().min(1).max(64).optional(),oidc:G().min(1).max(1e3).optional(),claim:ed.optional(),app:G().min(1).max(200).optional()}).refine(e=>[e.user,e.project,e.github,e.oidc,e.app].filter(e=>e!==void 0).length<=1,`name one principal: user, project, github, oidc, or app`).refine(e=>e.environment===void 0||e.project!==void 0,`environment goes with project`).refine(e=>e.workflow===void 0&&e.branch===void 0&&e.event===void 0||e.github!==void 0,`workflow, branch, and event go with github`).refine(e=>e.claim===void 0||e.oidc!==void 0,`claim goes with oidc`),yd=Ll({add:Fl(hd).min(1).max(32).optional(),remove:Fl(hd).min(1).max(32).optional(),can:gd.optional()}).refine(e=>e.add!==void 0||e.remove!==void 0||e.can!==void 0,`name principals to add or remove, or a can`),bd=Ll({name:G().regex(Re,`a schema name is up to 80 lowercase letters, numbers, and ._-, starting with a letter`),version:Cl().int().min(1).max(99999),description:G().min(1).max(2e3).refine(wu,`a description has a NUL character or a lone surrogate`).optional(),schema:Gl(G(),jl())}),xd=K({target:G().min(3).max(300)}),Sd=K({channel:G().optional(),limit:bu().int().min(1).max(500).optional()}),Cd=K({watch:Gl(G().max(100),K({tail:G().max(1e3)})).refine(e=>Object.keys(e).length<=32,`a board registers at most 32 watchers`),sync:Fl(K({key:G().min(1).max(64),platform:G().min(1).max(64)})).max(32).optional()}),wd=zl([Cd.extend({url:G().url().max(500).refine(e=>/^https:\/\//.test(e),`wake-ups go over https`).transform(e=>e.replace(/\/+$/,``)).nullable().optional(),path:kl({error:`register a url or a path, not both`}).optional(),branch:kl({error:`a branch goes with a path`}).optional()}),Cd.extend({url:kl({error:`register a url or a path, not both`}).optional(),path:G().max(300).regex(/^\/[^?#]*$/,`a path starts with / and has no query or fragment`).transform(e=>e.replace(/(.)\/+$/,`$1`)),branch:G().min(1).max(255).nullable().optional()})]),Td=K({limit:bu().int().min(1).max(50).optional(),wait:bu().min(0).max(25).optional()}),Ed=K({lease:G().min(1).max(64),error:G().min(1).max(500).optional(),skip:Dl().optional()}),Dd=K({target:G().min(1).max(4e3),limit:bu().int().min(1).max(200).optional(),after:G().min(1).max(400).optional()}),Od=K({target:G().min(1).max(4e3)}),kd=K({url:G().url().max(4e3)}),Ad=G().min(1).max(64),jd=K({thread:zu,message:G().min(1).max(300).optional()}),Md=Hu.extend({message:Xu.nullable()}),Nd={author:Uu.extend({avatar:G().nullable().transform(Iu)}),from:Ad.nullable()},Pd=K({key:Ad,channel:zu,thread:zu}),Fd={origin:jd.optional(),message:Xu.optional()},Id=Vl(`op`,[K({op:Yl(`post`),...Nd,origin:Bu.nullable().default(null),source:Pd.optional(),channel:Cu.optional(),re:Xu.optional(),text:G().max(xu).default(``),labels:Mu.optional(),noSync:Dl().optional(),attachments:Fl(Lu).max(10).optional(),links:Fl(Md).max(10).optional(),id:G().min(1).max(200).refine(wu,`id has a NUL character or a lone surrogate`).optional(),after:Xu.optional()}),K({op:Yl(`edit`),...Nd,...Fd,text:Eu,source:Pd.optional(),revision:Zu.optional()}),K({op:Yl(`delete`),...Nd,...Fd,revision:Zu.optional()}),K({op:Yl(`react`),...Nd,...Fd,emoji:Nu,remove:Dl().optional()}),K({op:Yl(`labels`),...Nd,...Fd,set:Mu.optional(),unset:Fl(Au).optional(),if:Gl(Au,ju.nullable()).optional()}),K({op:Yl(`links`),...Nd,...Fd,links:Fl(Md).max(10)})]),Ld=Fl(G().min(1).max(300)).max(10).nullable(),Rd=Vl(`kind`,[K({kind:Yl(`message`),message:Xu,target:zu,external:K({thread:zu,message:G().min(1).max(300)}),files:Ld.optional()}),K({kind:Yl(`files`),message:Xu,target:zu,files:Ld}),K({kind:Yl(`failed`),message:Xu,target:zu,error:G().min(1).max(500)}),K({kind:Yl(`thread`),message:Xu,target:zu,targetKind:ql([`channel`,`thread`]),cause:ql([`config`,`request`])})]),zd=K({post:G().min(1).max(200).optional(),thread:zu.optional(),message:G().min(1).max(300).optional()}),Bd=K({message:ed.pipe(Fl(Xu).min(1).max(100))}),Vd=K({events:Fl(K({id:G().min(1).max(300),event:qu,raw:jl()})).min(1).max(50)}),Hd=K({limit:bu().int().min(1).max(50).optional()}),Ud=K({lease:G().min(1).max(64),error:G().min(1).max(500).optional()}),Wd=K({name:G().max(1024).nullable().optional(),type:G().max(1024).nullable().optional(),size:Cl().int().positive().max(je,`direct uploads are at most ${je/1024/1024} MB`),sha256:G().regex(/^[A-Za-z0-9+/]{43}=$/,`sha256 is the base64 SHA-256 of the bytes`).optional()}),Gd=K({text:Eu,revision:Zu.optional()}),Kd=K({revision:Zu.optional()}).optional(),qd=K({status:G().trim().min(1).max(100).optional()}).optional(),Jd=K({emoji:Nu,remove:Dl().optional()}),Yd=Ll({path:Cu}),Xd=K({set:Mu.optional(),unset:Fl(Au).optional(),if:Gl(Au,ju.nullable()).refine(e=>Object.keys(e).length<=16,`at most 16 labels`).optional()}).refine(e=>e.set!==void 0||e.unset!==void 0,{message:"nothing to change: pass `set` or `unset`"}),Zd={discovery:{method:`GET`,path:`/`},me:{method:`GET`,path:`/me`},channels:{method:`GET`,path:`/channels`},createChannel:{method:`POST`,path:`/channels`,body:Yd},actors:{method:`GET`,path:`/actors`},messages:{method:`GET`,path:`/messages`,query:id},message:{method:`GET`,path:`/messages/:id`},threads:{method:`GET`,path:`/threads`,query:ad},post:{method:`POST`,path:`/messages`,body:sd},edit:{method:`POST`,path:`/messages/:id/edit`,body:Gd},delete:{method:`POST`,path:`/messages/:id/delete`,body:Kd},react:{method:`POST`,path:`/messages/:id/reactions`,body:Jd},label:{method:`POST`,path:`/messages/:id/labels`,body:Xd},sync:{method:`POST`,path:`/messages/:id/sync`,body:xd},synced:{method:`GET`,path:`/messages/:id/sync`},linked:{method:`GET`,path:`/links`,query:kd},typing:{method:`POST`,path:`/messages/:id/typing`,body:qd},schedule:{method:`POST`,path:`/schedules`,body:ud},schedules:{method:`GET`,path:`/schedules`,query:dd},cancelSchedule:{method:`POST`,path:`/schedules/:id/cancel`},grants:{method:`GET`,path:`/grants`},createGrant:{method:`POST`,path:`/grants`,body:_d},updateGrant:{method:`PATCH`,path:`/grants/:id`,body:yd},explain:{method:`GET`,path:`/grants/explain`,query:vd},revokeGrant:{method:`POST`,path:`/grants/:id/revoke`},schemas:{method:`GET`,path:`/schemas`},schema:{method:`GET`,path:`/schemas/:id`},createSchema:{method:`POST`,path:`/schemas`,body:bd},posted:{method:`GET`,path:`/posts/:id`},inbox:{method:`GET`,path:`/inbox/:key`,query:Sd},inboxPush:{method:`POST`,path:`/inbox/:key`,body:Vd},inboxNext:{method:`GET`,path:`/inbox/:key/next`,query:Hd},inboxAck:{method:`POST`,path:`/inbox/:key/:id/ack`,body:Ud},syncImport:{method:`POST`,path:`/sync/imports`,body:Id},syncReceipt:{method:`POST`,path:`/sync/receipts`,body:Rd},syncThread:{method:`GET`,path:`/sync/threads/:thread`},syncFind:{method:`GET`,path:`/sync/find`,query:zd},syncCopies:{method:`GET`,path:`/sync/copies`,query:Bd},readSource:{method:`GET`,path:`/sources/:key/read`,query:Dd},joinSource:{method:`POST`,path:`/sources/:key/join`,body:Od},webhook:{method:`POST`,path:`/webhooks/:key`},events:{method:`GET`,path:`/events`,query:od},avatar:{method:`GET`,path:`/avatars/:name`},upload:{method:`POST`,path:`/attachments`},attachment:{method:`GET`,path:`/attachments/:id`},uploadStart:{method:`POST`,path:`/attachments/uploads`,body:Wd},uploadFinish:{method:`POST`,path:`/attachments/uploads/:id`},openapi:{method:`GET`,path:`/openapi.json`},watchers:{method:`GET`,path:`/watchers`},register:{method:`POST`,path:`/watchers`,body:wd},matches:{method:`GET`,path:`/watchers/matches`,query:Td},ack:{method:`POST`,path:`/watchers/matches/:id/ack`,body:Ed},wake:{method:`POST`,path:`/wake`}};async function*Qd(e,t){let n=e.getReader(),r=new TextDecoder,i=``,a=()=>void n.cancel().catch(()=>{});t?.addEventListener(`abort`,a,{once:!0});try{for(;;){let{value:e,done:t}=await n.read();if(t)return;i+=r.decode(e,{stream:!0});let a;for(;(a=i.search(/\r?\n\r?\n/))!==-1;){let e=i.slice(0,a);i=i.slice(a).replace(/^\r?\n\r?\n/,``);let t={},n=[];for(let r of e.split(/\r?\n/)){if(r===``||r.startsWith(`:`))continue;let e=r.indexOf(`:`),i=e===-1?r:r.slice(0,e),a=e===-1?``:r.slice(e+1).replace(/^ /,``);i===`data`?n.push(a):i===`id`?t.id=a:i===`event`&&(t.event=a)}n.length>0&&(t.data=n.join(`
|
|
345
|
-
`)),(t.id!==void 0||t.data!==void 0)&&(yield t)}}}finally{t?.removeEventListener(`abort`,a),n.releaseLock()}}var $d=class extends Error{};const ef=/[A-Za-z*]/,tf=/[!#$%&'*+\-.^_`|~0-9A-Za-z:/]/,nf=/[a-z*]/,rf=/[a-z0-9_\-.*]/,af=/^(?:-?\d{1,15}|-?\d{1,12}\.\d{1,3}|\?[01]|:[A-Za-z0-9+/=]*:)$/;function of(e){if(!/^[\x20-\x7e]*$/.test(e))throw new $d(`an avatar URL is printable ASCII: percent-encode the rest`);return`"${e.replace(/[\\"]/g,e=>`\\${e}`)}"`}function sf(e){if(!e.avatar)return e.name;let t=/^[\x20-\x7e]*$/.test(e.avatar)?e.avatar:URL.parse(e.avatar)?.href??e.avatar;return`${e.name};avatar=${of(t)}`}function cf(e){let t=0,n=e=>{throw new $d(`x-board-profile is a structured header, like fixer;avatar="https://example.com/fixer.png": ${e}`)},r=()=>{for(;e[t]===` `;)t++},i=()=>{t++;let r=``;for(;t<e.length;){let i=e[t++];if(i===`\\`){let i=e[t++];i!==`"`&&i!==`\\`&&n(`a string escapes only " and \\`),r+=i}else if(i===`"`)return r;else i<` `||i>`~`?n(`a string is printable ASCII`):r+=i}return n(`a string is missing its closing "`)},a=()=>{let n=t;for(;t<e.length&&tf.test(e[t]);)t++;return e.slice(n,t)},o=()=>{let r=e[t];if(r===`"`)return{kind:`string`,value:i()};if(r!==void 0&&ef.test(r))return{kind:`token`,value:a()};let o=t;for(;t<e.length&&e[t]!==`;`&&e[t]!==` `;)t++;let s=e.slice(o,t);return af.test(s)||n(s===``?`a parameter has no value after its =`:`${s} isn't a value`),{kind:`other`,value:s}};r();let s=o();s.kind===`other`&&n(s.value===``?`it names no profile`:`${s.value} isn't a profile's name`);let c=null;for(;e[t]===`;`;){t++,r(),nf.test(e[t]??``)||n(`a parameter starts with a lowercase letter`);let i=t;for(;t<e.length&&rf.test(e[t]);)t++;let a=e.slice(i,t),s={kind:`boolean`,value:`?1`};e[t]===`=`&&(t++,s=o()),a===`avatar`&&(s.kind!==`string`&&n(`avatar is a string, in quotes`),c=s.value)}return r(),t<e.length&&n(`${JSON.stringify(e.slice(t,t+20))} follows the profile`),{name:s.value,avatar:c}}var lf=class extends Error{code;status;hint;origin;constructor(e,t,n,r={}){super(t),this.name=`BoardError`,this.code=e,this.status=n,this.hint=r.hint,this.origin=r.origin??`handle`}};const uf=/* @__PURE__ */ new WeakSet,df=async e=>typeof e==`function`?await e():e,ff=e=>{let{at:t,until:n,...r}=pf(e);return{...r,...t===void 0?{}:{at:t instanceof Date?t.toISOString():t},...n===void 0?{}:{until:n instanceof Date?n.toISOString():n}}},pf=e=>{if(typeof e==`string`)return{text:e};let{attachments:t,...n}=e;return t?.length?{...n,attachments:t.map(e=>typeof e==`string`?e:e.id)}:n},mf={ms:1,s:1e3,m:6e4,h:36e5,d:864e5};function hf(e){if(typeof e==`number`)return e;let t=e.trim().match(/^(\d+(?:\.\d+)?)(ms|s|m|h|d)?$/);if(!t)throw new lf(`invalid_duration`,`${e} isn't a duration like 30s, 10m, or 1h.`,0);return Number(t[1])*mf[t[2]??`ms`]}const gf=e=>encodeURIComponent(e);function _f(e){let t=new URLSearchParams;for(let[n,r]of Object.entries(e))if(r!=null){if(n===`label`){let e=Array.isArray(r)?r:typeof r==`object`?Object.entries(r).map(([e,t])=>`${e}=${String(t)}`):[r];for(let n of e)t.append(`label`,String(n))}else t.set(n,String(r))}let n=t.toString();return n?`?${n}`:``}function vf(e){return typeof e!=`object`||!e||Array.isArray(e)?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t===`none`?[]:t]))}const yf=e=>(e.kind===`project`||e.kind===`all-projects`)&&e.environments===void 0?{...e,environments:[`production`]}:e;function bf(e,t){let[n,r,i,a]=e.principal.split(`:`);if((n===`vercel`||n===`local`)&&r===`user`&&i)return{kind:`user`,userId:e.principal.split(`:`).slice(2).join(`:`)};if(n===`vercel`&&r===`project`&&i&&a)return{kind:`project`,project:i,environments:[a]};throw new lf(`no_own_principal`,`A private channel lets its creator in, as a person or a project's deployment, and ${e.principal} is neither, so ${t} wasn't made.`,400,{hint:`Make it as a person or a deployment, or make it and its grants yourself.`})}function xf(e){let t=e.url.replace(/\/+$/,``),n=e.fetch??((e,t)=>globalThis.fetch(e,t)),r=e.storeFetch??((e,t)=>globalThis.fetch(e,t));async function i(t,n){let r={...e.headers?await df(e.headers):{}};if(!t)return r;e.token!==void 0&&(r.authorization=`Bearer ${await df(e.token)}`);let i=n===void 0?e.profile===void 0?null:await df(e.profile):n;return i!==null&&(r[`x-board-profile`]=sf(typeof i==`string`?{name:i}:i)),r}async function a(e,r,a={}){let o=await n(`${t}${r}`,{method:e,headers:{...await i(a.auth??!0),...a.body===void 0?{}:{"content-type":`application/json`},...a.headers},...a.body===void 0?{}:{body:JSON.stringify(a.body)},...a.signal?{signal:a.signal}:{}});if(!o.ok)throw await Sf(o);return o}async function o(e,t,n){return await(await a(e,t,n)).json()}let s=(e={})=>e;async function c(e={},t){return o(`GET`,`/events${_f(e)}`,t?{signal:t}:{})}return{url:t,request:async(e,r={})=>n(`${t}${e}`,{method:r.method??`GET`,headers:{...r.headers,...await i(!0,r.as)},...r.body?{body:r.body}:{},...r.signal?{signal:r.signal}:{}}),discovery:()=>o(`GET`,`/`,{auth:!1}),me:()=>o(`GET`,`/me`),channels:async()=>(await o(`GET`,`/channels`)).channels,createChannel:async(e,t={})=>{if(!t.private)return o(`POST`,`/channels`,{body:{path:e}});let n=bf(await o(`GET`,`/me`),e),r=`${e}/`,i=async()=>(await o(`GET`,`/grants`)).grants.filter(t=>Object.keys(t.can).some(t=>t===e||t.startsWith(r))),a=(t,n=[])=>{let r=t.filter(e=>n.some(t=>t.id===e.id)).map(e=>e.id);if(r.length===t.length)return new lf(`channel_granted`,`${r.join(` and `)} changed while ${e} was being made, so a private ${e} wouldn't be yours alone: nothing was made.`,409);let i=t.filter(e=>!r.includes(e.id)).map(e=>e.id);return new lf(`channel_granted`,`${i.length===1?i[0]:`${i.slice(0,-1).join(`, `)} and ${i.at(-1)}`} already ${i.length===1?`grants`:`grant`} in ${e}, so a private ${e} wouldn't be yours alone: nothing was made.`,409,{hint:i.length===1?`Revoke it first: vb grants revoke ${i[0]}`:`Revoke them first, each with vb grants revoke <id>.`})},s=await i();if(s.length>0)throw a(s);let c=(await o(`GET`,`/channels`)).channels.find(t=>t.path===e||t.path.startsWith(r));if(c)throw new lf(`channel_exists`,c.path===e?`${e} is a channel already, so it stays as it is.`:`${c.path} is a channel already, and a private ${e} would close it too, so nothing was made.`,409,{hint:`Close it with a grant: everyone at ${r} with 'none'.`});let l=await o(`POST`,`/grants`,{body:{principals:[n],can:{[r]:`all`}}}),u=(e,t)=>e.filter(e=>{let n=t.find(t=>t.id===e.id);return n===void 0||JSON.stringify([e.principals,e.can])!==JSON.stringify([n.principals,n.can])}),d=u(await i(),[l.grant]);if(d.length>0)throw await o(`POST`,`/grants/${encodeURIComponent(l.grant.id)}/revoke`,{body:{}}),a(d,[l.grant]);let f=await o(`POST`,`/grants`,{body:{principals:[{kind:`everyone`}],can:{[r]:[]}}}),p=u(await i(),[l.grant,f.grant]);if(p.length>0){for(let e of[f.grant.id,l.grant.id])await o(`POST`,`/grants/${encodeURIComponent(e)}/revoke`,{body:{}});throw a(p,[l.grant,f.grant])}return{...await o(`POST`,`/channels`,{body:{path:e}}),grants:[l.grant,f.grant]}},actors:async()=>(await o(`GET`,`/actors`)).actors,messages:(e={})=>o(`GET`,`/messages${_f(e)}`),thread:e=>o(`GET`,`/messages/${gf(e)}`),posted:async e=>(await o(`GET`,`/posts/${gf(e)}`)).message,threads:(e={})=>o(`GET`,`/threads${_f(e)}`),async post(e,t){return(await o(`POST`,`/messages`,{body:{channel:e,...pf(t)}})).message},async reply(e,t){return(await o(`POST`,`/messages`,{body:{re:e,...pf(t)}})).message},async schedule(e,t){return(await o(`POST`,`/schedules`,{body:{...typeof e==`string`?{channel:e}:{re:e.re},...ff(t)}})).schedule},schedules:async(e={})=>(await o(`GET`,`/schedules${_f(e)}`)).schedules,cancelSchedule:e=>o(`POST`,`/schedules/${gf(e)}/cancel`,{body:{}}),createGrant:e=>o(`POST`,`/grants`,{body:{principals:e.principals.map(yf),can:vf(e.can)}}),updateGrant:(e,{add:t,remove:n,can:r})=>o(`PATCH`,`/grants/${gf(e)}`,{body:{...t?{add:t.map(yf)}:{},...n?{remove:n}:{},...r?{can:vf(r)}:{}}}),explain:(e,t={})=>{let{claims:n,...r}=t,i=new URLSearchParams({channel:e});for(let[e,t]of Object.entries(r))t!==void 0&&i.set(e,t);for(let[e,t]of Object.entries(n??{}))i.append(`claim`,`${e}=${t}`);return o(`GET`,`/grants/explain?${i}`)},grants:async()=>(await o(`GET`,`/grants`)).grants,revokeGrant:e=>o(`POST`,`/grants/${gf(e)}/revoke`,{body:{}}),schemas:async()=>(await o(`GET`,`/schemas`)).schemas,schema:async e=>(await o(`GET`,`/schemas/${gf(e)}`)).schema,createSchema:e=>o(`POST`,`/schemas`,{body:e}),async upload(e){let a=e.type||(e.data instanceof Blob?e.data.type:``)||Pe(e.name),s=e.data instanceof Blob?e.data.size:e.data.byteLength;if(s>4194304){if(s>104857600)throw new lf(`too_large`,`Attachments are at most ${je/1024/1024} MB.`,413);let t=e.data instanceof Blob?await e.data.arrayBuffer():e.data,n=btoa(String.fromCharCode(...new Uint8Array(await crypto.subtle.digest(`SHA-256`,t)))),i=await o(`POST`,`/attachments/uploads`,{body:{name:e.name,type:a,size:s,sha256:n}}).catch(e=>{throw e instanceof lf&&e.status===404&&e.code===`not_found`?new lf(`too_large`,`This board takes files of at most ${ke/1024/1024} MB.`,413):e}),c=await r(i.url,{method:`PUT`,headers:i.headers,body:e.data});if(!c.ok)throw new lf(`upload_failed`,`The blob store refused the file: ${c.status} ${(await c.text().catch(()=>``)).slice(0,300)||c.statusText}`,c.status);return(await o(`POST`,`/attachments/uploads/${encodeURIComponent(i.id)}`,{body:{}})).attachment}let c=await n(`${t}/attachments`,{method:`POST`,headers:{...await i(!0),"content-type":a,"x-board-filename":encodeURIComponent(e.name)},body:e.data});if(!c.ok)throw await Sf(c);return(await c.json()).attachment},download:(e,t={})=>a(`GET`,`/attachments/${encodeURIComponent(e)}`,t.signal?{signal:t.signal}:{}),edit:(e,t,n={})=>o(`POST`,`/messages/${gf(e)}/edit`,{body:{text:t,...n}}),delete:(e,t={})=>o(`POST`,`/messages/${gf(e)}/delete`,{body:{...t}}),react:(e,t,n={})=>o(`POST`,`/messages/${gf(e)}/reactions`,{body:{emoji:Oe(t),...n}}),label:(e,t)=>o(`POST`,`/messages/${gf(e)}/labels`,{body:t}),typing:async(e,t)=>(await o(`POST`,`/messages/${gf(e)}/typing`,{body:t?{status:t}:{}})).targets,sync:((e,t)=>t===void 0?o(`GET`,`/messages/${gf(e)}/sync`):o(`POST`,`/messages/${gf(e)}/sync`,{body:{target:t}})),linked:e=>o(`GET`,`/links${_f({url:e})}`),inbox:async(e,t={})=>(await o(`GET`,`/inbox/${e}${_f(t)}`)).events,register:e=>o(`POST`,`/watchers`,{body:e}),watchers:async()=>(await o(`GET`,`/watchers`)).watchers,matches:async(e={})=>{let{signal:t,...n}=e;return(await o(`GET`,`/watchers/matches${_f(n)}`,t?{signal:t}:{})).matches},ack:(e,t)=>o(`POST`,`/watchers/matches/${encodeURIComponent(e)}/ack`,{body:t}),readSource:(e,t,n={})=>o(`GET`,`/sources/${e}/read${_f({target:t,...n})}`),joinSource:(e,t)=>o(`POST`,`/sources/${e}/join`,{body:{target:t}}),poll:c,syncImport:e=>o(`POST`,`/sync/imports`,{body:e}),syncReceipt:e=>o(`POST`,`/sync/receipts`,{body:e}),syncThread:e=>o(`GET`,`/sync/threads/${gf(e)}`),syncFind:(e,t={})=>o(`GET`,`/sync/find${_f(e)}`,t.signal?{signal:t.signal}:{}),syncCopies:async e=>(await o(`GET`,`/sync/copies?${e.map(e=>`message=${encodeURIComponent(e)}`).join(`&`)}`)).copies,inboxPush:(e,t)=>o(`POST`,`/inbox/${gf(e)}`,{body:{events:t}}),inboxNext:async(e,t={})=>(await o(`GET`,`/inbox/${gf(e)}/next${_f(t)}`)).items,inboxAck:(e,t,n)=>o(`POST`,`/inbox/${gf(e)}/${gf(t)}/ack`,{body:n}),async*events(e={},t={}){let n=e.after,r=0;for(;!t.signal?.aborted;){let i;try{i=await a(`GET`,`/events${_f({...s(e),after:n})}`,{headers:{accept:`text/event-stream`},...t.signal?{signal:t.signal}:{}})}catch(e){if(t.signal?.aborted)return;if(e instanceof lf&&e.status>=400&&e.status<500)throw e;await new Promise(e=>setTimeout(e,Math.min(3e4,500*2**r++)));continue}r=0;try{for await(let e of Qd(i.body,t.signal))e.id!==void 0&&(n=e.id),e.event===`board`&&e.data&&(yield JSON.parse(e.data))}catch{if(t.signal?.aborted)return;await new Promise(e=>setTimeout(e,Math.min(3e4,500*2**r++)))}}},async wait(e={},t={}){let n=Date.now()+hf(t.timeout??`30m`),r=e.after??(await c({...e,after:void 0,wait:0},t.signal)).cursor;for(;Date.now()<n&&!t.signal?.aborted;){let i=Math.max(0,Math.min(25,Math.ceil((n-Date.now())/1e3))),a=await c({...e,after:r,wait:i},t.signal);if(a.events.length>0)return a.events[0];r=a.cursor}return null}}}async function Sf(e){try{let t=await e.json();if(t.error?.message)return new lf(t.error.code??`error`,t.error.message,e.status,{...typeof t.error.hint==`string`?{hint:t.error.hint}:{},origin:uf.has(e)?`handle`:`board`})}catch{}return new lf(`http_error`,`The board answered ${`${e.status} ${e.statusText}`.trim()}.`,e.status)}const Cf=e=>Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``);async function wf(e){return Cf(new Uint8Array(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e))))}async function Tf(...e){let t=new Uint8Array(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(JSON.stringify(e)))).slice(0,16);t[6]=t[6]&15|128,t[8]=t[8]&63|128;let n=Cf(t);return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20,32)}`}const Ef=/^[0-9a-f]{8}-[0-9a-f]{4}-8[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,Df=async(e,t)=>`key:${e}:${(await wf(`board-key\u001f${t}`)).slice(0,32)}`;var q=class extends Error{status;code;hint;origin;constructor(e,t,n,r={}){super(n),this.status=e,this.code=t,this.hint=r.hint,this.origin=r.origin??`board`}},Of=class extends q{response;constructor(e){super(e.status,`rejected`,`rejected with ${e.status}`),this.response=e}};const kf=(e,t=`invalid_request`)=>new q(400,t,e),Af=e=>new q(401,`unauthorized`,e),jf=e=>new q(403,`forbidden`,e),Mf=(e,t=`not_found`)=>new q(404,t,e),Nf=()=>new q(400,`text_too_long`,`A message's text is at most ${xu.toLocaleString(`en-US`)} characters.`,{hint:`Put the long part in a file and attach it to a message, with a short summary as the text.`}),Pf=()=>new q(409,`duplicate_id`,`that id was already used for a different write`),Ff=(e,t=200,n)=>new Response(JSON.stringify(e),{status:t,headers:{"content-type":`application/json`,...n}});function If(e){if(e.code!==`invalid_union`||e.errors.length===0)return e;let t=e.errors.reduce((e,t)=>t.length<e.length?t:e)[0];return t?If({...t,path:[...e.path,...t.path]}):e}function Lf(e){if(e instanceof Of)return e.response;if(e instanceof q){let t=Ff({error:{code:e.code,message:e.message,...e.hint===void 0?{}:{hint:e.hint}}},e.status);return e.origin===`handle`&&uf.add(t),t}if(e instanceof Nc){let t=e.issues[0]&&If(e.issues[0]);if(t?.code===`too_big`&&t.origin===`string`&&t.maximum===1e4&&t.path.length===1&&t.path[0]===`text`)return Lf(Nf());let n=t?.path.length?`${t.path.join(`.`)}: `:``;return Ff({error:{code:`invalid_request`,message:`${n}${t?.message??`invalid request`}`}},400)}let t=e?.code;return t===`INVALID_PAYLOAD`?Ff({error:{code:`invalid_request`,message:e.message}},400):t===`PARTIAL_DUPLICATE_BATCH`||t===`DUPLICATE_EVENT_ID`?Lf(Pf()):t===`STORE_UNAVAILABLE`||t===`STORE_NOT_CONFIGURED`?Ff({error:{code:`unavailable`,message:e.message}},503):(console.error(`[board]`,e),Ff({error:{code:`internal`,message:`internal error`}},500))}const Rf=`0.42.0`,zf=[`avatar`,`openapi`,`webhook`,`sync`],Bf=/* @__PURE__ */ `discovery.me.channels.createChannel.actors.messages.threads.message.post.posted.edit.delete.react.label.schedule.schedules.cancelSchedule.grants.createGrant.updateGrant.explain.revokeGrant.schemas.schema.createSchema.upload.attachment.uploadStart.uploadFinish.watchers.register.matches.ack.events.syncImport.syncReceipt.syncThread.syncFind.syncCopies.inboxPush.inboxNext.inboxAck.inbox.typing.readSource.joinSource.synced.linked`.split(`.`),Vf=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);function Hf(e,t,n,r){let i=t.split(`/`).filter(Boolean),a=i.map(e=>e.startsWith(`:`)?`/([^/]+)`:`/${Vf(e)}`).join(``);return{method:e,pattern:RegExp(`${a}$`),names:i.filter(e=>e.startsWith(`:`)).map(e=>e.slice(1)),target:n,segments:i.length,literals:i.filter(e=>!e.startsWith(`:`)).length,own:r}}function Uf(e,t){let n=[...zf.map(e=>Hf(Zd[e].method,Zd[e].path,{kind:`board`,name:e},!1)),...Bf.filter(e=>e!==`discovery`).map(e=>Hf(Zd[e].method,Zd[e].path,{kind:`protocol`,name:e},!1)),...e.map(e=>Hf(e.method,e.path,{kind:`backend`,route:e},!0))].sort((e,t)=>t.segments-e.segments||t.literals-e.literals||Number(t.own)-Number(e.own)),r=(e,t,n)=>{let r={};try{e.names.forEach((e,t)=>r[e]=decodeURIComponent(n[t]))}catch{return null}let i=e.names[0];return{target:e.target,base:t,param:i===void 0?null:r[i],params:r}},i=e=>({target:{kind:`protocol`,name:`discovery`},base:e,param:null,params:{},root:!0});return function(e,a){let o=a.length>1?a.replace(/\/+$/,``):a;if(t!==void 0){let a=t.replace(/\/+$/,``);if(o!==a&&!o.startsWith(`${a}/`))return null;let s=o.slice(a.length)||`/`;if(s===`/`)return e===`GET`?i(a):null;for(let t of n){let n=t.method===e?s.match(RegExp(`^${t.pattern.source}`)):null;if(n)return r(t,a,n.slice(1))}return null}for(let t of n){if(t.method!==e)continue;let n=o.match(t.pattern);if(n)return r(t,o.slice(0,n.index),n.slice(1))}return e===`GET`?i(o===`/`?``:o):null}}function Wf(e){let t={};for(let n of new Set(e.searchParams.keys())){let r=e.searchParams.getAll(n);t[n]=r.length>1?r:r[0]}return t}async function Gf(e){let t=await e.text();if(t.trim()!==``)try{return JSON.parse(t)}catch{throw kf(`request body is not valid JSON`)}}const Kf=()=>new q(413,`too_large`,`attachments are at most ${ke/1024/1024} MB`);async function qf(e,t){if(Number(e.headers.get(`content-length`)??0)>t)throw Kf();let n=[],r=0;for await(let i of e.body??[]){if(r+=i.byteLength,r>t)throw Kf();n.push(i)}let i=new Uint8Array(r),a=0;for(let e of n)i.set(e,a),a+=e.byteLength;return i}function Jf(){let e={};for(let[t,n]of Object.entries(Zd)){let r=n.path.replace(/:(\w+)/g,`{$1}`),i={operationId:t};`query`in n&&(i[`x-query-schema`]=kc(n.query,{io:`input`})),`body`in n&&(i.requestBody={content:{"application/json":{schema:kc(n.body,{io:`input`})}}}),(e[r]??={})[n.method.toLowerCase()]=i}return{openapi:`3.1.0`,info:{title:`board`,version:Rf},paths:e}}const Yf={re:{type:`string`,value:`id`,description:`in a thread: its root's ID`},by:{type:`string`,value:`handle`,description:`by an author: a handle, me, or an actor ID`},mentions:{type:`string`,value:`@handle`,optionalValue:!0,description:`mentioning a handle or email, or you without one`},label:{type:`string`,multiple:!0,value:`k[=v|w]`,description:`with a label on the message or its thread's root`},source:{type:`string`,value:`source`,description:`from a source: a sync key such as slack, or board`},text:{type:`string`,value:`words`,description:`containing this text, as one phrase (a substring, not word search)`},after:{type:`string`,value:`id`,description:`only what came after a message or a cursor (read and wait print one)`},url:{type:`string`,value:`url`,description:`the board at this URL, not the one the environment points at`},scope:{type:`string`,value:`team`,description:`a team's board in Vercel's API, by its slug or ID`},name:{type:`string`,value:`board`,description:`the team's board with this name, on --scope's team`},ensure:{type:`boolean`,description:`with --name: make that board if the team has none by that name`},team:{type:`string`,value:`team`,description:`the same as --scope`,hidden:!0},as:{type:`string`,value:`profile`,description:`write as a profile, such as an agent's name`},avatar:{type:`string`,value:`url`,description:`the profile's avatar, with --as`},json:{type:`boolean`,description:`JSON, for programs`},help:{type:`boolean`,short:`h`,description:`this help, or a command's`},version:{type:`boolean`,short:`v`,description:`the CLI's version`},limit:{type:`string`,short:`n`,value:`N`,description:`how many`},"idempotency-key":{type:`string`,value:`key`,description:`sending the same one again posts once`},sync:{type:`string`,multiple:!0,value:`target`,description:`sync the new thread to a target too, e.g. slack:#incidents`},"no-sync":{type:`boolean`,description:`keep it on the board: sync it nowhere`},attach:{type:`string`,multiple:!0,value:`file`,description:`attach a file`},"text-file":{type:`string`,value:`path`,description:`the text, from a file: - reads stdin`},unset:{type:`string`,multiple:!0,value:`k`,description:`remove a label`},if:{type:`string`,multiple:!0,value:`k=v`,description:`only while the message has this label now`},"if-unset":{type:`string`,multiple:!0,value:`k`,description:`only while the message doesn't have this label`},"if-revision":{type:`string`,value:`N`,description:`only if it is still at this revision, as read --json shows it`},channel:{type:`string`,value:`c`,description:`in a channel`},remove:{type:`boolean`,description:`take the reaction back`},all:{type:`boolean`,short:`a`,description:`everything, not only what most want`},timeout:{type:`string`,value:`duration`,description:`how long to wait: 30s, 10m, or a bare number of seconds (default: 30m)`},"no-open":{type:`boolean`,description:`don't open the browser`},in:{type:`string`,value:`duration`,description:`once, this long from now, e.g. 90s, 5m, 1d`},at:{type:`string`,value:`time`,description:`at a time: once, or with --every, the first`},every:{type:`string`,value:`duration`,description:`repeating at this interval, e.g. 30m`},until:{type:`string`,short:`u`,value:`time`,description:`repeating until a time`},for:{type:`string`,value:`duration`,description:`repeating for this long, e.g. 24h`},times:{type:`string`,value:`N`,description:`repeating this many times`},can:{type:`string`,multiple:!0,value:`pattern=perms`,description:`what they may do, repeated: perms, all, or none`},user:{type:`string`,multiple:!0,value:`email`,description:`a person on the team`},project:{type:`string`,multiple:!0,short:`p`,value:`name|id`,description:`a project's deployments`},github:{type:`string`,multiple:!0,value:`owner/repo`,description:`GitHub Actions' runs in a repository`},oidc:{type:`string`,multiple:!0,value:`issuer`,description:`an issuer's tokens, by its URL`},"all-users":{type:`boolean`,description:`every person on the team`},"all-projects":{type:`boolean`,description:`every project's deployments on the team`},app:{type:`string`,multiple:!0,value:`slug|id`,description:`an app installed on the team`},"all-apps":{type:`boolean`,description:`every app installed on the team`},everyone:{type:`boolean`,description:`everyone let in some other way, and no one new`},environment:{type:`string`,multiple:!0,short:`e`,value:`environment`,description:`where its --project runs`},workflow:{type:`string`,multiple:!0,value:`file`,description:`its --github's workflow, e.g. ci.yml`},"git-branch":{type:`string`,multiple:!0,value:`branch`,description:`its --github's branch`},event:{type:`string`,multiple:!0,value:`event`,description:`its --github's event, e.g. push`},claim:{type:`string`,multiple:!0,value:`k=v`,description:`a claim its --oidc's tokens carry`},"add-user":{type:`string`,multiple:!0,value:`email`,description:`add a person`},"add-project":{type:`string`,multiple:!0,value:`name|id`,description:`add a project's deployments`},"add-github":{type:`string`,multiple:!0,value:`owner/repo`,description:`add a repository's runs`},"add-oidc":{type:`string`,multiple:!0,value:`issuer`,description:`add an issuer's tokens`},"add-all-users":{type:`boolean`,description:`add every person on the team`},"add-all-projects":{type:`boolean`,description:`add every project on the team`},"add-app":{type:`string`,multiple:!0,value:`slug|id`,description:`add an app`},"add-all-apps":{type:`boolean`,description:`add every app on the team`},"add-everyone":{type:`boolean`,description:`add everyone something else lets in`},"remove-user":{type:`string`,multiple:!0,value:`email`,description:`remove a person`},"remove-project":{type:`string`,multiple:!0,value:`name|id`,description:`remove a project, whatever its environments`},"remove-github":{type:`string`,multiple:!0,value:`owner/repo`,description:`remove a repository's runs`},"remove-oidc":{type:`string`,multiple:!0,value:`issuer`,description:`remove an issuer's tokens`},"remove-all-users":{type:`boolean`,description:`remove every person on the team`},"remove-all-projects":{type:`boolean`,description:`remove every project on the team`},"remove-app":{type:`string`,multiple:!0,value:`slug|id`,description:`remove an app`},"remove-all-apps":{type:`boolean`,description:`remove every app on the team`},"remove-everyone":{type:`boolean`,description:`remove everyone`},private:{type:`boolean`,description:`closed to everyone but you, in the same write`},schema:{type:`string`,value:`json|@file`,description:`its JSON Schema: inline, @<file>, or - for stdin`},description:{type:`string`,value:`text`,description:`what it holds, in a sentence`},port:{type:`string`,value:`N`,description:`the port to listen on`},dir:{type:`string`,value:`dir`,description:`where the board keeps its log (default: .board/)`},"no-inspect":{type:`boolean`,description:`don't start the inspector`},agent:{type:`string`,value:`name`,description:`the agent whose turn ended`,hidden:!0}},J=(e,t,n)=>({name:e,...Yf[e],...t?{description:t}:{},...n?{value:n}:{}});[`re`,`by`,`source`,`label`,`text`,`mentions`,`after`].map(e=>J(e)),[`url`,`scope`,`name`,`ensure`,`team`,`as`,`avatar`,`json`,`help`,`version`].map(e=>J(e));const Xf=`a reply only while this is the thread's newest message`;[...[`user`,`project`,`github`,`oidc`,`app`,`all-users`,`all-projects`,`all-apps`,`everyone`].map(e=>J(e)),J(`environment`,`where its --project runs (default: production)`),...[`workflow`,`git-branch`,`event`,`claim`].map(e=>J(e)),J(`can`,`what they may do, repeated: perms, all, or none`,`pattern=perms`)],[...[`add-user`,`add-project`,`add-github`,`add-oidc`,`add-app`,`add-all-users`,`add-all-projects`,`add-all-apps`,`add-everyone`,`remove-user`,`remove-project`,`remove-github`,`remove-oidc`,`remove-app`,`remove-all-users`,`remove-all-projects`,`remove-all-apps`,`remove-everyone`,`environment`,`workflow`,`git-branch`,`event`,`claim`].map(e=>J(e)),J(`can`,`replaces what it lets them do`,`pattern=perms`)],[...[`user`,`project`,`github`,`oidc`,`app`,`environment`,`workflow`,`git-branch`,`event`,`claim`].map(e=>J(e))],J(`private`),J(`schema`),J(`description`),J(`limit`,`threads to list (default: 50)`),J(`label`,`label it`,`k=v`),J(`text-file`),J(`schema`,`the text is JSON for this schema, such as sandbox@1`,`schema`),J(`attach`),J(`sync`),J(`no-sync`),J(`idempotency-key`),J(`after`,Xf),J(`label`,`label it`,`k=v`),J(`text-file`),J(`schema`,`the text is JSON for this schema, such as sandbox@1`,`schema`),J(`attach`),J(`idempotency-key`),J(`no-sync`),J(`after`,Xf),J(`in`),J(`at`),J(`every`),J(`until`),J(`for`),J(`times`),J(`label`,`label it`,`k=v`),J(`text-file`),J(`schema`,`the text is JSON for this schema, such as sandbox@1`,`schema`),J(`attach`),J(`no-sync`),J(`by`,`scheduled by a handle`),J(`channel`,`posting in a channel`),J(`all`,`done and canceled ones too`),J(`text-file`),J(`schema`,`the text is JSON for this schema, such as sandbox@1`,`schema`),J(`if-revision`),J(`if-revision`),J(`remove`),J(`unset`),J(`if`),J(`if-unset`),J(`limit`,`events to list`),J(`limit`,`messages to read`),J(`after`,`where the last read left off: the cursor it printed`),J(`channel`,`the channel to check in (default: conformance)`),J(`agent`),J(`all`,`delivery receipts too`),J(`timeout`),J(`port`,`the port to listen on (default: a free one)`),J(`no-open`);const Zf={re:Yf.re,by:Yf.by,mentions:Yf.mentions,label:Yf.label,source:Yf.source,text:Yf.text},Qf=e=>e!==void 0&&!e.startsWith(`-`)&&(e===`me`||e.includes(`@`));function $f(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];if(r===`--`){t.push(...e.slice(n));break}r===`--mentions`?Qf(e[n+1])?t.push(`--mentions=${e[++n]}`):t.push(`--mentions=me`):t.push(r)}return t}function ep(e){let t=[],n=null,r=null;for(let i=0;i<e.length;i++){let a=e[i];r?a===r?r=null:a===`\\`&&r===`"`&&i+1<e.length?n+=e[++i]:n+=a:/\s/.test(a)?(n!==null&&t.push(n),n=null):a===`"`||a===`'`?(r=a,n??=``):n=a===`\\`&&i+1<e.length?(n??``)+e[++i]:(n??``)+a}if(r)throw Error(`unterminated ${r}`);return n!==null&&t.push(n),t}const tp={...Zf,all:{type:`boolean`}};function np(e){let t={},n=[];for(let r=0;r<e.length;r++){let i=e[r];if(i===`--`){n.push(...e.slice(r+1));break}if(!i.startsWith(`-`)||i===`-`){n.push(i);continue}let a=i.indexOf(`=`),o=i.startsWith(`--`)?i.slice(2,a===-1?void 0:a):null,s=o!==null&&Object.hasOwn(tp,o)?tp[o]:null;if(!s)throw Error(`${o===null?i.slice(0,2):`--${o}`} isn't a filter`);if(s.type===`boolean`){if(a!==-1)throw Error(`--${o} takes no value`);t[o]=!0;continue}let c;if(a!==-1)c=i.slice(a+1);else{let t=e[r+1];if(t===void 0||t.length>1&&t.startsWith(`-`))throw Error(`--${o} needs a value`);c=t,r++}t[o]=`multiple`in s?[...t[o]??[],c]:c}return{values:t,positionals:n}}function rp(e){let{values:t,positionals:n}=np($f(ep(e)));if(n.length>1)throw Error(`expected one channel, got: ${n.join(` `)}`);let r=n[0],i=rd.safeParse({...r?{channel:r}:{},...t.re?{re:t.re.replace(/^#/,``)}:{},...t.by?{by:t.by.replace(/^@/,``)}:{},...t.mentions?{mentions:t.mentions.replace(/^@/,``)}:{},...t.label?.length?{label:t.label}:{},...t.source?{from:t.source}:{},...t.text?{text:t.text}:{}});if(!i.success){let e=i.error.issues[0];throw Error(`${e?.path.length?`--${String(e.path[0])}: `:``}${e?.message??`invalid filters`}`)}return{filters:i.data,all:t.all===!0}}const ip=e=>e.channel!==void 0||e.re!==void 0||e.by!==void 0||e.mentions!==void 0||e.from!==void 0||e.text!==void 0||(e.label?.length??0)>0;function ap(e,t){let n,r;try{({filters:n,all:r}=rp(t.tail))}catch(t){throw Error(`watch ${e}: ${t.message}`)}if(n.mentions===`me`)throw Error(`watch ${e}: a watcher has no "me": use --mentions @handle`);return{filters:n,criteria:ip(n),all:r}}function op(e){try{Reflect.get(globalThis,Symbol.for(`@vercel/request-context`))?.get?.()?.waitUntil?.(e)}catch{}}const sp=1e4,cp=e=>((e instanceof Error?e.message:String(e))||`unknown error`).slice(0,500),lp=e=>e?.startsWith(`https://`)?e:null,up=e=>e.path===void 0,dp=()=>typeof process<`u`&&process.env.VERCEL===`1`&&process.env.VERCEL_ENV!==`development`;function fp(e){if(!e||!dp())return null;let t=process.env,n=(t.VERCEL_TARGET_ENV||t.VERCEL_ENV)===`preview`&&t.VERCEL_GIT_COMMIT_REF||null;return{path:new URL(e).pathname,...n?{branch:n}:{}}}function pp(e){let{registry:t,rethrow:n}=e,r=e.binding,i=null,a=null;async function o(n,r=!1){let o=await e.hash();return!r&&i&&i.url===n&&i.result.hash===o&&Date.now()-i.at<sp?i.result:(r&&a&&await a.catch(()=>{}),a??=e.wakeAt(n).then(e=>t.register(e)).then(e=>(i={url:n,at:Date.now(),result:e},e)).finally(()=>{a=null}),a)}async function s(e){let n={};if(!r().subscriptions[e.watcher])n={skip:!0};else try{await r().run(e.watcher,e.event,{trigger:`watch:${e.watcher}:${e.id}`,attempt:e.attempt+1})}catch(t){console.error(`[board] watcher ${e.watcher} failed:`,t),n={error:cp(t)}}await t.ack(e.id,{lease:e.lease,...n}).catch(e=>console.error(`[board] couldn't ack a match:`,cp(e)))}async function c(){let e=0,n=Date.now()+24e4;for(;Date.now()<n;){let n=await t.matches({limit:10});if(n.length===0)break;await Promise.all(n.map(s)),e+=n.length}return e+await r().pull()}let l=null;function u(){if(l||dp())return;let n=l=new AbortController;(async()=>{for(let i=1e3;!n.signal.aborted;)try{await o(null);let e=await t.matches({limit:10,wait:25,signal:n.signal});await Promise.all(e.map(s)),await r().pull(),i=1e3}catch(t){if(n.signal.aborted)break;console.error(`[board] couldn't pull matches from ${e.remote}:`,cp(t)),await new Promise(e=>setTimeout(e,i)),i=Math.min(i*2,6e4)}})()}let d=null,f=0;function p(){if(d)return d;if(!e.hasWork()||Date.now()-f<sp)return Promise.resolve();let t=lp(r().url());return!t&&dp()?Promise.resolve():(d=o(t).then(e=>{up(e)&&u()},t=>{d=null,f=Date.now(),console.error(`[board] couldn't register with ${e.remote}:`,cp(t))}),t||u(),d)}return{start:p,routes:[{method:`POST`,path:`/wake`,async handle(t){d??=Promise.resolve();let i=t.headers.get(`x-board-watchers`)!==await e.hash(),a=(async()=>(i&&await o(lp(r().url())),c()))();op(a.catch(e=>console.error(`[board] couldn't run what woke it:`,cp(e))));let s,l=new Promise(e=>s=setTimeout(()=>e(null),2e3));try{let e=await Promise.race([a.catch(n),l]);return e===null?new Response(null,{status:202}):Ff({ran:e})}finally{clearTimeout(s)}}},{method:`POST`,path:`/watchers`,async handle(t,{caller:i}){if(i)return e.registerFor(i,t);d??=Promise.resolve();let a=lp(r().url()),s=await o(a).catch(n);return(!a||up(s))&&u(),Ff(s)}}],registerNow:(e=!1)=>o(lp(r().url()),e),close:()=>{l?.abort(),l=null}}}const mp=e=>e>10,hp=e=>((e instanceof Error?e.message:String(e))||`unknown error`).slice(0,500);async function gp(e){let{watcher:t,match:n,attempt:r}=e,i=n.payload.event,a=async a=>{console.error(`[board] watcher ${t.id} gave up on event #${i.cursor} after ${r} tries:`,a),await e.record({matched:n.id,thread:n.payload.thread,error:a})},o=!mp(r);if(o&&r>=10)return a(`its run was cut short ${r-1} times (a timeout, or out of memory)`);try{await t.run(i)}catch(e){if(!o||r<5)throw e;await a(hp(e))}}const _p=1e3,vp=e=>((e instanceof Error?e.message:String(e))||`unknown error`).slice(0,500);function yp(e){let t=null,n=crypto.randomUUID(),r=0;async function i(t,i,o,s){let c,l=/* @__PURE__ */ new Map,u={...i,...o?{all:!0}:{}},d;for(let i=_p;!s.aborted;){let o;try{c??=await e.actorOf(t),o=await e.events(d===void 0?{...u,wait:0}:{...u,after:d,wait:25},s),i=_p}catch(e){if(s.aborted)return;console.error(`[board] watcher ${t} couldn't read the board:`,vp(e)),await bp(i,s),i=Math.min(i*2,6e4);continue}d=o.cursor;for(let e of o.events){if(e.actor?.id===c&&!(e.type===`message.posted`&&e.message?.schedule))continue;let i=e.message?.thread??``,o={id:`${n}:${r++}`,payload:{thread:i,event:e}},u=(l.get(i)??Promise.resolve()).then(()=>a(t,o,s));l.set(i,u),u.then(()=>{l.get(i)===u&&l.delete(i)})}}}async function a(t,n,r){let i=`watch:${t}:${n.id}`;for(let a=1,o=1e3;!r.aborted;a++,o=Math.min(o*2,3e4))try{await gp({watcher:{id:t,run:n=>e.run(t,n,{trigger:i,attempt:a})},match:n,attempt:a,record:async()=>{}});return}catch(e){console.error(`[board] watcher ${t} failed:`,e),await bp(o,r)}}return{start(){if(t)return;let{signal:n}=t=new AbortController;for(let[t,{filters:r,all:a}]of Object.entries(e.watchers))i(t,r,a,n)},close(){t?.abort(),t=null}}}const bp=(e,t)=>new Promise(n=>{if(t.aborted)return n();let r=setTimeout(n,e);t.addEventListener(`abort`,()=>(clearTimeout(r),n()),{once:!0})}),xp=[`read`,`post`,`react`,`label`,`sync`,`manage`];var Sp=class extends Error{code=`invalid_can`;constructor(e){super(e),this.name=`InvalidCan`}};const Cp={read:[],post:[],react:[`read`],label:[`read`],sync:[`read`],manage:[`read`,`post`,`react`,`label`,`sync`]},wp=new Map(xp.map((e,t)=>[e,t])),Tp=`write *, a channel, or a channel and its subtree (feedback/)`;function Ep(e){if(e===`*`)return{kind:`all`};if(e.includes(`*`)){let t=e.slice(0,e.indexOf(`*`)).replace(/\/+$/,``);throw new Sp(`invalid channel pattern ${e}: ${t===``?`write * for every channel`:Cu.safeParse(t).success?`write ${t}/ for ${t} and its subtree`:Tp}`)}let t=e.endsWith(`/`),n=t?e.slice(0,-1):e;if(!Cu.safeParse(n).success)throw new Sp(`invalid channel pattern ${e||`(empty)`}: ${Tp}`);return t?{kind:`subtree`,path:n}:{kind:`exact`,path:n}}const Dp=e=>e.kind===`all`?`*`:e.kind===`subtree`?`${e.path}/`:e.path;function Op(e){let t=/* @__PURE__ */ new Set,n=e=>{if(!wp.has(e))throw new Sp(`unknown permission ${String(e)}: use ${xp.join(`, `)}`);if(!t.has(e)){t.add(e);for(let t of Cp[e])n(t)}};for(let t of e===`all`?xp:e)n(t);return t}const kp=/* @__PURE__ */ new Set;function Ap(e){let t=null,n=/* @__PURE__ */ new Map,r=[];for(let[i,a]of e)i.kind===`all`?t=a:i.kind===`exact`?n.set(i.path,a):r.push([i.path,a]);return r.sort((e,t)=>t[0].length-e[0].length),{all:t,exact:n,subtrees:r}}const jp=(e,t)=>e===t||e.startsWith(`${t}/`);function Mp(e,t,n=!1){if(!n){let n=e.exact.get(t);if(n)return n}for(let[n,r]of e.subtrees)if(jp(t,n))return r;return e.all??kp}const Np=(e,t)=>t.kind===`all`?e.all??kp:Mp(e,t.path,t.kind===`subtree`),Pp=(e,t)=>e.size===t.size&&[...e].every(e=>t.has(e));function Fp(e,t){if(t.kind===`exact`)return Mp(e,t.path,!0);if(t.kind===`subtree`){for(let[n,r]of e.subtrees)if(n!==t.path&&jp(t.path,n))return r}return e.all??kp}function Ip(e){let t=Ap(e);return Ap(e.filter(([e,n])=>e.kind===`all`?n.size>0:!Pp(n,Fp(t,e))))}function Lp(e){return e===`all`||Array.isArray(e)?[[{kind:`all`},Op(e)]]:Object.entries(e).map(([e,t])=>[Ep(e),Op(t)])}const Rp=e=>[...e.all?[[{kind:`all`},e.all]]:[],...e.subtrees.map(([e,t])=>[{kind:`subtree`,path:e},t]),...[...e.exact].map(([e,t])=>[{kind:`exact`,path:e},t])],zp=Symbol(`board.access`),Bp=e=>typeof e==`object`&&zp in e;function Vp(e){let t=Rp(e),n=n=>(e.all?.has(n)??!1)&&t.every(([,e])=>e.has(n)),r=e.exact.size===0&&e.subtrees.length===0?e.all?.has(`read`)??!1:null,i=/* @__PURE__ */ new Map,a={[zp]:e,can:(t,n)=>Mp(e,n).has(t),readable(t){if(r!==null)return r;let n=i.get(t);return n===void 0&&(i.size>=4096&&i.clear(),i.set(t,n=Mp(e,t).has(`read`))),n},readsAll:n(`read`),everywhere:n,anywhere:e=>t.some(([,t])=>t.has(e)),at:(t,n)=>Np(e,Ep(n)).has(t),narrow(n){let r=Bp(n)?n[zp]:Ip(Lp(n)),i=/* @__PURE__ */ new Map([[`*`,{kind:`all`}]]);for(let[e]of[...t,...Rp(r)])i.set(Dp(e),e);return Vp(Ip([...i.values()].map(t=>{let n=Np(r,t);return[t,new Set([...Np(e,t)].filter(e=>n.has(e)))]})))},summary(){let e=t.map(([e,t])=>[Dp(e),t]);e.sort(([e],[t])=>e===`*`?-1:t===`*`?1:e.localeCompare(t));let n={};for(let[t,r]of e)n[t]=[...r].sort((e,t)=>wp.get(e)-wp.get(t));return n}};return Object.freeze(a)}function Hp(e){return Vp(Ip(Lp(e)))}const Up=Hp(`all`);Hp([]);const Wp=new Map([`principal`,`group`,`everyone`].map((e,t)=>[e,t])),Gp=e=>Lp(e);function Kp(e){let t=/* @__PURE__ */ new Map;for(let n of e)for(let[e,r]of Gp(n.can)){let i=Dp(e),a=t.get(i);if(!a||Wp.get(n.level)<Wp.get(a.level))t.set(i,{pattern:e,level:n.level,permissions:new Set(r),sources:[n.source]});else if(a.level===n.level){for(let e of r)a.permissions.add(e);a.sources.includes(n.source)||a.sources.push(n.source)}}return t}function qp(e){return Vp(Ip([...Kp(e).values()].map(({pattern:e,permissions:t})=>[e,t])))}function Jp(e,t){let n=[...Kp(e).values()].filter(({pattern:e})=>e.kind===`all`?!0:e.kind===`exact`?e.path===t:jp(t,e.path)),r=({pattern:e})=>e.kind===`exact`?1/0:e.kind===`subtree`?e.path.length:-1,[i,...a]=n.sort((e,t)=>r(t)-r(e));return i?{pattern:Dp(i.pattern),over:a.map(({pattern:e})=>Dp(e)),level:i.level,sources:i.sources,permissions:[...i.permissions].sort((e,t)=>wp.get(e)-wp.get(t))}:{pattern:null,over:[],level:null,sources:[],permissions:[]}}function Yp(e){let t=Object.entries(e.summary()).map(([e,t])=>`${e}=${t.join(`,`)}`);return t.length>0?t.join(`;`):`*=`}function Xp(e,t=`x-board-can`){if(e.length>4e3)throw new Sp(`${t} is longer than 4000 characters`);let n={},r=e.split(`;`).map(e=>e.trim());if(r.every(e=>e===``))throw new Sp(`${t} is empty: write pattern=permissions, like dev/=read,post`);for(let e of r){if(e===``)continue;let r=e.indexOf(`=`);if(r<0)throw new Sp(`${t} entry ${e} needs =: write pattern=permissions, like dev/=read,post`);let i=e.slice(0,r).trim(),a=e.slice(r+1).trim();if(Object.hasOwn(n,i))throw new Sp(`${t} lists ${i} twice`);Ep(i);let o=a===``?[]:a.split(`,`).map(e=>e.trim());if(o.length===1&&o[0]===`all`){n[i]=`all`;continue}for(let e of o)if(!wp.has(e))throw new Sp(`${t}: unknown permission ${e||`(empty)`}: use ${xp.join(`, `)}, or all`);n[i]=o}return n}function Zp(e,t){let{caller:n}=t;switch(e.kind){case`everyone`:return`everyone`;case`all-users`:return n.kind===`user`&&t.member===!0?`group`:null;case`user`:return n.kind===`user`&&n.userId===e.userId?`principal`:null;case`all-projects`:return n.kind===`project`&&t.teamProject===!0&&e.environments.includes(n.environment)?`group`:null;case`project`:return n.kind===`project`&&n.projectId===e.projectId&&(e.teamId===void 0||n.teamId===void 0||n.teamId===e.teamId)&&e.environments.includes(n.environment)?`principal`:null;case`github`:{if(n.kind!==`github`)return null;let t=e.repositoryId===void 0?n.repository===e.repository:n.repositoryId===e.repositoryId,r=e.workflow===void 0||n.ref!==void 0&&n.workflowRef===`${n.repository}/${e.workflow}@${n.ref}`,i=e.branch===void 0||n.ref===`refs/heads/${e.branch}`,a=e.event===void 0||n.event===e.event;return t&&r&&i&&a?`principal`:null}case`app`:return n.kind===`app`&&n.clientId===e.clientId?`principal`:null;case`all-apps`:return n.kind===`app`&&t.teamApp===!0?`group`:null;case`oidc`:return n.kind===`oidc`&&n.issuer===e.issuer&&Object.entries(e.claims).every(([e,t])=>{let r=n.claims[e];return r===void 0?!1:typeof t==`string`?String(r)===t:t.includes(String(r))})?`principal`:null}}const Qp={principal:0,group:1,everyone:2};function $p(e,t=!1){let n=[];for(let r of e.grants){let i=null;for(let n of r.principals){if(t&&n.kind===`everyone`)continue;let r=Zp(n,e);r!==null&&(i===null||Qp[r]<Qp[i])&&(i=r)}i!==null&&n.push({level:i,can:r.can,source:{grant:r}})}return n}function em(e,t=$p(e)){return e.caller.kind===`user`&&e.member===!0||t.some(e=>e.level!==`everyone`)}function tm(e,t){let n=t.cap===void 0?e:e.narrow({"*":[...t.cap]});return t.can!==void 0&&(n=n.narrow(Hp(t.can))),n}function nm(e){let t=$p(e);return em(e,t)?{caller:tm(qp(t),e),own:tm(qp($p(e,!0)),e)}:null}function rm(e,t){let n=$p(e);if(!em(e,n))return{pattern:null,over:[],level:null,grants:[],capped:!1,permissions:[]};let r=Jp(n,t),i=e.cap===void 0?null:Hp({"*":[...e.cap]}),a=i?r.permissions.filter(e=>i.can(e,t)):[...r.permissions],o=e.can===void 0?null:Hp(e.can);return{pattern:r.pattern,over:[...r.over],level:r.level,grants:r.sources.map(e=>e.grant),capped:a.length<r.permissions.length,permissions:o?a.filter(e=>o.can(e,t)):a}}const im=/^https:\/\/oidc\.vercel\.com(?:\/[a-z0-9-]+)?$/,am=e=>{let t=new URL(e);return`${t.host}${t.pathname.replace(/\/+$/,``)}`.replace(/[%:]/g,e=>e===`%`?`%25`:`%3A`)},om=Object.freeze({"*":Object.freeze([`read`,`post`,`react`,`label`])});function sm(e){let t=e.toLowerCase().replace(/\.$/,``);return t.startsWith(`[`)||/^\d+(\.\d+){3}$/.test(t)||/^\d+$/.test(t)||!t.includes(`.`)||t===`localhost`?!0:/\.(localhost|local|internal|home|lan|corp|intranet)$/.test(t)}const cm=e=>e.split(`:`).slice(2).join(`:`);function lm(e,t,n){let r=t?.claims??{};return e.kind===`person`?{caller:{kind:`user`,userId:cm(e.id)},member:!0}:t?.issuer===`vercel`?{caller:{kind:`project`,projectId:String(r.project_id??``),environment:String(r.environment??``),...typeof r.owner_id==`string`?{teamId:r.owner_id}:{}},teamProject:n!==null&&r.owner_id===n}:t?.issuer===`github`?{caller:{kind:`github`,repository:String(r.repository??``),...r.repository_id===void 0?{}:{repositoryId:String(r.repository_id)},...r.workflow_ref===void 0?{}:{workflowRef:String(r.workflow_ref)},...r.ref===void 0?{}:{ref:String(r.ref)},...r.event_name===void 0?{}:{event:String(r.event_name)}}}:t?.issuer===`oidc`?{caller:{kind:`oidc`,issuer:t.iss,claims:r}}:null}function um(e,t){let n=new Set(e.map(am)),r=[...e];for(let i of t){if(e.includes(i))continue;let t=URL.parse(i);if(t?.protocol!==`https:`||sm(t.hostname))continue;let a=am(i);n.has(a)||(n.add(a),r.push(i))}return r}const dm=e=>[...new Set(e.flatMap(e=>e.principals.flatMap(e=>e.kind===`oidc`?[e.issuer]:[])))],fm=(e,t)=>new q(403,`forbidden`,`this token can't use this board: no grant lets in ${e}`,{hint:`Grant it: vb grants create ${t}`});function pm(e){async function t(t,n,r,i){let a=i??(e.grants?await e.grants():[]),o=lm(t,n,r);return{grants:a,facts:o?{...o,grants:a}:null}}async function n(n,r,i){let a=r?.claims??{},o=r?.issuer===`vercel`?await e.project():null,s=String(a.environment??``),c=mm(),l=o!==null&&o.id!==null&&a.project_id===o.id;if(l&&c!==null&&s===c)return{fixed:Up};if(!r)throw jf(`this token can't use this board`);let{grants:u,facts:d}=await t(n,r,o?.teamId??null,i);if(d&&em(d))return{facts:d};if(r.issuer===`oidc`&&!dm(u).includes(r.iss))throw Af(`untrusted issuer: ${r.iss}`);if(r.issuer===`oidc`)throw jf(`this token can't use this board: no grant lets in its claims`);if(r.issuer===`github`){let e=String(a.repository??``);throw fm(e||`its repository`,`--github ${e||`<OWNER/REPO>`}`)}let f=String(a.project_id??``)||`<PROJECT_ID>`,p=`--project ${f} --environment ${s||`<ENVIRONMENT>`}`;throw l?new q(403,`forbidden`,`this token can't use this board: it runs in ${c??`no Vercel environment`}, and its ${s||`unnamed`} deployments need a grant`,{hint:`Grant them: vb grants create ${p}`}):fm(`project ${f} in ${s||`no environment`}`,p)}async function r(r,i){let a=r.facts?.issuer===`host`;if(r.id.startsWith(`board:`)||r.kind===`external`&&!a)return{fixed:Up};if(a){if(!e.hosts)throw jf(`this token can't use this board: its board no longer takes a host's principals`);let{exp:t}=r.facts.claims;if(typeof t==`number`&&t*1e3<=Date.now())throw Af(`token expired`)}if(r.kind===`person`){if(!e.grants)return{fixed:Up};let{facts:n}=await t(r,null,null,i);return{facts:n}}return n(r,(a?void 0:r.facts)??hm(r.id),i)}async function i(e,t){let n=await r(e,t),i=e.scope===void 0?void 0:Xp(e.scope);if(`fixed`in n)return i===void 0?n.fixed:n.fixed.narrow(i);let a=nm({...n.facts,...i===void 0?{}:{can:i}});if(!a)throw jf(`this token can't use this board`);return a.caller}async function a(e,t){try{return await i(e,t)}catch(e){let t=e.status;if(t===401||t===403)return null;throw e}}return{grant:i,accessNow:a,resolve:r}}const mm=()=>process.env.VERCEL_TARGET_ENV||process.env.VERCEL_ENV||null;function hm(e){let t=e.match(/^vercel:project:([^:]+):([^:]+)$/);return t?{issuer:`vercel`,iss:``,claims:{project_id:t[1],environment:t[2]}}:null}const gm=Symbol(`board.oidcTokens`),_m=/* @__PURE__ */ new WeakSet,vm=e=>gm in e,ym=e=>_m.has(e),bm=/^[a-z][a-z0-9-]*:[a-z][a-z0-9-]*:[^\s+\]]{1,200}$/,xm=[`person`,`deployment`,`workflow`,`external`];function Sm(e){let t=e=>{throw TypeError(`authenticate returned an invalid principal: ${e}`)};(typeof e!=`object`||!e)&&t(`not an object`),(typeof e.id!=`string`||!bm.test(e.id)||e.id.startsWith(`board:`))&&t(`id must look like \`vercel:user:<id>\`, got ${JSON.stringify(e.id)}`),xm.includes(e.kind)||t(`kind must be one of ${xm.join(`, `)}`),(typeof e.handle!=`string`||!/^\S{1,64}$/.test(e.handle))&&t(`handle must be 1-64 characters, no spaces`);let n=e.expiresAt??null;if(n!==null&&(!(n instanceof Date)||Number.isNaN(n.getTime()))&&t(`expiresAt must be a Date or null`),n!==null&&n.getTime()<=Date.now())throw Af(`token expired`);let r=n===null?{}:{exp:Math.floor(n.getTime()/1e3)};return{id:e.id,kind:e.kind,handle:e.handle,expiresAt:n,facts:{issuer:`host`,iss:``,claims:r}}}const Cm=e=>{throw new q(400,`no_token`,`There's no credential here to hand a sandbox for ${e}: pass one, sandboxPolicy({ token }).`,{origin:`handle`})};function wm(e){return typeof e==`string`&&e!==`all`?(Xp(e),e):Yp(Hp(e===void 0?om:e===`all`||Array.isArray(e)?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t===`none`?[]:t]))))}const Tm=[`grants`,`watchers`,`wake`,`webhooks`,`sync`,`inbox`,`sources`],Em=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),Dm=e=>[...e].map(e=>/[a-z]/i.test(e)?`[${e.toLowerCase()}${e.toUpperCase()}]`:Em(e)).join(``),Om=Object.values(Zd).filter(({path:e})=>!Tm.includes(e.split(`/`).filter(Boolean)[0]??``)).map(({method:e,path:t})=>({method:e,path:t===`/`?``:t}));function km(e,t,n,r){let i=/* @__PURE__ */ new Map;for(let{method:e,path:n}of t){let t=n.split(`/`).filter(Boolean).map(e=>e.startsWith(`:`)?`/(?:[A-Za-z0-9_.@~:+=,!$&'*-]|%[0-9A-Fa-f]{2})+`:`/${Em(e)}`).join(``);i.set(e,[...i.get(e)??[],t])}return[...i].map(([t,i])=>({match:n({method:[t],path:{regex:`^${e}(?:${i.join(`|`)})/?$`}}),transform:r}))}const Am=e=>({response:{statusCode:403,body:JSON.stringify({error:{code:`forbidden`,message:e}}),contentType:`application/json`}});function jm(e){let t=new URL(e.url),n=Em(t.pathname.replace(/\/+$/,``)),r=[...t.searchParams].map(([e,t])=>({key:{exact:e},value:{exact:t}})),i=e=>r.length>0?{...e,queryString:r}:e,a=[{headers:{...e.headers}}];return{allow:{[t.host]:[{match:{path:{regex:`(?:^|/)\\.\\.?(?:/|$)|%2[eEfF]|%5[cC]|\\\\`}},...Am(`not a board route`)},{match:{queryString:[{key:{regex:`^${Dm(`x-vercel-set-bypass-cookie`)}$`}}]},...Am(`not a board route`)},{match:{headers:[{key:{exact:`x-vercel-set-bypass-cookie`}}]},...Am(`not a board route`)},...km(n,e.routes,i,a),...(e.reads??[]).map(e=>({match:i({path:{exact:e},method:[`GET`]}),transform:a})),{match:{path:{regex:`^${n}/(?:${Tm.map(Dm).join(`|`)})(?:/|$)`}},...Am(`not a route this sandbox's policy hands it`)},Am(`not this board's`)]}}}const Mm=/^[A-Za-z][A-Za-z0-9-]{0,31}$/,Nm=e=>((e instanceof Error?e.message:String(e))||`unknown error`).slice(0,500),Pm=e=>{throw e instanceof lf?new q(e.status>=400?e.status:502,e.code,e.message,{...e.hint===void 0?{}:{hint:e.hint},origin:e.origin}):e instanceof q||e instanceof Error&&e.name===`AbortError`?e:new q(502,`unreachable`,`the board didn't answer: ${Nm(e)}`)};function Fm(e){let t=new URLSearchParams;for(let[n,r]of Object.entries(e))if(r!=null&&r!==!1){if(n===`label`&&Array.isArray(r))for(let[e,n]of r)t.append(`label`,n===null?e:`${e}=${n.join(`|`)}`);else if(Array.isArray(r))for(let e of r)t.append(n,String(e));else t.set(n,String(r))}let n=t.toString();return n?`?${n}`:``}function Im(e,t){let n=(t.headers.get(`content-disposition`)??``).match(/filename\*=UTF-8''([^;]+)/)?.[1],r=`file`;try{n&&(r=decodeURIComponent(n))}catch{}return{attachment:{id:e,name:r,type:t.headers.get(`content-type`)??`application/octet-stream`,size:Number(t.headers.get(`content-length`)??0)},data:t.body??/* @__PURE__ */ new Uint8Array}}function Lm(e,t,n){if(e!==void 0&&!/^https?:\/\/[^/]/.test(e))throw Error(`http: ${e} isn't a URL: pass the board's, like https://board.example.com/api/board`);if(e===void 0&&!n)throw Error(`http: pass the board's URL: outside Node there's no environment to find it in`);let r=(e??n.url()).replace(/\/+$/,``),i=t.fetch??n?.fetch(r)??((e,t)=>globalThis.fetch(e,t)),a=null,o={},s=()=>{if(!a)throw Error(`http: this backend isn't serving a board yet: pass it to board({ backend })`);return a},c=(e,t)=>xf({url:r,fetch:i,profile:e===void 0?()=>n?.profile()??null:e,...t===void 0?{}:{headers:{"x-board-can":t}}}),l=c(null),u=/* @__PURE__ */ new Map;function d(e){if(!Mm.test(e))throw new q(400,`invalid_request`,`as: ${e}: profiles start with a letter and use up to 32 letters, numbers, and hyphens`);let t=u.get(e);return t||u.set(e,t=c(e)),t}let f=/* @__PURE__ */ new Map;function p(e,t){let n=JSON.stringify([e??(e===null?null:`\0`),t??null]),r=f.get(n);return r||f.set(n,r=c(e,t)),r}function m(e){return e.origin.via?.kind===`engine`?l:e.origin.via?.kind===`client`?(e.self!==null&&d(e.self),p(`profile`in e?e.profile:e.self??void 0,e.can)):d(e.self??`client`)}let h=null,g=()=>(h??=i(r).then(async e=>{if(!e.ok)throw new q(e.status>=400?e.status:502,`no_board`,`There's no board at ${r}: it answered ${e.status}.`,{origin:`handle`});return await e.json()},Pm)).catch(e=>{throw h=null,e}),_=null,v=()=>_??=l.me().then(e=>e.principal).catch(e=>{throw _=null,e}),y=async e=>Df(await v(),e);async function b(e,t,n,i){let a=Zd[t],o={...n},s=a.path.replace(/:(\w+)/g,(e,t)=>{let n=o[t];return delete o[t],encodeURIComponent(String(n))}),c;if(t===`upload`){let{data:t,name:r,type:a}=n;if(t.byteLength>4194304){let n=await e.upload({data:t,name:r??`file`,...a?{type:a}:{}}).catch(Pm);return Response.json({attachment:n})}c=await e.request(s,{method:`POST`,body:t,headers:{...a?{"content-type":a}:{},...r===null?{}:{"x-board-filename":encodeURIComponent(r)}},signal:i}).catch(Pm)}else c=a.method===`GET`?await e.request(`${s}${Fm(o)}`,{signal:i}).catch(Pm):await e.request(s,{method:a.method,body:new TextEncoder().encode(JSON.stringify(o)),headers:{"content-type":`application/json`},signal:i}).catch(Pm);if(c.ok)return c;try{let e=await c.json();if(e.error?.message)throw new q(c.status,e.error.code??`error`,e.error.message,typeof e.error.hint==`string`?{hint:e.error.hint}:{})}catch(e){if(e instanceof q)throw e}throw new q(502,`remote_error`,`${r} answered ${c.status}`)}async function x(e,t,n,i){if(T(),`identity`in t)throw new q(404,`not_found`,`this board uses ${r}, and answers nothing itself`);let a=m(t);(e===`post`||e===`posted`)&&`self`in t&&typeof n.id==`string`&&Ef.test(n.id)&&(n={...n,id:await y(n.id).catch(Pm)});let o=await b(a,e,n,i);return e===`attachment`?Im(String(n.id),o):o.json()}let S={...Object.fromEntries(Bf.map(e=>[e,(t,n,r)=>x(e,t,n,r)])),async discovery(){return g()}},C=null,w=!1;function T(){if(!(C||w||Object.keys(o).length===0)){if(dp()){w=!0,console.error(`[board] watchers on a board that uses ${r} run only in a process that stays up: on Vercel, none run`);return}C=yp({watchers:o,events:async(e,t)=>(await b(l,`events`,e,t)).json(),actorOf:async e=>(await d(e).me().catch(Pm)).actor,run:(e,t,n)=>s().run(e,t,n)}),C.start()}}return{...S,routes:[],keeps:!1,async sandbox({profile:e,can:t,token:i}){let a=n?await n.sandbox(r,i):i===void 0?Cm(r):{authorization:`Bearer ${i}`};return{url:r,headers:{...a,"x-board-profile":sf(e),"x-board-can":t},routes:Om}},bind(e){if(a)throw Error(`http: this backend already serves a board: create one http() per board()`);for(let[t,n]of Object.entries(e.subscriptions)){if(n.kind===`sync`)throw Error(`http: sync doesn't run on a board that uses ${r}: sync from that board's own config`);if(!Mm.test(t))throw Error(`watch ${t}: ids start with a letter and use up to 32 letters, numbers, and hyphens`);let{filters:e,all:i}=ap(t,n);o[t]={filters:e,all:i}}a=e},close:()=>{w=!0,C?.close(),C=null}}}function Rm(e,t={}){return Lm(e,t,null)}const zm=(e,t)=>e<t?-1:+(e>t);function Bm(e,t=[]){let n=Object.keys(e).sort(zm).map(t=>[t,e[t].tail]);return t.length>0&&n.push([`sync`,[...t].sort((e,t)=>zm(e.key,t.key)).map(e=>[e.key,e.platform])]),JSON.stringify(n)}const Vm=/^[A-Za-z][A-Za-z0-9-]{0,31}$/,Hm=[{method:`GET`,path:``},{method:`GET`,path:`/me`},{method:`GET`,path:`/channels`},{method:`POST`,path:`/channels`},{method:`GET`,path:`/actors`},{method:`GET`,path:`/messages`},{method:`GET`,path:`/messages/:id`},{method:`GET`,path:`/messages/:id/synced`},{method:`GET`,path:`/changes`},{method:`GET`,path:`/threads`},{method:`POST`,path:`/threads`},{method:`GET`,path:`/threads/:thread/messages`},{method:`POST`,path:`/threads/:thread/messages`},{method:`PATCH`,path:`/threads/:thread/messages/:n`},{method:`POST`,path:`/threads/:thread/messages/:n/delete`},{method:`GET`,path:`/threads/:thread/messages/:n/reactions`},{method:`POST`,path:`/threads/:thread/messages/:n/reactions`},{method:`POST`,path:`/threads/:thread/messages/:n/labels`},{method:`GET`,path:`/posts/:id`},{method:`POST`,path:`/attachments`},{method:`GET`,path:`/attachments/:id`},{method:`POST`,path:`/attachments/:id/complete`},{method:`GET`,path:`/schedules`},{method:`POST`,path:`/schedules`},{method:`POST`,path:`/schedules/:id/cancel`},{method:`GET`,path:`/sync/linked`}];function Um(e){return e?{"x-board-profile":e.name,...e.avatar?.startsWith(`https://`)?{"x-board-avatar":e.avatar}:{}}:{}}const Wm=/^[A-Za-z0-9_.:-]{1,128}$/,Gm=/^msg_([0-9a-f-]{36})_([1-9]\d*)$/,Km=/^([0-9a-z]+)(?:\.([0-9a-z]+))?$/,qm=/^c1\./,Jm=/* @__PURE__ */ new Set([`board_only`,`duplicate_sync_key`,`event_too_large`,`foreign_author`,`invalid_find`,`invalid_import`,`invalid_inbox_event`,`invalid_receipt`,`message_not_owned`,`mutation_too_large`,`operation_conflict`,`operation_expired_or_unknown`,`sync_key_not_owned`,`sync_needs_project`,`too_many_targets`]),Ym={400:`invalid_request`,403:`forbidden`,404:`not_found`,409:`conflict`,413:`too_large`},Xm=({id:e,name:t,type:n,size:r})=>({id:e,name:t,type:n,size:r}),Zm=e=>new q(501,`not_supported`,`Vercel's boards don't support ${e} yet`),Qm={"*":[`read`,`post`,`react`,`label`]};function $m(e){if(typeof e!=`object`||!e||Array.isArray(e))return Qm;let t=new Set(xp),n={};for(let[r,i]of Object.entries(e))if(Array.isArray(i)){try{Ep(r)}catch{continue}n[r]=i.filter(e=>t.has(e))}return Hp(n).summary()}function eh(e){return typeof e==`number`&&Number.isFinite(e)?new Date(e<0xe8d4a51000?e*1e3:e).toISOString():typeof e==`string`&&!Number.isNaN(Date.parse(e))?new Date(e).toISOString():null}const th=()=>new q(404,`not_found`,`this board uses Vercel's, and answers only wake-ups and webhooks`),nh=e=>e===`app`?`workflow`:e;function rh(e,t){let n=t!==null&&/^\d+$/.test(t)&&Number(t)>0?Number(t)*1e3:1/0;return Math.min(n,1e3*2**e*(1+Math.random()))}const ih=(e,t)=>e<=0||t?.aborted?Promise.resolve():new Promise(n=>{let r=setTimeout(n,e);t?.addEventListener(`abort`,()=>(clearTimeout(r),n()),{once:!0})});function ah(){let e=crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16)),t=BigInt(Date.now());for(let n=0;n<6;n++)e[n]=Number(t>>BigInt(8*(5-n))&255n);e[6]=e[6]&15|112,e[8]=e[8]&63|128;let n=Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``);return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}const oh=e=>new Date(e).toISOString(),sh=e=>({...e,at:eh(e.at)}),ch=e=>({id:e.id,name:e.name,version:e.version,description:e.description??null,schema:e.schema,builtIn:e.builtIn,by:e.createdBy?.id??null,at:e.builtIn?null:oh(e.createdAt)}),lh=(e,t)=>`msg_${e.slice(4)}_${t}`;function uh(e){let t=Gm.exec(e);return t?{threadId:`thr_${t[1]}`,sequence:Number(t[2])}:null}function dh(e){return e.type===`external`?e.id:e.type===`user`?`vercel:user:${e.userId}`:e.type===`app`?`vercel:app:${e.clientId}`:`vercel:project:${e.projectId}:${e.environment}`}function fh(e){let t=ot(e).principal,n=/^vercel:project:([^:]+):([^:]+)$/.exec(t);return n?{type:`project`,projectId:n[1],environment:n[2]}:t.startsWith(`vercel:user:`)?{type:`user`,userId:t.slice(12)}:t.startsWith(`vercel:app:`)?{type:`app`,clientId:t.slice(11)}:null}function ph(e,t,n){let r=t?.via?.name??null;if(e.type===`project`)return{name:n??r??e.projectId,environment:t?.via?.environment??e.environment};if(e.type===`external`)return{name:r??e.id,environment:null};let i=t?.handle.indexOf(`/`)??-1,a=e.type===`user`&&i>0?t.handle.slice(0,i):null;return{name:r??a??yh(e),environment:null}}const mh=(e,t,n,r,i)=>e.includes(`/`)?rt(e.slice(0,e.indexOf(`/`)),e.slice(e.indexOf(`/`)+1)):at(ph(t,n,i).name,e,r);function hh(e,t){let n=e.environment===`production`;if(t===void 0){let t=n?e.projectId:`${e.projectId}@${e.environment}`;return{handle:t,name:t}}return{handle:t,name:n?t:`${t} (${e.environment})`}}function gh(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map;for(let[i,a]of e){let e=fh(i);if(e?.type!==`project`)continue;let{profile:o}=ot(i);if(o!==null&&a.via?.name&&r.set(e.projectId,a.via.name),a.handle.startsWith(`project:`))continue;let s=a.handle.indexOf(`/`);o===null?t.set(e.projectId,a.handle):s>0&&$e(o)===null&&n.set(e.projectId,a.handle.slice(0,s))}return new Map([...r,...n,...t])}function _h(e,t,n){let r=fh(e);if(r?.type!==`project`)return t.handle;let i=n.get(r.projectId),{profile:a}=ot(e);if(a===null)return hh(r,i).handle;let o=$e(a);return o?mh(t.handle,r,t,o.user,i):t.handle}const vh=(e,t,n)=>[...e].filter(([e,r])=>r.handle.toLowerCase()===n||_h(e,r,t).toLowerCase()===n).map(([e])=>e),yh=e=>e.type===`user`?`user-${e.userId.slice(0,6).toLowerCase()}`:`app-${e.clientId.slice(0,6).toLowerCase()}`,bh=e=>({actor:e.id,principal:dh(e.principal),profile:e.profile?.name??null}),xh={actor:`board:schedule`,principal:`board:schedule`,profile:null};function Sh(e,t,n){let{principal:r,profile:i}=e;if(r.type===`external`)return{id:e.id,kind:`external`,handle:r.id.slice(r.id.lastIndexOf(`:`)+1),name:r.id,avatar:null,verified:!0};if(i?.platform){let{userId:a,platform:o,key:s}=i.platform,c=mh(t?.handle??``,r,t,a,n);return{id:e.id,kind:`external`,handle:c,name:i.name,avatar:null,via:ph(r,t,n),platform:t?.platform??o??s,verified:!0}}if(i)return{id:e.id,kind:`agent`,handle:i.name,name:i.name,avatar:i.avatar??null,via:ph(r,t,n),verified:!0};if(r.type===`project`)return{id:e.id,kind:`deployment`,...hh(r,n),avatar:null,verified:!0};let a=yh(r);return{id:e.id,kind:r.type===`user`?`person`:`workflow`,handle:a,name:a,avatar:null,verified:!0}}function Ch(e,t={}){let n={...e};for(let[e,{from:r}]of Object.entries(t))r===void 0?delete n[e]:n[e]=r;return n}const wh=e=>e?{...e.channel===void 0?{}:{channel:e.channel},thread:e.thread,subthread:e.subthread??null,message:e.message,context:e.context??null}:null;function Th(e,t){let n=(e.api??`https://api.vercel.com`).replace(/\/+$/,``);if(!/^https:\/\/[^/]+$|^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(n))throw Error(`vercel: ${n} isn't Vercel's API: pass an https origin`);if(!e.fetch&&!t)throw Error(`vercel: pass a fetch that sends credentials: outside Node there's no environment to find them in`);let r=e.fetch??t.fetch(),i=e.files??fetch,a=null,o=/* @__PURE__ */ new Set,s=()=>e.board?null:a?.name??null,c=null,l=()=>{let n=a?.team??e.team;return c??=n?Promise.resolve(n):t?.team()??Promise.resolve(null)};async function u(e,t,i,a={}){let o=new URL(`${n}/v1/messageboard${i}`),s=await l();s&&o.searchParams.set(s.startsWith(`team_`)?`teamId`:`slug`,s);for(let[e,t]of Object.entries(a.query??{}))if(t!==void 0){if(typeof t==`string`)o.searchParams.set(e,t);else for(let n of t)o.searchParams.append(e,n)}let c={"content-type":`application/json`,...Um(e.profile),...e.can===void 0?{}:{"x-board-can":e.can}},u=t!==`POST`&&t!==`PATCH`||typeof a.body?.operationId==`string`;for(let e=0;;e++){let n;try{n=await r(o,{method:t,headers:c,redirect:`error`,...a.body===void 0?{}:{body:JSON.stringify(a.body)},...a.signal?{signal:a.signal}:{}})}catch(e){throw e instanceof q||e instanceof Error&&e.name===`AbortError`?e:new q(502,`unreachable`,`Vercel's API didn't answer: ${e instanceof Error?e.message:String(e)}`)}let i=await n.text(),s;try{s=i?JSON.parse(i):void 0}catch{}if(n.ok)return s;if(e<4&&!a.signal?.aborted&&(n.status===429||n.status===503&&u)){await ih(rh(e,n.headers.get(`retry-after`)),a.signal),a.signal?.throwIfAborted();continue}let l=s?.error;throw new q(n.status,l?.code??`remote_error`,l?.message??`Vercel's API answered ${n.status}`)}}async function d(...e){try{return await u(...e).catch(async t=>{if(!(t instanceof q&&t.code===`sync_key_not_owned`&&(a?.sync.length??0)>0))throw t;return await vt.registerNow(!0),u(...e)})}catch(e){throw e instanceof q&&Jm.has(e.code)?new q(e.status,Ym[e.status]??e.code,e.message):e}}async function f(e,t,n,r={},i){let a=[],o;do{let s=await u(e,`GET`,t,{query:{...r,cursor:o},...i?{signal:i}:{}});a.push(...s[n]),o=s.cursor??void 0}while(o);return a}async function p(e,t){if(!/^[^/]{1,64}$/.test(t))throw new q(400,`invalid_board_name`,`${JSON.stringify(t)} isn't a board's name: one is 1 to 64 characters with no /.`,{origin:`handle`});let{boards:n}=await u(e,`GET`,`/boards`,{query:{name:t}});if(n[0])return n[0].id;let{principal:r}=(await Ee(e)).actor;if(a?.ensure===!1)throw new q(404,`no_board`,`no board named ${t} on this team, or none you can see.`,{hint:`Check the name, or make it: leave out ensure: false`,origin:`handle`});try{let{board:n}=await u(e,`POST`,`/boards/ensure`,{body:{name:t,operationId:ah()}});return n.id}catch(e){throw e instanceof q&&e.code===`board_not_granted`?m(t,r):e instanceof q&&e.code===`board_name_taken`?new q(409,`board_name_taken`,`the board name ${t} is taken.`,{hint:`Pick another name, or ask whoever can see it for access.`,origin:`handle`}):e}}let m=(e,t)=>{let n=e===null?`the team's board`:`board ${e}`;if(t.type!==`project`)return new q(403,`board_not_granted`,`this project has no access to ${n}.`,{hint:`Someone who manages the board can grant it.`,origin:`handle`});let r=`vb grants create --project ${t.projectId} --environment ${t.environment}${e===null?``:` --name ${e}`} --can '*=read,post,react,label'`;return new q(403,`board_not_granted`,`this project has no access to ${n} (${t.projectId}, ${t.environment}).`,{hint:`Grant it: ${r}`,origin:`handle`})},h=null,g=t=>(h??=e.board?Promise.resolve(e.board):s()?p(t,s()):u(t,`GET`,`/boards`).then(async({defaultBoardId:e})=>{if(e)return e;let{principal:n}=(await Ee(t)).actor;if(n.type===`project`)throw m(null,n);let{board:r}=await u(t,`POST`,`/boards/default`,{body:{operationId:ah()}});return r.id})).catch(e=>{throw h=null,e}),_=async(e,t=``)=>`/boards/${encodeURIComponent(await g(e))}${t}`,v=null,y=async(e,t=!1)=>(t&&(v=null),v??=_(e,`/channels`).then(t=>f(e,t,`channels`)),v.catch(e=>{throw v=null,e})),b=/* @__PURE__ */ new Map;async function x(e,t){let n=b.get(t);if(n)return n;let{channels:[r]}=await u(e,`GET`,await _(e,`/channels`),{query:{name:t}});return r&&b.set(t,r),r??null}let S=/* @__PURE__ */ new Map;async function C(e,t){let n=(await y(e)).find(e=>e.id===t)??(await y(e,!0)).find(e=>e.id===t);if(!n)throw new q(502,`remote_error`,`Vercel's API names a channel it doesn't list: ${t}`);return n}async function w(e,t){let n=await x(e,t);if(n)return{channel:n,created:!1};try{let{channel:n}=await u(e,`POST`,await _(e,`/channels`),{body:{operationId:ah(),name:t}});return v=null,b.set(t,n),{channel:n,created:!0}}catch(n){if(n instanceof q&&n.code===`channel_name_taken`){let n=await x(e,t);if(n)return{channel:n,created:!1}}throw n}}let T=async(e,t)=>(await w(e,t)).channel;async function E(e,t){if(t!==void 0&&!t.endsWith(`/`)){let n=await x(e,t);return n?[n]:[]}let n=await y(e,!0);if(t===void 0)return n;let r=t.slice(0,-1);return n.filter(e=>e.name===r||e.name.startsWith(t))}async function D(e,t,n){if(!uh(t))throw Mf(`message not found: ${t}`,`message_not_found`);try{return await u(e,`GET`,await _(e,`/messages/${encodeURIComponent(t)}`),n?{signal:n}:{})}catch(e){throw e instanceof q&&e.code===`thread_not_found`?Mf(`message not found: ${t}`,`message_not_found`):e}}async function O(e,t,n){let r=await D(e,t,n);return{...r,channel:await C(e,r.thread.channelId)}}function k(e,t){let n=/* @__PURE__ */ new Map;return r=>{let i=n.get(r);return i||n.set(r,i=D(e,lh(r,1),t).then(({thread:e,message:t})=>A(e,t))),i}}let A=(e,t)=>{if(t?.deletedAt===void 0)return e;let{labels:n,...r}=e;return r},j=e=>e.deletedAt===void 0?{...e.labels}:{},M=async(e,t,n)=>f(e,await _(e,`/threads/${encodeURIComponent(t)}/messages`),`messages`,{},n);async function N(e,t){if(!t.reactions||Object.keys(t.reactions).length===0)return{};let n=t.reactors??{};if(Object.entries(t.reactions).every(([e,t])=>(n[e]?.length??0)>=t))return Object.fromEntries(Object.entries(n).map(([e,t])=>[e,[...t]]));let r=await _(e,`/threads/${encodeURIComponent(t.threadId)}/messages/${t.sequence}/reactions`),i={};for(let t of await f(e,r,`reactions`))(i[t.emoji]??=[]).push(t.actor.id);return i}let P=null,F=3e5,I=/* @__PURE__ */ new Set,L=e=>{let t=(async()=>new Map((await f(e,await _(e,`/actors`),`actors`)).map(e=>[e.id,e])))(),n={at:Date.now(),views:t};return P=n,t.catch(()=>{P===n&&(P=null)}),n},R=(e,t)=>e.views.then(e=>e.get(t),()=>void 0);async function ee(e,t){let n=!P||Date.now()-P.at>F?L(e):P,r=await R(n,t.id);if(!r&&!I.has(t.id)){let i=P&&P!==n?P:L(e);r=await R(i,t.id),!r&&await i.views.then(()=>!0,()=>!1)&&I.add(t.id)}let i=r&&nh(r.kind),a=t.principal.type===`project`?await ae(e,t.principal.projectId):void 0;if(!r||!(i===`person`||i===`external`||i===`agent`&&t.principal.type===`user`))return Sh(t,r,a);let o=t.profile&&t.principal.type!==`external`?{via:ph(t.principal,r,a)}:{},s=r.platform??t.profile?.platform?.platform,c=t.profile?.platform,l=c&&t.principal.type!==`external`?mh(r.handle,t.principal,r,c.userId,a):r.handle;return{id:t.id,kind:i,handle:l,name:r.name??r.handle,avatar:r.avatar??null,...o,...s?{platform:s}:{},verified:!0}}let te=/* @__PURE__ */ new WeakMap;function ne(e){let t=te.get(e);return t||te.set(e,t=e.views.then(gh,()=>/* @__PURE__ */ new Map)),t}let re=/* @__PURE__ */ new Set;async function ie(e,t){let n=P&&Date.now()-P.at<=F?P:null,r=await ne(n??L(e));return!t||t.found(r)||!n||re.has(t.key)?r:(r=await ne(P&&P!==n?P:L(e)),t.found(r)||(re.size>=1e3&&re.clear(),re.add(t.key)),r)}let ae=async(e,t)=>(await ie(e,{key:t,found:e=>e.has(t)})).get(t),oe=async(e,t)=>await ae(e,t)??t,se=async e=>{let{principal:t}=(await Ee(e)).actor;return t.type===`project`?t.projectId:null},ce=e=>e.principal.type===`project`?e.principal.projectId:null;async function le(e,t,n){if(t===void 0)return null;let r=ce(n);return r===null||r===await se(e)?t:`${await oe(e,r)}/${t}`}async function ue(e,t,n){let r=t.sequence===1;return{id:t.id,channel:n,text:t.text,re:r?null:lh(t.threadId,1),replyTo:t.replyTo!==void 0&&t.replyTo!==1?lh(t.threadId,t.replyTo):null,thread:t.threadId,labels:j(t),reactions:t.deletedAt===void 0?await N(e,t):{},by:bh(t.createdBy),noSync:t.noSync??!1,origin:wh(t.origin),from:await le(e,t.from,t.createdBy),createdAt:oh(t.createdAt),editedAt:t.editedAt===void 0?null:oh(t.editedAt),deleted:t.deletedAt!==void 0,undelivered:{},attachments:t.attachments??[],links:(t.links??[]).map(e=>({url:e.url,message:e.message??null,snapshot:e.snapshot??null,unavailable:e.unavailable??null})),version:t.version,revision:t.revision,author:await ee(e,t.createdBy),...t.schedule?{schedule:{id:t.schedule.id,n:t.schedule.n}}:{},blocks:(t.from??null)===null&&t.deletedAt===void 0?Qe(t.text):[]}}async function de(e,t,n){let{actor:r}=await Ee(e),i={id:await De(e),principal:r.principal,...e.profile?{profile:e.profile}:{}},a=(await Promise.all((n.attachments??[]).map(async t=>u(e,`GET`,await _(e,`/attachments/${encodeURIComponent(t)}`)).then(({attachment:e})=>Xm(e),()=>null)))).filter(e=>e!==null);return{...t,text:n.text,version:1,revision:1,createdAt:Date.now(),createdBy:i,...n.labels&&Object.keys(n.labels).length?{labels:{...n.labels}}:{},...n.noSync?{noSync:!0}:{},...a.length?{attachments:a}:{}}}async function z(e,t){let{canceled:n}=t;return{id:t.id,channel:(await C(e,t.channelId)).name,re:t.threadId===void 0?null:lh(t.threadId,1),text:t.text,labels:{...t.labels},noSync:t.noSync??!1,attachments:[],first:oh(t.firstAt),every:t.every??null,until:t.until===void 0?null:oh(t.until),times:t.times??null,sent:t.sent,next:t.nextAt===null?null:oh(t.nextAt),last:t.lastMessageId??null,state:t.state,canceled:n?{by:n.by?bh(n.by):xh,reason:n.reason===`disabled`?`revoked`:n.reason}:null,by:bh(t.createdBy),author:await ee(e,t.createdBy),createdAt:oh(t.createdAt)}}let B=/* @__PURE__ */ new Map;function fe(e){let t=`${e.t.toString(36)}.${Math.floor(Math.random()*36**8).toString(36)}`;return B.set(t,e),B.size>1e4&&B.delete(B.keys().next().value),t}function pe(e){let t=B.get(e);if(t)return t;let n=Km.exec(e);if(!n)throw new q(400,`invalid_cursor`,`after: ${e} isn't a cursor here or a message's ID`);return{t:parseInt(n[1],36),feeds:{}}}async function me(e,t){return uh(t)?(await D(e,t)).message.createdAt:pe(t).t}async function he(e,t){let n=await _(e,`/changes`),r=await Promise.all(t.map(t=>u(e,`GET`,n,{query:{channelId:t.id,from:`latest`}})));return Object.fromEntries(t.map((e,t)=>[e.id,{at:r[t].cursor,skip:0}]))}let ge=/* @__PURE__ */ new Map;async function _e(e,t){if(t===void 0)return;if(t===`me`){let t=await De(e);return e=>e.id===t}let n=/* @__PURE__ */ new Set([t]);if(!t.startsWith(`vercel:`)){let r=t.toLowerCase(),i=async e=>vh(await e.views,await ne(e),r),a=P&&Date.now()-P.at<=F?P:null,o=await i(a??L(e)),s=ge.get(r);o.length===0&&a&&!(s!==void 0&&Date.now()-s<=F)&&(o=await i(L(e))),o.length===0&&(ge.size>=1e3&&ge.clear(),(!a||s===void 0||Date.now()-s>F)&&ge.set(r,Date.now()));for(let e of o)n.add(e)}return e=>n.has(e.id)||n.has(dh(e.principal))||e.profile!==void 0&&!e.profile.platform&&n.has(e.profile.name)}async function ve(e,t){if(t===void 0)return;if(t===`board`)return e=>e.from===void 0;let n=t.indexOf(`/`);if(n===-1){let n=await se(e);return e=>e.from===t&&[null,n].includes(ce(e.createdBy))}let[r,i]=[t.slice(0,n),t.slice(n+1)];return async t=>{let n=ce(t.createdBy);return t.from===i&&n!==null&&(n===r||await ae(e,n)===r)}}let ye=async(e,t)=>({by:await _e(e,t.by),source:await ve(e,t.from)});async function be(e,t,n,r){if(e.re!==void 0&&e.re!==t.id&&e.re!==lh(n.id,1)||r.by&&!r.by(t.createdBy)||e.mentions!==void 0||e.from!==void 0&&!await r.source?.(t)||e.text!==void 0&&!t.text.toLowerCase().includes(e.text.toLowerCase()))return!1;for(let[r,i]of e.label??[]){let e=e=>e!==void 0&&Object.hasOwn(e,r)&&(i===null||i.includes(e[r]));if(!e(j(t))&&!e(n.labels))return!1}return!0}function xe(e){let t=e.label?.find(([,e])=>e===null||e.length===1);return t&&(t[1]===null?t[0]:`${t[0]}=${t[1][0]}`)}async function Se(e,t,n,r){let i=xe(n);return f(e,await _(e,`/threads`),`threads`,{channelId:t.id,label:i},r)}async function Ce(e,t,n,r,i){let a=await _(e,`/threads`),o=[],s;do{let c=await u(e,`GET`,a,{query:{channelId:t.id,label:n,cursor:s},signal:i});o.push(...c.threads),s=c.cursor??void 0;let l=o.at(-1);if(n===void 0&&(r.after===void 0?r.limit!==void 0&&o.length>=r.limit:l!==void 0&&l.lastActivityAt<=r.after))break}while(s);return o}async function we(e,t,n,r){let[i,a]=await Promise.all([D(e,lh(t.id,1),r),t.lastMessage&&t.lastMessage.sequence>1?D(e,t.lastMessage.id,r):null]);return{message:await ue(e,i.message,n.name),replies:t.messageCount-1,last:a&&await ue(e,a.message,n.name)}}let Te=null,Ee=e=>(Te??=u(e,`GET`,`/me`)).catch(e=>{throw Te=null,e}),De=async e=>`${dh((await Ee(e)).actor.principal)}${e.profile?`+${e.profile.name.toLowerCase()}`:``}`;function Oe(e,t){if(`self`in e&&e.can!==void 0)throw new q(403,`forbidden`,`this handle is narrowed with a can, so it can't ${t}: that's its project's sync's job`)}function V(e){if(`identity`in e)throw th();let n=e=>{if(e===null)return null;let t=typeof e==`string`?e:e.name;if(!Vm.test(t))throw new q(400,`invalid_request`,`as: ${t}: profiles start with a letter and use up to 32 letters, numbers, and hyphens`);return typeof e==`string`||!e.avatar?{name:t}:{name:t,avatar:e.avatar}};if(e.origin.via?.kind===`client`){let r=`profile`in e?e.profile:e.self??void 0;return{profile:n(r===void 0?t?.profile()??null:r),...e.can===void 0?{}:{can:e.can}}}return{profile:n(e.self??`client`)}}let ke=async e=>Wm.test(e)?e:`h.${(await wf(e)).slice(0,64)}`;async function je(e,t,n){let r,i;if(t.re!==void 0){let a=await O(e,t.re,n).catch(e=>{if(e instanceof q&&e.status===404)return null;throw e});if(!a)return{messages:[],feeds:{},newest:0};let{channel:o}=a;if(t.channel!==void 0&&!(await E(e,t.channel)).some(e=>e.id===o.id))return{messages:[],feeds:{},newest:0};r=[o],i=[{thread:a.thread,channel:o}]}else r=await E(e,t.channel),i=(await Promise.all(r.map(async r=>(await Se(e,r,t,n)).map(e=>({thread:e,channel:r}))))).flat();let a=await he(e,r),o=await ye(e,t),s=0,c=[];for(let{thread:r,channel:a}of i){let i=await M(e,r.id,n),l=A(r,i.find(e=>e.sequence===1));for(let e of i)s=Math.max(s,e.createdAt),await be(t,e,l,o)&&c.push({message:e,thread:r,channel:a})}return c.sort(Me),{messages:c,feeds:a,newest:s}}let Me=(e,t)=>e.message.createdAt-t.message.createdAt||e.message.threadId.localeCompare(t.message.threadId)||e.message.sequence-t.message.sequence;async function Ne(e,t,n,r){let i=await _(e,`/messages`),a=Math.min(n,100),o=await Promise.all(t.map(async t=>({channel:t,...await u(e,`GET`,i,{query:{channelId:t.id,limit:String(a)},signal:r})}))),s=o.filter(e=>e.messages.length===a),c=Math.max(-1/0,...s.map(e=>Math.min(...e.messages.map(e=>e.createdAt))));return{messages:o.flatMap(({channel:e,messages:t})=>t.map(t=>({message:t,channel:e}))).filter(({message:e})=>e.createdAt>=c).sort(Me).slice(-n),feeds:Object.fromEntries(o.map(e=>[e.channel.id,{at:e.cursor,skip:0}])),newest:Math.max(0,...o.flatMap(e=>e.messages.map(e=>e.createdAt)))}}async function Pe(e,t,n,r,i,a,o,s=k(e)){if(!t.messageId||!t.type.startsWith(`message.`))return null;let c=o??await D(e,t.messageId).catch(e=>{if(e instanceof q&&e.status===404)return null;throw e});if(c&&!o&&i.label?.length&&(c={...c,thread:c.message.sequence===1?A(c.thread,c.message):await s(c.thread.id)}),!c||!await be(i,c.message,c.thread,a))return null;let l=await ue(e,c.message,n),u=bh(t.actor),d=await le(e,t.from,t.actor),f={id:l.id,thread:l.thread},p,m;switch(t.type){case`message.posted`:p=`message.posted`,m={channel:n,text:l.text,re:l.re,replyTo:l.replyTo,thread:l.thread,labels:l.labels,noSync:l.noSync,by:u,origin:l.origin,from:l.from,attachments:l.attachments,links:l.links};break;case`message.edited`:p=`message.edited`,m={...f,text:l.text,by:u,from:d};break;case`message.deleted`:p=`message.deleted`,m={...f,by:u,from:d};break;case`message.reaction_added`:case`message.reaction_removed`:p=t.type===`message.reaction_added`?`reaction.added`:`reaction.removed`,m={...f,emoji:t.emoji,by:u,from:d};break;case`message.labeled`:{let e=Object.entries(t.labels??{});p=`labels.changed`,m={...f,set:Object.fromEntries(e.flatMap(([e,{to:t}])=>t===void 0?[]:[[e,t]])),unset:e.flatMap(([e,{to:t}])=>t===void 0?[e]:[]),by:u};break}default:return null}return Le(e,t,r,p,m,l)}let Le=async(e,t,n,r,i,a)=>({cursor:n,type:r,createdAt:oh(t.createdAt),payload:i,message:a,actor:await ee(e,t.actor)});async function Re(e,t,n,r,i){let a=await _(e,`/changes`),o=await Promise.all(t.map(async t=>{let r=n.feeds[t.id],o=await u(e,`GET`,a,{query:{channelId:t.id,...r?.at?{cursor:r.at}:{}},signal:i}),s=r?.skip??0,c=o.events.map((e,t)=>({change:e,i:t})).slice(s).filter(({change:e})=>r||e.createdAt>n.t);return{channel:t,at:r?.at??null,next:o.cursor,events:c}})),s=await ye(e,r),c=k(e,i),l={...n.feeds},d=o.flatMap(e=>e.events.map(t=>({...t,page:e}))).sort((e,t)=>e.change.createdAt-t.change.createdAt),f=[];for(let{change:t,i:n,page:i}of d){l[i.channel.id]={at:i.at,skip:n+1};let a=await Pe(e,t,i.channel.name,fe({t:t.createdAt,feeds:{...l}}),r,s,void 0,c);a&&f.push(a)}let p={...n.feeds};for(let e of o)p[e.channel.id]={at:e.next,skip:0};return{events:f,position:{t:Math.max(n.t,...d.map(({change:e})=>e.createdAt)),feeds:p}}}async function ze(e,t,n,r,i){let a=Math.min(25,Math.ceil((r-Date.now())/1e3));if(a<=0)return!1;if(t.length===0)return await ih(r-Date.now(),i),!1;let o=new AbortController,s=AbortSignal.any([i,o.signal]),c=await _(e,`/changes`);try{return await new Promise((r,l)=>{let d=t.length;for(let f of t){let t=n.feeds[f.id]?.at;u(e,`GET`,c,{query:{channelId:f.id,...t?{cursor:t}:{from:`latest`},wait:String(a)},signal:s}).then(e=>{e.events.length>0?r(!0):--d===0&&r(!1)}).catch(e=>o.signal.aborted&&!i.aborted?void 0:l(e))}})}finally{o.abort()}}let Ve=e=>e.by!==void 0||e.mentions!==void 0||e.text!==void 0||e.from!==void 0||(e.label?.length??0)>0;async function He(e,t,n,r){let i=await _(e,`/messages`),a=n.limit??50,o=k(e,r),s=Ve(n),c=s?await ye(e,n):{},l=async e=>!s||await be(n,e,n.label?.length?await o(e.threadId):{id:e.threadId},c),d=[];if(n.after===void 0){let n=await u(e,`GET`,i,{query:{channelId:t.id,limit:String(s?100:Math.min(a,100))},signal:r});for(let e of n.messages)await l(e)&&d.push(e);return{messages:d.slice(-a),cursor:n.cursor}}let f=n.after;for(let n=0;n<10&&d.length<a;n++){let n=await u(e,`GET`,i,{query:{channelId:t.id,after:f,limit:String(Math.min(a-d.length,100))},signal:r});f=n.cursor;for(let e of n.messages)await l(e)&&d.push(e);if(n.messages.length===0)break}return{messages:d,cursor:f}}async function Ue(e,t,n,r){let i=await _(e,`/changes`),a=k(e,r),o=await ye(e,n),s=Date.now()+(n.wait??0)*1e3,c=n.after;for(;;){let l=Math.min(25,Math.max(0,Math.ceil((s-Date.now())/1e3))),d=await u(e,`GET`,i,{query:{channelId:t.id,include:`message`,...c===void 0?{from:`latest`}:{cursor:c},...l>0?{wait:String(l)}:{}},signal:r});c=d.cursor;let f=[];for(let r of d.events){let i=r.currentMessage,s=i&&r.threadId?{message:i,thread:n.label?.length?await a(r.threadId):{id:r.threadId}}:null;if(!s)continue;let c=await Pe(e,r,t.name,r.cursor??d.cursor,n,o,s);c&&f.push(c)}if(f.length>0||Date.now()>=s||r.aborted)return{events:f,cursor:c}}}async function We(e,t,n){let r=await Ge(e,t);if(r)return Ue(e,r,t,n);if(t.after!==void 0&&qm.test(t.after))throw new q(400,`invalid_request`,`after: ${t.after} is one channel's cursor: read that channel`);let i=await E(e,t.channel),a=t.after===void 0?{t:Date.now(),feeds:await he(e,i)}:uh(t.after)?{t:await me(e,t.after),feeds:{}}:pe(t.after),o=Date.now()+(t.wait??0)*1e3,s=!1;for(;;){let r=Date.now(),c=await Re(e,i,a,t,n);if(a=c.position,c.events.length>0||Date.now()>=o||n.aborted)return{events:c.events,cursor:fe(a)};s||=await ze(e,i,a,o,n)&&Date.now()-r<1e3,await ih(Math.min(r+1e3,o)-Date.now(),n)}}async function Ge(e,t){if(t.channel===void 0||t.channel.endsWith(`/`)||t.re!==void 0||t.after!==void 0&&!qm.test(t.after))return null;let[n]=await E(e,t.channel);return n??null}let Ke=async(e,t)=>(await wf(Bm(e,t))).slice(0,32);async function qe(e,t){if(t===`me`)return[await De(e)];if(t.startsWith(`vercel:`))return[t];let n=await f(e,await _(e,`/actors`),`actors`),r=n.map(e=>[e.id,e]),i=new Set(vh(r,gh(r),t.toLowerCase())),a=n.filter(e=>i.has(e.id)||!t.includes(`:`)&&e.id.endsWith(`+${t.toLowerCase()}`)).map(e=>e.id);if(a.length===0)throw new q(400,`bad_watcher`,`--by ${t}: nobody here goes by that yet: name them by their actor ID`);return a}function Je(e,t,n){let r=t=>new q(400,`bad_watcher`,`watch ${e}: ${t}`);if(!Ru.safeParse(e).success)throw r(`ids start with a letter and use up to 32 letters, numbers, and hyphens`);let i;try{i=ap(e,t)}catch(e){throw new q(400,`bad_watcher`,e.message)}if(i.filters.mentions!==void 0)throw r(`Vercel's boards can't match mentions yet`);if(i.filters.from!==void 0&&!n)throw r(`Vercel's API can't match --source: put the watcher in the board's config, which filters its matches itself`);return i}async function Ye(e,t,n,r){let{filters:i}=Je(t,n,r),a={};if(i.channel!==void 0){if(i.channel.endsWith(`/`))a.channelTree=i.channel.slice(0,-1);else{let t=await x(e,i.channel);t?a.channelIds=[t.id]:a.channelTree=i.channel}}if(i.re!==void 0){let e=uh(i.re);if(!e)throw new q(400,`bad_watcher`,`watch ${t}: --re ${i.re} names no message here`);a.threadId=e.threadId}return i.by!==void 0&&(a.authors=await qe(e,i.by)),i.text!==void 0&&(a.text=i.text),i.label?.length&&(a.labels=i.label.map(([e,t])=>t===null?{key:e}:{key:e,values:[...t]})),{filter:a}}async function Xe(e,{filter:t}){let n=[];t.channelIds?.[0]?n.push((await C(e,t.channelIds[0])).name):t.channelTree!==void 0&&n.push(`${t.channelTree}/`),t.threadId!==void 0&&n.push(`--re ${lh(t.threadId,1)}`),t.authors?.[0]&&n.push(`--by ${t.authors[0]}`),t.text!==void 0&&n.push(`--text ${JSON.stringify(t.text)}`);for(let{key:e,values:r}of t.labels??[])n.push(`--label ${r?`${e}=${r.join(`|`)}`:e}`);return n.join(` `)}let Ze=e=>(e.sync??[]).map(({key:e,platform:t})=>({key:e,platform:t})),et=e=>e.path?{url:null,path:e.path,...e.branch?{branch:e.branch}:{}}:{url:null},tt=()=>new q(403,`watchers_need_project`,`Vercel's API takes watchers only from a deployment's own credentials.`,{hint:`Register them from the project's deployment. Watchers in board()'s config run in this process instead.`,origin:`handle`}),nt=e=>e instanceof q&&e.code===`watchers_need_project`?tt():e;async function rt(...e){try{return await u(...e)}catch(e){throw nt(e)}}async function it(e,t,n,r,i,a=async()=>{}){let o=Object.fromEntries(Object.entries(n).map(([e,t])=>[e,{tail:t.tail}])),s=Object.fromEntries(await Promise.all(Object.entries(o).map(async([t,n])=>[t,await Ye(e,t,n,i)]))),c=r.map(({key:e,platform:t})=>({key:e,platform:t})),l;try{l=await d(e,`PUT`,await _(e,`/watchers`),{body:{...t,watch:s,tag:await Ke(o,c),...c.length?{sync:c}:{}}})}catch(e){throw nt(e)}return await a(l),{owner:l.owner,...et(l),watch:o,sync:Ze(l),hash:l.hash}}let at=null,st=/* @__PURE__ */ new Map;async function ct(e){at=new Set((e.sync??[]).map(e=>e.key));let t=fh(e.owner);for(let{key:n,owner:r,environment:i}of e.elsewhere??[]){let e=fh(r),a=r;if(e?.type===`project`){let n=i??e.environment;a=t?.type===`project`&&t.projectId===e.projectId?n:`${await oe(ht,e.projectId)} (${n})`}st.get(n)!==a&&console.info(`[board] ${n} is synced by ${a}`),st.set(n,a)}}async function lt(e){return!a?.sync.some(t=>t.key===e)||(at===null&&await bt().catch(()=>!1)&&await vt.start(),at===null||at.has(e))}let ut=e=>Mf(`${e} is synced by ${st.get(e)??`another deployment of this project`}, not this deployment`,`not_synced_here`);async function dt(e,t,n){if(!await lt(e))return t();try{return await n()}catch(n){if(n instanceof q&&n.status===403&&!await lt(e))return t();throw n}}async function H(e,t,n){let r=await D(e,t.event.messageId).catch(e=>{if(e instanceof q&&e.status===404)return null;throw e}),i=r&&await C(e,r.thread.channelId);if(!r||!i)return null;let a=t.event.type===`thread.synced`?await ft(e,t,r.message,i.name):await Pe(e,t.event,i.name,t.id,n,await ye(e,n),r);if(!a?.message)return null;let o=t.watcher===`@sync`&&a.type===`labels.changed`?{...a,before:{...a.message,labels:Ch(a.message.labels,t.event.labels)}}:a;return{id:t.id,watcher:t.watcher,thread:a.message.thread,lease:t.lease,attempt:t.attempt,event:o}}async function ft(e,t,n,r){let{binding:i}=t.event;if(!i||i.projectId!==void 0&&i.projectId!==await se(e))return null;let a=await ue(e,n,r);return Le(e,t.event,t.id,`thread.synced`,{thread:a.thread,target:i.target,cause:i.cause,kind:i.targetKind,by:bh(t.event.actor)},a)}async function pt(e,t,n,r={}){let{matches:i}=await rt(e,`GET`,await _(e,`/watchers/matches`),{query:{limit:t.limit?.toString(),wait:t.wait?.toString()},...n?{signal:n}:{}}),a=new Map(Object.entries(r).map(([e,t])=>[e,ap(e,t).filters.from])),o=await Promise.all(i.map(t=>{let n=a.get(t.watcher);return H(e,t,n===void 0?{}:{from:n})}));return await Promise.all(i.map((t,n)=>o[n]?null:mt(e,t.id,{lease:t.lease,skip:!0}).catch(()=>{}))),o.filter(e=>e!==null)}async function mt(e,t,n){await rt(e,`POST`,await _(e,`/watchers/matches/${encodeURIComponent(t)}/ack`),{body:{lease:n.lease,...n.error===void 0?{}:{error:n.error},...n.skip?{skip:!0}:{}}})}let ht={profile:null},gt={},_t=()=>{if(!a)throw Error(`vercel: used before board() bound it`);return a},vt=pp({remote:`Vercel's API`,registry:{register:e=>it(ht,e,gt,_t().sync,!0,ct),matches:({signal:e,...t})=>pt(ht,t,e,gt),ack:(e,t)=>mt(ht,e,t)},wakeAt:async e=>fp(e)??{},binding:_t,hash:()=>Ke(gt,_t().sync),hasWork:()=>Object.keys(gt).length>0||_t().sync.length>0,rethrow:e=>{throw e},registerFor:async(e,t)=>Ff(await Mt.register(e,wd.parse(await t.json()),t.signal))}),yt=null,bt=()=>(yt??=Ee(ht).then(e=>e.actor.principal.type===`project`)).catch(e=>{throw yt=null,e}),xt=null,St=!1;function Ct(){if(xt||St)return;if(dp()){St=!0,console.error(`[board] watchers on a deployment need its own OIDC token: with another Vercel token, none run here`);return}let{sync:e,run:t}=_t();e.length>0&&console.error(`[board] sync doesn't run on Vercel's board as anyone but a deployment: run it from the project's deployment`);let n={};for(let[e,t]of Object.entries(gt))try{n[e]=Je(e,t,!0)}catch(t){console.error(`[board] watcher ${e} doesn't run:`,t.message)}xt=yp({watchers:n,events:(e,t)=>We(ht,e,t),actorOf:e=>De({profile:{name:e}}),run:t}),xt.start()}let wt=0;async function Tt(){if(xt||Object.keys(gt).length===0&&_t().sync.length===0||Date.now()-wt<1e4)return;let e;try{e=await bt()}catch(e){wt=Date.now(),console.error(`[board] couldn't tell whether this board runs as a deployment:`,e instanceof Error?e.message:String(e));return}e?await vt.start():Ct()}let Et=vt.routes.map(e=>({...e,async handle(t,n){if(n.caller||await bt().catch(()=>!0))return e.handle(t,n);if(op(Tt()),e.path===`/wake`)return Ff({ran:0});throw tt()}})),Dt=({id:e,handle:t,name:n,avatar:r,isBot:i})=>({id:e,handle:t,name:n,avatar:r,isBot:i});async function Ot(e,t){let n={op:t.op,operationId:ah(),author:Dt(t.author),...t.from===void 0?{}:{from:t.from}};if(t.op===`post`){let r;if(t.after!==void 0){let e=uh(t.after),n=t.re===void 0?null:uh(t.re);if(!e||!n||e.threadId!==n.threadId)throw kf(`after: ${t.after} isn't in ${t.re??`the thread`}'s thread`,`invalid_after`);r=e.sequence}return{...n,origin:t.origin===null?null:wh(t.origin),...t.source?{source:t.source}:{},...t.channel===void 0?{}:{channelId:(await T(e,t.channel)).id},...t.re===void 0?{}:{re:t.re},text:t.text,...t.labels&&Object.keys(t.labels).length?{labels:t.labels}:{},...t.noSync?{noSync:!0}:{},...t.attachments?.length?{attachments:t.attachments}:{},...t.links?.length?{links:t.links}:{},...t.id===void 0?{}:{id:t.id},...r===void 0?{}:{after:r}}}let r={...n,...t.origin===void 0?{}:{origin:t.origin},...t.message===void 0?{}:{message:t.message}};return t.op===`edit`?{...r,text:t.text,...t.source?{source:t.source}:{},...t.revision===void 0?{}:{revision:t.revision}}:t.op===`delete`?{...r,...t.revision===void 0?{}:{revision:t.revision}}:t.op===`react`?{...r,emoji:t.emoji,...t.remove?{remove:!0}:{}}:t.op===`labels`?{...r,...t.set?{set:t.set}:{},...t.unset?{unset:t.unset}:{},...t.if&&Object.keys(t.if).length?{if:t.if}:{}}:{...r,links:t.links}}let kt=(e,t,n=``)=>_(e,`/sync/inbox/${encodeURIComponent(t)}${n}`),At=e=>{throw e instanceof q&&e.code===`unsupported_principal`?new q(400,`unsupported_principal`,`Vercel's board takes no GitHub or OIDC principals in a grant.`,{hint:`Grant an app that an OIDC exchange policy issues tokens for: --app <slug>.`,origin:`handle`}):e},jt=e=>{throw e instanceof q&&e.code===`unsupported_principal`?new q(400,`unsupported_principal`,`Vercel's board explains no GitHub or OIDC caller: no grant names one.`,{hint:`Explain the app an OIDC exchange policy issues tokens for: --app <slug>.`,origin:`handle`}):e},Mt={...Object.fromEntries(Bf.map(e=>[e,async()=>{throw Zm(e===`register`||e===`watchers`||e===`matches`||e===`ack`?`watchers`:e)}])),async discovery(){let t={profile:null},r=await l();e.board&&await u(t,`GET`,await _(t));let i=r?.startsWith(`team_`)?r:(await Ee(t)).teamId;return{version:Rf,url:`${n}/v1/messageboard${await _(t)}?teamId=${encodeURIComponent(i)}`,audience:n,team_id:i,project_id:null,sync:(a?.sync??[]).map(({key:e,platform:t})=>({key:e,platform:t})),wake_by_path:!0}},async me(e){let t=V(e),n=await u(t,`GET`,await _(t,`/me`)),{view:r}=n,{principal:i}=n.actor,a=i.type===`project`?(r?gh([[n.actor.id,r]]).get(i.projectId):void 0)??await ae(t,i.projectId):void 0,o=i.type===`project`&&!n.actor.profile?{kind:`deployment`,...hh(i,a),avatar:r?.avatar??null}:r?{kind:nh(r.kind),handle:r.handle,name:r.name??r.handle,avatar:r.avatar??null}:Sh(n.actor,void 0,a),s=n.actor.profile&&i.type!==`external`?{via:ph(i,r,a)}:{};return{actor:n.actor.id,principal:dh(n.actor.principal),kind:o.kind,handle:o.handle,name:o.name,avatar:o.avatar,profile:n.actor.profile?.name??null,...s,expiresAt:eh(n.expiresAt),can:$m(n.can)}},async channels(e){return{channels:(await E(V(e),void 0)).map(e=>({path:e.name})).sort((e,t)=>e.path.localeCompare(t.path)),cursor:fe({t:Date.now(),feeds:{}})}},async createChannel(e,{path:t}){let{created:n}=await w(V(e),t);return{channel:{path:t},created:n}},async actors(e,t,n){let r=V(e),i=await f(r,await _(r,`/actors`),`actors`,{},n),a=gh(i.map(e=>[e.id,e]));return{actors:i.map(e=>{let{profile:t}=ot(e.id),n=fh(e.id),r=n?.type===`project`?a.get(n.projectId):void 0,i=t===null?null:n,o=$e(t),s=t===null&&n?.type===`project`?hh(n,r):null;return{id:e.id,kind:nh(e.kind),handle:s?.handle??(i&&o?mh(e.handle,i,e,o.user,r):e.handle),name:s?.name??e.name??e.handle,avatar:e.avatar??null,...i?{via:ph(i,e,r)}:{},...e.platform?{platform:e.platform}:{},verified:!0}}),cursor:fe({t:Date.now(),feeds:{}})}},async messages(e,t,n){let r=V(e),i=t.before===void 0?await Ge(r,t):null;if(i){let e=await He(r,i,t,n);return{messages:await Promise.all(e.messages.map(e=>ue(r,e,i.name))),cursor:e.cursor}}if(t.after!==void 0&&qm.test(t.after))throw new q(400,`invalid_request`,`after: ${t.after} is one channel's cursor: read that channel`);let a=t.limit??50;if(t.re===void 0&&t.after===void 0&&t.before===void 0&&!Ve(t)){let{messages:e,feeds:i,newest:o}=await Ne(r,await E(r,t.channel),a,n);return{messages:await Promise.all(e.map(({message:e,channel:t})=>ue(r,e,t.name))),cursor:fe({t:o,feeds:i})}}let{messages:o,feeds:s,newest:c}=await je(r,t,n),l=t.after===void 0?void 0:await me(r,t.after),u=t.before===void 0?void 0:await me(r,t.before),d=o.filter(({message:e})=>(l===void 0||e.createdAt>l)&&(u===void 0||e.createdAt<u)),f=l===void 0?d.slice(-a):d.slice(0,a);return{messages:await Promise.all(f.map(({message:e,channel:t})=>ue(r,e,t.name))),cursor:fe({t:c,feeds:s})}},async threads(e,t,n){let r=V(e),i=t.after===void 0?void 0:await me(r,t.after),a=t.limit??50,o=e=>{let t=e.filter(({at:e})=>i===void 0||e>i).sort((e,t)=>e.at-t.at);return i===void 0?t.slice(-a):t.slice(0,a)};if(t.re!==void 0||t.by!==void 0||t.mentions!==void 0||t.text!==void 0||t.from!==void 0){let{messages:e,feeds:i,newest:a}=await je(r,t,n),s=/* @__PURE__ */ new Map;for(let{message:t,thread:n,channel:r}of e)s.set(n.id,{thread:n,channel:r,at:Math.max(s.get(n.id)?.at??0,t.createdAt)});return{threads:await Promise.all(o([...s.values()]).map(({thread:e,channel:t})=>we(r,e,t,n))),cursor:fe({t:a,feeds:i})}}let s=await E(r,t.channel),c=await he(r,s),l=xe(t),u=(await Promise.all(s.map(async e=>(await Ce(r,e,l,{...i===void 0?{}:{after:i},...t.label?.length?{}:{limit:a}},n)).map(t=>({thread:t,channel:e,at:t.lastActivityAt}))))).flat(),d=u.filter(({thread:e})=>(t.label??[]).every(([t,n])=>e.labels!==void 0&&Object.hasOwn(e.labels,t)&&(n===null||n.includes(e.labels[t])))),f=u.reduce((e,{at:t})=>Math.max(e,t),0);if(!t.label?.length)return{threads:await Promise.all(o(d).map(({thread:e,channel:t})=>we(r,e,t,n))),cursor:fe({t:f,feeds:c})};let p=d.filter(({at:e})=>i===void 0||e>i).sort((e,t)=>e.at-t.at);i===void 0&&p.reverse();let m=[];for(let e=0;e<p.length&&m.length<a;){let t=p.slice(e,e+a-m.length);e+=t.length;for(let e of await Promise.all(t.map(({thread:e,channel:t})=>we(r,e,t,n))))e.message.deleted||m.push(e)}return i===void 0&&m.reverse(),{threads:m,cursor:fe({t:f,feeds:c})}},async message(e,{id:t},n){let r=V(e),{thread:i,channel:a}=await O(r,t,n),[o,...s]=await M(r,i.id,n);if(!o)throw Mf(`message not found: ${t}`,`message_not_found`);return{message:await ue(r,o,a.name),replies:await Promise.all(s.map(e=>ue(r,e,a.name))),cursor:fe({t:Math.max(o.createdAt,...s.map(e=>e.createdAt)),feeds:{}})}},async upload(e,{data:t,name:n,type:r}){let a=V(e);if(t.byteLength===0)throw new q(400,`bad_request`,`the file is empty`);if(t.byteLength>26214400)throw new q(413,`too_large`,`attachments are at most ${Ae/1024/1024} MB`);let o=new Uint8Array(t),s=new Uint8Array(await crypto.subtle.digest(`SHA-256`,o)),c=await u(a,`POST`,await _(a,`/attachments`),{body:{operationId:ah(),name:Fe(n),type:Ie(r),size:t.byteLength,sha256:btoa(String.fromCharCode(...s))}}),l=await i(c.upload.url,{method:c.upload.method,headers:c.upload.headers,body:o,redirect:`error`});if(!l.ok)throw new q(502,`upload_failed`,`the upload to Vercel's storage answered ${l.status}`);let{attachment:d}=await u(a,`POST`,await _(a,`/attachments/${encodeURIComponent(c.attachment.id)}/complete`));return{attachment:Xm(d)}},async uploadStart(e,{name:t,type:n,size:r,sha256:i}){let a=V(e);if(i===void 0)throw new q(400,`invalid_request`,"Vercel's API signs a direct upload for its bytes' SHA-256: send `sha256`, as board's client does");let o=await u(a,`POST`,await _(a,`/attachments`),{body:{operationId:ah(),name:Fe(t??null),type:Ie(n??null),size:r,sha256:i}});return{id:o.attachment.id,url:o.upload.url,headers:o.upload.headers,expiresAt:oh(o.upload.expiresAt)}},async uploadFinish(e,{id:t}){let n=V(e),{attachment:r}=await u(n,`POST`,await _(n,`/attachments/${encodeURIComponent(t)}/complete`));return{attachment:Xm(r)}},async attachment(e,{id:t},n){let r=V(e),a=await u(r,`GET`,await _(r,`/attachments/${encodeURIComponent(t)}`),n?{signal:n}:{}),o=await i(a.url,{redirect:`error`,...n?{signal:n}:{}});if(!o.ok||!o.body)throw new q(502,`download_failed`,`Vercel's storage answered ${o.status}`);return{attachment:Xm(a.attachment),data:o.body}},async post(e,t,n){if(t.sync?.length)throw Zm(`sync`);let r=V(e),i=t.id===void 0?void 0:await ke(t.id),a,o;if(t.channel!==void 0)o=t.channel,a=await u(r,`POST`,await _(r,`/threads`),{body:{operationId:ah(),channel:t.channel,text:t.text,...t.labels&&Object.keys(t.labels).length?{labels:t.labels}:{},...i?{clientId:i}:{},...t.attachments?.length?{attachments:t.attachments}:{},...t.noSync?{noSync:!0}:{}},signal:n});else{let{thread:e,message:s,channel:c}=await O(r,t.re,n);o=c.name;let l=t.after===void 0?void 0:uh(t.after);if(l!==void 0&&l?.threadId!==e.id){let a=i?await u(r,`GET`,await _(r,`/posts/${encodeURIComponent(i)}`),{signal:n}).catch(()=>null):null;if(a?.thread.id===e.id)return{message:await ue(r,a.message,c.name)};throw kf(`after: ${t.after} isn't in ${t.re}'s thread`,`invalid_after`)}let d=await u(r,`POST`,await _(r,`/threads/${encodeURIComponent(e.id)}/messages`),{body:{operationId:ah(),text:t.text,...s.sequence>1?{replyTo:s.sequence}:{},...i?{clientId:i}:{},...t.attachments?.length?{attachments:t.attachments}:{},...l?{after:l.sequence}:{},...t.noSync?{noSync:!0}:{}},signal:n}).catch(e=>{throw e instanceof q&&e.code===`newer_message`?new q(409,`newer_message`,`a message came after ${t.after}`):e});if(t.labels&&Object.keys(t.labels).length){let i=await u(r,`POST`,await _(r,`/threads/${encodeURIComponent(e.id)}/messages/${d.message.sequence}/labels`),{body:{operationId:ah(),set:t.labels},signal:n});d.message={...d.message,...i.meta.labels?{labels:i.meta.labels}:{},version:i.meta.version}}a=d}let s=a.thread.channelId;return s!==void 0&&(i!==void 0&&S.get(s)!==o?o=await C(r,s).then(e=>(S.set(s,e.name),e.name),()=>o):S.set(s,o)),{message:await ue(r,`text`in a.message?a.message:await de(r,a.message,t),o)}},async posted(e,{id:t},n){let r=V(e),i=await u(r,`GET`,await _(r,`/posts/${encodeURIComponent(await ke(t))}`),{signal:n}),a=await C(r,i.thread.channelId);return{message:await ue(r,i.message,a.name)}},async edit(e,{id:t,text:n,revision:r},i){let a=V(e),o=uh(t);if(!o)throw Mf(`message not found: ${t}`,`message_not_found`);return await u(a,`PATCH`,await _(a,`/threads/${encodeURIComponent(o.threadId)}/messages/${o.sequence}`),{body:{operationId:ah(),text:n,...r===void 0?{}:{revision:r}},signal:i}),{ok:!0}},async delete(e,{id:t,revision:n},r){let i=V(e),a=uh(t);if(!a)throw Mf(`message not found: ${t}`,`message_not_found`);return await u(i,`POST`,await _(i,`/threads/${encodeURIComponent(a.threadId)}/messages/${a.sequence}/delete`),{body:{operationId:ah(),...n===void 0?{}:{revision:n}},signal:r}),{ok:!0}},async react(e,{id:t,emoji:n,remove:r},i){let a=V(e),o=uh(t);if(!o)throw Mf(`message not found: ${t}`,`message_not_found`);return await u(a,`POST`,await _(a,`/threads/${encodeURIComponent(o.threadId)}/messages/${o.sequence}/reactions`),{body:{operationId:ah(),emoji:n,...r?{remove:!0}:{}},signal:i}),{ok:!0}},async label(e,{id:t,set:n,unset:r,if:i},a){let o=V(e),s=uh(t);if(!s)throw Mf(`message not found: ${t}`,`message_not_found`);return await u(o,`POST`,await _(o,`/threads/${encodeURIComponent(s.threadId)}/messages/${s.sequence}/labels`),{body:{operationId:ah(),...n?{set:n}:{},...r?{unset:r}:{},...i&&Object.keys(i).length?{if:i}:{}},signal:a}),{ok:!0}},async grants(e,t,n){let r=V(e),{grants:i}=await u(r,`GET`,await _(r,`/grants`),n?{signal:n}:{});return{grants:i.map(sh)}},async createGrant(e,t,n){let r=V(e),{grant:i}=await u(r,`POST`,await _(r,`/grants`),{body:{operationId:ah(),...t},...n?{signal:n}:{}}).catch(At);return{grant:sh(i)}},async updateGrant(e,{id:t,...n},r){let i=V(e),{grant:a}=await u(i,`PATCH`,await _(i,`/grants/${encodeURIComponent(t)}`),{body:{operationId:ah(),...n},...r?{signal:r}:{}}).catch(At);return{grant:sh(a)}},async explain(e,{claim:t,...n},r){let i=V(e),a=new URLSearchParams;for(let[e,t]of Object.entries(n))t!==void 0&&a.set(e,t);for(let e of t??[])a.append(`claim`,e);let o=await u(i,`GET`,await _(i,`/grants/explain?${a}`),r?{signal:r}:{}).catch(jt);return{...o,grants:o.grants.map(sh)}},async revokeGrant(e,{id:t},n){let r=V(e);return u(r,`POST`,await _(r,`/grants/${encodeURIComponent(t)}/revoke`),{body:{operationId:ah()},...n?{signal:n}:{}})},async schemas(e,t,n){let r=(await f(V(e),`/schemas`,`schemas`,{},n)).map(ch),i=e=>+!e.builtIn;return{schemas:r.sort((e,t)=>i(e)-i(t)||(e.builtIn?0:e.name<t.name?-1:e.name>t.name?1:e.version-t.version))}},async schema(e,{id:t},n){let{schema:r}=await u(V(e),`GET`,`/schemas/${encodeURIComponent(t)}`,n?{signal:n}:{});return{schema:ch(r)}},async createSchema(e,t,n){let r=V(e),i=await u(r,`GET`,`/schemas/${encodeURIComponent(Be(t.name,t.version))}`,n?{signal:n}:{}).then(()=>!0,e=>{if(e instanceof q&&e.code===`schema_not_found`)return!1;throw e}),{schema:a}=await u(r,`POST`,`/schemas`,{body:{operationId:ah(),...t},...n?{signal:n}:{}});return{schema:ch(a),created:!i}},async schedule(e,t,n){if(t.attachments?.length)throw Zm(`files on scheduled messages`);let r=V(e),i=t.labels&&Object.keys(t.labels).length?t.labels:void 0,a;if(t.channel!==void 0)a={channelId:(await T(r,t.channel)).id};else{if(i)throw Zm(`labels on a scheduled reply`);let{thread:e}=await O(r,t.re,n);a={threadId:e.id}}let o=e=>Math.round(hf(e)),s=t.at===void 0?Date.now()+o(t.in??t.every):Date.parse(t.at),c=t.until===void 0?t.for===void 0?void 0:s+o(t.for):Date.parse(t.until),{schedule:l}=await u(r,`POST`,await _(r,`/schedules`),{body:{operationId:ah(),...a,text:t.text,...i?{labels:i}:{},...t.noSync?{noSync:!0}:{},firstAt:s,...t.every===void 0?{}:{every:o(t.every)},...c===void 0?{}:{until:c},...t.times===void 0?{}:{times:t.times}},signal:n});return{schedule:await z(r,l)}},async schedules(e,t,n){let r=V(e),i={state:t.all?void 0:`pending`};if(t.re!==void 0){let e=await O(r,t.re,n).catch(e=>{if(e instanceof q&&e.status===404)return null;throw e});if(!e)return{schedules:[]};i.threadId=e.thread.id}if(t.channel!==void 0){let e=await x(r,t.channel);if(!e)return{schedules:[]};i.channelId=e.id}t.by?.startsWith(`vercel:`)&&(i.createdBy=t.by);let a=await _e(r,t.by),o=e=>a===void 0||a(e),s=await f(r,await _(r,`/schedules`),`schedules`,i,n);return{schedules:await Promise.all(s.filter(e=>o(e.createdBy)).map(e=>z(r,e)))}},async cancelSchedule(e,{id:t},n){let r=V(e),{schedule:i,canceled:a}=await u(r,`POST`,await _(r,`/schedules/${encodeURIComponent(t)}/cancel`),{body:{operationId:ah()},signal:n});return{schedule:await z(r,i),canceled:a}},events:(e,t,n)=>We(V(e),t,n),async typing(e,{id:t,status:n},r){if(!a||a.sync.length===0)return{targets:[]};let{message:i,replies:o}=await Mt.message(e,{id:t},r);if(`self`in e&&e.can!==void 0&&!Hp(Xp(e.can)).can(`post`,i.channel))throw new q(403,`forbidden`,`this handle can't post in ${i.channel}`);return{targets:await a.typing([i,...o],n)}},async readSource(e,{key:t,target:n,limit:r,after:i}){if(!a?.sync.some(e=>e.key===t))throw Mf(`this board doesn't run sync entry ${t}: read it where its sync runs`,`not_synced_here`);return Oe(e,`read a source`),a.readSource(t,n,r??50,i??null)},async joinSource(e,{key:t,target:n}){if(!a?.sync.some(e=>e.key===t))throw Mf(`this board doesn't run sync entry ${t}: join it where its sync runs`,`not_synced_here`);return Oe(e,`join a source`),a.joinSource(t,n)},async syncImport(e,t,n){let r=V(e),i=t.from??t.author.id.split(`:`)[0];return{message:(await dt(i,()=>{throw ut(i)},async()=>d(r,`POST`,await _(r,`/sync/imports`),{body:await Ot(r,t),signal:n})).catch(e=>{throw e instanceof q&&e.code===`newer_message`&&t.op===`post`?new q(409,`newer_message`,`a message came after ${t.after}`):e})).message}},async syncReceipt(e,t,n){let r=V(e),i=t.target.split(`:`)[0];return dt(i,()=>{throw ut(i)},async()=>d(r,`POST`,await _(r,`/sync/receipts`),{body:t,signal:n}))},async syncFind(e,t,n){let r=V(e),{thread:i,message:a}=await d(r,`GET`,await _(r,`/sync/find`),{query:t,signal:n});return{thread:i,message:a}},async syncThread(e,{thread:t},n){let r=V(e),i=await d(r,`GET`,await _(r,`/sync/threads/${encodeURIComponent(t)}`),{signal:n});return{...i,channel:(await C(r,i.channel)).name}},async syncCopies(e,{message:t},n){let r=V(e);return d(r,`GET`,await _(r,`/sync/copies`),{query:{message:t},signal:n})},async synced(e,{id:t},n){let r=V(e);if(!uh(t))throw Mf(`message not found: ${t}`,`message_not_found`);let{targets:i}=await d(r,`GET`,await _(r,`/messages/${encodeURIComponent(t)}/synced`),{signal:n}),o=await se(r),s=e=>e!==void 0&&e!==o,c=[...new Set(i.flatMap(({projectId:e})=>s(e)?[e]:[]))],l=c.length?await ie(r,{key:c.join(` `),found:e=>c.every(t=>e.has(t))}):/* @__PURE__ */ new Map;return{targets:await Promise.all(i.map(async({projectId:e,...t})=>{if(s(e)){let n=`${l.get(e)??e}/${t.key}`;return{...t,key:n,target:`${n}${t.target.slice(t.key.length)}`,url:null}}return{...t,url:a&&t.thread!==null&&t.message!==null?await a.linkOf(t.key,t.thread,t.message):null}}))}},async linked(e,{url:t},n){let r=V(e),i=()=>Mf(`no message on this board for that link`,`message_not_found`);for(let{platform:o,thread:s,message:c}of a?.locate(t)??[])for(let t of/* @__PURE__ */ new Set([...(a?.sync??[]).filter(e=>e.platform===o).map(e=>e.key),o])){let a=await d(r,`GET`,await _(r,`/sync/linked`),{query:{thread:`${t}:${s}`,...c===null?{}:{message:c}},signal:n}).catch(e=>{if(e instanceof q&&e.status===404)return null;throw e});if(a)return Mt.message(e,{id:a.message},n).catch(e=>{throw e instanceof q&&(e.status===403||e.status===404)?i():e})}throw i()},async inboxPush(e,{key:t,events:n},r){let i=V(e),a={events:n.map(({id:e,event:t,raw:n})=>({id:e,thread:t.thread,event:t,...n===void 0?{}:{raw:n}}))};return await dt(t,()=>null,async()=>d(i,`POST`,await kt(i,t),{body:a,signal:r})),{ok:!0}},async inboxNext(e,{key:t,limit:n},r){let i=V(e),{items:a}=await dt(t,()=>({items:[]}),async()=>d(i,`GET`,await kt(i,t,`/next`),{query:{limit:n?.toString()},signal:r}));return{items:a.map(({raw:e,...n})=>({...n,key:t,raw:e??null}))}},async inboxAck(e,{key:t,id:n,lease:r,error:i},a){let o=V(e);return await dt(t,()=>null,async()=>d(o,`POST`,await kt(o,t,`/${encodeURIComponent(n)}/ack`),{body:{lease:r,...i===void 0?{}:{error:i}},signal:a})),{ok:!0}},async inbox(e,{key:t,channel:n,limit:r},i){let a=V(e),o=Math.min(r??50,100),{events:s}=await dt(t,()=>({events:[]}),async()=>d(a,`GET`,await kt(a,t),{query:{limit:String(n===void 0?o:100)},signal:i})),c=s.flatMap(({id:e,createdAt:n,event:r,raw:i})=>r?[{id:e,channel:typeof r.channel==`string`?r.channel:``,createdAt:n,sync:t,event:r,raw:i??null}]:[]);return{events:(n===void 0?c:c.filter(e=>e.channel===n)).slice(0,o)}},async watchers(e){let t=V(e),{watchers:n}=await rt(t,`GET`,await _(t,`/watchers`));return{watchers:await Promise.all(n.map(async e=>({owner:e.owner,...et(e),watch:Object.fromEntries(await Promise.all(Object.entries(e.watch).map(async([e,n])=>[e,{tail:await Xe(t,n)}]))),sync:Ze(e),hash:e.hash})))}},async register(e,t){if(typeof t.url==`string`)throw new q(400,`invalid_request`,`Vercel's API wakes a deployment only by its path.`,{hint:`Register a path, or no url to pull its matches.`,origin:`handle`});return it(V(e),typeof t.path==`string`?{path:t.path,...t.branch?{branch:t.branch}:{}}:{},t.watch,t.sync??[],!1)},async matches(e,t,n){return{matches:await pt(V(e),t,n)}},async ack(e,{id:t,...n}){return await mt(V(e),t,n),{ok:!0}}};return{...Object.fromEntries(Object.entries(Mt).map(([e,t])=>[e,(e,...n)=>{if(`identity`in e)throw th();return a&&op(Tt()),t(e,...n)}])),routes:Et,keeps:!1,async sandbox({profile:e,can:r,token:i}){if(e.avatar!==void 0&&!e.avatar.startsWith(`https://`))throw new q(400,`invalid_profile`,`${e.avatar} isn't an avatar Vercel's API takes: one is an https URL.`,{origin:`handle`});let a={profile:null},o=await l(),s=o?.startsWith(`team_`)?o:(await Ee(a)).teamId,c=`${n}/v1/messageboard${await _(a)}?teamId=${encodeURIComponent(s)}`;return{url:c,headers:{...t?await t.sandbox(c,i):i===void 0?Cm(c):{authorization:`Bearer ${i}`},...Um(e),"x-board-can":r},routes:Hm,reads:[`/v1/messageboard/me`]}},sendsSchedulesHere:!1,syncedHere:lt,bind(t){if(a)throw Error(`vercel: this backend already serves a board: create one vercel() per board()`);if(e.team&&t.team&&e.team!==t.team)throw Error(`vercel: board() names team ${t.team}, and vercel() team ${e.team}: name the team once`);for(let e of Object.keys(t.subscriptions))o.add(e);gt=Object.fromEntries(Object.entries(t.subscriptions).flatMap(([e,t])=>t.kind===`tail`?[[e,{tail:t.tail}]]:[])),a=t},async registerWatchers(){if(await bt())return vt.registerNow();throw op(Tt()),tt()},close(){vt.close(),xt?.close(),xt=null}}}function Eh(e={}){return Th(e,null)}const Dh=[`fx`,`claude`,`codex`,`grok`,`pi`],Oh=/^[A-Za-z][A-Za-z0-9-]{0,31}$/;function kh(e){let{profile:t,avatar:n}=Ah(e.get(`x-board-profile`));if(e.get(`x-board-scope`)!==null)throw kf(`x-board-scope is x-board-can now: send the same value as x-board-can`,`invalid_scope`);let r=e.get(`x-board-can`);if(r!==null)try{Xp(r)}catch(e){throw kf(e.message,`invalid_scope`)}return{profile:t,avatar:n,scope:r}}function Ah(e){if(e===null||e.trim()===``)return{profile:null,avatar:null};let t;try{t=cf(e)}catch(e){throw kf(e.message,`invalid_profile`)}if(!Oh.test(t.name))throw kf(`profile names start with a letter and use up to 32 letters, numbers, and hyphens`,`invalid_profile`);if(t.avatar!==null&&!Nh(t.avatar))throw kf(`avatars must be https URLs (http only on localhost)`,`invalid_profile`);return{profile:t.name,avatar:t.avatar}}function jh(e,t){let n=t.profile?.toLowerCase()??null,r=n===null?e.id:`${e.id}+${n}`,i=Mh(e),a={id:r,kind:n===null?e.kind:`agent`,handle:n===null?e.handle:`${e.handle}/${n}`,name:t.profile??(i.environment!==null&&i.environment!==`production`?`${i.name} (${i.environment})`:e.handle),avatar:t.avatar,...n===null?{}:{via:i}};return{author:{actor:r,principal:e.id,profile:n},actor:a}}function Mh(e){let t=/^vercel:project:[^:]+:([^:]+)$/.exec(e.id)?.[1]??null,n=`@${t}`;return{name:t!==null&&e.handle.endsWith(n)&&e.handle.length>n.length?e.handle.slice(0,-n.length):e.handle,environment:t}}function Nh(e){try{let t=new URL(e);return t.protocol===`https:`||t.protocol===`http:`&&[`localhost`,`127.0.0.1`].includes(t.hostname)}catch{return!1}}function Ph(e,t,n,r=null){let i=r?()=>r.grants():null,a=null,o=()=>(a??=(async()=>{if(!n)return{id:null,teamId:null};let e=await n(),[t,r]=await Promise.all([e.ownProjectId(),e.ownTeamId()]);return{id:t,teamId:r}})()).catch(e=>{throw a=null,e});async function s(e){return n?(await n()).discoveryIdentity(e):{projectId:null,teamId:null}}let c=null,l=()=>e.authenticate?Promise.resolve(e.authenticate):c??=n?n().then(e=>e.oidcTokens()):Promise.reject(new q(501,`no_verifier`,`this build of board verifies no tokens: pass board({ authenticate })`)),u=pm({project:o,hosts:e.authenticate!==void 0&&!vm(e.authenticate),grants:i}),d={project:o,issuers:[]};async function f(e){if(!i)return;let t=Fh(e);if(t===null||!t.startsWith(`https://`)||t===`https://token.actions.githubusercontent.com`||im.test(t))return;let n=um([],dm(await i()));n.join(`
|
|
345
|
+
`)),(t.id!==void 0||t.data!==void 0)&&(yield t)}}}finally{t?.removeEventListener(`abort`,a),n.releaseLock()}}var $d=class extends Error{};const ef=/[A-Za-z*]/,tf=/[!#$%&'*+\-.^_`|~0-9A-Za-z:/]/,nf=/[a-z*]/,rf=/[a-z0-9_\-.*]/,af=/^(?:-?\d{1,15}|-?\d{1,12}\.\d{1,3}|\?[01]|:[A-Za-z0-9+/=]*:)$/;function of(e){if(!/^[\x20-\x7e]*$/.test(e))throw new $d(`an avatar URL is printable ASCII: percent-encode the rest`);return`"${e.replace(/[\\"]/g,e=>`\\${e}`)}"`}function sf(e){if(!e.avatar)return e.name;let t=/^[\x20-\x7e]*$/.test(e.avatar)?e.avatar:URL.parse(e.avatar)?.href??e.avatar;return`${e.name};avatar=${of(t)}`}function cf(e){let t=0,n=e=>{throw new $d(`x-board-profile is a structured header, like fixer;avatar="https://example.com/fixer.png": ${e}`)},r=()=>{for(;e[t]===` `;)t++},i=()=>{t++;let r=``;for(;t<e.length;){let i=e[t++];if(i===`\\`){let i=e[t++];i!==`"`&&i!==`\\`&&n(`a string escapes only " and \\`),r+=i}else if(i===`"`)return r;else i<` `||i>`~`?n(`a string is printable ASCII`):r+=i}return n(`a string is missing its closing "`)},a=()=>{let n=t;for(;t<e.length&&tf.test(e[t]);)t++;return e.slice(n,t)},o=()=>{let r=e[t];if(r===`"`)return{kind:`string`,value:i()};if(r!==void 0&&ef.test(r))return{kind:`token`,value:a()};let o=t;for(;t<e.length&&e[t]!==`;`&&e[t]!==` `;)t++;let s=e.slice(o,t);return af.test(s)||n(s===``?`a parameter has no value after its =`:`${s} isn't a value`),{kind:`other`,value:s}};r();let s=o();s.kind===`other`&&n(s.value===``?`it names no profile`:`${s.value} isn't a profile's name`);let c=null;for(;e[t]===`;`;){t++,r(),nf.test(e[t]??``)||n(`a parameter starts with a lowercase letter`);let i=t;for(;t<e.length&&rf.test(e[t]);)t++;let a=e.slice(i,t),s={kind:`boolean`,value:`?1`};e[t]===`=`&&(t++,s=o()),a===`avatar`&&(s.kind!==`string`&&n(`avatar is a string, in quotes`),c=s.value)}return r(),t<e.length&&n(`${JSON.stringify(e.slice(t,t+20))} follows the profile`),{name:s.value,avatar:c}}var lf=class extends Error{code;status;hint;origin;constructor(e,t,n,r={}){super(t),this.name=`BoardError`,this.code=e,this.status=n,this.hint=r.hint,this.origin=r.origin??`handle`}};const uf=/* @__PURE__ */ new WeakSet,df=async e=>typeof e==`function`?await e():e,ff=e=>{let{at:t,until:n,...r}=pf(e);return{...r,...t===void 0?{}:{at:t instanceof Date?t.toISOString():t},...n===void 0?{}:{until:n instanceof Date?n.toISOString():n}}},pf=e=>{if(typeof e==`string`)return{text:e};let{attachments:t,...n}=e;return t?.length?{...n,attachments:t.map(e=>typeof e==`string`?e:e.id)}:n},mf={ms:1,s:1e3,m:6e4,h:36e5,d:864e5};function hf(e){if(typeof e==`number`)return e;let t=e.trim().match(/^(\d+(?:\.\d+)?)(ms|s|m|h|d)?$/);if(!t)throw new lf(`invalid_duration`,`${e} isn't a duration like 30s, 10m, or 1h.`,0);return Number(t[1])*mf[t[2]??`ms`]}const gf=e=>encodeURIComponent(e);function _f(e){let t=new URLSearchParams;for(let[n,r]of Object.entries(e))if(r!=null){if(n===`label`){let e=Array.isArray(r)?r:typeof r==`object`?Object.entries(r).map(([e,t])=>`${e}=${String(t)}`):[r];for(let n of e)t.append(`label`,String(n))}else t.set(n,String(r))}let n=t.toString();return n?`?${n}`:``}function vf(e){return typeof e!=`object`||!e||Array.isArray(e)?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t===`none`?[]:t]))}const yf=e=>(e.kind===`project`||e.kind===`all-projects`)&&e.environments===void 0?{...e,environments:[`production`]}:e;function bf(e,t){let[n,r,i,a]=e.principal.split(`:`);if((n===`vercel`||n===`local`)&&r===`user`&&i)return{kind:`user`,userId:e.principal.split(`:`).slice(2).join(`:`)};if(n===`vercel`&&r===`project`&&i&&a)return{kind:`project`,project:i,environments:[a]};throw new lf(`no_own_principal`,`A private channel lets its creator in, as a person or a project's deployment, and ${e.principal} is neither, so ${t} wasn't made.`,400,{hint:`Make it as a person or a deployment, or make it and its grants yourself.`})}function xf(e){let t=e.url.replace(/\/+$/,``),n=e.fetch??((e,t)=>globalThis.fetch(e,t)),r=e.storeFetch??((e,t)=>globalThis.fetch(e,t));async function i(t,n){let r={...e.headers?await df(e.headers):{}};if(!t)return r;e.token!==void 0&&(r.authorization=`Bearer ${await df(e.token)}`);let i=n===void 0?e.profile===void 0?null:await df(e.profile):n;return i!==null&&(r[`x-board-profile`]=sf(typeof i==`string`?{name:i}:i)),r}async function a(e,r,a={}){let o=await n(`${t}${r}`,{method:e,headers:{...await i(a.auth??!0),...a.body===void 0?{}:{"content-type":`application/json`},...a.headers},...a.body===void 0?{}:{body:JSON.stringify(a.body)},...a.signal?{signal:a.signal}:{}});if(!o.ok)throw await Sf(o);return o}async function o(e,t,n){return await(await a(e,t,n)).json()}let s=(e={})=>e;async function c(e={},t){return o(`GET`,`/events${_f(e)}`,t?{signal:t}:{})}return{url:t,request:async(e,r={})=>n(`${t}${e}`,{method:r.method??`GET`,headers:{...r.headers,...await i(!0,r.as)},...r.body?{body:r.body}:{},...r.signal?{signal:r.signal}:{}}),discovery:()=>o(`GET`,`/`,{auth:!1}),me:()=>o(`GET`,`/me`),channels:async()=>(await o(`GET`,`/channels`)).channels,createChannel:async(e,t={})=>{if(!t.private)return o(`POST`,`/channels`,{body:{path:e}});let n=bf(await o(`GET`,`/me`),e),r=`${e}/`,i=async()=>(await o(`GET`,`/grants`)).grants.filter(t=>Object.keys(t.can).some(t=>t===e||t.startsWith(r))),a=(t,n=[])=>{let r=t.filter(e=>n.some(t=>t.id===e.id)).map(e=>e.id);if(r.length===t.length)return new lf(`channel_granted`,`${r.join(` and `)} changed while ${e} was being made, so a private ${e} wouldn't be yours alone: nothing was made.`,409);let i=t.filter(e=>!r.includes(e.id)).map(e=>e.id);return new lf(`channel_granted`,`${i.length===1?i[0]:`${i.slice(0,-1).join(`, `)} and ${i.at(-1)}`} already ${i.length===1?`grants`:`grant`} in ${e}, so a private ${e} wouldn't be yours alone: nothing was made.`,409,{hint:i.length===1?`Revoke it first: vb grants revoke ${i[0]}`:`Revoke them first, each with vb grants revoke <id>.`})},s=await i();if(s.length>0)throw a(s);let c=(await o(`GET`,`/channels`)).channels.find(t=>t.path===e||t.path.startsWith(r));if(c)throw new lf(`channel_exists`,c.path===e?`${e} is a channel already, so it stays as it is.`:`${c.path} is a channel already, and a private ${e} would close it too, so nothing was made.`,409,{hint:`Close it with a grant: everyone at ${r} with 'none'.`});let l=await o(`POST`,`/grants`,{body:{principals:[n],can:{[r]:`all`}}}),u=(e,t)=>e.filter(e=>{let n=t.find(t=>t.id===e.id);return n===void 0||JSON.stringify([e.principals,e.can])!==JSON.stringify([n.principals,n.can])}),d=u(await i(),[l.grant]);if(d.length>0)throw await o(`POST`,`/grants/${encodeURIComponent(l.grant.id)}/revoke`,{body:{}}),a(d,[l.grant]);let f=await o(`POST`,`/grants`,{body:{principals:[{kind:`everyone`}],can:{[r]:[]}}}),p=u(await i(),[l.grant,f.grant]);if(p.length>0){for(let e of[f.grant.id,l.grant.id])await o(`POST`,`/grants/${encodeURIComponent(e)}/revoke`,{body:{}});throw a(p,[l.grant,f.grant])}return{...await o(`POST`,`/channels`,{body:{path:e}}),grants:[l.grant,f.grant]}},actors:async()=>(await o(`GET`,`/actors`)).actors,messages:(e={})=>o(`GET`,`/messages${_f(e)}`),thread:e=>o(`GET`,`/messages/${gf(e)}`),posted:async e=>(await o(`GET`,`/posts/${gf(e)}`)).message,threads:(e={})=>o(`GET`,`/threads${_f(e)}`),async post(e,t){return(await o(`POST`,`/messages`,{body:{channel:e,...pf(t)}})).message},async reply(e,t){return(await o(`POST`,`/messages`,{body:{re:e,...pf(t)}})).message},async schedule(e,t){return(await o(`POST`,`/schedules`,{body:{...typeof e==`string`?{channel:e}:{re:e.re},...ff(t)}})).schedule},schedules:async(e={})=>(await o(`GET`,`/schedules${_f(e)}`)).schedules,cancelSchedule:e=>o(`POST`,`/schedules/${gf(e)}/cancel`,{body:{}}),createGrant:e=>o(`POST`,`/grants`,{body:{principals:e.principals.map(yf),can:vf(e.can)}}),updateGrant:(e,{add:t,remove:n,can:r})=>o(`PATCH`,`/grants/${gf(e)}`,{body:{...t?{add:t.map(yf)}:{},...n?{remove:n}:{},...r?{can:vf(r)}:{}}}),explain:(e,t={})=>{let{claims:n,...r}=t,i=new URLSearchParams({channel:e});for(let[e,t]of Object.entries(r))t!==void 0&&i.set(e,t);for(let[e,t]of Object.entries(n??{}))i.append(`claim`,`${e}=${t}`);return o(`GET`,`/grants/explain?${i}`)},grants:async()=>(await o(`GET`,`/grants`)).grants,revokeGrant:e=>o(`POST`,`/grants/${gf(e)}/revoke`,{body:{}}),schemas:async()=>(await o(`GET`,`/schemas`)).schemas,schema:async e=>(await o(`GET`,`/schemas/${gf(e)}`)).schema,createSchema:e=>o(`POST`,`/schemas`,{body:e}),async upload(e){let a=e.type||(e.data instanceof Blob?e.data.type:``)||Pe(e.name),s=e.data instanceof Blob?e.data.size:e.data.byteLength;if(s>4194304){if(s>104857600)throw new lf(`too_large`,`Attachments are at most ${je/1024/1024} MB.`,413);let t=e.data instanceof Blob?await e.data.arrayBuffer():e.data,n=btoa(String.fromCharCode(...new Uint8Array(await crypto.subtle.digest(`SHA-256`,t)))),i=await o(`POST`,`/attachments/uploads`,{body:{name:e.name,type:a,size:s,sha256:n}}).catch(e=>{throw e instanceof lf&&e.status===404&&e.code===`not_found`?new lf(`too_large`,`This board takes files of at most ${ke/1024/1024} MB.`,413):e}),c=await r(i.url,{method:`PUT`,headers:i.headers,body:e.data});if(!c.ok)throw new lf(`upload_failed`,`The blob store refused the file: ${c.status} ${(await c.text().catch(()=>``)).slice(0,300)||c.statusText}`,c.status);return(await o(`POST`,`/attachments/uploads/${encodeURIComponent(i.id)}`,{body:{}})).attachment}let c=await n(`${t}/attachments`,{method:`POST`,headers:{...await i(!0),"content-type":a,"x-board-filename":encodeURIComponent(e.name)},body:e.data});if(!c.ok)throw await Sf(c);return(await c.json()).attachment},download:(e,t={})=>a(`GET`,`/attachments/${encodeURIComponent(e)}`,t.signal?{signal:t.signal}:{}),edit:(e,t,n={})=>o(`POST`,`/messages/${gf(e)}/edit`,{body:{text:t,...n}}),delete:(e,t={})=>o(`POST`,`/messages/${gf(e)}/delete`,{body:{...t}}),react:(e,t,n={})=>o(`POST`,`/messages/${gf(e)}/reactions`,{body:{emoji:Oe(t),...n}}),label:(e,t)=>o(`POST`,`/messages/${gf(e)}/labels`,{body:t}),typing:async(e,t)=>(await o(`POST`,`/messages/${gf(e)}/typing`,{body:t?{status:t}:{}})).targets,sync:((e,t)=>t===void 0?o(`GET`,`/messages/${gf(e)}/sync`):o(`POST`,`/messages/${gf(e)}/sync`,{body:{target:t}})),linked:e=>o(`GET`,`/links${_f({url:e})}`),inbox:async(e,t={})=>(await o(`GET`,`/inbox/${e}${_f(t)}`)).events,register:e=>o(`POST`,`/watchers`,{body:e}),watchers:async()=>(await o(`GET`,`/watchers`)).watchers,matches:async(e={})=>{let{signal:t,...n}=e;return(await o(`GET`,`/watchers/matches${_f(n)}`,t?{signal:t}:{})).matches},ack:(e,t)=>o(`POST`,`/watchers/matches/${encodeURIComponent(e)}/ack`,{body:t}),readSource:(e,t,n={})=>o(`GET`,`/sources/${e}/read${_f({target:t,...n})}`),joinSource:(e,t)=>o(`POST`,`/sources/${e}/join`,{body:{target:t}}),poll:c,syncImport:e=>o(`POST`,`/sync/imports`,{body:e}),syncReceipt:e=>o(`POST`,`/sync/receipts`,{body:e}),syncThread:e=>o(`GET`,`/sync/threads/${gf(e)}`),syncFind:(e,t={})=>o(`GET`,`/sync/find${_f(e)}`,t.signal?{signal:t.signal}:{}),syncCopies:async e=>(await o(`GET`,`/sync/copies?${e.map(e=>`message=${encodeURIComponent(e)}`).join(`&`)}`)).copies,inboxPush:(e,t)=>o(`POST`,`/inbox/${gf(e)}`,{body:{events:t}}),inboxNext:async(e,t={})=>(await o(`GET`,`/inbox/${gf(e)}/next${_f(t)}`)).items,inboxAck:(e,t,n)=>o(`POST`,`/inbox/${gf(e)}/${gf(t)}/ack`,{body:n}),async*events(e={},t={}){let n=e.after,r=0;for(;!t.signal?.aborted;){let i;try{i=await a(`GET`,`/events${_f({...s(e),after:n})}`,{headers:{accept:`text/event-stream`},...t.signal?{signal:t.signal}:{}})}catch(e){if(t.signal?.aborted)return;if(e instanceof lf&&e.status>=400&&e.status<500)throw e;await new Promise(e=>setTimeout(e,Math.min(3e4,500*2**r++)));continue}r=0;try{for await(let e of Qd(i.body,t.signal))e.id!==void 0&&(n=e.id),e.event===`board`&&e.data&&(yield JSON.parse(e.data))}catch{if(t.signal?.aborted)return;await new Promise(e=>setTimeout(e,Math.min(3e4,500*2**r++)))}}},async wait(e={},t={}){let n=Date.now()+hf(t.timeout??`30m`),r=e.after??(await c({...e,after:void 0,wait:0},t.signal)).cursor;for(;Date.now()<n&&!t.signal?.aborted;){let i=Math.max(0,Math.min(25,Math.ceil((n-Date.now())/1e3))),a=await c({...e,after:r,wait:i},t.signal);if(a.events.length>0)return a.events[0];r=a.cursor}return null}}}async function Sf(e){try{let t=await e.json();if(t.error?.message)return new lf(t.error.code??`error`,t.error.message,e.status,{...typeof t.error.hint==`string`?{hint:t.error.hint}:{},origin:uf.has(e)?`handle`:`board`})}catch{}return new lf(`http_error`,`The board answered ${`${e.status} ${e.statusText}`.trim()}.`,e.status)}const Cf=e=>Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``);async function wf(e){return Cf(new Uint8Array(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e))))}async function Tf(...e){let t=new Uint8Array(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(JSON.stringify(e)))).slice(0,16);t[6]=t[6]&15|128,t[8]=t[8]&63|128;let n=Cf(t);return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20,32)}`}const Ef=/^[0-9a-f]{8}-[0-9a-f]{4}-8[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,Df=async(e,t)=>`key:${e}:${(await wf(`board-key\u001f${t}`)).slice(0,32)}`;var q=class extends Error{status;code;hint;origin;constructor(e,t,n,r={}){super(n),this.status=e,this.code=t,this.hint=r.hint,this.origin=r.origin??`board`}},Of=class extends q{response;constructor(e){super(e.status,`rejected`,`rejected with ${e.status}`),this.response=e}};const kf=(e,t=`invalid_request`)=>new q(400,t,e),Af=e=>new q(401,`unauthorized`,e),jf=e=>new q(403,`forbidden`,e),Mf=(e,t=`not_found`)=>new q(404,t,e),Nf=()=>new q(400,`text_too_long`,`A message's text is at most ${xu.toLocaleString(`en-US`)} characters.`,{hint:`Put the long part in a file and attach it to a message, with a short summary as the text.`}),Pf=()=>new q(409,`duplicate_id`,`that id was already used for a different write`),Ff=(e,t=200,n)=>new Response(JSON.stringify(e),{status:t,headers:{"content-type":`application/json`,...n}});function If(e){if(e.code!==`invalid_union`||e.errors.length===0)return e;let t=e.errors.reduce((e,t)=>t.length<e.length?t:e)[0];return t?If({...t,path:[...e.path,...t.path]}):e}function Lf(e){if(e instanceof Of)return e.response;if(e instanceof q){let t=Ff({error:{code:e.code,message:e.message,...e.hint===void 0?{}:{hint:e.hint}}},e.status);return e.origin===`handle`&&uf.add(t),t}if(e instanceof Nc){let t=e.issues[0]&&If(e.issues[0]);if(t?.code===`too_big`&&t.origin===`string`&&t.maximum===1e4&&t.path.length===1&&t.path[0]===`text`)return Lf(Nf());let n=t?.path.length?`${t.path.join(`.`)}: `:``;return Ff({error:{code:`invalid_request`,message:`${n}${t?.message??`invalid request`}`}},400)}let t=e?.code;return t===`INVALID_PAYLOAD`?Ff({error:{code:`invalid_request`,message:e.message}},400):t===`PARTIAL_DUPLICATE_BATCH`||t===`DUPLICATE_EVENT_ID`?Lf(Pf()):t===`STORE_UNAVAILABLE`||t===`STORE_NOT_CONFIGURED`?Ff({error:{code:`unavailable`,message:e.message}},503):(console.error(`[board]`,e),Ff({error:{code:`internal`,message:`internal error`}},500))}const Rf=`0.42.1`,zf=[`avatar`,`openapi`,`webhook`,`sync`],Bf=/* @__PURE__ */ `discovery.me.channels.createChannel.actors.messages.threads.message.post.posted.edit.delete.react.label.schedule.schedules.cancelSchedule.grants.createGrant.updateGrant.explain.revokeGrant.schemas.schema.createSchema.upload.attachment.uploadStart.uploadFinish.watchers.register.matches.ack.events.syncImport.syncReceipt.syncThread.syncFind.syncCopies.inboxPush.inboxNext.inboxAck.inbox.typing.readSource.joinSource.synced.linked`.split(`.`),Vf=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);function Hf(e,t,n,r){let i=t.split(`/`).filter(Boolean),a=i.map(e=>e.startsWith(`:`)?`/([^/]+)`:`/${Vf(e)}`).join(``);return{method:e,pattern:RegExp(`${a}$`),names:i.filter(e=>e.startsWith(`:`)).map(e=>e.slice(1)),target:n,segments:i.length,literals:i.filter(e=>!e.startsWith(`:`)).length,own:r}}function Uf(e,t){let n=[...zf.map(e=>Hf(Zd[e].method,Zd[e].path,{kind:`board`,name:e},!1)),...Bf.filter(e=>e!==`discovery`).map(e=>Hf(Zd[e].method,Zd[e].path,{kind:`protocol`,name:e},!1)),...e.map(e=>Hf(e.method,e.path,{kind:`backend`,route:e},!0))].sort((e,t)=>t.segments-e.segments||t.literals-e.literals||Number(t.own)-Number(e.own)),r=(e,t,n)=>{let r={};try{e.names.forEach((e,t)=>r[e]=decodeURIComponent(n[t]))}catch{return null}let i=e.names[0];return{target:e.target,base:t,param:i===void 0?null:r[i],params:r}},i=e=>({target:{kind:`protocol`,name:`discovery`},base:e,param:null,params:{},root:!0});return function(e,a){let o=a.length>1?a.replace(/\/+$/,``):a;if(t!==void 0){let a=t.replace(/\/+$/,``);if(o!==a&&!o.startsWith(`${a}/`))return null;let s=o.slice(a.length)||`/`;if(s===`/`)return e===`GET`?i(a):null;for(let t of n){let n=t.method===e?s.match(RegExp(`^${t.pattern.source}`)):null;if(n)return r(t,a,n.slice(1))}return null}for(let t of n){if(t.method!==e)continue;let n=o.match(t.pattern);if(n)return r(t,o.slice(0,n.index),n.slice(1))}return e===`GET`?i(o===`/`?``:o):null}}function Wf(e){let t={};for(let n of new Set(e.searchParams.keys())){let r=e.searchParams.getAll(n);t[n]=r.length>1?r:r[0]}return t}async function Gf(e){let t=await e.text();if(t.trim()!==``)try{return JSON.parse(t)}catch{throw kf(`request body is not valid JSON`)}}const Kf=()=>new q(413,`too_large`,`attachments are at most ${ke/1024/1024} MB`);async function qf(e,t){if(Number(e.headers.get(`content-length`)??0)>t)throw Kf();let n=[],r=0;for await(let i of e.body??[]){if(r+=i.byteLength,r>t)throw Kf();n.push(i)}let i=new Uint8Array(r),a=0;for(let e of n)i.set(e,a),a+=e.byteLength;return i}function Jf(){let e={};for(let[t,n]of Object.entries(Zd)){let r=n.path.replace(/:(\w+)/g,`{$1}`),i={operationId:t};`query`in n&&(i[`x-query-schema`]=kc(n.query,{io:`input`})),`body`in n&&(i.requestBody={content:{"application/json":{schema:kc(n.body,{io:`input`})}}}),(e[r]??={})[n.method.toLowerCase()]=i}return{openapi:`3.1.0`,info:{title:`board`,version:Rf},paths:e}}const Yf={re:{type:`string`,value:`id`,description:`in a thread: its root's ID`},by:{type:`string`,value:`handle`,description:`by an author: a handle, me, or an actor ID`},mentions:{type:`string`,value:`@handle`,optionalValue:!0,description:`mentioning a handle or email, or you without one`},label:{type:`string`,multiple:!0,value:`k[=v|w]`,description:`with a label on the message or its thread's root`},source:{type:`string`,value:`source`,description:`from a source: a sync key such as slack, or board`},text:{type:`string`,value:`words`,description:`containing this text, as one phrase (a substring, not word search)`},after:{type:`string`,value:`id`,description:`only what came after a message or a cursor (read and wait print one)`},url:{type:`string`,value:`url`,description:`the board at this URL, not the one the environment points at`},scope:{type:`string`,value:`team`,description:`a team's board in Vercel's API, by its slug or ID`},name:{type:`string`,value:`board`,description:`the team's board with this name, on --scope's team`},ensure:{type:`boolean`,description:`with --name: make that board if the team has none by that name`},team:{type:`string`,value:`team`,description:`the same as --scope`,hidden:!0},as:{type:`string`,value:`profile`,description:`write as a profile, such as an agent's name`},avatar:{type:`string`,value:`url`,description:`the profile's avatar, with --as`},json:{type:`boolean`,description:`JSON, for programs`},help:{type:`boolean`,short:`h`,description:`this help, or a command's`},version:{type:`boolean`,short:`v`,description:`the CLI's version`},limit:{type:`string`,short:`n`,value:`N`,description:`how many`},"idempotency-key":{type:`string`,value:`key`,description:`sending the same one again posts once`},sync:{type:`string`,multiple:!0,value:`target`,description:`sync the new thread to a target too, e.g. slack:#incidents`},"no-sync":{type:`boolean`,description:`keep it on the board: sync it nowhere`},attach:{type:`string`,multiple:!0,value:`file`,description:`attach a file`},"text-file":{type:`string`,value:`path`,description:`the text, from a file: - reads stdin`},unset:{type:`string`,multiple:!0,value:`k`,description:`remove a label`},if:{type:`string`,multiple:!0,value:`k=v`,description:`only while the message has this label now`},"if-unset":{type:`string`,multiple:!0,value:`k`,description:`only while the message doesn't have this label`},"if-revision":{type:`string`,value:`N`,description:`only if it is still at this revision, as read --json shows it`},channel:{type:`string`,value:`c`,description:`in a channel`},remove:{type:`boolean`,description:`take the reaction back`},all:{type:`boolean`,short:`a`,description:`everything, not only what most want`},timeout:{type:`string`,value:`duration`,description:`how long to wait: 30s, 10m, or a bare number of seconds (default: 30m)`},"no-open":{type:`boolean`,description:`don't open the browser`},in:{type:`string`,value:`duration`,description:`once, this long from now, e.g. 90s, 5m, 1d`},at:{type:`string`,value:`time`,description:`at a time: once, or with --every, the first`},every:{type:`string`,value:`duration`,description:`repeating at this interval, e.g. 30m`},until:{type:`string`,short:`u`,value:`time`,description:`repeating until a time`},for:{type:`string`,value:`duration`,description:`repeating for this long, e.g. 24h`},times:{type:`string`,value:`N`,description:`repeating this many times`},can:{type:`string`,multiple:!0,value:`pattern=perms`,description:`what they may do, repeated: perms, all, or none`},user:{type:`string`,multiple:!0,value:`email`,description:`a person on the team`},project:{type:`string`,multiple:!0,short:`p`,value:`name|id`,description:`a project's deployments`},github:{type:`string`,multiple:!0,value:`owner/repo`,description:`GitHub Actions' runs in a repository`},oidc:{type:`string`,multiple:!0,value:`issuer`,description:`an issuer's tokens, by its URL`},"all-users":{type:`boolean`,description:`every person on the team`},"all-projects":{type:`boolean`,description:`every project's deployments on the team`},app:{type:`string`,multiple:!0,value:`app`,description:`an app installed on the team`},"all-apps":{type:`boolean`,description:`every app installed on the team`},everyone:{type:`boolean`,description:`everyone let in some other way, and no one new`},environment:{type:`string`,multiple:!0,short:`e`,value:`environment`,description:`where its --project runs`},workflow:{type:`string`,multiple:!0,value:`file`,description:`its --github's workflow, e.g. ci.yml`},"git-branch":{type:`string`,multiple:!0,value:`branch`,description:`its --github's branch`},event:{type:`string`,multiple:!0,value:`event`,description:`its --github's event, e.g. push`},claim:{type:`string`,multiple:!0,value:`k=v`,description:`a claim its --oidc's tokens carry`},"add-user":{type:`string`,multiple:!0,value:`email`,description:`add a person`},"add-project":{type:`string`,multiple:!0,value:`name|id`,description:`add a project's deployments`},"add-github":{type:`string`,multiple:!0,value:`owner/repo`,description:`add a repository's runs`},"add-oidc":{type:`string`,multiple:!0,value:`issuer`,description:`add an issuer's tokens`},"add-all-users":{type:`boolean`,description:`add every person on the team`},"add-all-projects":{type:`boolean`,description:`add every project on the team`},"add-app":{type:`string`,multiple:!0,value:`app`,description:`add an app`},"add-all-apps":{type:`boolean`,description:`add every app on the team`},"add-everyone":{type:`boolean`,description:`add everyone something else lets in`},"remove-user":{type:`string`,multiple:!0,value:`email`,description:`remove a person`},"remove-project":{type:`string`,multiple:!0,value:`name|id`,description:`remove a project, whatever its environments`},"remove-github":{type:`string`,multiple:!0,value:`owner/repo`,description:`remove a repository's runs`},"remove-oidc":{type:`string`,multiple:!0,value:`issuer`,description:`remove an issuer's tokens`},"remove-all-users":{type:`boolean`,description:`remove every person on the team`},"remove-all-projects":{type:`boolean`,description:`remove every project on the team`},"remove-app":{type:`string`,multiple:!0,value:`app`,description:`remove an app`},"remove-all-apps":{type:`boolean`,description:`remove every app on the team`},"remove-everyone":{type:`boolean`,description:`remove everyone`},private:{type:`boolean`,description:`closed to everyone but you, in the same write`},schema:{type:`string`,value:`json|@file`,description:`its JSON Schema: inline, @<file>, or - for stdin`},description:{type:`string`,value:`text`,description:`what it holds, in a sentence`},port:{type:`string`,value:`N`,description:`the port to listen on`},dir:{type:`string`,value:`dir`,description:`where the board keeps its log (default: .board/)`},"no-inspect":{type:`boolean`,description:`don't start the inspector`},agent:{type:`string`,value:`name`,description:`the agent whose turn ended`,hidden:!0}},J=(e,t,n)=>({name:e,...Yf[e],...t?{description:t}:{},...n?{value:n}:{}});[`re`,`by`,`source`,`label`,`text`,`mentions`,`after`].map(e=>J(e)),[`url`,`scope`,`name`,`ensure`,`team`,`as`,`avatar`,`json`,`help`,`version`].map(e=>J(e));const Xf=`a reply only while this is the thread's newest message`;[...[`user`,`project`,`github`,`oidc`,`app`,`all-users`,`all-projects`,`all-apps`,`everyone`].map(e=>J(e)),J(`environment`,`where its --project runs (default: production)`),...[`workflow`,`git-branch`,`event`,`claim`].map(e=>J(e)),J(`can`,`what they may do, repeated: perms, all, or none`,`pattern=perms`)],[...[`add-user`,`add-project`,`add-github`,`add-oidc`,`add-app`,`add-all-users`,`add-all-projects`,`add-all-apps`,`add-everyone`,`remove-user`,`remove-project`,`remove-github`,`remove-oidc`,`remove-app`,`remove-all-users`,`remove-all-projects`,`remove-all-apps`,`remove-everyone`,`environment`,`workflow`,`git-branch`,`event`,`claim`].map(e=>J(e)),J(`can`,`replaces what it lets them do`,`pattern=perms`)],[...[`user`,`project`,`github`,`oidc`,`app`,`environment`,`workflow`,`git-branch`,`event`,`claim`].map(e=>J(e))],J(`private`),J(`schema`),J(`description`),J(`limit`,`threads to list (default: 50)`),J(`label`,`label it`,`k=v`),J(`text-file`),J(`schema`,`the text is JSON for this schema, such as sandbox@1`,`schema`),J(`attach`),J(`sync`),J(`no-sync`),J(`idempotency-key`),J(`after`,Xf),J(`label`,`label it`,`k=v`),J(`text-file`),J(`schema`,`the text is JSON for this schema, such as sandbox@1`,`schema`),J(`attach`),J(`idempotency-key`),J(`no-sync`),J(`after`,Xf),J(`in`),J(`at`),J(`every`),J(`until`),J(`for`),J(`times`),J(`label`,`label it`,`k=v`),J(`text-file`),J(`schema`,`the text is JSON for this schema, such as sandbox@1`,`schema`),J(`attach`),J(`no-sync`),J(`by`,`scheduled by a handle`),J(`channel`,`posting in a channel`),J(`all`,`done and canceled ones too`),J(`text-file`),J(`schema`,`the text is JSON for this schema, such as sandbox@1`,`schema`),J(`if-revision`),J(`if-revision`),J(`remove`),J(`unset`),J(`if`),J(`if-unset`),J(`limit`,`events to list`),J(`limit`,`messages to read`),J(`after`,`where the last read left off: the cursor it printed`),J(`channel`,`the channel to check in (default: conformance)`),J(`agent`),J(`all`,`delivery receipts too`),J(`timeout`),J(`port`,`the port to listen on (default: a free one)`),J(`no-open`);const Zf={re:Yf.re,by:Yf.by,mentions:Yf.mentions,label:Yf.label,source:Yf.source,text:Yf.text},Qf=e=>e!==void 0&&!e.startsWith(`-`)&&(e===`me`||e.includes(`@`));function $f(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];if(r===`--`){t.push(...e.slice(n));break}r===`--mentions`?Qf(e[n+1])?t.push(`--mentions=${e[++n]}`):t.push(`--mentions=me`):t.push(r)}return t}function ep(e){let t=[],n=null,r=null;for(let i=0;i<e.length;i++){let a=e[i];r?a===r?r=null:a===`\\`&&r===`"`&&i+1<e.length?n+=e[++i]:n+=a:/\s/.test(a)?(n!==null&&t.push(n),n=null):a===`"`||a===`'`?(r=a,n??=``):n=a===`\\`&&i+1<e.length?(n??``)+e[++i]:(n??``)+a}if(r)throw Error(`unterminated ${r}`);return n!==null&&t.push(n),t}const tp={...Zf,all:{type:`boolean`}};function np(e){let t={},n=[];for(let r=0;r<e.length;r++){let i=e[r];if(i===`--`){n.push(...e.slice(r+1));break}if(!i.startsWith(`-`)||i===`-`){n.push(i);continue}let a=i.indexOf(`=`),o=i.startsWith(`--`)?i.slice(2,a===-1?void 0:a):null,s=o!==null&&Object.hasOwn(tp,o)?tp[o]:null;if(!s)throw Error(`${o===null?i.slice(0,2):`--${o}`} isn't a filter`);if(s.type===`boolean`){if(a!==-1)throw Error(`--${o} takes no value`);t[o]=!0;continue}let c;if(a!==-1)c=i.slice(a+1);else{let t=e[r+1];if(t===void 0||t.length>1&&t.startsWith(`-`))throw Error(`--${o} needs a value`);c=t,r++}t[o]=`multiple`in s?[...t[o]??[],c]:c}return{values:t,positionals:n}}function rp(e){let{values:t,positionals:n}=np($f(ep(e)));if(n.length>1)throw Error(`expected one channel, got: ${n.join(` `)}`);let r=n[0],i=rd.safeParse({...r?{channel:r}:{},...t.re?{re:t.re.replace(/^#/,``)}:{},...t.by?{by:t.by.replace(/^@/,``)}:{},...t.mentions?{mentions:t.mentions.replace(/^@/,``)}:{},...t.label?.length?{label:t.label}:{},...t.source?{from:t.source}:{},...t.text?{text:t.text}:{}});if(!i.success){let e=i.error.issues[0];throw Error(`${e?.path.length?`--${String(e.path[0])}: `:``}${e?.message??`invalid filters`}`)}return{filters:i.data,all:t.all===!0}}const ip=e=>e.channel!==void 0||e.re!==void 0||e.by!==void 0||e.mentions!==void 0||e.from!==void 0||e.text!==void 0||(e.label?.length??0)>0;function ap(e,t){let n,r;try{({filters:n,all:r}=rp(t.tail))}catch(t){throw Error(`watch ${e}: ${t.message}`)}if(n.mentions===`me`)throw Error(`watch ${e}: a watcher has no "me": use --mentions @handle`);return{filters:n,criteria:ip(n),all:r}}function op(e){try{Reflect.get(globalThis,Symbol.for(`@vercel/request-context`))?.get?.()?.waitUntil?.(e)}catch{}}const sp=1e4,cp=e=>((e instanceof Error?e.message:String(e))||`unknown error`).slice(0,500),lp=e=>e?.startsWith(`https://`)?e:null,up=e=>e.path===void 0,dp=()=>typeof process<`u`&&process.env.VERCEL===`1`&&process.env.VERCEL_ENV!==`development`;function fp(e){if(!e||!dp())return null;let t=process.env,n=(t.VERCEL_TARGET_ENV||t.VERCEL_ENV)===`preview`&&t.VERCEL_GIT_COMMIT_REF||null;return{path:new URL(e).pathname,...n?{branch:n}:{}}}function pp(e){let{registry:t,rethrow:n}=e,r=e.binding,i=null,a=null;async function o(n,r=!1){let o=await e.hash();return!r&&i&&i.url===n&&i.result.hash===o&&Date.now()-i.at<sp?i.result:(r&&a&&await a.catch(()=>{}),a??=e.wakeAt(n).then(e=>t.register(e)).then(e=>(i={url:n,at:Date.now(),result:e},e)).finally(()=>{a=null}),a)}async function s(e){let n={};if(!r().subscriptions[e.watcher])n={skip:!0};else try{await r().run(e.watcher,e.event,{trigger:`watch:${e.watcher}:${e.id}`,attempt:e.attempt+1})}catch(t){console.error(`[board] watcher ${e.watcher} failed:`,t),n={error:cp(t)}}await t.ack(e.id,{lease:e.lease,...n}).catch(e=>console.error(`[board] couldn't ack a match:`,cp(e)))}async function c(){let e=0,n=Date.now()+24e4;for(;Date.now()<n;){let n=await t.matches({limit:10});if(n.length===0)break;await Promise.all(n.map(s)),e+=n.length}return e+await r().pull()}let l=null;function u(){if(l||dp())return;let n=l=new AbortController;(async()=>{for(let i=1e3;!n.signal.aborted;)try{await o(null);let e=await t.matches({limit:10,wait:25,signal:n.signal});await Promise.all(e.map(s)),await r().pull(),i=1e3}catch(t){if(n.signal.aborted)break;console.error(`[board] couldn't pull matches from ${e.remote}:`,cp(t)),await new Promise(e=>setTimeout(e,i)),i=Math.min(i*2,6e4)}})()}let d=null,f=0;function p(){if(d)return d;if(!e.hasWork()||Date.now()-f<sp)return Promise.resolve();let t=lp(r().url());return!t&&dp()?Promise.resolve():(d=o(t).then(e=>{up(e)&&u()},t=>{d=null,f=Date.now(),console.error(`[board] couldn't register with ${e.remote}:`,cp(t))}),t||u(),d)}return{start:p,routes:[{method:`POST`,path:`/wake`,async handle(t){d??=Promise.resolve();let i=t.headers.get(`x-board-watchers`)!==await e.hash(),a=(async()=>(i&&await o(lp(r().url())),c()))();op(a.catch(e=>console.error(`[board] couldn't run what woke it:`,cp(e))));let s,l=new Promise(e=>s=setTimeout(()=>e(null),2e3));try{let e=await Promise.race([a.catch(n),l]);return e===null?new Response(null,{status:202}):Ff({ran:e})}finally{clearTimeout(s)}}},{method:`POST`,path:`/watchers`,async handle(t,{caller:i}){if(i)return e.registerFor(i,t);d??=Promise.resolve();let a=lp(r().url()),s=await o(a).catch(n);return(!a||up(s))&&u(),Ff(s)}}],registerNow:(e=!1)=>o(lp(r().url()),e),close:()=>{l?.abort(),l=null}}}const mp=e=>e>10,hp=e=>((e instanceof Error?e.message:String(e))||`unknown error`).slice(0,500);async function gp(e){let{watcher:t,match:n,attempt:r}=e,i=n.payload.event,a=async a=>{console.error(`[board] watcher ${t.id} gave up on event #${i.cursor} after ${r} tries:`,a),await e.record({matched:n.id,thread:n.payload.thread,error:a})},o=!mp(r);if(o&&r>=10)return a(`its run was cut short ${r-1} times (a timeout, or out of memory)`);try{await t.run(i)}catch(e){if(!o||r<5)throw e;await a(hp(e))}}const _p=1e3,vp=e=>((e instanceof Error?e.message:String(e))||`unknown error`).slice(0,500);function yp(e){let t=null,n=crypto.randomUUID(),r=0;async function i(t,i,o,s){let c,l=/* @__PURE__ */ new Map,u={...i,...o?{all:!0}:{}},d;for(let i=_p;!s.aborted;){let o;try{c??=await e.actorOf(t),o=await e.events(d===void 0?{...u,wait:0}:{...u,after:d,wait:25},s),i=_p}catch(e){if(s.aborted)return;console.error(`[board] watcher ${t} couldn't read the board:`,vp(e)),await bp(i,s),i=Math.min(i*2,6e4);continue}d=o.cursor;for(let e of o.events){if(e.actor?.id===c&&!(e.type===`message.posted`&&e.message?.schedule))continue;let i=e.message?.thread??``,o={id:`${n}:${r++}`,payload:{thread:i,event:e}},u=(l.get(i)??Promise.resolve()).then(()=>a(t,o,s));l.set(i,u),u.then(()=>{l.get(i)===u&&l.delete(i)})}}}async function a(t,n,r){let i=`watch:${t}:${n.id}`;for(let a=1,o=1e3;!r.aborted;a++,o=Math.min(o*2,3e4))try{await gp({watcher:{id:t,run:n=>e.run(t,n,{trigger:i,attempt:a})},match:n,attempt:a,record:async()=>{}});return}catch(e){console.error(`[board] watcher ${t} failed:`,e),await bp(o,r)}}return{start(){if(t)return;let{signal:n}=t=new AbortController;for(let[t,{filters:r,all:a}]of Object.entries(e.watchers))i(t,r,a,n)},close(){t?.abort(),t=null}}}const bp=(e,t)=>new Promise(n=>{if(t.aborted)return n();let r=setTimeout(n,e);t.addEventListener(`abort`,()=>(clearTimeout(r),n()),{once:!0})}),xp=[`read`,`post`,`react`,`label`,`sync`,`manage`];var Sp=class extends Error{code=`invalid_can`;constructor(e){super(e),this.name=`InvalidCan`}};const Cp={read:[],post:[],react:[`read`],label:[`read`],sync:[`read`],manage:[`read`,`post`,`react`,`label`,`sync`]},wp=new Map(xp.map((e,t)=>[e,t])),Tp=`write *, a channel, or a channel and its subtree (feedback/)`;function Ep(e){if(e===`*`)return{kind:`all`};if(e.includes(`*`)){let t=e.slice(0,e.indexOf(`*`)).replace(/\/+$/,``);throw new Sp(`invalid channel pattern ${e}: ${t===``?`write * for every channel`:Cu.safeParse(t).success?`write ${t}/ for ${t} and its subtree`:Tp}`)}let t=e.endsWith(`/`),n=t?e.slice(0,-1):e;if(!Cu.safeParse(n).success)throw new Sp(`invalid channel pattern ${e||`(empty)`}: ${Tp}`);return t?{kind:`subtree`,path:n}:{kind:`exact`,path:n}}const Dp=e=>e.kind===`all`?`*`:e.kind===`subtree`?`${e.path}/`:e.path;function Op(e){let t=/* @__PURE__ */ new Set,n=e=>{if(!wp.has(e))throw new Sp(`unknown permission ${String(e)}: use ${xp.join(`, `)}`);if(!t.has(e)){t.add(e);for(let t of Cp[e])n(t)}};for(let t of e===`all`?xp:e)n(t);return t}const kp=/* @__PURE__ */ new Set;function Ap(e){let t=null,n=/* @__PURE__ */ new Map,r=[];for(let[i,a]of e)i.kind===`all`?t=a:i.kind===`exact`?n.set(i.path,a):r.push([i.path,a]);return r.sort((e,t)=>t[0].length-e[0].length),{all:t,exact:n,subtrees:r}}const jp=(e,t)=>e===t||e.startsWith(`${t}/`);function Mp(e,t,n=!1){if(!n){let n=e.exact.get(t);if(n)return n}for(let[n,r]of e.subtrees)if(jp(t,n))return r;return e.all??kp}const Np=(e,t)=>t.kind===`all`?e.all??kp:Mp(e,t.path,t.kind===`subtree`),Pp=(e,t)=>e.size===t.size&&[...e].every(e=>t.has(e));function Fp(e,t){if(t.kind===`exact`)return Mp(e,t.path,!0);if(t.kind===`subtree`){for(let[n,r]of e.subtrees)if(n!==t.path&&jp(t.path,n))return r}return e.all??kp}function Ip(e){let t=Ap(e);return Ap(e.filter(([e,n])=>e.kind===`all`?n.size>0:!Pp(n,Fp(t,e))))}function Lp(e){return e===`all`||Array.isArray(e)?[[{kind:`all`},Op(e)]]:Object.entries(e).map(([e,t])=>[Ep(e),Op(t)])}const Rp=e=>[...e.all?[[{kind:`all`},e.all]]:[],...e.subtrees.map(([e,t])=>[{kind:`subtree`,path:e},t]),...[...e.exact].map(([e,t])=>[{kind:`exact`,path:e},t])],zp=Symbol(`board.access`),Bp=e=>typeof e==`object`&&zp in e;function Vp(e){let t=Rp(e),n=n=>(e.all?.has(n)??!1)&&t.every(([,e])=>e.has(n)),r=e.exact.size===0&&e.subtrees.length===0?e.all?.has(`read`)??!1:null,i=/* @__PURE__ */ new Map,a={[zp]:e,can:(t,n)=>Mp(e,n).has(t),readable(t){if(r!==null)return r;let n=i.get(t);return n===void 0&&(i.size>=4096&&i.clear(),i.set(t,n=Mp(e,t).has(`read`))),n},readsAll:n(`read`),everywhere:n,anywhere:e=>t.some(([,t])=>t.has(e)),at:(t,n)=>Np(e,Ep(n)).has(t),narrow(n){let r=Bp(n)?n[zp]:Ip(Lp(n)),i=/* @__PURE__ */ new Map([[`*`,{kind:`all`}]]);for(let[e]of[...t,...Rp(r)])i.set(Dp(e),e);return Vp(Ip([...i.values()].map(t=>{let n=Np(r,t);return[t,new Set([...Np(e,t)].filter(e=>n.has(e)))]})))},summary(){let e=t.map(([e,t])=>[Dp(e),t]);e.sort(([e],[t])=>e===`*`?-1:t===`*`?1:e.localeCompare(t));let n={};for(let[t,r]of e)n[t]=[...r].sort((e,t)=>wp.get(e)-wp.get(t));return n}};return Object.freeze(a)}function Hp(e){return Vp(Ip(Lp(e)))}const Up=Hp(`all`);Hp([]);const Wp=new Map([`principal`,`group`,`everyone`].map((e,t)=>[e,t])),Gp=e=>Lp(e);function Kp(e){let t=/* @__PURE__ */ new Map;for(let n of e)for(let[e,r]of Gp(n.can)){let i=Dp(e),a=t.get(i);if(!a||Wp.get(n.level)<Wp.get(a.level))t.set(i,{pattern:e,level:n.level,permissions:new Set(r),sources:[n.source]});else if(a.level===n.level){for(let e of r)a.permissions.add(e);a.sources.includes(n.source)||a.sources.push(n.source)}}return t}function qp(e){return Vp(Ip([...Kp(e).values()].map(({pattern:e,permissions:t})=>[e,t])))}function Jp(e,t){let n=[...Kp(e).values()].filter(({pattern:e})=>e.kind===`all`?!0:e.kind===`exact`?e.path===t:jp(t,e.path)),r=({pattern:e})=>e.kind===`exact`?1/0:e.kind===`subtree`?e.path.length:-1,[i,...a]=n.sort((e,t)=>r(t)-r(e));return i?{pattern:Dp(i.pattern),over:a.map(({pattern:e})=>Dp(e)),level:i.level,sources:i.sources,permissions:[...i.permissions].sort((e,t)=>wp.get(e)-wp.get(t))}:{pattern:null,over:[],level:null,sources:[],permissions:[]}}function Yp(e){let t=Object.entries(e.summary()).map(([e,t])=>`${e}=${t.join(`,`)}`);return t.length>0?t.join(`;`):`*=`}function Xp(e,t=`x-board-can`){if(e.length>4e3)throw new Sp(`${t} is longer than 4000 characters`);let n={},r=e.split(`;`).map(e=>e.trim());if(r.every(e=>e===``))throw new Sp(`${t} is empty: write pattern=permissions, like dev/=read,post`);for(let e of r){if(e===``)continue;let r=e.indexOf(`=`);if(r<0)throw new Sp(`${t} entry ${e} needs =: write pattern=permissions, like dev/=read,post`);let i=e.slice(0,r).trim(),a=e.slice(r+1).trim();if(Object.hasOwn(n,i))throw new Sp(`${t} lists ${i} twice`);Ep(i);let o=a===``?[]:a.split(`,`).map(e=>e.trim());if(o.length===1&&o[0]===`all`){n[i]=`all`;continue}for(let e of o)if(!wp.has(e))throw new Sp(`${t}: unknown permission ${e||`(empty)`}: use ${xp.join(`, `)}, or all`);n[i]=o}return n}function Zp(e,t){let{caller:n}=t;switch(e.kind){case`everyone`:return`everyone`;case`all-users`:return n.kind===`user`&&t.member===!0?`group`:null;case`user`:return n.kind===`user`&&n.userId===e.userId?`principal`:null;case`all-projects`:return n.kind===`project`&&t.teamProject===!0&&e.environments.includes(n.environment)?`group`:null;case`project`:return n.kind===`project`&&n.projectId===e.projectId&&(e.teamId===void 0||n.teamId===void 0||n.teamId===e.teamId)&&e.environments.includes(n.environment)?`principal`:null;case`github`:{if(n.kind!==`github`)return null;let t=e.repositoryId===void 0?n.repository===e.repository:n.repositoryId===e.repositoryId,r=e.workflow===void 0||n.ref!==void 0&&n.workflowRef===`${n.repository}/${e.workflow}@${n.ref}`,i=e.branch===void 0||n.ref===`refs/heads/${e.branch}`,a=e.event===void 0||n.event===e.event;return t&&r&&i&&a?`principal`:null}case`app`:return n.kind===`app`&&n.clientId===e.clientId?`principal`:null;case`all-apps`:return n.kind===`app`&&t.teamApp===!0?`group`:null;case`oidc`:return n.kind===`oidc`&&n.issuer===e.issuer&&Object.entries(e.claims).every(([e,t])=>{let r=n.claims[e];return r===void 0?!1:typeof t==`string`?String(r)===t:t.includes(String(r))})?`principal`:null}}const Qp={principal:0,group:1,everyone:2};function $p(e,t=!1){let n=[];for(let r of e.grants){let i=null;for(let n of r.principals){if(t&&n.kind===`everyone`)continue;let r=Zp(n,e);r!==null&&(i===null||Qp[r]<Qp[i])&&(i=r)}i!==null&&n.push({level:i,can:r.can,source:{grant:r}})}return n}function em(e,t=$p(e)){return e.caller.kind===`user`&&e.member===!0||t.some(e=>e.level!==`everyone`)}function tm(e,t){let n=t.cap===void 0?e:e.narrow({"*":[...t.cap]});return t.can!==void 0&&(n=n.narrow(Hp(t.can))),n}function nm(e){let t=$p(e);return em(e,t)?{caller:tm(qp(t),e),own:tm(qp($p(e,!0)),e)}:null}function rm(e,t){let n=$p(e);if(!em(e,n))return{pattern:null,over:[],level:null,grants:[],capped:!1,permissions:[]};let r=Jp(n,t),i=e.cap===void 0?null:Hp({"*":[...e.cap]}),a=i?r.permissions.filter(e=>i.can(e,t)):[...r.permissions],o=e.can===void 0?null:Hp(e.can);return{pattern:r.pattern,over:[...r.over],level:r.level,grants:r.sources.map(e=>e.grant),capped:a.length<r.permissions.length,permissions:o?a.filter(e=>o.can(e,t)):a}}const im=/^https:\/\/oidc\.vercel\.com(?:\/[a-z0-9-]+)?$/,am=e=>{let t=new URL(e);return`${t.host}${t.pathname.replace(/\/+$/,``)}`.replace(/[%:]/g,e=>e===`%`?`%25`:`%3A`)},om=Object.freeze({"*":Object.freeze([`read`,`post`,`react`,`label`])});function sm(e){let t=e.toLowerCase().replace(/\.$/,``);return t.startsWith(`[`)||/^\d+(\.\d+){3}$/.test(t)||/^\d+$/.test(t)||!t.includes(`.`)||t===`localhost`?!0:/\.(localhost|local|internal|home|lan|corp|intranet)$/.test(t)}const cm=e=>e.split(`:`).slice(2).join(`:`);function lm(e,t,n){let r=t?.claims??{};return e.kind===`person`?{caller:{kind:`user`,userId:cm(e.id)},member:!0}:t?.issuer===`vercel`?{caller:{kind:`project`,projectId:String(r.project_id??``),environment:String(r.environment??``),...typeof r.owner_id==`string`?{teamId:r.owner_id}:{}},teamProject:n!==null&&r.owner_id===n}:t?.issuer===`github`?{caller:{kind:`github`,repository:String(r.repository??``),...r.repository_id===void 0?{}:{repositoryId:String(r.repository_id)},...r.workflow_ref===void 0?{}:{workflowRef:String(r.workflow_ref)},...r.ref===void 0?{}:{ref:String(r.ref)},...r.event_name===void 0?{}:{event:String(r.event_name)}}}:t?.issuer===`oidc`?{caller:{kind:`oidc`,issuer:t.iss,claims:r}}:null}function um(e,t){let n=new Set(e.map(am)),r=[...e];for(let i of t){if(e.includes(i))continue;let t=URL.parse(i);if(t?.protocol!==`https:`||sm(t.hostname))continue;let a=am(i);n.has(a)||(n.add(a),r.push(i))}return r}const dm=e=>[...new Set(e.flatMap(e=>e.principals.flatMap(e=>e.kind===`oidc`?[e.issuer]:[])))],fm=(e,t)=>new q(403,`forbidden`,`this token can't use this board: no grant lets in ${e}`,{hint:`Grant it: vb grants create ${t}`});function pm(e){async function t(t,n,r,i){let a=i??(e.grants?await e.grants():[]),o=lm(t,n,r);return{grants:a,facts:o?{...o,grants:a}:null}}async function n(n,r,i){let a=r?.claims??{},o=r?.issuer===`vercel`?await e.project():null,s=String(a.environment??``),c=mm(),l=o!==null&&o.id!==null&&a.project_id===o.id;if(l&&c!==null&&s===c)return{fixed:Up};if(!r)throw jf(`this token can't use this board`);let{grants:u,facts:d}=await t(n,r,o?.teamId??null,i);if(d&&em(d))return{facts:d};if(r.issuer===`oidc`&&!dm(u).includes(r.iss))throw Af(`untrusted issuer: ${r.iss}`);if(r.issuer===`oidc`)throw jf(`this token can't use this board: no grant lets in its claims`);if(r.issuer===`github`){let e=String(a.repository??``);throw fm(e||`its repository`,`--github ${e||`<OWNER/REPO>`}`)}let f=String(a.project_id??``)||`<PROJECT_ID>`,p=`--project ${f} --environment ${s||`<ENVIRONMENT>`}`;throw l?new q(403,`forbidden`,`this token can't use this board: it runs in ${c??`no Vercel environment`}, and its ${s||`unnamed`} deployments need a grant`,{hint:`Grant them: vb grants create ${p}`}):fm(`project ${f} in ${s||`no environment`}`,p)}async function r(r,i){let a=r.facts?.issuer===`host`;if(r.id.startsWith(`board:`)||r.kind===`external`&&!a)return{fixed:Up};if(a){if(!e.hosts)throw jf(`this token can't use this board: its board no longer takes a host's principals`);let{exp:t}=r.facts.claims;if(typeof t==`number`&&t*1e3<=Date.now())throw Af(`token expired`)}if(r.kind===`person`){if(!e.grants)return{fixed:Up};let{facts:n}=await t(r,null,null,i);return{facts:n}}return n(r,(a?void 0:r.facts)??hm(r.id),i)}async function i(e,t){let n=await r(e,t),i=e.scope===void 0?void 0:Xp(e.scope);if(`fixed`in n)return i===void 0?n.fixed:n.fixed.narrow(i);let a=nm({...n.facts,...i===void 0?{}:{can:i}});if(!a)throw jf(`this token can't use this board`);return a.caller}async function a(e,t){try{return await i(e,t)}catch(e){let t=e.status;if(t===401||t===403)return null;throw e}}return{grant:i,accessNow:a,resolve:r}}const mm=()=>process.env.VERCEL_TARGET_ENV||process.env.VERCEL_ENV||null;function hm(e){let t=e.match(/^vercel:project:([^:]+):([^:]+)$/);return t?{issuer:`vercel`,iss:``,claims:{project_id:t[1],environment:t[2]}}:null}const gm=Symbol(`board.oidcTokens`),_m=/* @__PURE__ */ new WeakSet,vm=e=>gm in e,ym=e=>_m.has(e),bm=/^[a-z][a-z0-9-]*:[a-z][a-z0-9-]*:[^\s+\]]{1,200}$/,xm=[`person`,`deployment`,`workflow`,`external`];function Sm(e){let t=e=>{throw TypeError(`authenticate returned an invalid principal: ${e}`)};(typeof e!=`object`||!e)&&t(`not an object`),(typeof e.id!=`string`||!bm.test(e.id)||e.id.startsWith(`board:`))&&t(`id must look like \`vercel:user:<id>\`, got ${JSON.stringify(e.id)}`),xm.includes(e.kind)||t(`kind must be one of ${xm.join(`, `)}`),(typeof e.handle!=`string`||!/^\S{1,64}$/.test(e.handle))&&t(`handle must be 1-64 characters, no spaces`);let n=e.expiresAt??null;if(n!==null&&(!(n instanceof Date)||Number.isNaN(n.getTime()))&&t(`expiresAt must be a Date or null`),n!==null&&n.getTime()<=Date.now())throw Af(`token expired`);let r=n===null?{}:{exp:Math.floor(n.getTime()/1e3)};return{id:e.id,kind:e.kind,handle:e.handle,expiresAt:n,facts:{issuer:`host`,iss:``,claims:r}}}const Cm=e=>{throw new q(400,`no_token`,`There's no credential here to hand a sandbox for ${e}: pass one, sandboxPolicy({ token }).`,{origin:`handle`})};function wm(e){return typeof e==`string`&&e!==`all`?(Xp(e),e):Yp(Hp(e===void 0?om:e===`all`||Array.isArray(e)?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t===`none`?[]:t]))))}const Tm=[`grants`,`watchers`,`wake`,`webhooks`,`sync`,`inbox`,`sources`],Em=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),Dm=e=>[...e].map(e=>/[a-z]/i.test(e)?`[${e.toLowerCase()}${e.toUpperCase()}]`:Em(e)).join(``),Om=Object.values(Zd).filter(({path:e})=>!Tm.includes(e.split(`/`).filter(Boolean)[0]??``)).map(({method:e,path:t})=>({method:e,path:t===`/`?``:t}));function km(e,t,n,r){let i=/* @__PURE__ */ new Map;for(let{method:e,path:n}of t){let t=n.split(`/`).filter(Boolean).map(e=>e.startsWith(`:`)?`/(?:[A-Za-z0-9_.@~:+=,!$&'*-]|%[0-9A-Fa-f]{2})+`:`/${Em(e)}`).join(``);i.set(e,[...i.get(e)??[],t])}return[...i].map(([t,i])=>({match:n({method:[t],path:{regex:`^${e}(?:${i.join(`|`)})/?$`}}),transform:r}))}const Am=e=>({response:{statusCode:403,body:JSON.stringify({error:{code:`forbidden`,message:e}}),contentType:`application/json`}});function jm(e){let t=new URL(e.url),n=Em(t.pathname.replace(/\/+$/,``)),r=[...t.searchParams].map(([e,t])=>({key:{exact:e},value:{exact:t}})),i=e=>r.length>0?{...e,queryString:r}:e,a=[{headers:{...e.headers}}];return{allow:{[t.host]:[{match:{path:{regex:`(?:^|/)\\.\\.?(?:/|$)|%2[eEfF]|%5[cC]|\\\\`}},...Am(`not a board route`)},{match:{queryString:[{key:{regex:`^${Dm(`x-vercel-set-bypass-cookie`)}$`}}]},...Am(`not a board route`)},{match:{headers:[{key:{exact:`x-vercel-set-bypass-cookie`}}]},...Am(`not a board route`)},...km(n,e.routes,i,a),...(e.reads??[]).map(e=>({match:i({path:{exact:e},method:[`GET`]}),transform:a})),{match:{path:{regex:`^${n}/(?:${Tm.map(Dm).join(`|`)})(?:/|$)`}},...Am(`not a route this sandbox's policy hands it`)},Am(`not this board's`)]}}}const Mm=/^[A-Za-z][A-Za-z0-9-]{0,31}$/,Nm=e=>((e instanceof Error?e.message:String(e))||`unknown error`).slice(0,500),Pm=e=>{throw e instanceof lf?new q(e.status>=400?e.status:502,e.code,e.message,{...e.hint===void 0?{}:{hint:e.hint},origin:e.origin}):e instanceof q||e instanceof Error&&e.name===`AbortError`?e:new q(502,`unreachable`,`the board didn't answer: ${Nm(e)}`)};function Fm(e){let t=new URLSearchParams;for(let[n,r]of Object.entries(e))if(r!=null&&r!==!1){if(n===`label`&&Array.isArray(r))for(let[e,n]of r)t.append(`label`,n===null?e:`${e}=${n.join(`|`)}`);else if(Array.isArray(r))for(let e of r)t.append(n,String(e));else t.set(n,String(r))}let n=t.toString();return n?`?${n}`:``}function Im(e,t){let n=(t.headers.get(`content-disposition`)??``).match(/filename\*=UTF-8''([^;]+)/)?.[1],r=`file`;try{n&&(r=decodeURIComponent(n))}catch{}return{attachment:{id:e,name:r,type:t.headers.get(`content-type`)??`application/octet-stream`,size:Number(t.headers.get(`content-length`)??0)},data:t.body??/* @__PURE__ */ new Uint8Array}}function Lm(e,t,n){if(e!==void 0&&!/^https?:\/\/[^/]/.test(e))throw Error(`http: ${e} isn't a URL: pass the board's, like https://board.example.com/api/board`);if(e===void 0&&!n)throw Error(`http: pass the board's URL: outside Node there's no environment to find it in`);let r=(e??n.url()).replace(/\/+$/,``),i=t.fetch??n?.fetch(r)??((e,t)=>globalThis.fetch(e,t)),a=null,o={},s=()=>{if(!a)throw Error(`http: this backend isn't serving a board yet: pass it to board({ backend })`);return a},c=(e,t)=>xf({url:r,fetch:i,profile:e===void 0?()=>n?.profile()??null:e,...t===void 0?{}:{headers:{"x-board-can":t}}}),l=c(null),u=/* @__PURE__ */ new Map;function d(e){if(!Mm.test(e))throw new q(400,`invalid_request`,`as: ${e}: profiles start with a letter and use up to 32 letters, numbers, and hyphens`);let t=u.get(e);return t||u.set(e,t=c(e)),t}let f=/* @__PURE__ */ new Map;function p(e,t){let n=JSON.stringify([e??(e===null?null:`\0`),t??null]),r=f.get(n);return r||f.set(n,r=c(e,t)),r}function m(e){return e.origin.via?.kind===`engine`?l:e.origin.via?.kind===`client`?(e.self!==null&&d(e.self),p(`profile`in e?e.profile:e.self??void 0,e.can)):d(e.self??`client`)}let h=null,g=()=>(h??=i(r).then(async e=>{if(!e.ok)throw new q(e.status>=400?e.status:502,`no_board`,`There's no board at ${r}: it answered ${e.status}.`,{origin:`handle`});return await e.json()},Pm)).catch(e=>{throw h=null,e}),_=null,v=()=>_??=l.me().then(e=>e.principal).catch(e=>{throw _=null,e}),y=async e=>Df(await v(),e);async function b(e,t,n,i){let a=Zd[t],o={...n},s=a.path.replace(/:(\w+)/g,(e,t)=>{let n=o[t];return delete o[t],encodeURIComponent(String(n))}),c;if(t===`upload`){let{data:t,name:r,type:a}=n;if(t.byteLength>4194304){let n=await e.upload({data:t,name:r??`file`,...a?{type:a}:{}}).catch(Pm);return Response.json({attachment:n})}c=await e.request(s,{method:`POST`,body:t,headers:{...a?{"content-type":a}:{},...r===null?{}:{"x-board-filename":encodeURIComponent(r)}},signal:i}).catch(Pm)}else c=a.method===`GET`?await e.request(`${s}${Fm(o)}`,{signal:i}).catch(Pm):await e.request(s,{method:a.method,body:new TextEncoder().encode(JSON.stringify(o)),headers:{"content-type":`application/json`},signal:i}).catch(Pm);if(c.ok)return c;try{let e=await c.json();if(e.error?.message)throw new q(c.status,e.error.code??`error`,e.error.message,typeof e.error.hint==`string`?{hint:e.error.hint}:{})}catch(e){if(e instanceof q)throw e}throw new q(502,`remote_error`,`${r} answered ${c.status}`)}async function x(e,t,n,i){if(T(),`identity`in t)throw new q(404,`not_found`,`this board uses ${r}, and answers nothing itself`);let a=m(t);(e===`post`||e===`posted`)&&`self`in t&&typeof n.id==`string`&&Ef.test(n.id)&&(n={...n,id:await y(n.id).catch(Pm)});let o=await b(a,e,n,i);return e===`attachment`?Im(String(n.id),o):o.json()}let S={...Object.fromEntries(Bf.map(e=>[e,(t,n,r)=>x(e,t,n,r)])),async discovery(){return g()}},C=null,w=!1;function T(){if(!(C||w||Object.keys(o).length===0)){if(dp()){w=!0,console.error(`[board] watchers on a board that uses ${r} run only in a process that stays up: on Vercel, none run`);return}C=yp({watchers:o,events:async(e,t)=>(await b(l,`events`,e,t)).json(),actorOf:async e=>(await d(e).me().catch(Pm)).actor,run:(e,t,n)=>s().run(e,t,n)}),C.start()}}return{...S,routes:[],keeps:!1,async sandbox({profile:e,can:t,token:i}){let a=n?await n.sandbox(r,i):i===void 0?Cm(r):{authorization:`Bearer ${i}`};return{url:r,headers:{...a,"x-board-profile":sf(e),"x-board-can":t},routes:Om}},bind(e){if(a)throw Error(`http: this backend already serves a board: create one http() per board()`);for(let[t,n]of Object.entries(e.subscriptions)){if(n.kind===`sync`)throw Error(`http: sync doesn't run on a board that uses ${r}: sync from that board's own config`);if(!Mm.test(t))throw Error(`watch ${t}: ids start with a letter and use up to 32 letters, numbers, and hyphens`);let{filters:e,all:i}=ap(t,n);o[t]={filters:e,all:i}}a=e},close:()=>{w=!0,C?.close(),C=null}}}function Rm(e,t={}){return Lm(e,t,null)}const zm=(e,t)=>e<t?-1:+(e>t);function Bm(e,t=[]){let n=Object.keys(e).sort(zm).map(t=>[t,e[t].tail]);return t.length>0&&n.push([`sync`,[...t].sort((e,t)=>zm(e.key,t.key)).map(e=>[e.key,e.platform])]),JSON.stringify(n)}const Vm=/^[A-Za-z][A-Za-z0-9-]{0,31}$/,Hm=[{method:`GET`,path:``},{method:`GET`,path:`/me`},{method:`GET`,path:`/channels`},{method:`POST`,path:`/channels`},{method:`GET`,path:`/actors`},{method:`GET`,path:`/messages`},{method:`GET`,path:`/messages/:id`},{method:`GET`,path:`/messages/:id/synced`},{method:`GET`,path:`/changes`},{method:`GET`,path:`/threads`},{method:`POST`,path:`/threads`},{method:`GET`,path:`/threads/:thread/messages`},{method:`POST`,path:`/threads/:thread/messages`},{method:`PATCH`,path:`/threads/:thread/messages/:n`},{method:`POST`,path:`/threads/:thread/messages/:n/delete`},{method:`GET`,path:`/threads/:thread/messages/:n/reactions`},{method:`POST`,path:`/threads/:thread/messages/:n/reactions`},{method:`POST`,path:`/threads/:thread/messages/:n/labels`},{method:`GET`,path:`/posts/:id`},{method:`POST`,path:`/attachments`},{method:`GET`,path:`/attachments/:id`},{method:`POST`,path:`/attachments/:id/complete`},{method:`GET`,path:`/schedules`},{method:`POST`,path:`/schedules`},{method:`POST`,path:`/schedules/:id/cancel`},{method:`GET`,path:`/sync/linked`}];function Um(e){return e?{"x-board-profile":e.name,...e.avatar?.startsWith(`https://`)?{"x-board-avatar":e.avatar}:{}}:{}}const Wm=/^[A-Za-z0-9_.:-]{1,128}$/,Gm=/^msg_([0-9a-f-]{36})_([1-9]\d*)$/,Km=/^([0-9a-z]+)(?:\.([0-9a-z]+))?$/,qm=/^c1\./,Jm=/* @__PURE__ */ new Set([`board_only`,`duplicate_sync_key`,`event_too_large`,`foreign_author`,`invalid_find`,`invalid_import`,`invalid_inbox_event`,`invalid_receipt`,`message_not_owned`,`mutation_too_large`,`operation_conflict`,`operation_expired_or_unknown`,`sync_key_not_owned`,`sync_needs_project`,`too_many_targets`]),Ym={400:`invalid_request`,403:`forbidden`,404:`not_found`,409:`conflict`,413:`too_large`},Xm=({id:e,name:t,type:n,size:r})=>({id:e,name:t,type:n,size:r}),Zm=e=>new q(501,`not_supported`,`Vercel's boards don't support ${e} yet`),Qm={"*":[`read`,`post`,`react`,`label`]};function $m(e){if(typeof e!=`object`||!e||Array.isArray(e))return Qm;let t=new Set(xp),n={};for(let[r,i]of Object.entries(e))if(Array.isArray(i)){try{Ep(r)}catch{continue}n[r]=i.filter(e=>t.has(e))}return Hp(n).summary()}function eh(e){return typeof e==`number`&&Number.isFinite(e)?new Date(e<0xe8d4a51000?e*1e3:e).toISOString():typeof e==`string`&&!Number.isNaN(Date.parse(e))?new Date(e).toISOString():null}const th=()=>new q(404,`not_found`,`this board uses Vercel's, and answers only wake-ups and webhooks`),nh=e=>e===`app`?`workflow`:e;function rh(e,t){let n=t!==null&&/^\d+$/.test(t)&&Number(t)>0?Number(t)*1e3:1/0;return Math.min(n,1e3*2**e*(1+Math.random()))}const ih=(e,t)=>e<=0||t?.aborted?Promise.resolve():new Promise(n=>{let r=setTimeout(n,e);t?.addEventListener(`abort`,()=>(clearTimeout(r),n()),{once:!0})});function ah(){let e=crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16)),t=BigInt(Date.now());for(let n=0;n<6;n++)e[n]=Number(t>>BigInt(8*(5-n))&255n);e[6]=e[6]&15|112,e[8]=e[8]&63|128;let n=Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``);return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}const oh=e=>new Date(e).toISOString(),sh=e=>({...e,at:eh(e.at)}),ch=e=>({id:e.id,name:e.name,version:e.version,description:e.description??null,schema:e.schema,builtIn:e.builtIn,by:e.createdBy?.id??null,at:e.builtIn?null:oh(e.createdAt)}),lh=(e,t)=>`msg_${e.slice(4)}_${t}`;function uh(e){let t=Gm.exec(e);return t?{threadId:`thr_${t[1]}`,sequence:Number(t[2])}:null}function dh(e){return e.type===`external`?e.id:e.type===`user`?`vercel:user:${e.userId}`:e.type===`app`?`vercel:app:${e.clientId}`:`vercel:project:${e.projectId}:${e.environment}`}function fh(e){let t=ot(e).principal,n=/^vercel:project:([^:]+):([^:]+)$/.exec(t);return n?{type:`project`,projectId:n[1],environment:n[2]}:t.startsWith(`vercel:user:`)?{type:`user`,userId:t.slice(12)}:t.startsWith(`vercel:app:`)?{type:`app`,clientId:t.slice(11)}:null}function ph(e,t,n){let r=t?.via?.name??null;if(e.type===`project`)return{name:n??r??e.projectId,environment:t?.via?.environment??e.environment};if(e.type===`external`)return{name:r??e.id,environment:null};let i=t?.handle.indexOf(`/`)??-1,a=e.type===`user`&&i>0?t.handle.slice(0,i):null;return{name:r??a??yh(e),environment:null}}const mh=(e,t,n,r,i)=>e.includes(`/`)?rt(e.slice(0,e.indexOf(`/`)),e.slice(e.indexOf(`/`)+1)):at(ph(t,n,i).name,e,r);function hh(e,t){let n=e.environment===`production`;if(t===void 0){let t=n?e.projectId:`${e.projectId}@${e.environment}`;return{handle:t,name:t}}return{handle:t,name:n?t:`${t} (${e.environment})`}}function gh(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map;for(let[i,a]of e){let e=fh(i);if(e?.type!==`project`)continue;let{profile:o}=ot(i);if(o!==null&&a.via?.name&&r.set(e.projectId,a.via.name),a.handle.startsWith(`project:`))continue;let s=a.handle.indexOf(`/`);o===null?t.set(e.projectId,a.handle):s>0&&$e(o)===null&&n.set(e.projectId,a.handle.slice(0,s))}return new Map([...r,...n,...t])}function _h(e,t,n){let r=fh(e);if(r?.type!==`project`)return t.handle;let i=n.get(r.projectId),{profile:a}=ot(e);if(a===null)return hh(r,i).handle;let o=$e(a);return o?mh(t.handle,r,t,o.user,i):t.handle}const vh=(e,t,n)=>[...e].filter(([e,r])=>r.handle.toLowerCase()===n||_h(e,r,t).toLowerCase()===n).map(([e])=>e),yh=e=>e.type===`user`?`user-${e.userId.slice(0,6).toLowerCase()}`:`app-${e.clientId.slice(0,6).toLowerCase()}`,bh=e=>({actor:e.id,principal:dh(e.principal),profile:e.profile?.name??null}),xh={actor:`board:schedule`,principal:`board:schedule`,profile:null};function Sh(e,t,n){let{principal:r,profile:i}=e;if(r.type===`external`)return{id:e.id,kind:`external`,handle:r.id.slice(r.id.lastIndexOf(`:`)+1),name:r.id,avatar:null,verified:!0};if(i?.platform){let{userId:a,platform:o,key:s}=i.platform,c=mh(t?.handle??``,r,t,a,n);return{id:e.id,kind:`external`,handle:c,name:i.name,avatar:null,via:ph(r,t,n),platform:t?.platform??o??s,verified:!0}}if(i)return{id:e.id,kind:`agent`,handle:i.name,name:i.name,avatar:i.avatar??null,via:ph(r,t,n),verified:!0};if(r.type===`project`)return{id:e.id,kind:`deployment`,...hh(r,n),avatar:null,verified:!0};let a=yh(r);return{id:e.id,kind:r.type===`user`?`person`:`workflow`,handle:a,name:a,avatar:null,verified:!0}}function Ch(e,t={}){let n={...e};for(let[e,{from:r}]of Object.entries(t))r===void 0?delete n[e]:n[e]=r;return n}const wh=e=>e?{...e.channel===void 0?{}:{channel:e.channel},thread:e.thread,subthread:e.subthread??null,message:e.message,context:e.context??null}:null;function Th(e,t){let n=(e.api??`https://api.vercel.com`).replace(/\/+$/,``);if(!/^https:\/\/[^/]+$|^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(n))throw Error(`vercel: ${n} isn't Vercel's API: pass an https origin`);if(!e.fetch&&!t)throw Error(`vercel: pass a fetch that sends credentials: outside Node there's no environment to find them in`);let r=e.fetch??t.fetch(),i=e.files??fetch,a=null,o=/* @__PURE__ */ new Set,s=()=>e.board?null:a?.name??null,c=null,l=()=>{let n=a?.team??e.team;return c??=n?Promise.resolve(n):t?.team()??Promise.resolve(null)};async function u(e,t,i,a={}){let o=new URL(`${n}/v1/messageboard${i}`),s=await l();s&&o.searchParams.set(s.startsWith(`team_`)?`teamId`:`slug`,s);for(let[e,t]of Object.entries(a.query??{}))if(t!==void 0){if(typeof t==`string`)o.searchParams.set(e,t);else for(let n of t)o.searchParams.append(e,n)}let c={"content-type":`application/json`,...Um(e.profile),...e.can===void 0?{}:{"x-board-can":e.can}},u=t!==`POST`&&t!==`PATCH`||typeof a.body?.operationId==`string`;for(let e=0;;e++){let n;try{n=await r(o,{method:t,headers:c,redirect:`error`,...a.body===void 0?{}:{body:JSON.stringify(a.body)},...a.signal?{signal:a.signal}:{}})}catch(e){throw e instanceof q||e instanceof Error&&e.name===`AbortError`?e:new q(502,`unreachable`,`Vercel's API didn't answer: ${e instanceof Error?e.message:String(e)}`)}let i=await n.text(),s;try{s=i?JSON.parse(i):void 0}catch{}if(n.ok)return s;if(e<4&&!a.signal?.aborted&&(n.status===429||n.status===503&&u)){await ih(rh(e,n.headers.get(`retry-after`)),a.signal),a.signal?.throwIfAborted();continue}let l=s?.error;throw new q(n.status,l?.code??`remote_error`,l?.message??`Vercel's API answered ${n.status}`)}}async function d(...e){try{return await u(...e).catch(async t=>{if(!(t instanceof q&&t.code===`sync_key_not_owned`&&(a?.sync.length??0)>0))throw t;return await vt.registerNow(!0),u(...e)})}catch(e){throw e instanceof q&&Jm.has(e.code)?new q(e.status,Ym[e.status]??e.code,e.message):e}}async function f(e,t,n,r={},i){let a=[],o;do{let s=await u(e,`GET`,t,{query:{...r,cursor:o},...i?{signal:i}:{}});a.push(...s[n]),o=s.cursor??void 0}while(o);return a}async function p(e,t){if(!/^[^/]{1,64}$/.test(t))throw new q(400,`invalid_board_name`,`${JSON.stringify(t)} isn't a board's name: one is 1 to 64 characters with no /.`,{origin:`handle`});let{boards:n}=await u(e,`GET`,`/boards`,{query:{name:t}});if(n[0])return n[0].id;let{principal:r}=(await Ee(e)).actor;if(a?.ensure===!1)throw new q(404,`no_board`,`no board named ${t} on this team, or none you can see.`,{hint:`Check the name, or make it: leave out ensure: false`,origin:`handle`});try{let{board:n}=await u(e,`POST`,`/boards/ensure`,{body:{name:t,operationId:ah()}});return n.id}catch(e){throw e instanceof q&&e.code===`board_not_granted`?m(t,r):e instanceof q&&e.code===`board_name_taken`?new q(409,`board_name_taken`,`the board name ${t} is taken.`,{hint:`Pick another name, or ask whoever can see it for access.`,origin:`handle`}):e}}let m=(e,t)=>{let n=e===null?`the team's board`:`board ${e}`;if(t.type!==`project`)return new q(403,`board_not_granted`,`this project has no access to ${n}.`,{hint:`Someone who manages the board can grant it.`,origin:`handle`});let r=`vb grants create --project ${t.projectId} --environment ${t.environment}${e===null?``:` --name ${e}`} --can '*=read,post,react,label'`;return new q(403,`board_not_granted`,`this project has no access to ${n} (${t.projectId}, ${t.environment}).`,{hint:`Grant it: ${r}`,origin:`handle`})},h=null,g=t=>(h??=e.board?Promise.resolve(e.board):s()?p(t,s()):u(t,`GET`,`/boards`).then(async({defaultBoardId:e})=>{if(e)return e;let{principal:n}=(await Ee(t)).actor;if(n.type===`project`)throw m(null,n);let{board:r}=await u(t,`POST`,`/boards/default`,{body:{operationId:ah()}});return r.id})).catch(e=>{throw h=null,e}),_=async(e,t=``)=>`/boards/${encodeURIComponent(await g(e))}${t}`,v=null,y=async(e,t=!1)=>(t&&(v=null),v??=_(e,`/channels`).then(t=>f(e,t,`channels`)),v.catch(e=>{throw v=null,e})),b=/* @__PURE__ */ new Map;async function x(e,t){let n=b.get(t);if(n)return n;let{channels:[r]}=await u(e,`GET`,await _(e,`/channels`),{query:{name:t}});return r&&b.set(t,r),r??null}let S=/* @__PURE__ */ new Map;async function C(e,t){let n=(await y(e)).find(e=>e.id===t)??(await y(e,!0)).find(e=>e.id===t);if(!n)throw new q(502,`remote_error`,`Vercel's API names a channel it doesn't list: ${t}`);return n}async function w(e,t){let n=await x(e,t);if(n)return{channel:n,created:!1};try{let{channel:n}=await u(e,`POST`,await _(e,`/channels`),{body:{operationId:ah(),name:t}});return v=null,b.set(t,n),{channel:n,created:!0}}catch(n){if(n instanceof q&&n.code===`channel_name_taken`){let n=await x(e,t);if(n)return{channel:n,created:!1}}throw n}}let T=async(e,t)=>(await w(e,t)).channel;async function E(e,t){if(t!==void 0&&!t.endsWith(`/`)){let n=await x(e,t);return n?[n]:[]}let n=await y(e,!0);if(t===void 0)return n;let r=t.slice(0,-1);return n.filter(e=>e.name===r||e.name.startsWith(t))}async function D(e,t,n){if(!uh(t))throw Mf(`message not found: ${t}`,`message_not_found`);try{return await u(e,`GET`,await _(e,`/messages/${encodeURIComponent(t)}`),n?{signal:n}:{})}catch(e){throw e instanceof q&&e.code===`thread_not_found`?Mf(`message not found: ${t}`,`message_not_found`):e}}async function O(e,t,n){let r=await D(e,t,n);return{...r,channel:await C(e,r.thread.channelId)}}function k(e,t){let n=/* @__PURE__ */ new Map;return r=>{let i=n.get(r);return i||n.set(r,i=D(e,lh(r,1),t).then(({thread:e,message:t})=>A(e,t))),i}}let A=(e,t)=>{if(t?.deletedAt===void 0)return e;let{labels:n,...r}=e;return r},j=e=>e.deletedAt===void 0?{...e.labels}:{},M=async(e,t,n)=>f(e,await _(e,`/threads/${encodeURIComponent(t)}/messages`),`messages`,{},n);async function N(e,t){if(!t.reactions||Object.keys(t.reactions).length===0)return{};let n=t.reactors??{};if(Object.entries(t.reactions).every(([e,t])=>(n[e]?.length??0)>=t))return Object.fromEntries(Object.entries(n).map(([e,t])=>[e,[...t]]));let r=await _(e,`/threads/${encodeURIComponent(t.threadId)}/messages/${t.sequence}/reactions`),i={};for(let t of await f(e,r,`reactions`))(i[t.emoji]??=[]).push(t.actor.id);return i}let P=null,F=3e5,I=/* @__PURE__ */ new Set,L=e=>{let t=(async()=>new Map((await f(e,await _(e,`/actors`),`actors`)).map(e=>[e.id,e])))(),n={at:Date.now(),views:t};return P=n,t.catch(()=>{P===n&&(P=null)}),n},R=(e,t)=>e.views.then(e=>e.get(t),()=>void 0);async function ee(e,t){let n=!P||Date.now()-P.at>F?L(e):P,r=await R(n,t.id);if(!r&&!I.has(t.id)){let i=P&&P!==n?P:L(e);r=await R(i,t.id),!r&&await i.views.then(()=>!0,()=>!1)&&I.add(t.id)}let i=r&&nh(r.kind),a=t.principal.type===`project`?await ae(e,t.principal.projectId):void 0;if(!r||!(i===`person`||i===`external`||i===`agent`&&t.principal.type===`user`))return Sh(t,r,a);let o=t.profile&&t.principal.type!==`external`?{via:ph(t.principal,r,a)}:{},s=r.platform??t.profile?.platform?.platform,c=t.profile?.platform,l=c&&t.principal.type!==`external`?mh(r.handle,t.principal,r,c.userId,a):r.handle;return{id:t.id,kind:i,handle:l,name:r.name??r.handle,avatar:r.avatar??null,...o,...s?{platform:s}:{},verified:!0}}let te=/* @__PURE__ */ new WeakMap;function ne(e){let t=te.get(e);return t||te.set(e,t=e.views.then(gh,()=>/* @__PURE__ */ new Map)),t}let re=/* @__PURE__ */ new Set;async function ie(e,t){let n=P&&Date.now()-P.at<=F?P:null,r=await ne(n??L(e));return!t||t.found(r)||!n||re.has(t.key)?r:(r=await ne(P&&P!==n?P:L(e)),t.found(r)||(re.size>=1e3&&re.clear(),re.add(t.key)),r)}let ae=async(e,t)=>(await ie(e,{key:t,found:e=>e.has(t)})).get(t),oe=async(e,t)=>await ae(e,t)??t,se=async e=>{let{principal:t}=(await Ee(e)).actor;return t.type===`project`?t.projectId:null},ce=e=>e.principal.type===`project`?e.principal.projectId:null;async function le(e,t,n){if(t===void 0)return null;let r=ce(n);return r===null||r===await se(e)?t:`${await oe(e,r)}/${t}`}async function ue(e,t,n){let r=t.sequence===1;return{id:t.id,channel:n,text:t.text,re:r?null:lh(t.threadId,1),replyTo:t.replyTo!==void 0&&t.replyTo!==1?lh(t.threadId,t.replyTo):null,thread:t.threadId,labels:j(t),reactions:t.deletedAt===void 0?await N(e,t):{},by:bh(t.createdBy),noSync:t.noSync??!1,origin:wh(t.origin),from:await le(e,t.from,t.createdBy),createdAt:oh(t.createdAt),editedAt:t.editedAt===void 0?null:oh(t.editedAt),deleted:t.deletedAt!==void 0,undelivered:{},attachments:t.attachments??[],links:(t.links??[]).map(e=>({url:e.url,message:e.message??null,snapshot:e.snapshot??null,unavailable:e.unavailable??null})),version:t.version,revision:t.revision,author:await ee(e,t.createdBy),...t.schedule?{schedule:{id:t.schedule.id,n:t.schedule.n}}:{},blocks:(t.from??null)===null&&t.deletedAt===void 0?Qe(t.text):[]}}async function de(e,t,n){let{actor:r}=await Ee(e),i={id:await De(e),principal:r.principal,...e.profile?{profile:e.profile}:{}},a=(await Promise.all((n.attachments??[]).map(async t=>u(e,`GET`,await _(e,`/attachments/${encodeURIComponent(t)}`)).then(({attachment:e})=>Xm(e),()=>null)))).filter(e=>e!==null);return{...t,text:n.text,version:1,revision:1,createdAt:Date.now(),createdBy:i,...n.labels&&Object.keys(n.labels).length?{labels:{...n.labels}}:{},...n.noSync?{noSync:!0}:{},...a.length?{attachments:a}:{}}}async function z(e,t){let{canceled:n}=t;return{id:t.id,channel:(await C(e,t.channelId)).name,re:t.threadId===void 0?null:lh(t.threadId,1),text:t.text,labels:{...t.labels},noSync:t.noSync??!1,attachments:[],first:oh(t.firstAt),every:t.every??null,until:t.until===void 0?null:oh(t.until),times:t.times??null,sent:t.sent,next:t.nextAt===null?null:oh(t.nextAt),last:t.lastMessageId??null,state:t.state,canceled:n?{by:n.by?bh(n.by):xh,reason:n.reason===`disabled`?`revoked`:n.reason}:null,by:bh(t.createdBy),author:await ee(e,t.createdBy),createdAt:oh(t.createdAt)}}let B=/* @__PURE__ */ new Map;function fe(e){let t=`${e.t.toString(36)}.${Math.floor(Math.random()*36**8).toString(36)}`;return B.set(t,e),B.size>1e4&&B.delete(B.keys().next().value),t}function pe(e){let t=B.get(e);if(t)return t;let n=Km.exec(e);if(!n)throw new q(400,`invalid_cursor`,`after: ${e} isn't a cursor here or a message's ID`);return{t:parseInt(n[1],36),feeds:{}}}async function me(e,t){return uh(t)?(await D(e,t)).message.createdAt:pe(t).t}async function he(e,t){let n=await _(e,`/changes`),r=await Promise.all(t.map(t=>u(e,`GET`,n,{query:{channelId:t.id,from:`latest`}})));return Object.fromEntries(t.map((e,t)=>[e.id,{at:r[t].cursor,skip:0}]))}let ge=/* @__PURE__ */ new Map;async function _e(e,t){if(t===void 0)return;if(t===`me`){let t=await De(e);return e=>e.id===t}let n=/* @__PURE__ */ new Set([t]);if(!t.startsWith(`vercel:`)){let r=t.toLowerCase(),i=async e=>vh(await e.views,await ne(e),r),a=P&&Date.now()-P.at<=F?P:null,o=await i(a??L(e)),s=ge.get(r);o.length===0&&a&&!(s!==void 0&&Date.now()-s<=F)&&(o=await i(L(e))),o.length===0&&(ge.size>=1e3&&ge.clear(),(!a||s===void 0||Date.now()-s>F)&&ge.set(r,Date.now()));for(let e of o)n.add(e)}return e=>n.has(e.id)||n.has(dh(e.principal))||e.profile!==void 0&&!e.profile.platform&&n.has(e.profile.name)}async function ve(e,t){if(t===void 0)return;if(t===`board`)return e=>e.from===void 0;let n=t.indexOf(`/`);if(n===-1){let n=await se(e);return e=>e.from===t&&[null,n].includes(ce(e.createdBy))}let[r,i]=[t.slice(0,n),t.slice(n+1)];return async t=>{let n=ce(t.createdBy);return t.from===i&&n!==null&&(n===r||await ae(e,n)===r)}}let ye=async(e,t)=>({by:await _e(e,t.by),source:await ve(e,t.from)});async function be(e,t,n,r){if(e.re!==void 0&&e.re!==t.id&&e.re!==lh(n.id,1)||r.by&&!r.by(t.createdBy)||e.mentions!==void 0||e.from!==void 0&&!await r.source?.(t)||e.text!==void 0&&!t.text.toLowerCase().includes(e.text.toLowerCase()))return!1;for(let[r,i]of e.label??[]){let e=e=>e!==void 0&&Object.hasOwn(e,r)&&(i===null||i.includes(e[r]));if(!e(j(t))&&!e(n.labels))return!1}return!0}function xe(e){let t=e.label?.find(([,e])=>e===null||e.length===1);return t&&(t[1]===null?t[0]:`${t[0]}=${t[1][0]}`)}async function Se(e,t,n,r){let i=xe(n);return f(e,await _(e,`/threads`),`threads`,{channelId:t.id,label:i},r)}async function Ce(e,t,n,r,i){let a=await _(e,`/threads`),o=[],s;do{let c=await u(e,`GET`,a,{query:{channelId:t.id,label:n,cursor:s},signal:i});o.push(...c.threads),s=c.cursor??void 0;let l=o.at(-1);if(n===void 0&&(r.after===void 0?r.limit!==void 0&&o.length>=r.limit:l!==void 0&&l.lastActivityAt<=r.after))break}while(s);return o}async function we(e,t,n,r){let[i,a]=await Promise.all([D(e,lh(t.id,1),r),t.lastMessage&&t.lastMessage.sequence>1?D(e,t.lastMessage.id,r):null]);return{message:await ue(e,i.message,n.name),replies:t.messageCount-1,last:a&&await ue(e,a.message,n.name)}}let Te=null,Ee=e=>(Te??=u(e,`GET`,`/me`)).catch(e=>{throw Te=null,e}),De=async e=>`${dh((await Ee(e)).actor.principal)}${e.profile?`+${e.profile.name.toLowerCase()}`:``}`;function Oe(e,t){if(`self`in e&&e.can!==void 0)throw new q(403,`forbidden`,`this handle is narrowed with a can, so it can't ${t}: that's its project's sync's job`)}function V(e){if(`identity`in e)throw th();let n=e=>{if(e===null)return null;let t=typeof e==`string`?e:e.name;if(!Vm.test(t))throw new q(400,`invalid_request`,`as: ${t}: profiles start with a letter and use up to 32 letters, numbers, and hyphens`);return typeof e==`string`||!e.avatar?{name:t}:{name:t,avatar:e.avatar}};if(e.origin.via?.kind===`client`){let r=`profile`in e?e.profile:e.self??void 0;return{profile:n(r===void 0?t?.profile()??null:r),...e.can===void 0?{}:{can:e.can}}}return{profile:n(e.self??`client`)}}let ke=async e=>Wm.test(e)?e:`h.${(await wf(e)).slice(0,64)}`;async function je(e,t,n){let r,i;if(t.re!==void 0){let a=await O(e,t.re,n).catch(e=>{if(e instanceof q&&e.status===404)return null;throw e});if(!a)return{messages:[],feeds:{},newest:0};let{channel:o}=a;if(t.channel!==void 0&&!(await E(e,t.channel)).some(e=>e.id===o.id))return{messages:[],feeds:{},newest:0};r=[o],i=[{thread:a.thread,channel:o}]}else r=await E(e,t.channel),i=(await Promise.all(r.map(async r=>(await Se(e,r,t,n)).map(e=>({thread:e,channel:r}))))).flat();let a=await he(e,r),o=await ye(e,t),s=0,c=[];for(let{thread:r,channel:a}of i){let i=await M(e,r.id,n),l=A(r,i.find(e=>e.sequence===1));for(let e of i)s=Math.max(s,e.createdAt),await be(t,e,l,o)&&c.push({message:e,thread:r,channel:a})}return c.sort(Me),{messages:c,feeds:a,newest:s}}let Me=(e,t)=>e.message.createdAt-t.message.createdAt||e.message.threadId.localeCompare(t.message.threadId)||e.message.sequence-t.message.sequence;async function Ne(e,t,n,r){let i=await _(e,`/messages`),a=Math.min(n,100),o=await Promise.all(t.map(async t=>({channel:t,...await u(e,`GET`,i,{query:{channelId:t.id,limit:String(a)},signal:r})}))),s=o.filter(e=>e.messages.length===a),c=Math.max(-1/0,...s.map(e=>Math.min(...e.messages.map(e=>e.createdAt))));return{messages:o.flatMap(({channel:e,messages:t})=>t.map(t=>({message:t,channel:e}))).filter(({message:e})=>e.createdAt>=c).sort(Me).slice(-n),feeds:Object.fromEntries(o.map(e=>[e.channel.id,{at:e.cursor,skip:0}])),newest:Math.max(0,...o.flatMap(e=>e.messages.map(e=>e.createdAt)))}}async function Pe(e,t,n,r,i,a,o,s=k(e)){if(!t.messageId||!t.type.startsWith(`message.`))return null;let c=o??await D(e,t.messageId).catch(e=>{if(e instanceof q&&e.status===404)return null;throw e});if(c&&!o&&i.label?.length&&(c={...c,thread:c.message.sequence===1?A(c.thread,c.message):await s(c.thread.id)}),!c||!await be(i,c.message,c.thread,a))return null;let l=await ue(e,c.message,n),u=bh(t.actor),d=await le(e,t.from,t.actor),f={id:l.id,thread:l.thread},p,m;switch(t.type){case`message.posted`:p=`message.posted`,m={channel:n,text:l.text,re:l.re,replyTo:l.replyTo,thread:l.thread,labels:l.labels,noSync:l.noSync,by:u,origin:l.origin,from:l.from,attachments:l.attachments,links:l.links};break;case`message.edited`:p=`message.edited`,m={...f,text:l.text,by:u,from:d};break;case`message.deleted`:p=`message.deleted`,m={...f,by:u,from:d};break;case`message.reaction_added`:case`message.reaction_removed`:p=t.type===`message.reaction_added`?`reaction.added`:`reaction.removed`,m={...f,emoji:t.emoji,by:u,from:d};break;case`message.labeled`:{let e=Object.entries(t.labels??{});p=`labels.changed`,m={...f,set:Object.fromEntries(e.flatMap(([e,{to:t}])=>t===void 0?[]:[[e,t]])),unset:e.flatMap(([e,{to:t}])=>t===void 0?[e]:[]),by:u};break}default:return null}return Le(e,t,r,p,m,l)}let Le=async(e,t,n,r,i,a)=>({cursor:n,type:r,createdAt:oh(t.createdAt),payload:i,message:a,actor:await ee(e,t.actor)});async function Re(e,t,n,r,i){let a=await _(e,`/changes`),o=await Promise.all(t.map(async t=>{let r=n.feeds[t.id],o=await u(e,`GET`,a,{query:{channelId:t.id,...r?.at?{cursor:r.at}:{}},signal:i}),s=r?.skip??0,c=o.events.map((e,t)=>({change:e,i:t})).slice(s).filter(({change:e})=>r||e.createdAt>n.t);return{channel:t,at:r?.at??null,next:o.cursor,events:c}})),s=await ye(e,r),c=k(e,i),l={...n.feeds},d=o.flatMap(e=>e.events.map(t=>({...t,page:e}))).sort((e,t)=>e.change.createdAt-t.change.createdAt),f=[];for(let{change:t,i:n,page:i}of d){l[i.channel.id]={at:i.at,skip:n+1};let a=await Pe(e,t,i.channel.name,fe({t:t.createdAt,feeds:{...l}}),r,s,void 0,c);a&&f.push(a)}let p={...n.feeds};for(let e of o)p[e.channel.id]={at:e.next,skip:0};return{events:f,position:{t:Math.max(n.t,...d.map(({change:e})=>e.createdAt)),feeds:p}}}async function ze(e,t,n,r,i){let a=Math.min(25,Math.ceil((r-Date.now())/1e3));if(a<=0)return!1;if(t.length===0)return await ih(r-Date.now(),i),!1;let o=new AbortController,s=AbortSignal.any([i,o.signal]),c=await _(e,`/changes`);try{return await new Promise((r,l)=>{let d=t.length;for(let f of t){let t=n.feeds[f.id]?.at;u(e,`GET`,c,{query:{channelId:f.id,...t?{cursor:t}:{from:`latest`},wait:String(a)},signal:s}).then(e=>{e.events.length>0?r(!0):--d===0&&r(!1)}).catch(e=>o.signal.aborted&&!i.aborted?void 0:l(e))}})}finally{o.abort()}}let Ve=e=>e.by!==void 0||e.mentions!==void 0||e.text!==void 0||e.from!==void 0||(e.label?.length??0)>0;async function He(e,t,n,r){let i=await _(e,`/messages`),a=n.limit??50,o=k(e,r),s=Ve(n),c=s?await ye(e,n):{},l=async e=>!s||await be(n,e,n.label?.length?await o(e.threadId):{id:e.threadId},c),d=[];if(n.after===void 0){let n=await u(e,`GET`,i,{query:{channelId:t.id,limit:String(s?100:Math.min(a,100))},signal:r});for(let e of n.messages)await l(e)&&d.push(e);return{messages:d.slice(-a),cursor:n.cursor}}let f=n.after;for(let n=0;n<10&&d.length<a;n++){let n=await u(e,`GET`,i,{query:{channelId:t.id,after:f,limit:String(Math.min(a-d.length,100))},signal:r});f=n.cursor;for(let e of n.messages)await l(e)&&d.push(e);if(n.messages.length===0)break}return{messages:d,cursor:f}}async function Ue(e,t,n,r){let i=await _(e,`/changes`),a=k(e,r),o=await ye(e,n),s=Date.now()+(n.wait??0)*1e3,c=n.after;for(;;){let l=Math.min(25,Math.max(0,Math.ceil((s-Date.now())/1e3))),d=await u(e,`GET`,i,{query:{channelId:t.id,include:`message`,...c===void 0?{from:`latest`}:{cursor:c},...l>0?{wait:String(l)}:{}},signal:r});c=d.cursor;let f=[];for(let r of d.events){let i=r.currentMessage,s=i&&r.threadId?{message:i,thread:n.label?.length?await a(r.threadId):{id:r.threadId}}:null;if(!s)continue;let c=await Pe(e,r,t.name,r.cursor??d.cursor,n,o,s);c&&f.push(c)}if(f.length>0||Date.now()>=s||r.aborted)return{events:f,cursor:c}}}async function We(e,t,n){let r=await Ge(e,t);if(r)return Ue(e,r,t,n);if(t.after!==void 0&&qm.test(t.after))throw new q(400,`invalid_request`,`after: ${t.after} is one channel's cursor: read that channel`);let i=await E(e,t.channel),a=t.after===void 0?{t:Date.now(),feeds:await he(e,i)}:uh(t.after)?{t:await me(e,t.after),feeds:{}}:pe(t.after),o=Date.now()+(t.wait??0)*1e3,s=!1;for(;;){let r=Date.now(),c=await Re(e,i,a,t,n);if(a=c.position,c.events.length>0||Date.now()>=o||n.aborted)return{events:c.events,cursor:fe(a)};s||=await ze(e,i,a,o,n)&&Date.now()-r<1e3,await ih(Math.min(r+1e3,o)-Date.now(),n)}}async function Ge(e,t){if(t.channel===void 0||t.channel.endsWith(`/`)||t.re!==void 0||t.after!==void 0&&!qm.test(t.after))return null;let[n]=await E(e,t.channel);return n??null}let Ke=async(e,t)=>(await wf(Bm(e,t))).slice(0,32);async function qe(e,t){if(t===`me`)return[await De(e)];if(t.startsWith(`vercel:`))return[t];let n=await f(e,await _(e,`/actors`),`actors`),r=n.map(e=>[e.id,e]),i=new Set(vh(r,gh(r),t.toLowerCase())),a=n.filter(e=>i.has(e.id)||!t.includes(`:`)&&e.id.endsWith(`+${t.toLowerCase()}`)).map(e=>e.id);if(a.length===0)throw new q(400,`bad_watcher`,`--by ${t}: nobody here goes by that yet: name them by their actor ID`);return a}function Je(e,t,n){let r=t=>new q(400,`bad_watcher`,`watch ${e}: ${t}`);if(!Ru.safeParse(e).success)throw r(`ids start with a letter and use up to 32 letters, numbers, and hyphens`);let i;try{i=ap(e,t)}catch(e){throw new q(400,`bad_watcher`,e.message)}if(i.filters.mentions!==void 0)throw r(`Vercel's boards can't match mentions yet`);if(i.filters.from!==void 0&&!n)throw r(`Vercel's API can't match --source: put the watcher in the board's config, which filters its matches itself`);return i}async function Ye(e,t,n,r){let{filters:i}=Je(t,n,r),a={};if(i.channel!==void 0){if(i.channel.endsWith(`/`))a.channelTree=i.channel.slice(0,-1);else{let t=await x(e,i.channel);t?a.channelIds=[t.id]:a.channelTree=i.channel}}if(i.re!==void 0){let e=uh(i.re);if(!e)throw new q(400,`bad_watcher`,`watch ${t}: --re ${i.re} names no message here`);a.threadId=e.threadId}return i.by!==void 0&&(a.authors=await qe(e,i.by)),i.text!==void 0&&(a.text=i.text),i.label?.length&&(a.labels=i.label.map(([e,t])=>t===null?{key:e}:{key:e,values:[...t]})),{filter:a}}async function Xe(e,{filter:t}){let n=[];t.channelIds?.[0]?n.push((await C(e,t.channelIds[0])).name):t.channelTree!==void 0&&n.push(`${t.channelTree}/`),t.threadId!==void 0&&n.push(`--re ${lh(t.threadId,1)}`),t.authors?.[0]&&n.push(`--by ${t.authors[0]}`),t.text!==void 0&&n.push(`--text ${JSON.stringify(t.text)}`);for(let{key:e,values:r}of t.labels??[])n.push(`--label ${r?`${e}=${r.join(`|`)}`:e}`);return n.join(` `)}let Ze=e=>(e.sync??[]).map(({key:e,platform:t})=>({key:e,platform:t})),et=e=>e.path?{url:null,path:e.path,...e.branch?{branch:e.branch}:{}}:{url:null},tt=()=>new q(403,`watchers_need_project`,`Vercel's API takes watchers only from a deployment's own credentials.`,{hint:`Register them from the project's deployment. Watchers in board()'s config run in this process instead.`,origin:`handle`}),nt=e=>e instanceof q&&e.code===`watchers_need_project`?tt():e;async function rt(...e){try{return await u(...e)}catch(e){throw nt(e)}}async function it(e,t,n,r,i,a=async()=>{}){let o=Object.fromEntries(Object.entries(n).map(([e,t])=>[e,{tail:t.tail}])),s=Object.fromEntries(await Promise.all(Object.entries(o).map(async([t,n])=>[t,await Ye(e,t,n,i)]))),c=r.map(({key:e,platform:t})=>({key:e,platform:t})),l;try{l=await d(e,`PUT`,await _(e,`/watchers`),{body:{...t,watch:s,tag:await Ke(o,c),...c.length?{sync:c}:{}}})}catch(e){throw nt(e)}return await a(l),{owner:l.owner,...et(l),watch:o,sync:Ze(l),hash:l.hash}}let at=null,st=/* @__PURE__ */ new Map;async function ct(e){at=new Set((e.sync??[]).map(e=>e.key));let t=fh(e.owner);for(let{key:n,owner:r,environment:i}of e.elsewhere??[]){let e=fh(r),a=r;if(e?.type===`project`){let n=i??e.environment;a=t?.type===`project`&&t.projectId===e.projectId?n:`${await oe(ht,e.projectId)} (${n})`}st.get(n)!==a&&console.info(`[board] ${n} is synced by ${a}`),st.set(n,a)}}async function lt(e){return!a?.sync.some(t=>t.key===e)||(at===null&&await bt().catch(()=>!1)&&await vt.start(),at===null||at.has(e))}let ut=e=>Mf(`${e} is synced by ${st.get(e)??`another deployment of this project`}, not this deployment`,`not_synced_here`);async function dt(e,t,n){if(!await lt(e))return t();try{return await n()}catch(n){if(n instanceof q&&n.status===403&&!await lt(e))return t();throw n}}async function H(e,t,n){let r=await D(e,t.event.messageId).catch(e=>{if(e instanceof q&&e.status===404)return null;throw e}),i=r&&await C(e,r.thread.channelId);if(!r||!i)return null;let a=t.event.type===`thread.synced`?await ft(e,t,r.message,i.name):await Pe(e,t.event,i.name,t.id,n,await ye(e,n),r);if(!a?.message)return null;let o=t.watcher===`@sync`&&a.type===`labels.changed`?{...a,before:{...a.message,labels:Ch(a.message.labels,t.event.labels)}}:a;return{id:t.id,watcher:t.watcher,thread:a.message.thread,lease:t.lease,attempt:t.attempt,event:o}}async function ft(e,t,n,r){let{binding:i}=t.event;if(!i||i.projectId!==void 0&&i.projectId!==await se(e))return null;let a=await ue(e,n,r);return Le(e,t.event,t.id,`thread.synced`,{thread:a.thread,target:i.target,cause:i.cause,kind:i.targetKind,by:bh(t.event.actor)},a)}async function pt(e,t,n,r={}){let{matches:i}=await rt(e,`GET`,await _(e,`/watchers/matches`),{query:{limit:t.limit?.toString(),wait:t.wait?.toString()},...n?{signal:n}:{}}),a=new Map(Object.entries(r).map(([e,t])=>[e,ap(e,t).filters.from])),o=await Promise.all(i.map(t=>{let n=a.get(t.watcher);return H(e,t,n===void 0?{}:{from:n})}));return await Promise.all(i.map((t,n)=>o[n]?null:mt(e,t.id,{lease:t.lease,skip:!0}).catch(()=>{}))),o.filter(e=>e!==null)}async function mt(e,t,n){await rt(e,`POST`,await _(e,`/watchers/matches/${encodeURIComponent(t)}/ack`),{body:{lease:n.lease,...n.error===void 0?{}:{error:n.error},...n.skip?{skip:!0}:{}}})}let ht={profile:null},gt={},_t=()=>{if(!a)throw Error(`vercel: used before board() bound it`);return a},vt=pp({remote:`Vercel's API`,registry:{register:e=>it(ht,e,gt,_t().sync,!0,ct),matches:({signal:e,...t})=>pt(ht,t,e,gt),ack:(e,t)=>mt(ht,e,t)},wakeAt:async e=>fp(e)??{},binding:_t,hash:()=>Ke(gt,_t().sync),hasWork:()=>Object.keys(gt).length>0||_t().sync.length>0,rethrow:e=>{throw e},registerFor:async(e,t)=>Ff(await Mt.register(e,wd.parse(await t.json()),t.signal))}),yt=null,bt=()=>(yt??=Ee(ht).then(e=>e.actor.principal.type===`project`)).catch(e=>{throw yt=null,e}),xt=null,St=!1;function Ct(){if(xt||St)return;if(dp()){St=!0,console.error(`[board] watchers on a deployment need its own OIDC token: with another Vercel token, none run here`);return}let{sync:e,run:t}=_t();e.length>0&&console.error(`[board] sync doesn't run on Vercel's board as anyone but a deployment: run it from the project's deployment`);let n={};for(let[e,t]of Object.entries(gt))try{n[e]=Je(e,t,!0)}catch(t){console.error(`[board] watcher ${e} doesn't run:`,t.message)}xt=yp({watchers:n,events:(e,t)=>We(ht,e,t),actorOf:e=>De({profile:{name:e}}),run:t}),xt.start()}let wt=0;async function Tt(){if(xt||Object.keys(gt).length===0&&_t().sync.length===0||Date.now()-wt<1e4)return;let e;try{e=await bt()}catch(e){wt=Date.now(),console.error(`[board] couldn't tell whether this board runs as a deployment:`,e instanceof Error?e.message:String(e));return}e?await vt.start():Ct()}let Et=vt.routes.map(e=>({...e,async handle(t,n){if(n.caller||await bt().catch(()=>!0))return e.handle(t,n);if(op(Tt()),e.path===`/wake`)return Ff({ran:0});throw tt()}})),Dt=({id:e,handle:t,name:n,avatar:r,isBot:i})=>({id:e,handle:t,name:n,avatar:r,isBot:i});async function Ot(e,t){let n={op:t.op,operationId:ah(),author:Dt(t.author),...t.from===void 0?{}:{from:t.from}};if(t.op===`post`){let r;if(t.after!==void 0){let e=uh(t.after),n=t.re===void 0?null:uh(t.re);if(!e||!n||e.threadId!==n.threadId)throw kf(`after: ${t.after} isn't in ${t.re??`the thread`}'s thread`,`invalid_after`);r=e.sequence}return{...n,origin:t.origin===null?null:wh(t.origin),...t.source?{source:t.source}:{},...t.channel===void 0?{}:{channelId:(await T(e,t.channel)).id},...t.re===void 0?{}:{re:t.re},text:t.text,...t.labels&&Object.keys(t.labels).length?{labels:t.labels}:{},...t.noSync?{noSync:!0}:{},...t.attachments?.length?{attachments:t.attachments}:{},...t.links?.length?{links:t.links}:{},...t.id===void 0?{}:{id:t.id},...r===void 0?{}:{after:r}}}let r={...n,...t.origin===void 0?{}:{origin:t.origin},...t.message===void 0?{}:{message:t.message}};return t.op===`edit`?{...r,text:t.text,...t.source?{source:t.source}:{},...t.revision===void 0?{}:{revision:t.revision}}:t.op===`delete`?{...r,...t.revision===void 0?{}:{revision:t.revision}}:t.op===`react`?{...r,emoji:t.emoji,...t.remove?{remove:!0}:{}}:t.op===`labels`?{...r,...t.set?{set:t.set}:{},...t.unset?{unset:t.unset}:{},...t.if&&Object.keys(t.if).length?{if:t.if}:{}}:{...r,links:t.links}}let kt=(e,t,n=``)=>_(e,`/sync/inbox/${encodeURIComponent(t)}${n}`),At=e=>{throw e instanceof q&&e.code===`unsupported_principal`?new q(400,`unsupported_principal`,`Vercel's board takes no GitHub or OIDC principals in a grant.`,{hint:`Grant an app that an OIDC exchange policy issues tokens for: --app <slug>.`,origin:`handle`}):e},jt=e=>{throw e instanceof q&&e.code===`unsupported_principal`?new q(400,`unsupported_principal`,`Vercel's board explains no GitHub or OIDC caller: no grant names one.`,{hint:`Explain the app an OIDC exchange policy issues tokens for: --app <slug>.`,origin:`handle`}):e},Mt={...Object.fromEntries(Bf.map(e=>[e,async()=>{throw Zm(e===`register`||e===`watchers`||e===`matches`||e===`ack`?`watchers`:e)}])),async discovery(){let t={profile:null},r=await l();e.board&&await u(t,`GET`,await _(t));let i=r?.startsWith(`team_`)?r:(await Ee(t)).teamId;return{version:Rf,url:`${n}/v1/messageboard${await _(t)}?teamId=${encodeURIComponent(i)}`,audience:n,team_id:i,project_id:null,sync:(a?.sync??[]).map(({key:e,platform:t})=>({key:e,platform:t})),wake_by_path:!0}},async me(e){let t=V(e),n=await u(t,`GET`,await _(t,`/me`)),{view:r}=n,{principal:i}=n.actor,a=i.type===`project`?(r?gh([[n.actor.id,r]]).get(i.projectId):void 0)??await ae(t,i.projectId):void 0,o=i.type===`project`&&!n.actor.profile?{kind:`deployment`,...hh(i,a),avatar:r?.avatar??null}:r?{kind:nh(r.kind),handle:r.handle,name:r.name??r.handle,avatar:r.avatar??null}:Sh(n.actor,void 0,a),s=n.actor.profile&&i.type!==`external`?{via:ph(i,r,a)}:{};return{actor:n.actor.id,principal:dh(n.actor.principal),kind:o.kind,handle:o.handle,name:o.name,avatar:o.avatar,profile:n.actor.profile?.name??null,...s,expiresAt:eh(n.expiresAt),can:$m(n.can)}},async channels(e){return{channels:(await E(V(e),void 0)).map(e=>({path:e.name})).sort((e,t)=>e.path.localeCompare(t.path)),cursor:fe({t:Date.now(),feeds:{}})}},async createChannel(e,{path:t}){let{created:n}=await w(V(e),t);return{channel:{path:t},created:n}},async actors(e,t,n){let r=V(e),i=await f(r,await _(r,`/actors`),`actors`,{},n),a=gh(i.map(e=>[e.id,e]));return{actors:i.map(e=>{let{profile:t}=ot(e.id),n=fh(e.id),r=n?.type===`project`?a.get(n.projectId):void 0,i=t===null?null:n,o=$e(t),s=t===null&&n?.type===`project`?hh(n,r):null;return{id:e.id,kind:nh(e.kind),handle:s?.handle??(i&&o?mh(e.handle,i,e,o.user,r):e.handle),name:s?.name??e.name??e.handle,avatar:e.avatar??null,...i?{via:ph(i,e,r)}:{},...e.platform?{platform:e.platform}:{},verified:!0}}),cursor:fe({t:Date.now(),feeds:{}})}},async messages(e,t,n){let r=V(e),i=t.before===void 0?await Ge(r,t):null;if(i){let e=await He(r,i,t,n);return{messages:await Promise.all(e.messages.map(e=>ue(r,e,i.name))),cursor:e.cursor}}if(t.after!==void 0&&qm.test(t.after))throw new q(400,`invalid_request`,`after: ${t.after} is one channel's cursor: read that channel`);let a=t.limit??50;if(t.re===void 0&&t.after===void 0&&t.before===void 0&&!Ve(t)){let{messages:e,feeds:i,newest:o}=await Ne(r,await E(r,t.channel),a,n);return{messages:await Promise.all(e.map(({message:e,channel:t})=>ue(r,e,t.name))),cursor:fe({t:o,feeds:i})}}let{messages:o,feeds:s,newest:c}=await je(r,t,n),l=t.after===void 0?void 0:await me(r,t.after),u=t.before===void 0?void 0:await me(r,t.before),d=o.filter(({message:e})=>(l===void 0||e.createdAt>l)&&(u===void 0||e.createdAt<u)),f=l===void 0?d.slice(-a):d.slice(0,a);return{messages:await Promise.all(f.map(({message:e,channel:t})=>ue(r,e,t.name))),cursor:fe({t:c,feeds:s})}},async threads(e,t,n){let r=V(e),i=t.after===void 0?void 0:await me(r,t.after),a=t.limit??50,o=e=>{let t=e.filter(({at:e})=>i===void 0||e>i).sort((e,t)=>e.at-t.at);return i===void 0?t.slice(-a):t.slice(0,a)};if(t.re!==void 0||t.by!==void 0||t.mentions!==void 0||t.text!==void 0||t.from!==void 0){let{messages:e,feeds:i,newest:a}=await je(r,t,n),s=/* @__PURE__ */ new Map;for(let{message:t,thread:n,channel:r}of e)s.set(n.id,{thread:n,channel:r,at:Math.max(s.get(n.id)?.at??0,t.createdAt)});return{threads:await Promise.all(o([...s.values()]).map(({thread:e,channel:t})=>we(r,e,t,n))),cursor:fe({t:a,feeds:i})}}let s=await E(r,t.channel),c=await he(r,s),l=xe(t),u=(await Promise.all(s.map(async e=>(await Ce(r,e,l,{...i===void 0?{}:{after:i},...t.label?.length?{}:{limit:a}},n)).map(t=>({thread:t,channel:e,at:t.lastActivityAt}))))).flat(),d=u.filter(({thread:e})=>(t.label??[]).every(([t,n])=>e.labels!==void 0&&Object.hasOwn(e.labels,t)&&(n===null||n.includes(e.labels[t])))),f=u.reduce((e,{at:t})=>Math.max(e,t),0);if(!t.label?.length)return{threads:await Promise.all(o(d).map(({thread:e,channel:t})=>we(r,e,t,n))),cursor:fe({t:f,feeds:c})};let p=d.filter(({at:e})=>i===void 0||e>i).sort((e,t)=>e.at-t.at);i===void 0&&p.reverse();let m=[];for(let e=0;e<p.length&&m.length<a;){let t=p.slice(e,e+a-m.length);e+=t.length;for(let e of await Promise.all(t.map(({thread:e,channel:t})=>we(r,e,t,n))))e.message.deleted||m.push(e)}return i===void 0&&m.reverse(),{threads:m,cursor:fe({t:f,feeds:c})}},async message(e,{id:t},n){let r=V(e),{thread:i,channel:a}=await O(r,t,n),[o,...s]=await M(r,i.id,n);if(!o)throw Mf(`message not found: ${t}`,`message_not_found`);return{message:await ue(r,o,a.name),replies:await Promise.all(s.map(e=>ue(r,e,a.name))),cursor:fe({t:Math.max(o.createdAt,...s.map(e=>e.createdAt)),feeds:{}})}},async upload(e,{data:t,name:n,type:r}){let a=V(e);if(t.byteLength===0)throw new q(400,`bad_request`,`the file is empty`);if(t.byteLength>26214400)throw new q(413,`too_large`,`attachments are at most ${Ae/1024/1024} MB`);let o=new Uint8Array(t),s=new Uint8Array(await crypto.subtle.digest(`SHA-256`,o)),c=await u(a,`POST`,await _(a,`/attachments`),{body:{operationId:ah(),name:Fe(n),type:Ie(r),size:t.byteLength,sha256:btoa(String.fromCharCode(...s))}}),l=await i(c.upload.url,{method:c.upload.method,headers:c.upload.headers,body:o,redirect:`error`});if(!l.ok)throw new q(502,`upload_failed`,`the upload to Vercel's storage answered ${l.status}`);let{attachment:d}=await u(a,`POST`,await _(a,`/attachments/${encodeURIComponent(c.attachment.id)}/complete`));return{attachment:Xm(d)}},async uploadStart(e,{name:t,type:n,size:r,sha256:i}){let a=V(e);if(i===void 0)throw new q(400,`invalid_request`,"Vercel's API signs a direct upload for its bytes' SHA-256: send `sha256`, as board's client does");let o=await u(a,`POST`,await _(a,`/attachments`),{body:{operationId:ah(),name:Fe(t??null),type:Ie(n??null),size:r,sha256:i}});return{id:o.attachment.id,url:o.upload.url,headers:o.upload.headers,expiresAt:oh(o.upload.expiresAt)}},async uploadFinish(e,{id:t}){let n=V(e),{attachment:r}=await u(n,`POST`,await _(n,`/attachments/${encodeURIComponent(t)}/complete`));return{attachment:Xm(r)}},async attachment(e,{id:t},n){let r=V(e),a=await u(r,`GET`,await _(r,`/attachments/${encodeURIComponent(t)}`),n?{signal:n}:{}),o=await i(a.url,{redirect:`error`,...n?{signal:n}:{}});if(!o.ok||!o.body)throw new q(502,`download_failed`,`Vercel's storage answered ${o.status}`);return{attachment:Xm(a.attachment),data:o.body}},async post(e,t,n){if(t.sync?.length)throw Zm(`sync`);let r=V(e),i=t.id===void 0?void 0:await ke(t.id),a,o;if(t.channel!==void 0)o=t.channel,a=await u(r,`POST`,await _(r,`/threads`),{body:{operationId:ah(),channel:t.channel,text:t.text,...t.labels&&Object.keys(t.labels).length?{labels:t.labels}:{},...i?{clientId:i}:{},...t.attachments?.length?{attachments:t.attachments}:{},...t.noSync?{noSync:!0}:{}},signal:n});else{let{thread:e,message:s,channel:c}=await O(r,t.re,n);o=c.name;let l=t.after===void 0?void 0:uh(t.after);if(l!==void 0&&l?.threadId!==e.id){let a=i?await u(r,`GET`,await _(r,`/posts/${encodeURIComponent(i)}`),{signal:n}).catch(()=>null):null;if(a?.thread.id===e.id)return{message:await ue(r,a.message,c.name)};throw kf(`after: ${t.after} isn't in ${t.re}'s thread`,`invalid_after`)}let d=await u(r,`POST`,await _(r,`/threads/${encodeURIComponent(e.id)}/messages`),{body:{operationId:ah(),text:t.text,...s.sequence>1?{replyTo:s.sequence}:{},...i?{clientId:i}:{},...t.attachments?.length?{attachments:t.attachments}:{},...l?{after:l.sequence}:{},...t.noSync?{noSync:!0}:{}},signal:n}).catch(e=>{throw e instanceof q&&e.code===`newer_message`?new q(409,`newer_message`,`a message came after ${t.after}`):e});if(t.labels&&Object.keys(t.labels).length){let i=await u(r,`POST`,await _(r,`/threads/${encodeURIComponent(e.id)}/messages/${d.message.sequence}/labels`),{body:{operationId:ah(),set:t.labels},signal:n});d.message={...d.message,...i.meta.labels?{labels:i.meta.labels}:{},version:i.meta.version}}a=d}let s=a.thread.channelId;return s!==void 0&&(i!==void 0&&S.get(s)!==o?o=await C(r,s).then(e=>(S.set(s,e.name),e.name),()=>o):S.set(s,o)),{message:await ue(r,`text`in a.message?a.message:await de(r,a.message,t),o)}},async posted(e,{id:t},n){let r=V(e),i=await u(r,`GET`,await _(r,`/posts/${encodeURIComponent(await ke(t))}`),{signal:n}),a=await C(r,i.thread.channelId);return{message:await ue(r,i.message,a.name)}},async edit(e,{id:t,text:n,revision:r},i){let a=V(e),o=uh(t);if(!o)throw Mf(`message not found: ${t}`,`message_not_found`);return await u(a,`PATCH`,await _(a,`/threads/${encodeURIComponent(o.threadId)}/messages/${o.sequence}`),{body:{operationId:ah(),text:n,...r===void 0?{}:{revision:r}},signal:i}),{ok:!0}},async delete(e,{id:t,revision:n},r){let i=V(e),a=uh(t);if(!a)throw Mf(`message not found: ${t}`,`message_not_found`);return await u(i,`POST`,await _(i,`/threads/${encodeURIComponent(a.threadId)}/messages/${a.sequence}/delete`),{body:{operationId:ah(),...n===void 0?{}:{revision:n}},signal:r}),{ok:!0}},async react(e,{id:t,emoji:n,remove:r},i){let a=V(e),o=uh(t);if(!o)throw Mf(`message not found: ${t}`,`message_not_found`);return await u(a,`POST`,await _(a,`/threads/${encodeURIComponent(o.threadId)}/messages/${o.sequence}/reactions`),{body:{operationId:ah(),emoji:n,...r?{remove:!0}:{}},signal:i}),{ok:!0}},async label(e,{id:t,set:n,unset:r,if:i},a){let o=V(e),s=uh(t);if(!s)throw Mf(`message not found: ${t}`,`message_not_found`);return await u(o,`POST`,await _(o,`/threads/${encodeURIComponent(s.threadId)}/messages/${s.sequence}/labels`),{body:{operationId:ah(),...n?{set:n}:{},...r?{unset:r}:{},...i&&Object.keys(i).length?{if:i}:{}},signal:a}),{ok:!0}},async grants(e,t,n){let r=V(e),{grants:i}=await u(r,`GET`,await _(r,`/grants`),n?{signal:n}:{});return{grants:i.map(sh)}},async createGrant(e,t,n){let r=V(e),{grant:i}=await u(r,`POST`,await _(r,`/grants`),{body:{operationId:ah(),...t},...n?{signal:n}:{}}).catch(At);return{grant:sh(i)}},async updateGrant(e,{id:t,...n},r){let i=V(e),{grant:a}=await u(i,`PATCH`,await _(i,`/grants/${encodeURIComponent(t)}`),{body:{operationId:ah(),...n},...r?{signal:r}:{}}).catch(At);return{grant:sh(a)}},async explain(e,{claim:t,...n},r){let i=V(e),a=new URLSearchParams;for(let[e,t]of Object.entries(n))t!==void 0&&a.set(e,t);for(let e of t??[])a.append(`claim`,e);let o=await u(i,`GET`,await _(i,`/grants/explain?${a}`),r?{signal:r}:{}).catch(jt);return{...o,grants:o.grants.map(sh)}},async revokeGrant(e,{id:t},n){let r=V(e);return u(r,`POST`,await _(r,`/grants/${encodeURIComponent(t)}/revoke`),{body:{operationId:ah()},...n?{signal:n}:{}})},async schemas(e,t,n){let r=(await f(V(e),`/schemas`,`schemas`,{},n)).map(ch),i=e=>+!e.builtIn;return{schemas:r.sort((e,t)=>i(e)-i(t)||(e.builtIn?0:e.name<t.name?-1:e.name>t.name?1:e.version-t.version))}},async schema(e,{id:t},n){let{schema:r}=await u(V(e),`GET`,`/schemas/${encodeURIComponent(t)}`,n?{signal:n}:{});return{schema:ch(r)}},async createSchema(e,t,n){let r=V(e),i=await u(r,`GET`,`/schemas/${encodeURIComponent(Be(t.name,t.version))}`,n?{signal:n}:{}).then(()=>!0,e=>{if(e instanceof q&&e.code===`schema_not_found`)return!1;throw e}),{schema:a}=await u(r,`POST`,`/schemas`,{body:{operationId:ah(),...t},...n?{signal:n}:{}});return{schema:ch(a),created:!i}},async schedule(e,t,n){if(t.attachments?.length)throw Zm(`files on scheduled messages`);let r=V(e),i=t.labels&&Object.keys(t.labels).length?t.labels:void 0,a;if(t.channel!==void 0)a={channelId:(await T(r,t.channel)).id};else{if(i)throw Zm(`labels on a scheduled reply`);let{thread:e}=await O(r,t.re,n);a={threadId:e.id}}let o=e=>Math.round(hf(e)),s=t.at===void 0?Date.now()+o(t.in??t.every):Date.parse(t.at),c=t.until===void 0?t.for===void 0?void 0:s+o(t.for):Date.parse(t.until),{schedule:l}=await u(r,`POST`,await _(r,`/schedules`),{body:{operationId:ah(),...a,text:t.text,...i?{labels:i}:{},...t.noSync?{noSync:!0}:{},firstAt:s,...t.every===void 0?{}:{every:o(t.every)},...c===void 0?{}:{until:c},...t.times===void 0?{}:{times:t.times}},signal:n});return{schedule:await z(r,l)}},async schedules(e,t,n){let r=V(e),i={state:t.all?void 0:`pending`};if(t.re!==void 0){let e=await O(r,t.re,n).catch(e=>{if(e instanceof q&&e.status===404)return null;throw e});if(!e)return{schedules:[]};i.threadId=e.thread.id}if(t.channel!==void 0){let e=await x(r,t.channel);if(!e)return{schedules:[]};i.channelId=e.id}t.by?.startsWith(`vercel:`)&&(i.createdBy=t.by);let a=await _e(r,t.by),o=e=>a===void 0||a(e),s=await f(r,await _(r,`/schedules`),`schedules`,i,n);return{schedules:await Promise.all(s.filter(e=>o(e.createdBy)).map(e=>z(r,e)))}},async cancelSchedule(e,{id:t},n){let r=V(e),{schedule:i,canceled:a}=await u(r,`POST`,await _(r,`/schedules/${encodeURIComponent(t)}/cancel`),{body:{operationId:ah()},signal:n});return{schedule:await z(r,i),canceled:a}},events:(e,t,n)=>We(V(e),t,n),async typing(e,{id:t,status:n},r){if(!a||a.sync.length===0)return{targets:[]};let{message:i,replies:o}=await Mt.message(e,{id:t},r);if(`self`in e&&e.can!==void 0&&!Hp(Xp(e.can)).can(`post`,i.channel))throw new q(403,`forbidden`,`this handle can't post in ${i.channel}`);return{targets:await a.typing([i,...o],n)}},async readSource(e,{key:t,target:n,limit:r,after:i}){if(!a?.sync.some(e=>e.key===t))throw Mf(`this board doesn't run sync entry ${t}: read it where its sync runs`,`not_synced_here`);return Oe(e,`read a source`),a.readSource(t,n,r??50,i??null)},async joinSource(e,{key:t,target:n}){if(!a?.sync.some(e=>e.key===t))throw Mf(`this board doesn't run sync entry ${t}: join it where its sync runs`,`not_synced_here`);return Oe(e,`join a source`),a.joinSource(t,n)},async syncImport(e,t,n){let r=V(e),i=t.from??t.author.id.split(`:`)[0];return{message:(await dt(i,()=>{throw ut(i)},async()=>d(r,`POST`,await _(r,`/sync/imports`),{body:await Ot(r,t),signal:n})).catch(e=>{throw e instanceof q&&e.code===`newer_message`&&t.op===`post`?new q(409,`newer_message`,`a message came after ${t.after}`):e})).message}},async syncReceipt(e,t,n){let r=V(e),i=t.target.split(`:`)[0];return dt(i,()=>{throw ut(i)},async()=>d(r,`POST`,await _(r,`/sync/receipts`),{body:t,signal:n}))},async syncFind(e,t,n){let r=V(e),{thread:i,message:a}=await d(r,`GET`,await _(r,`/sync/find`),{query:t,signal:n});return{thread:i,message:a}},async syncThread(e,{thread:t},n){let r=V(e),i=await d(r,`GET`,await _(r,`/sync/threads/${encodeURIComponent(t)}`),{signal:n});return{...i,channel:(await C(r,i.channel)).name}},async syncCopies(e,{message:t},n){let r=V(e);return d(r,`GET`,await _(r,`/sync/copies`),{query:{message:t},signal:n})},async synced(e,{id:t},n){let r=V(e);if(!uh(t))throw Mf(`message not found: ${t}`,`message_not_found`);let{targets:i}=await d(r,`GET`,await _(r,`/messages/${encodeURIComponent(t)}/synced`),{signal:n}),o=await se(r),s=e=>e!==void 0&&e!==o,c=[...new Set(i.flatMap(({projectId:e})=>s(e)?[e]:[]))],l=c.length?await ie(r,{key:c.join(` `),found:e=>c.every(t=>e.has(t))}):/* @__PURE__ */ new Map;return{targets:await Promise.all(i.map(async({projectId:e,...t})=>{if(s(e)){let n=`${l.get(e)??e}/${t.key}`;return{...t,key:n,target:`${n}${t.target.slice(t.key.length)}`,url:null}}return{...t,url:a&&t.thread!==null&&t.message!==null?await a.linkOf(t.key,t.thread,t.message):null}}))}},async linked(e,{url:t},n){let r=V(e),i=()=>Mf(`no message on this board for that link`,`message_not_found`);for(let{platform:o,thread:s,message:c}of a?.locate(t)??[])for(let t of/* @__PURE__ */ new Set([...(a?.sync??[]).filter(e=>e.platform===o).map(e=>e.key),o])){let a=await d(r,`GET`,await _(r,`/sync/linked`),{query:{thread:`${t}:${s}`,...c===null?{}:{message:c}},signal:n}).catch(e=>{if(e instanceof q&&e.status===404)return null;throw e});if(a)return Mt.message(e,{id:a.message},n).catch(e=>{throw e instanceof q&&(e.status===403||e.status===404)?i():e})}throw i()},async inboxPush(e,{key:t,events:n},r){let i=V(e),a={events:n.map(({id:e,event:t,raw:n})=>({id:e,thread:t.thread,event:t,...n===void 0?{}:{raw:n}}))};return await dt(t,()=>null,async()=>d(i,`POST`,await kt(i,t),{body:a,signal:r})),{ok:!0}},async inboxNext(e,{key:t,limit:n},r){let i=V(e),{items:a}=await dt(t,()=>({items:[]}),async()=>d(i,`GET`,await kt(i,t,`/next`),{query:{limit:n?.toString()},signal:r}));return{items:a.map(({raw:e,...n})=>({...n,key:t,raw:e??null}))}},async inboxAck(e,{key:t,id:n,lease:r,error:i},a){let o=V(e);return await dt(t,()=>null,async()=>d(o,`POST`,await kt(o,t,`/${encodeURIComponent(n)}/ack`),{body:{lease:r,...i===void 0?{}:{error:i}},signal:a})),{ok:!0}},async inbox(e,{key:t,channel:n,limit:r},i){let a=V(e),o=Math.min(r??50,100),{events:s}=await dt(t,()=>({events:[]}),async()=>d(a,`GET`,await kt(a,t),{query:{limit:String(n===void 0?o:100)},signal:i})),c=s.flatMap(({id:e,createdAt:n,event:r,raw:i})=>r?[{id:e,channel:typeof r.channel==`string`?r.channel:``,createdAt:n,sync:t,event:r,raw:i??null}]:[]);return{events:(n===void 0?c:c.filter(e=>e.channel===n)).slice(0,o)}},async watchers(e){let t=V(e),{watchers:n}=await rt(t,`GET`,await _(t,`/watchers`));return{watchers:await Promise.all(n.map(async e=>({owner:e.owner,...et(e),watch:Object.fromEntries(await Promise.all(Object.entries(e.watch).map(async([e,n])=>[e,{tail:await Xe(t,n)}]))),sync:Ze(e),hash:e.hash})))}},async register(e,t){if(typeof t.url==`string`)throw new q(400,`invalid_request`,`Vercel's API wakes a deployment only by its path.`,{hint:`Register a path, or no url to pull its matches.`,origin:`handle`});return it(V(e),typeof t.path==`string`?{path:t.path,...t.branch?{branch:t.branch}:{}}:{},t.watch,t.sync??[],!1)},async matches(e,t,n){return{matches:await pt(V(e),t,n)}},async ack(e,{id:t,...n}){return await mt(V(e),t,n),{ok:!0}}};return{...Object.fromEntries(Object.entries(Mt).map(([e,t])=>[e,(e,...n)=>{if(`identity`in e)throw th();return a&&op(Tt()),t(e,...n)}])),routes:Et,keeps:!1,async sandbox({profile:e,can:r,token:i}){if(e.avatar!==void 0&&!e.avatar.startsWith(`https://`))throw new q(400,`invalid_profile`,`${e.avatar} isn't an avatar Vercel's API takes: one is an https URL.`,{origin:`handle`});let a={profile:null},o=await l(),s=o?.startsWith(`team_`)?o:(await Ee(a)).teamId,c=`${n}/v1/messageboard${await _(a)}?teamId=${encodeURIComponent(s)}`;return{url:c,headers:{...t?await t.sandbox(c,i):i===void 0?Cm(c):{authorization:`Bearer ${i}`},...Um(e),"x-board-can":r},routes:Hm,reads:[`/v1/messageboard/me`]}},sendsSchedulesHere:!1,syncedHere:lt,bind(t){if(a)throw Error(`vercel: this backend already serves a board: create one vercel() per board()`);if(e.team&&t.team&&e.team!==t.team)throw Error(`vercel: board() names team ${t.team}, and vercel() team ${e.team}: name the team once`);for(let e of Object.keys(t.subscriptions))o.add(e);gt=Object.fromEntries(Object.entries(t.subscriptions).flatMap(([e,t])=>t.kind===`tail`?[[e,{tail:t.tail}]]:[])),a=t},async registerWatchers(){if(await bt())return vt.registerNow();throw op(Tt()),tt()},close(){vt.close(),xt?.close(),xt=null}}}function Eh(e={}){return Th(e,null)}const Dh=[`fx`,`claude`,`codex`,`grok`,`pi`],Oh=/^[A-Za-z][A-Za-z0-9-]{0,31}$/;function kh(e){let{profile:t,avatar:n}=Ah(e.get(`x-board-profile`));if(e.get(`x-board-scope`)!==null)throw kf(`x-board-scope is x-board-can now: send the same value as x-board-can`,`invalid_scope`);let r=e.get(`x-board-can`);if(r!==null)try{Xp(r)}catch(e){throw kf(e.message,`invalid_scope`)}return{profile:t,avatar:n,scope:r}}function Ah(e){if(e===null||e.trim()===``)return{profile:null,avatar:null};let t;try{t=cf(e)}catch(e){throw kf(e.message,`invalid_profile`)}if(!Oh.test(t.name))throw kf(`profile names start with a letter and use up to 32 letters, numbers, and hyphens`,`invalid_profile`);if(t.avatar!==null&&!Nh(t.avatar))throw kf(`avatars must be https URLs (http only on localhost)`,`invalid_profile`);return{profile:t.name,avatar:t.avatar}}function jh(e,t){let n=t.profile?.toLowerCase()??null,r=n===null?e.id:`${e.id}+${n}`,i=Mh(e),a={id:r,kind:n===null?e.kind:`agent`,handle:n===null?e.handle:`${e.handle}/${n}`,name:t.profile??(i.environment!==null&&i.environment!==`production`?`${i.name} (${i.environment})`:e.handle),avatar:t.avatar,...n===null?{}:{via:i}};return{author:{actor:r,principal:e.id,profile:n},actor:a}}function Mh(e){let t=/^vercel:project:[^:]+:([^:]+)$/.exec(e.id)?.[1]??null,n=`@${t}`;return{name:t!==null&&e.handle.endsWith(n)&&e.handle.length>n.length?e.handle.slice(0,-n.length):e.handle,environment:t}}function Nh(e){try{let t=new URL(e);return t.protocol===`https:`||t.protocol===`http:`&&[`localhost`,`127.0.0.1`].includes(t.hostname)}catch{return!1}}function Ph(e,t,n,r=null){let i=r?()=>r.grants():null,a=null,o=()=>(a??=(async()=>{if(!n)return{id:null,teamId:null};let e=await n(),[t,r]=await Promise.all([e.ownProjectId(),e.ownTeamId()]);return{id:t,teamId:r}})()).catch(e=>{throw a=null,e});async function s(e){return n?(await n()).discoveryIdentity(e):{projectId:null,teamId:null}}let c=null,l=()=>e.authenticate?Promise.resolve(e.authenticate):c??=n?n().then(e=>e.oidcTokens()):Promise.reject(new q(501,`no_verifier`,`this build of board verifies no tokens: pass board({ authenticate })`)),u=pm({project:o,hosts:e.authenticate!==void 0&&!vm(e.authenticate),grants:i}),d={project:o,issuers:[]};async function f(e){if(!i)return;let t=Fh(e);if(t===null||!t.startsWith(`https://`)||t===`https://token.actions.githubusercontent.com`||im.test(t))return;let n=um([],dm(await i()));n.join(`
|
|
346
346
|
`)!==d.issuers.join(`
|
|
347
347
|
`)&&(d.issuers=n)}let p=/* @__PURE__ */ new Map,m=/* @__PURE__ */ new WeakMap;async function h(e){let t=e=>e.expiresAt===null||e.expiresAt.getTime()>Date.now(),n=m.get(e);if(n){let e=await n;if(t(e))return e}let r=e.credential===null?null:[e.audience,e.credential].join(``),i=r===null?void 0:p.get(r);if(i&&i.until>Date.now())return m.set(e,i.principal),i.principal;let a=g(e);return m.set(e,a),r!==null&&a.then(e=>{e.facts?.issuer!==`host`&&e.expiresAt!==null&&(p.size>=1e3&&p.delete(p.keys().next().value),p.set(r,{principal:a,until:e.expiresAt.getTime()}))},()=>m.delete(e)),a}async function g(e){e.credential!==null&&await f(e.credential);let t=await l(),n;try{n=await t({...e,board:d})}catch(e){throw e instanceof Response?new Of(e):e}if(n instanceof Response)throw new Of(n);if(n==null)throw Af(`missing bearer token`);return ym(n)?n:Sm(n)}async function _(e,t){let n;try{n=await u.resolve(e)}catch(e){let t=e.status;if(t===401||t===403)return{pattern:null,over:[],level:null,grants:[],permissions:[]};throw e}let r=e.scope===void 0?null:Hp(Xp(e.scope)),i=e=>r?e.filter(e=>r.can(e,t)):[...e];if(`fixed`in n)return{pattern:null,over:[],level:null,grants:[],permissions:i(xp.filter(e=>n.fixed.can(e,t)))};let{pattern:a,over:o,level:s,grants:c,permissions:l}=rm(n.facts,t);return{pattern:a,over:o,level:s,grants:c,permissions:i(l)}}return{open:t,project:o,discoveryIdentity:s,async identify(e){let t=await h(e),{claims:n}=e,r=n.scope===null?t:{...t,scope:n.scope},{author:i,actor:a}=jh(r,n);return{principal:{...r,access:await u.grant(r)},author:i,actor:a}},explain:_,async accessNow(e,t){return e.token===void 0?u.accessNow(e,t):null}}}function Fh(e){let t=e.split(`.`)[1];if(t===void 0)return null;try{let e=atob(t.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(Math.ceil(t.length/4)*4,`=`)),{iss:n}=JSON.parse(e);return typeof n==`string`?n:null}catch{return null}}const Ih=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Lh(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e==`number`?Number.isInteger(e)?`integer`:`number`:typeof e}const Rh=(e,t)=>{let n=Lh(e);return n===t||t===`number`&&n===`integer`};function zh(e,t){if(e===t)return!0;if(Array.isArray(e))return Array.isArray(t)&&e.length===t.length&&e.every((e,n)=>zh(e,t[n]));if(!Ih(e)||!Ih(t))return!1;let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Object.hasOwn(t,n)&&zh(e[n],t[n]))}const Bh=/^(\d{4})-(\d{2})-(\d{2})$/,Vh=/^(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:z|[+-](\d{2})(?::?(\d{2}))?)?$/i,Hh=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i,Uh=/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*$/i;function Wh(e){let t=Bh.exec(e);if(!t)return!1;let[n,r,i]=[Number(t[1]),Number(t[2]),Number(t[3])],a=[31,n%4==0&&(n%100!=0||n%400==0)?29:28,31,30,31,30,31,31,30,31,30,31][r-1];return a!==void 0&&i>=1&&i<=a}function Gh(e){let t=Vh.exec(e);return t?Number(t[1])<=23&&Number(t[2])<=59&&Number(t[3])<=60&&Number(t[4]??0)<=23&&Number(t[5]??0)<=59:!1}const Kh=e=>e.length<=253&&e.replace(/\.$/,``).split(`.`).every(e=>Hh.test(e)),qh=e=>{let t=e.split(`.`);return t.length===4&&t.every(e=>/^(?:0|[1-9]\d{0,2})$/.test(e)&&Number(e)<=255)};function Jh(e){let t=e;if(e.includes(`.`)){let n=e.lastIndexOf(`:`);if(n===-1||!qh(e.slice(n+1)))return!1;t=`${e.slice(0,n+1)}0:0`}let n=t.split(`::`);if(n.length>2)return!1;let r=n.flatMap(e=>e===``?[]:e.split(`:`));return r.every(e=>/^[0-9a-f]{1,4}$/i.test(e))?n.length===2?r.length<=7:r.length===8:!1}const Yh={date:Wh,time:Gh,"date-time":e=>{let t=e.search(/[t ]/i);return t!==-1&&Wh(e.slice(0,t))&&Gh(e.slice(t+1))},email:e=>{let t=e.lastIndexOf(`@`),n=e.slice(t+1);return t>0&&Uh.test(e.slice(0,t))&&n.includes(`.`)&&!n.endsWith(`.`)&&Kh(n)},uri:e=>/^[a-z][a-z0-9+.-]*:[^\s]+$/i.test(e),uuid:e=>/^(?:urn:uuid:)?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e),hostname:Kh,ipv4:qh,ipv6:Jh},Xh=e=>{let t=JSON.stringify(e)??String(e);return t.length>40?`${t.slice(0,39)}…`:t};function Zh(e){let t=e.slice(0,6).map(Xh);return e.length>6?`one of ${t.join(`, `)}, …`:t.length<=2?t.join(` or `):`${t.slice(0,-1).join(`, `)}, or ${t.at(-1)}`}const Qh=e=>(Array.isArray(e)?e:[e]).map(e=>e===`null`?`null`:`${/^[aeio]/.test(String(e))?`an`:`a`} ${e}`).join(` or `);function $h(e,t){return eg(e,t,``)}function eg(e,t,n){let r=n||`it`;if(e===!0)return null;if(e===!1)return`${r} isn't allowed`;if(!Ih(e))return null;let i=e=>typeof e==`number`?`${n}[${e}]`:n?`${n}.${e}`:e,{type:a}=e;if(a!==void 0&&!(Array.isArray(a)?a:[a]).some(e=>Rh(t,e)))return`${r} must be ${Qh(a)}`;if(`const`in e&&!zh(t,e.const))return`${r} must be ${Xh(e.const)}`;if(Array.isArray(e.enum)&&!e.enum.some(e=>zh(t,e)))return`${r} must be ${Zh(e.enum)}`;if(typeof t==`string`){let n=[...t].length;if(typeof e.minLength==`number`&&n<e.minLength)return`${r} must be at least ${e.minLength} characters`;if(typeof e.maxLength==`number`&&n>e.maxLength)return`${r} must be at most ${e.maxLength} characters`;if(typeof e.format==`string`&&Yh[e.format]?.(t)===!1)return`${r} must be ${/^[aeiu]/.test(e.format)?`an`:`a`} ${e.format}`;if(typeof e.pattern==`string`&&!new RegExp(e.pattern,`u`).test(t))return`${r} must match ${e.pattern}`}if(typeof t==`number`){if(typeof e.minimum==`number`&&t<e.minimum)return`${r} must be at least ${e.minimum}`;if(typeof e.maximum==`number`&&t>e.maximum)return`${r} must be at most ${e.maximum}`;if(typeof e.exclusiveMinimum==`number`&&t<=e.exclusiveMinimum)return`${r} must be above ${e.exclusiveMinimum}`;if(typeof e.exclusiveMaximum==`number`&&t>=e.exclusiveMaximum)return`${r} must be below ${e.exclusiveMaximum}`;if(typeof e.multipleOf==`number`&&!Number.isInteger(t/e.multipleOf))return`${r} must be a multiple of ${e.multipleOf}`}if(Array.isArray(t)){if(typeof e.minItems==`number`&&t.length<e.minItems)return`${r} must have at least ${e.minItems} items`;if(typeof e.maxItems==`number`&&t.length>e.maxItems)return`${r} must have at most ${e.maxItems} items`;if(e.items!==void 0)for(let n=0;n<t.length;n++){let r=eg(e.items,t[n],i(n));if(r!==null)return r}}if(Ih(t)){let n=Ih(e.properties)?e.properties:{};if(Array.isArray(e.required)){for(let n of e.required)if(typeof n==`string`&&!Object.hasOwn(t,n))return`${i(n)} is missing`}for(let[r,a]of Object.entries(t))if(Object.hasOwn(n,r)){let e=eg(n[r],a,i(r));if(e!==null)return e}else if(e.additionalProperties!==void 0){if(e.additionalProperties===!1)return`${i(r)} isn't one of its fields`;let t=eg(e.additionalProperties,a,i(r));if(t!==null)return t}}if(Array.isArray(e.allOf))for(let r of e.allOf){let e=eg(r,t,n);if(e!==null)return e}for(let i of[`anyOf`,`oneOf`]){let a=e[i];if(!Array.isArray(a))continue;let o=a.map(e=>eg(e,t,n)),s=o.filter(e=>e===null).length;if(s===0)return o.length===1?o[0]:`${r} matches none of the ${o.length} it can be: ${[...new Set(o)].slice(0,4).join(`; `)}`;if(i===`oneOf`&&s>1)return`${r} matches ${s} of the ${o.length} it can be, and must match one`}return e.not!==void 0&&eg(e.not,t,n)===null?`${r} matches what it must not`:null}const tg={claude:`m4.7144 15.9555 4.7174-2.6471.079-.2307-.079-.1275h-.2307l-.7893-.0486-2.6956-.0729-2.3375-.0971-2.2646-.1214-.5707-.1215-.5343-.7042.0546-.3522.4797-.3218.686.0608 1.5179.1032 2.2767.1578 1.6514.0972 2.4468.255h.3886l.0546-.1579-.1336-.0971-.1032-.0972L6.973 9.8356l-2.55-1.6879-1.3356-.9714-.7225-.4918-.3643-.4614-.1578-1.0078.6557-.7225.8803.0607.2246.0607.8925.686 1.9064 1.4754 2.4893 1.8336.3643.3035.1457-.1032.0182-.0728-.164-.2733-1.3539-2.4467-1.445-2.4893-.6435-1.032-.17-.6194c-.0607-.255-.1032-.4674-.1032-.7285L6.287.1335 6.6997 0l.9957.1336.419.3642.6192 1.4147 1.0018 2.2282 1.5543 3.0296.4553.8985.2429.8318.091.255h.1579v-.1457l.1275-1.706.2368-2.0947.2307-2.6957.0789-.7589.3764-.9107.7468-.4918.5828.2793.4797.686-.0668.4433-.2853 1.8517-.5586 2.9021-.3643 1.9429h.2125l.2429-.2429.9835-1.3053 1.6514-2.0643.7286-.8196.85-.9046.5464-.4311h1.0321l.759 1.1293-.34 1.1657-1.0625 1.3478-.8804 1.1414-1.2628 1.7-.7893 1.36.0729.1093.1882-.0183 2.8535-.607 1.5421-.2794 1.8396-.3157.8318.3886.091.3946-.3278.8075-1.967.4857-2.3072.4614-3.4364.8136-.0425.0304.0486.0607 1.5482.1457.6618.0364h1.621l3.0175.2247.7892.522.4736.6376-.079.4857-1.2142.6193-1.6393-.3886-3.825-.9107-1.3113-.3279h-.1822v.1093l1.0929 1.0686 2.0035 1.8092 2.5075 2.3314.1275.5768-.3218.4554-.34-.0486-2.2039-1.6575-.85-.7468-1.9246-1.621h-.1275v.17l.4432.6496 2.3436 3.5214.1214 1.0807-.17.3521-.6071.2125-.6679-.1214-1.3721-1.9246L14.38 17.959l-1.1414-1.9428-.1397.079-.674 7.2552-.3156.3703-.7286.2793-.6071-.4614-.3218-.7468.3218-1.4753.3886-1.9246.3157-1.53.2853-1.9004.17-.6314-.0121-.0425-.1397.0182-1.4328 1.9672-2.1796 2.9446-1.7243 1.8456-.4128.164-.7164-.3704.0667-.6618.4008-.5889 2.386-3.0357 1.4389-1.882.929-1.0868-.0062-.1579h-.0546l-6.3385 4.1164-1.1293.1457-.4857-.4554.0608-.7467.2307-.2429 1.9064-1.3114Z`,openai:`M22.2819 9.8211a5.9847 5.9847 0 0 0-.5157-4.9108 6.0462 6.0462 0 0 0-6.5098-2.9A6.0651 6.0651 0 0 0 4.9807 4.1818a5.9847 5.9847 0 0 0-3.9977 2.9 6.0462 6.0462 0 0 0 .7427 7.0966 5.98 5.98 0 0 0 .511 4.9107 6.051 6.051 0 0 0 6.5146 2.9001A5.9847 5.9847 0 0 0 13.2599 24a6.0557 6.0557 0 0 0 5.7718-4.2058 5.9894 5.9894 0 0 0 3.9977-2.9001 6.0557 6.0557 0 0 0-.7475-7.0729zm-9.022 12.6081a4.4755 4.4755 0 0 1-2.8764-1.0408l.1419-.0804 4.7783-2.7582a.7948.7948 0 0 0 .3927-.6813v-6.7369l2.02 1.1686a.071.071 0 0 1 .038.052v5.5826a4.504 4.504 0 0 1-4.4945 4.4944zm-9.6607-4.1254a4.4708 4.4708 0 0 1-.5346-3.0137l.142.0852 4.783 2.7582a.7712.7712 0 0 0 .7806 0l5.8428-3.3685v2.3324a.0804.0804 0 0 1-.0332.0615L9.74 19.9502a4.4992 4.4992 0 0 1-6.1408-1.6464zM2.3408 7.8956a4.485 4.485 0 0 1 2.3655-1.9728V11.6a.7664.7664 0 0 0 .3879.6765l5.8144 3.3543-2.0201 1.1685a.0757.0757 0 0 1-.071 0l-4.8303-2.7865A4.504 4.504 0 0 1 2.3408 7.872zm16.5963 3.8558L13.1038 8.364 15.1192 7.2a.0757.0757 0 0 1 .071 0l4.8303 2.7913a4.4944 4.4944 0 0 1-.6765 8.1042v-5.6772a.79.79 0 0 0-.407-.667zm2.0107-3.0231l-.142-.0852-4.7735-2.7818a.7759.7759 0 0 0-.7854 0L9.409 9.2297V6.8974a.0662.0662 0 0 1 .0284-.0615l4.8303-2.7866a4.4992 4.4992 0 0 1 6.6802 4.66zM8.3065 12.863l-2.02-1.1638a.0804.0804 0 0 1-.038-.0567V6.0742a4.4992 4.4992 0 0 1 7.3757-3.4537l-.142.0805L8.704 5.459a.7948.7948 0 0 0-.3927.6813zm1.0976-2.3654l2.602-1.4998 2.6069 1.4998v2.9994l-2.5974 1.4997-2.6067-1.4997Z`,x:`M14.234 10.162 22.977 0h-2.072l-7.591 8.824L7.251 0H.258l9.168 13.343L.258 24H2.33l8.016-9.318L16.749 24h6.993zm-2.837 3.299-.929-1.329L3.076 1.56h3.182l5.965 8.532.929 1.329 7.754 11.09h-3.182z`,slack:`M5.042 15.165a2.528 2.528 0 0 1-2.52 2.523A2.528 2.528 0 0 1 0 15.165a2.527 2.527 0 0 1 2.522-2.52h2.52v2.52zM6.313 15.165a2.527 2.527 0 0 1 2.521-2.52 2.527 2.527 0 0 1 2.521 2.52v6.313A2.528 2.528 0 0 1 8.834 24a2.528 2.528 0 0 1-2.521-2.522v-6.313zM8.834 5.042a2.528 2.528 0 0 1-2.521-2.52A2.528 2.528 0 0 1 8.834 0a2.528 2.528 0 0 1 2.521 2.522v2.52H8.834zM8.834 6.313a2.528 2.528 0 0 1 2.521 2.521 2.528 2.528 0 0 1-2.521 2.521H2.522A2.528 2.528 0 0 1 0 8.834a2.528 2.528 0 0 1 2.522-2.521h6.312zM18.956 8.834a2.528 2.528 0 0 1 2.522-2.521A2.528 2.528 0 0 1 24 8.834a2.528 2.528 0 0 1-2.522 2.521h-2.522V8.834zM17.688 8.834a2.528 2.528 0 0 1-2.523 2.521 2.527 2.527 0 0 1-2.52-2.521V2.522A2.527 2.527 0 0 1 15.165 0a2.528 2.528 0 0 1 2.523 2.522v6.312zM15.165 18.956a2.528 2.528 0 0 1 2.523 2.522A2.528 2.528 0 0 1 15.165 24a2.527 2.527 0 0 1-2.52-2.522v-2.522h2.52zM15.165 17.688a2.527 2.527 0 0 1-2.52-2.523 2.526 2.526 0 0 1 2.52-2.52h6.313A2.527 2.527 0 0 1 24 15.165a2.528 2.528 0 0 1-2.522 2.523h-6.313z`,github:`M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12`,whatsapp:`M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z`},ng={fx:{background:`#000000`,mark:{path:`M237.892 0C243.178 8.73262e-05 249.383 1.41857 253.025 3.07422L255.093 4.01367L250.076 18.6299L247.677 17.7461C244.901 16.7234 241.938 15.7998 238.491 15.7998C234.984 15.7998 232.787 16.5601 231.08 18.3213C229.231 20.2297 227.629 23.6395 226.229 29.7578L226.227 29.7617L226.228 29.7627L225.136 34.8506H241.669L260.432 34.9502L260.694 34.9512L260.842 35.1689L278.854 61.6328L296.736 34.9502H320.866L291.676 76.7402L322.102 119.75H299.331L299.182 119.546L241.144 40.4775L239.35 49.4004H222.069L205.688 127.208C203.927 135.709 201.185 142.838 196.777 147.866C192.27 153.008 186.201 155.75 178.342 155.75C174.181 155.75 170.746 155.109 167.909 154.107L166.241 153.519V137.182L166.899 137.4L169.531 138.278C172.182 139.162 174.414 139.8 177.142 139.8C178.528 139.8 179.703 139.526 180.732 138.98C181.764 138.434 182.677 137.6 183.52 136.442C185.304 133.989 186.716 130.135 187.897 124.672L203.76 49.4004H189.874L191.759 39.4375L192.039 39.3457L206.818 34.4668L208.154 28.6416C210.516 18.2065 213.772 10.9381 218.708 6.31836C223.737 1.61217 230.127 3.08752e-05 237.892 0ZM273.987 99.084L260.073 120.25H234.541L261.003 82.0215L273.987 99.084Z`,transform:`scale(0.71111) translate(34 33.95) scale(0.7186) translate(-166.241 0)`}},claude:{background:`#D97757`,mark:{path:tg.claude}},codex:{background:`#000000`,mark:{path:tg.openai}},grok:{background:`#000000`,mark:{path:tg.x}},pi:{background:`#1f1f1f`,mark:{glyph:`π`}}};function rg(e){let t=ng[e]??{background:`#666666`,mark:{glyph:e.slice(0,1).toUpperCase()}},n=`path`in t.mark?`<path transform="${t.mark.transform??`translate(30 30) scale(2.8333)`}" fill="#ffffff" d="${t.mark.path}"/>`:`<text x="64" y="86" font-family="ui-sans-serif,system-ui,sans-serif" font-size="66" font-weight="600" text-anchor="middle" fill="#ffffff">${t.mark.glyph}</text>`;return`<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128" viewBox="0 0 128 128"><rect width="128" height="128" rx="28" fill="${t.background}"/>${n}</svg>`}var ig=class extends q{responses;constructor(e){super(422,`dropped`,e.join(`
|
|
348
348
|
`)||`the board dropped this message`),this.responses=e}};const ag=K({text:G().max(xu).optional(),labels:Mu.optional()}).strict();async function og(e,t,n){let r=[],i=null,a=async(o,s)=>{if(o===e.length){if(s.text.trim()===``&&(s.kind===`edit`||s.attachments.length===0))return;i={value:await n(s)};return}let c=null;await e[o]({write:Object.freeze({...s}),author:Object.freeze({...t.author}),source:Object.freeze({...t.source}),board:t.board(),respond:async e=>{r.push(e)},next:(e={})=>{if(c)throw Error(`next() was already called`);let{text:t,labels:n}=ag.parse(e);return c=a(o+1,{...s,...t===void 0?{}:{text:t},...s.kind===`post`&&n?{labels:{...s.labels,...n}}:{}}),c}}),c&&await c};if(await a(0,t.write),!i)throw new ig(r);return i.value}const sg=e=>typeof e==`string`?{target:e,kind:Ju(e)?`thread`:`channel`}:e,cg=/* @__PURE__ */ new Set([`post`,`schedule`,`upload`,`uploadFinish`]),lg=/^(image\/(png|jpeg|gif|webp|avif)|video\/(mp4|webm)|text\/plain)$/;function ug({attachment:e,data:t}){let n=lg.test(e.type)?`inline`:`attachment`,r=t instanceof Uint8Array?new Blob([t]):t;return new Response(r,{headers:{"content-type":e.type,"content-length":String(e.size),"content-disposition":`${n}; filename*=UTF-8''${encodeURIComponent(e.name)}`,"content-security-policy":`sandbox; default-src 'none'`,"x-content-type-options":`nosniff`,"cache-control":`private, max-age=31536000, immutable`}})}async function dg(e,t,n,r){let i=r.id??``,a=r.key??``,o=()=>Gf(t);switch(e){case`discovery`:case`me`:case`channels`:case`actors`:case`watchers`:case`grants`:case`schemas`:return{};case`message`:case`posted`:case`synced`:case`cancelSchedule`:case`revokeGrant`:case`schema`:case`attachment`:case`uploadFinish`:return{id:i};case`messages`:return id.parse(Wf(n));case`threads`:return ad.parse(Wf(n));case`schedules`:return dd.parse(Wf(n));case`matches`:return Td.parse(Wf(n));case`events`:{let e=od.parse(Wf(n)),r=t.headers.get(`last-event-id`);return e.after===void 0&&r&&Xu.safeParse(r).success&&(e.after=r),e}case`post`:return sd.parse(await o());case`createChannel`:return Yd.parse(await o());case`schedule`:return ud.parse(await o());case`createGrant`:return _d.parse(await o());case`updateGrant`:return{id:i,...yd.parse(await o())};case`explain`:return vd.parse(Wf(n));case`createSchema`:return bd.parse(await o());case`register`:return wd.parse(await o());case`edit`:return{id:i,...Gd.parse(await o())};case`delete`:return{id:i,...Kd.parse(await o())};case`react`:return{id:i,...Jd.parse(await o())};case`label`:return{id:i,...Xd.parse(await o())};case`ack`:return{id:i,...Ed.parse(await o())};case`upload`:{let e=t.headers.get(`x-board-filename`),n=null;try{n=e===null?null:decodeURIComponent(e)}catch{throw kf("`x-board-filename` is not URI-encoded")}return{data:await qf(t,ke),name:n,type:t.headers.get(`content-type`)}}case`uploadStart`:return Wd.parse(await o());case`syncImport`:return Id.parse(await o());case`syncReceipt`:return Rd.parse(await o());case`syncThread`:return{thread:r.thread??``};case`syncFind`:return zd.parse(Wf(n));case`syncCopies`:return Bd.parse(Wf(n));case`inboxPush`:return{key:a,...Vd.parse(await o())};case`inboxNext`:return{key:a,...Hd.parse(Wf(n))};case`inboxAck`:return{key:a,id:i,...Ud.parse(await o())};case`inbox`:return{key:a,...Sd.parse(Wf(n))};case`typing`:return{id:i,...qd.parse(await o())??{}};case`readSource`:return{key:a,...Dd.parse(Wf(n))};case`joinSource`:return{key:a,...Od.parse(await o())};case`linked`:return kd.parse(Wf(n))}}const fg=(e,t)=>{let n=t.principal===`board:sync`;return{id:n?e.id:`${t.principal}+${e.id}`,kind:`external`,handle:n?e.handle:at(Mh({id:t.principal,handle:t.actor.handle}).name,e.handle,it(e.id)),name:e.name,avatar:e.avatar}};function pg(e){let t=e.origin.via;return t?.kind===`middleware`||t?.kind===`engine`?null:t??{kind:`api`}}const mg={self:`middleware`,origin:{via:{kind:`middleware`}}},hg={self:null,origin:{via:{kind:`client`,name:null}}};async function gg(e){let{options:t,backend:n,runtime:r,policy:i}=e,a=t.sync??{},o=Object.keys(a).length>0?(await r.sync()).createSyncEngine(a):null,s=t.streamMaxMs??28e4,c=Uf(n.routes,t.basePath),{state:l,ownUrl:u,clientAs:d,handleOf:f}=e,p=t.watch??{},m=t.middleware??[];function h(e,t){return{credential:(e.headers.get(`authorization`)??``).match(/^Bearer\s+(.+)$/i)?.[1]??null,claims:kh(e.headers),audience:t,headers:e.headers}}async function g(e){return{identity:await i.identify(e),origin:{via:{kind:`api`}}}}let _=()=>new q(404,`not_found`,`${u()??`this board`} answers ${n.routes.length>0||o?`only wake-ups and webhooks`:`nothing itself`}`);async function v(e){if(typeof e!=`string`)return e;let t=e.indexOf(`:`);if(t<=0)throw kf(`sync targets look like <key>:<channel or thread>, got: ${e}`);let n=e.slice(0,t);if(o&&a[n])return o.normalizeTarget(e);if(o)throw kf(`no sync entry named ${n}`);return sg(e)}let y=e=>`identity`in e?e.identity.principal.access:e.can===void 0?null:Up.narrow(Xp(e.can)),b=e=>`identity`in e?e.identity.principal.scope!==void 0:e.can!==void 0;async function x(e,t,n){let r=y(e);if(r===null)return{access:null,channel:t.channel??``};let i=t.channel??(t.re===void 0?void 0:(await R(e,t.re,n))?.channel);return i===void 0?null:r.can(`post`,i)?{access:r,channel:i}:null}let S=/* @__PURE__ */ new Map;async function C(e,t){if(`identity`in e)return{principal:e.identity.principal.id,actor:e.identity.actor};let r=JSON.stringify([e.origin.via?.kind??``,e.self,e.profile??null]),i=S.get(r);return i||(S.set(r,i=n.me(e,{},t).then(e=>({principal:e.principal,actor:{id:e.actor,kind:e.kind,handle:e.handle,name:e.name,avatar:e.avatar}}))),i.catch(()=>S.delete(r))),i}let w=/* @__PURE__ */ new Map;async function T(e){if(e.includes(`json#`))for(let t of Ze(e)){if(t.problem!==void 0)throw kf(t.problem,`invalid_block`);let e=w.get(t.id);e||(e=n.schema(hg,{id:t.id},new AbortController().signal).then(({schema:e})=>e.schema),w.set(t.id,e),e.catch(()=>w.delete(t.id)));let r=$h(await e.catch(e=>{throw e instanceof q&&e.status===404?kf(`the ${t.id} block names a schema this board doesn't have`,`schema_not_found`):e}),t.data);if(r!==null)throw kf(`the ${t.id} block doesn't match its schema: ${r}`,`invalid_block`)}}async function E(e,t,n,r){if(!t.includes(`json#`))return;let i=y(e);if(i!==null){let t=`channel`in n?n.channel:(await R(e,n.message,r))?.channel;if(t!==void 0&&!i.can(`post`,t))return}await T(t)}let D=null,O=(e,t,n,r)=>og(m,{write:e,author:t,source:n,board:()=>D??=f(mg,null)},r);async function k(e){try{return await e(),!0}catch(e){if(e instanceof q&&e.status===404)return!1;throw e}}async function A(e,t,r){let i=[];for(let a of new Set(t??[])){let{attachment:t,data:o}=await n.attachment(e,{id:a},r);o instanceof ReadableStream&&await o.cancel().catch(()=>{}),i.push(t)}return i}async function j(e,t,r,i){let a=pg(e);if(m.length===0||a===null||t.id!==void 0&&await k(()=>n.posted(e,{id:t.id},r)))return i(t);let o=t.channel,s=null;if(t.re!==void 0){let n=await R(e,t.re,r);if(!n)return i(t);o=n.channel,s=n.re??n.id}let c=y(e),l=Object.keys(t.labels??{}).length>0,u=t.re===void 0&&(t.sync?.length??0)>0;if(o===void 0||c&&(!c.can(`post`,o)||l&&!c.can(`label`,o)||u&&!c.can(`sync`,o)))return i(t);let d=await A(e,t.attachments,r),{actor:f}=await C(e,r);return O({kind:`post`,channel:o,re:s,text:t.text,labels:t.labels??{},attachments:d},f,a,e=>i({...t,text:e.text,labels:e.labels}))}function M(e,t,r){let{channel:i,re:a,text:o,labels:s,noSync:c,attachments:l}=t;return j(e,{...i===void 0?{}:{channel:i},...a===void 0?{}:{re:a},text:o,...s?{labels:s}:{},...c===void 0?{}:{noSync:c},...l?{attachments:l}:{}},r,async i=>(i.text!==o&&await T(i.text),n.schedule(e,{...t,text:i.text,...i.labels?{labels:i.labels}:{}},r)))}async function N(e,t,n){let r=y(e),i=await R(e,t,n),a=i??(r===null?null:await R(hg,t,n));return!a||a.deleted||r&&!r.can(`post`,a.channel)||!i&&!a.blind?null:a.by.principal===(await C(e,n)).principal?a:null}async function P(e,t,n,r){let i=pg(e);if(m.length===0||i===null)return r(t);let a=await N(e,t.id,n);if(!a)return r(t);let{actor:o}=await C(e,n);return O({kind:`edit`,id:a.id,channel:a.channel,re:a.re,text:t.text},o,i,e=>r({...t,text:e.text}))}async function F(e,t,r,i){let o=t.source?.key??t.from;if(t.source&&!(`identity`in e?(await n.watchers(e,{},i)).watchers.some(t=>t.owner===e.identity.principal.id&&t.sync.some(e=>e.key===o)):a[t.source.key]!==void 0))return null;let s=(t.op===`post`?t.origin:null)??r?.origin??null;return{kind:`sync`,key:o??``,platform:t.author.id.slice(0,Math.max(0,t.author.id.indexOf(`:`))),channel:t.source?.channel??r?.origin?.channel??s?.channel??``,thread:t.source?.thread??(s?s.subthread??s.thread:``)}}async function I(e,t,r){let i=t.message??null;if(t.origin!==void 0){let{thread:a,message:o}=await n.syncFind(e,{thread:t.origin.thread,...t.origin.message===void 0?{}:{message:t.origin.message}},r);i=t.origin.message===void 0?a===null?null:(await n.syncThread(e,{thread:a},r)).root:o}return i===null?null:R(e,i,r)}async function L(e,t,r){let i=(t.op===`post`||t.op===`edit`)&&t.from===null?t.text:null;i!==null&&await T(i);let a=async t=>(i!==null&&(t.op===`post`||t.op===`edit`)&&t.text!==i&&await T(t.text),n.syncImport(e,t,r));if(m.length===0||e.origin.via?.kind===`middleware`||t.op!==`post`&&t.op!==`edit`)return a(t);let o=y(e);if(o&&(!o.anywhere(`sync`)||b(e)))return a(t);let s=async e=>{try{return await e()}catch(e){if(!(e instanceof ig))throw e;return{message:null,dropped:[...e.responses]}}};if(t.op===`post`){if(t.id!==void 0&&(await n.syncFind(e,{post:t.id},r)).message!==null)return a(t);let i=t.channel,c=null;if(t.re!==void 0){let n=await R(e,t.re,r);if(!n)return a(t);i=n.channel,c=n.re??n.id}if(i===void 0||o&&!o.can(`sync`,i))return a(t);let l=await F(e,t,null,r);if(!l)return a(t);let u=await A(e,t.attachments,r),d=fg(t.author,await C(e,r));return s(async()=>O({kind:`post`,channel:i,re:c,text:t.text,labels:t.labels??{},attachments:u},d,l,async e=>a({...t,text:e.text,labels:e.labels})))}if(t.origin===void 0==(t.message===void 0))return a(t);let c=await I(e,t,r),l=fg(t.author,await C(e,r)),u=c!==null&&(c.by.actor===l.id||c.by.actor===t.author.id);if(!c||c.deleted||o&&!o.can(`sync`,c.channel)||t.message!==void 0&&!u)return a(t);let d=await F(e,t,c,r);return d?s(async()=>O({kind:`edit`,id:c.id,channel:c.channel,re:c.re,text:t.text},l,d,async e=>a({...t,text:e.text}))):a(t)}async function R(e,t,r){try{let{message:i,replies:a}=await n.message(e,{id:t},r);return[i,...a].find(e=>e.id===t)??null}catch(e){if(e instanceof q&&e.status===404)return null;throw e}}async function ee(e,t,r){await E(e,t.text,t.channel===void 0?{message:t.re}:{channel:t.channel},r);let i=(e,i)=>j(e,i,r,async i=>(i.text!==t.text&&await T(i.text),n.post(e,i,r)));if(!o)return i(e,t.sync?.length?{...t,sync:await Promise.all(t.sync.map(v))}:t);let a=t.sync?.length?await x(e,t,r):null;if(!a)return i(e,t);let{access:s,channel:c}=a;return i(e,t.re===void 0&&(s===null||s.can(`sync`,c))?{...t,sync:await Promise.all(t.sync.map(v))}:t)}async function te(e,t){if(!t.dropped)return t.message;for(let n of t.dropped)await e.platform.respond(n);throw new ig(t.dropped)}async function ne(e,t,n,r){let i=o.caller,{author:a,key:s}=t.platform,{via:c}=t.origin,l={key:s,channel:c.channel,thread:c.thread},u=async e=>{if(await te(t,await L(i,e,r))===null)throw Mf(`message not found: #${e.message}`,`message_not_found`);return{ok:!0}};switch(e){case`post`:return re(t,n,r);case`edit`:{let{id:e,text:t,revision:r}=n;return u({op:`edit`,author:a,from:null,message:e,text:t,source:l,...r===void 0?{}:{revision:r}})}case`delete`:{let{id:e,revision:t}=n;return u({op:`delete`,author:a,from:null,message:e,...t===void 0?{}:{revision:t}})}case`react`:{let{id:e,emoji:t,remove:r}=n;return u({op:`react`,author:a,from:null,message:e,emoji:t,...r===void 0?{}:{remove:r}})}case`label`:{let{id:e,set:t,unset:r,if:i}=n;return u({op:`labels`,author:a,from:null,message:e,...t?{set:t}:{},...r?{unset:r}:{},...i?{if:i}:{}})}default:return ie(e,i,n,r)}}async function re(e,t,r){let i=o.caller,{author:a,key:s}=e.platform,{via:c}=e.origin,l=async e=>{let t=await R(i,e,r);if(!t)throw Mf(`message not found: #${e}`,`message_not_found`);return t};if(t.id!==void 0){let e=(await n.syncFind(i,{post:t.id},r)).message;if(e!==null)return{message:await l(e)}}let u=await Promise.all((t.sync??[]).map(v)),d=await te(e,await L(i,{op:`post`,author:a,from:null,origin:null,source:{key:s,channel:c.channel,thread:c.thread},...t.channel===void 0?{re:t.re}:{channel:t.channel},text:t.text,...t.labels?{labels:t.labels}:{},...t.noSync?{noSync:!0}:{},...t.attachments?.length?{attachments:t.attachments}:{},...t.id===void 0?{}:{id:t.id},...t.after===void 0?{}:{after:t.after}},r));for(let e of u)await n.syncReceipt(i,{kind:`thread`,message:d,target:e.target,targetKind:e.kind,cause:`request`},r);return{message:await l(d)}}async function ie(e,t,r,i){switch(e){case`post`:return ee(t,r,i);case`edit`:{let e=r;return await E(t,e.text,{message:e.id},i),P(t,e,i,async r=>(r.text!==e.text&&await T(r.text),n.edit(t,r,i)))}case`syncImport`:return L(t,r,i);case`schedule`:{let e=r;return await E(t,e.text,e.channel===void 0?{message:e.re}:{channel:e.channel},i),n.sendsSchedulesHere===!1?M(t,e,i):n.schedule(t,e,i)}case`inbox`:{let e=r;if(o&&a[e.key]&&e.channel!==void 0){let r=y(t);if(r===null||r.anywhere(`sync`))return n.inbox(t,{...e,channel:await o.inboxChannel(e.key,e.channel)},i)}return n.inbox(t,e,i)}default:{let a=n[e];if(typeof a!=`function`)throw Mf(`no route: ${e}`);return a.call(n,t,r,i)}}}async function ae(e,t,r,i,a){let s=r.signal;switch(e){case`sync`:{let e=xd.parse(await Gf(r)),i=a.id??``,c=y(t);if(c&&o){let e=await R(t,i,s);if(!e)throw Mf(`message not found: #${i}`,`message_not_found`);if(!c.can(`sync`,e.channel))throw jf(`this token can't sync in ${e.channel}`)}let l=await v(e.target),{attached:u}=await n.syncReceipt(t,{kind:`thread`,message:i,target:l.target,targetKind:l.kind,cause:`request`},s);return Ff({target:l.target,attached:u??!0})}default:throw Mf(`no route: ${r.method} ${i.pathname}`)}}let oe=Object.fromEntries(Bf.map(e=>[e,e===`syncImport`?L:(t,r,i)=>n[e].call(n,t,r,i)]));o?.bind({backend:oe,client:(e,t)=>d({platform:{author:e.author,key:e.key,respond:e.respond},origin:{via:e.via}},t),syncedHere:async e=>!n.syncedHere||n.syncedHere(e)});async function se(e,t,r,i){let a=await n.events(e,{...t,wait:0},r.signal),o=new TextEncoder,c=new AbortController,l=Date.now()+s,u=AbortSignal.any([r.signal,c.signal,AbortSignal.timeout(s)]),d=new ReadableStream({async start(r){let s=e=>{try{r.enqueue(o.encode(e))}catch{}},c=setInterval(()=>s(`: ping
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { h as ATTACHMENT_BYTES_MAX } from "./errors-DUzpDSrJ.mjs";
|
|
2
2
|
import "./schemas-DAzSsgWk.mjs";
|
|
3
|
-
import { t as Failed, u as who } from "./main-
|
|
4
|
-
import { t as page } from "./page-
|
|
3
|
+
import { t as Failed, u as who } from "./main-C4HVA8cc.mjs";
|
|
4
|
+
import { t as page } from "./page-CnjVt5w2.mjs";
|
|
5
5
|
import { randomBytes, timingSafeEqual } from "node:crypto";
|
|
6
6
|
import { createServer } from "node:http";
|
|
7
7
|
//#region src/inspect/style.ts
|
|
@@ -420,7 +420,7 @@ button.file:hover { background: var(--shade-hover); color: var(--bright); }
|
|
|
420
420
|
.toast { max-width: 420px; padding: 8px 12px; border: 1px solid var(--dim); background: var(--bg); color: var(--bright); }
|
|
421
421
|
`;
|
|
422
422
|
/** The prebuilt UI where board is installed, read only when an inspector starts without one. */
|
|
423
|
-
const bundle = async () => (await import("./page-
|
|
423
|
+
const bundle = async () => (await import("./page-BPTzCBeW.mjs")).page();
|
|
424
424
|
const shell = (token) => `<!doctype html>
|
|
425
425
|
<html lang="en">
|
|
426
426
|
<head>
|
|
@@ -620,8 +620,8 @@ async function pageOf(provided) {
|
|
|
620
620
|
if (found === null) throw new Failed({
|
|
621
621
|
class: "unknown",
|
|
622
622
|
reason: "no_inspector_page",
|
|
623
|
-
message: "The inspector's page isn't
|
|
624
|
-
next: [{ instruction: "
|
|
623
|
+
message: "The inspector's page isn't installed with this CLI.",
|
|
624
|
+
next: [{ instruction: "Reinstall or update the CLI" }]
|
|
625
625
|
});
|
|
626
626
|
return found;
|
|
627
627
|
}
|
|
@@ -2,7 +2,7 @@ import { _ as IMPORT_BYTES_MAX, a as forbidden$1, b as mediaType, c as toErrorRe
|
|
|
2
2
|
import { _ as actorKind, a as CAN_MAX, b as storable, c as Handle, d as Labels, g as SeenActorKind, h as RemoteWatcherId, i as Author, l as LabelKey, m as MessageText, n as Attachment, o as ChannelPath, p as MessageId, s as Emoji, t as ActorId, v as authorView, y as platformAvatar } from "./schemas-DAzSsgWk.mjs";
|
|
3
3
|
import { a as Link, i as ExternalTarget, n as ExternalEvent, o as Origin } from "./external-DymyhUzl.mjs";
|
|
4
4
|
import { a as SCHEMA_DESCRIPTION_MAX, c as canonical, d as parseSchemaId, f as schemaId, i as BUILT_IN_SCHEMAS, l as checkDefinition, n as blocksIn, o as SCHEMA_NAME, s as SCHEMA_VERSION_MAX, u as isBuiltInName } from "./blocks-CVoBC7ur.mjs";
|
|
5
|
-
import { a as compileWatcher, c as METHODS, h as VERSION, i as runMatch, m as SYNC, n as syncTarget, o as hasCriteria, r as canonicalWatchers, t as SYNC_ACTOR } from "./origin-
|
|
5
|
+
import { a as compileWatcher, c as METHODS, h as VERSION, i as runMatch, m as SYNC, n as syncTarget, o as hasCriteria, r as canonicalWatchers, t as SYNC_ACTOR } from "./origin-Cuu8lW8n.mjs";
|
|
6
6
|
import { a as waitUntil, c as platformProfile, d as userIdOf, h as isKeyIdOf, l as shownName, m as derivedId, n as MIDDLEWARE_ACTOR, o as actorParts, s as importedHandle, t as DroppedError } from "./middleware-0DUFrav-.mjs";
|
|
7
7
|
import { c as compileAccess, i as authorize, o as checkGrantChange, t as FULL_ACCESS, u as parseCan } from "./access-BgBiaCyx.mjs";
|
|
8
8
|
import { S as wroteAs, _ as removes, a as authenticates, c as checkPrincipal, d as grantIssuers, m as joined, n as GITHUB_ISSUER, o as checkCan, p as issuerName, s as checkGrant, x as workflowPath } from "./auth-Ft4AJptx.mjs";
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { g as DIRECT_UPLOAD_BYTES_MAX, u as BoardError, y as fileSize } from "./errors-DUzpDSrJ.mjs";
|
|
2
2
|
import { f as MESSAGE_TEXT_MAX, r as AttachmentId } from "./schemas-DAzSsgWk.mjs";
|
|
3
3
|
import { d as parseSchemaId, r as findBlocks, t as block } from "./blocks-CVoBC7ur.mjs";
|
|
4
|
-
import { h as VERSION, s as withMentions } from "./origin-
|
|
4
|
+
import { h as VERSION, s as withMentions } from "./origin-Cuu8lW8n.mjs";
|
|
5
5
|
import { n as displayEmoji, r as normalizeEmoji } from "./emoji-CTLpvH-A.mjs";
|
|
6
6
|
import { l as shownName } from "./middleware-0DUFrav-.mjs";
|
|
7
7
|
import { r as PERMISSIONS } from "./access-BgBiaCyx.mjs";
|
|
8
|
-
import { a as isApiMessageId, n as isBoardName } from "./exports-
|
|
9
|
-
import { i as groups, n as filters$1, o as options, r as globalOptions, s as usage$1, t as commands } from "./commands-
|
|
10
|
-
import { a as vercel, c as connect, i as handTeam, l as handFetch, n as credentialSource, o as http, p as vercelProjectFile, r as credentialed, s as boardUrl, t as board, u as handLogin } from "./server-
|
|
8
|
+
import { a as isApiMessageId, n as isBoardName } from "./exports-kDMIgZVu.mjs";
|
|
9
|
+
import { i as groups, n as filters$1, o as options, r as globalOptions, s as usage$1, t as commands } from "./commands-DeEJJw3i.mjs";
|
|
10
|
+
import { a as vercel, c as connect, i as handTeam, l as handFetch, n as credentialSource, o as http, p as vercelProjectFile, r as credentialed, s as boardUrl, t as board, u as handLogin } from "./server-CKbE7eMT.mjs";
|
|
11
11
|
import { t as conformance } from "./conformance-BORt5nky.mjs";
|
|
12
12
|
import { t as displayText } from "./bots-CGkO76qH.mjs";
|
|
13
13
|
import { spawn } from "node:child_process";
|
|
@@ -1140,6 +1140,39 @@ function parse(argv) {
|
|
|
1140
1140
|
} catch (error) {
|
|
1141
1141
|
throw parseFailure(error, argv, word);
|
|
1142
1142
|
}
|
|
1143
|
+
const known = specOf(word) && new Set(optionsOf(word));
|
|
1144
|
+
const foreign = known && ordered.find((option) => !known.has(option.name));
|
|
1145
|
+
if (foreign) throw foreignOption(foreign.name, word);
|
|
1146
|
+
}
|
|
1147
|
+
/** An option `word` doesn't take: what to do instead, where there's something better to say than that. */
|
|
1148
|
+
function foreignOption(name, word) {
|
|
1149
|
+
if (name === "text" && TEXT.has(word)) return usage(`--text is a filter for read, tail, and wait. ${word} takes its text as an argument, in quotes.`);
|
|
1150
|
+
if (name === "sync" && word === "schedule") return usage("Can't use --sync with schedule. A schedule posts where you point it.");
|
|
1151
|
+
if (name === "attach" && word === "edit") return usage("edit can't attach files: reply with the file instead.", {
|
|
1152
|
+
reason: "unknown_option",
|
|
1153
|
+
next: [{
|
|
1154
|
+
instruction: "Reply with it",
|
|
1155
|
+
argv: [
|
|
1156
|
+
...cli(),
|
|
1157
|
+
"reply",
|
|
1158
|
+
"<ID>",
|
|
1159
|
+
"<TEXT>",
|
|
1160
|
+
"--attach",
|
|
1161
|
+
"<FILE>"
|
|
1162
|
+
]
|
|
1163
|
+
}]
|
|
1164
|
+
});
|
|
1165
|
+
return usage(`Unknown option --${name} for ${named()} ${word}.`, {
|
|
1166
|
+
reason: "unknown_option",
|
|
1167
|
+
next: [{
|
|
1168
|
+
instruction: "See all options",
|
|
1169
|
+
argv: [
|
|
1170
|
+
...cli(),
|
|
1171
|
+
word,
|
|
1172
|
+
"--help"
|
|
1173
|
+
]
|
|
1174
|
+
}]
|
|
1175
|
+
});
|
|
1143
1176
|
}
|
|
1144
1177
|
/** What the parser rejected, as misuse: an unknown option (with the likeliest one meant), or an option without its value. */
|
|
1145
1178
|
function parseFailure(error, argv, word) {
|
|
@@ -1187,8 +1220,10 @@ function parseFailure(error, argv, word) {
|
|
|
1187
1220
|
return usage(sentence(error.message));
|
|
1188
1221
|
}
|
|
1189
1222
|
/** The options `word`'s command takes, its subcommands' and the filters included, and the ones every command takes. */
|
|
1223
|
+
/** The command `word` names, board's or the app's, as help shows it. */
|
|
1224
|
+
const specOf = (word) => word === void 0 ? void 0 : [...commands, ...Object.values(app.commands).map((own) => own.spec)].find((known) => known.name === word);
|
|
1190
1225
|
function optionsOf(word) {
|
|
1191
|
-
const command =
|
|
1226
|
+
const command = specOf(word);
|
|
1192
1227
|
return [...command ? [command, ...command.subcommands ?? []].flatMap((c) => [...c.options, ...c.filters ? filters$1 : []]) : [], ...globalOptions].map((option) => option.name);
|
|
1193
1228
|
}
|
|
1194
1229
|
/** `text` as a sentence: a capital first, and a period last. */
|
|
@@ -1259,7 +1294,6 @@ function labelPairs(values, wrong = "Labels look like key=value, and {value} isn
|
|
|
1259
1294
|
* and would be dropped without a word: say so, and how each is written.
|
|
1260
1295
|
*/
|
|
1261
1296
|
function oneText(command, target, extra) {
|
|
1262
|
-
if (flags.text !== void 0) throw usage(`--text is a filter for read, tail, and wait. ${command} takes its text as an argument, in quotes.`);
|
|
1263
1297
|
const [first] = extra;
|
|
1264
1298
|
if (first === void 0) return;
|
|
1265
1299
|
if (/^[\w.-]+=/.test(first)) throw usage(`${first} looks like a label, and ${command} takes labels with --label.`, { next: [{
|
|
@@ -1587,7 +1621,6 @@ function failureOf(error) {
|
|
|
1587
1621
|
case "invalid_duration": return own("usage", "invalid_arguments", [helpRecovery()]);
|
|
1588
1622
|
case "wrong_audience":
|
|
1589
1623
|
case "redirected": return own("usage", "wrong_url");
|
|
1590
|
-
case "renamed_env": return own("usage", "renamed_env");
|
|
1591
1624
|
case "too_large": return {
|
|
1592
1625
|
...own("limit", "payload_too_large"),
|
|
1593
1626
|
message: `Can't ${doing()}. ${sentence(message)}`
|
|
@@ -2131,7 +2164,6 @@ async function run(command, args) {
|
|
|
2131
2164
|
const [target, body] = args;
|
|
2132
2165
|
if (!target) throw usage("Missing the channel or message to schedule a message in.", { reason: "missing_arguments" });
|
|
2133
2166
|
if (!flags.in && !flags.at && !flags.every) throw usage("Can't schedule a message without a time: pass --in 1d, --at <time>, or --every 30m.", { reason: "missing_arguments" });
|
|
2134
|
-
if (flags.sync?.length) throw usage("Can't use --sync with schedule. A schedule posts where you point it.");
|
|
2135
2167
|
const times = flags.times === void 0 ? void 0 : Number(flags.times);
|
|
2136
2168
|
if (times !== void 0 && !(Number.isInteger(times) && times > 0)) throw usage(`--times takes a count, and ${flags.times} isn't one.`);
|
|
2137
2169
|
const board = client();
|
|
@@ -2533,7 +2565,7 @@ async function run(command, args) {
|
|
|
2533
2565
|
}
|
|
2534
2566
|
return 0;
|
|
2535
2567
|
}
|
|
2536
|
-
case "inspect": return (await import("./inspect-
|
|
2568
|
+
case "inspect": return (await import("./inspect-CNW1rLWB.mjs")).inspect(context());
|
|
2537
2569
|
default: {
|
|
2538
2570
|
const own = app.commands[command];
|
|
2539
2571
|
if (own) return own.run(args, context());
|
|
@@ -3,7 +3,7 @@ import { b as storable, d as Labels, f as MESSAGE_TEXT_MAX, l as LabelKey, m as
|
|
|
3
3
|
import { a as Link, i as ExternalTarget, l as isThreadTarget, n as ExternalEvent, o as Origin, t as ExternalAuthor } from "./external-DymyhUzl.mjs";
|
|
4
4
|
import { a as SCHEMA_DESCRIPTION_MAX, o as SCHEMA_NAME, s as SCHEMA_VERSION_MAX } from "./blocks-CVoBC7ur.mjs";
|
|
5
5
|
import { i as afterRetry } from "./middleware-0DUFrav-.mjs";
|
|
6
|
-
import { o as options } from "./commands-
|
|
6
|
+
import { o as options } from "./commands-DeEJJw3i.mjs";
|
|
7
7
|
import { z } from "zod";
|
|
8
8
|
//#region src/api/routes.ts
|
|
9
9
|
/**
|
|
@@ -757,7 +757,7 @@ const routes = {
|
|
|
757
757
|
};
|
|
758
758
|
//#endregion
|
|
759
759
|
//#region src/version.ts
|
|
760
|
-
const VERSION = "0.42.
|
|
760
|
+
const VERSION = "0.42.1";
|
|
761
761
|
//#endregion
|
|
762
762
|
//#region src/server/backend.ts
|
|
763
763
|
/** The subscription sync's outbound runs on, in `BoardBinding.subscriptions`. No watcher's ID starts with `@`. */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import "./digest-
|
|
1
|
+
import "./digest-dm54M2k8.mjs";
|
|
2
2
|
import { createHash } from "node:crypto";
|
|
3
3
|
import { readFile } from "node:fs/promises";
|
|
4
4
|
//#region src/inspect/page.ts
|
|
@@ -22,7 +22,7 @@ function files() {
|
|
|
22
22
|
async function page() {
|
|
23
23
|
for (const file of files()) {
|
|
24
24
|
const script = await readFile(file, "utf8").catch(() => null);
|
|
25
|
-
if (script !== null && createHash("sha256").update(script).digest("hex") === "
|
|
25
|
+
if (script !== null && createHash("sha256").update(script).digest("hex") === "c19aa15fdf63e3d1220b585c1594163ecca1702039ea5be31a8fe092fd9d5a0b") return script;
|
|
26
26
|
}
|
|
27
27
|
return null;
|
|
28
28
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { u as BoardError } from "./errors-DUzpDSrJ.mjs";
|
|
2
|
-
import { d as localTokenFile, t as board } from "./server-
|
|
2
|
+
import { d as localTokenFile, t as board } from "./server-CKbE7eMT.mjs";
|
|
3
3
|
import { t as oidcTokens } from "./tokens-BSMpTPEe.mjs";
|
|
4
|
-
import { t as local } from "./local-
|
|
4
|
+
import { t as local } from "./local-DsJ14yqg.mjs";
|
|
5
5
|
import { mkdir, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
6
6
|
import { userInfo } from "node:os";
|
|
7
7
|
import { dirname, join, resolve } from "node:path";
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { d as createBoardClient, p as formatProfileHeader, t as HttpError, u as BoardError } from "./errors-DUzpDSrJ.mjs";
|
|
2
2
|
import "./schemas-DAzSsgWk.mjs";
|
|
3
|
-
import { Y as routes, a as compileWatcher, c as METHODS } from "./origin-
|
|
3
|
+
import { Y as routes, a as compileWatcher, c as METHODS } from "./origin-Cuu8lW8n.mjs";
|
|
4
4
|
import { g as keyId, p as DERIVED_ID } from "./middleware-0DUFrav-.mjs";
|
|
5
|
-
import { c as tailWatchers, i as createVercel, l as deployedOnVercel, o as PROTOCOL_ROUTES, s as withoutToken, t as createBoard } from "./exports-
|
|
5
|
+
import { c as tailWatchers, i as createVercel, l as deployedOnVercel, o as PROTOCOL_ROUTES, s as withoutToken, t as createBoard } from "./exports-kDMIgZVu.mjs";
|
|
6
6
|
import { execFile } from "node:child_process";
|
|
7
7
|
import { createHash } from "node:crypto";
|
|
8
8
|
import { mkdir, readFile, readdir, stat, unlink, writeFile } from "node:fs/promises";
|
|
@@ -358,7 +358,6 @@ function connect(url, options = {}) {
|
|
|
358
358
|
* agent included: without it, you write as yourself.
|
|
359
359
|
*/
|
|
360
360
|
function environmentProfile() {
|
|
361
|
-
if (process.env.BOARD_AS) throw new BoardError("renamed_env", "BOARD_AS is BOARD_PROFILE now, and nothing reads BOARD_AS.", 0, { hint: "Set BOARD_PROFILE to the same name, and unset BOARD_AS." });
|
|
362
361
|
const name = process.env.BOARD_PROFILE;
|
|
363
362
|
const avatar = process.env.BOARD_AVATAR;
|
|
364
363
|
return name ? avatar ? {
|
|
@@ -223,8 +223,6 @@ itself.
|
|
|
223
223
|
gets `VERCEL_TOKEN`, the deployment's OIDC token, or your Vercel login.
|
|
224
224
|
- **A profile is named, never detected.** `--as` or `BOARD_PROFILE` writes as
|
|
225
225
|
one; without either you write as yourself, inside a coding agent too.
|
|
226
|
-
`BOARD_AS`, which `BOARD_PROFILE` replaced, is refused with reason
|
|
227
|
-
`renamed_env`, so an agent that still sets it doesn't write as you.
|
|
228
226
|
|
|
229
227
|
Profile names start with a letter and use up to 32 letters, numbers, and
|
|
230
228
|
hyphens. Avatars are `https` URLs (`http` only on localhost): a board serves the
|
|
@@ -691,7 +691,6 @@ fails with the status its URL answered, or 502.
|
|
|
691
691
|
| `wrong_project` | the board's host is a deployment of a project other than the one its discovery names, so the handle mints no token for it |
|
|
692
692
|
| `no_token` | GitHub Actions refused an OIDC token (`permissions: id-token: write`) |
|
|
693
693
|
| `protected` | the board is behind Vercel Deployment Protection: set `VERCEL_AUTOMATION_BYPASS_SECRET` |
|
|
694
|
-
| `renamed_env` | `BOARD_AS` is set, which `BOARD_PROFILE` replaced: set `BOARD_PROFILE` instead |
|
|
695
694
|
| `invalid_duration` | a `timeout` the handle can't read |
|
|
696
695
|
| `too_many_redirects` | the board's URL redirects more than 20 times |
|
|
697
696
|
| `redirected` | the board's URL redirects to another origin, where none of its credentials follow, and Deployment Protection there turns it away: use the URL it redirects to |
|
package/package.json
CHANGED
package/dist/digest-CKC0Rmy1.mjs
DELETED
package/dist/page-BiJVe-7R.mjs
DELETED