@vercel/board 0.49.0 → 0.50.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/dist/{access-B8DnrnHa.mjs → access-BbgmsAFF.mjs} +2 -2
  2. package/dist/access.mjs +5 -5
  3. package/dist/{actors-DewJKyqy.mjs → actors-CX2D22hL.mjs} +3 -3
  4. package/dist/{auth-CEU06Nyp.mjs → auth-DJDTfgAL.mjs} +2 -2
  5. package/dist/{backend-BzCXxVZ-.d.mts → backend-CcaaS9Xl.d.mts} +12 -3
  6. package/dist/backend-local.d.mts +1 -1
  7. package/dist/backend-local.mjs +1 -1
  8. package/dist/{chat-provider-BS_fr61g.mjs → chat-provider-HJ7y_ipp.mjs} +2 -2
  9. package/dist/cli-embedded.d.mts +8 -2
  10. package/dist/cli-embedded.mjs +9 -3
  11. package/dist/cli.mjs +5 -5
  12. package/dist/{conformance-0xONNKcB.mjs → conformance-Cr-umDl0.mjs} +3 -3
  13. package/dist/conformance.d.mts +1 -1
  14. package/dist/conformance.mjs +1 -1
  15. package/dist/{engine-BH_nfJ3N.mjs → engine-DJZ8Xy_g.mjs} +9 -7
  16. package/dist/{errors-DwV7I0g4.mjs → errors-DYF4hhIc.mjs} +1 -1
  17. package/dist/{events-B76-4bNp.mjs → events-BdOCmnZh.mjs} +3 -3
  18. package/dist/{exports-DLzyKwEp.mjs → exports-CuD-Mxkw.mjs} +62 -45
  19. package/dist/{exports-CKEK1fxf.d.mts → exports-lmr6UHHc.d.mts} +1 -1
  20. package/dist/{external-BLI4W_-V.mjs → external-D2jq_DEQ.mjs} +1 -1
  21. package/dist/{index-DxqSw8yd.d.mts → index-_KxJu15n.d.mts} +2 -2
  22. package/dist/index.d.mts +2 -2
  23. package/dist/index.mjs +4 -4
  24. package/dist/index.node.d.mts +3 -3
  25. package/dist/index.node.mjs +4 -4
  26. package/dist/inspect/app.js +35 -35
  27. package/dist/inspect/engine.js +3 -3
  28. package/dist/{inspect-B2ImmOvw.mjs → inspect-CZeoSm7E.mjs} +3 -3
  29. package/dist/inspect-UCcPViyA.mjs +2 -0
  30. package/dist/inspect.mjs +2 -2
  31. package/dist/{local-DPpSEq2_.mjs → local-BVSFSSYf.mjs} +46 -24
  32. package/dist/{main-CqX7JqzE.mjs → main-B016auoG.mjs} +23 -13
  33. package/dist/{memory-DzqkXIB-.mjs → memory-C2lzMV_t.mjs} +2 -2
  34. package/dist/{middleware-ysFm2S4v.mjs → middleware-DUKIITFZ.mjs} +3 -3
  35. package/dist/{routes-qS92xz8U.mjs → routes-BE0y6wCk.mjs} +9 -9
  36. package/dist/{schemas-TeVe4Udh.mjs → schemas-CUSTEFIy.mjs} +7 -1
  37. package/dist/{serve-CYr4RwRM.mjs → serve-B10e7QaY.mjs} +5 -5
  38. package/dist/{server-V7qyVUiJ.mjs → server-ViWNvg5q.mjs} +58 -28
  39. package/dist/{serving-BzNxlnDV.mjs → serving-SbqeWqlA.mjs} +1 -1
  40. package/dist/{shell-BLHZoP-x.mjs → shell-DmpmgOPC.mjs} +1 -1
  41. package/dist/{sql-DIKQd5Me.mjs → sql-iABdyCiz.mjs} +18 -5
  42. package/dist/{sqlite-BF9kBDh1.mjs → sqlite-28EMrmk7.mjs} +2 -2
  43. package/dist/{sqlite-db-CSYwiZ4E.mjs → sqlite-db-Ckd-ceNe.mjs} +1 -1
  44. package/dist/sync-chat-sdk.mjs +2 -2
  45. package/dist/sync-github.mjs +3 -3
  46. package/dist/sync-linear.mjs +3 -3
  47. package/dist/sync-slack.mjs +4 -4
  48. package/dist/sync.mjs +2 -2
  49. package/dist/{tags-BpFo6q0_.mjs → tags-D0qra0Qy.mjs} +1 -1
  50. package/dist/{task-batch-CujTLmTB.mjs → task-batch-9lVDG3d-.mjs} +6 -6
  51. package/dist/{tokens-BmCDAT4N.mjs → tokens-C-iK0Cku.mjs} +2 -2
  52. package/dist/{version-BCoWGLEW.mjs → version-C70RLVEK.mjs} +1 -1
  53. package/docs/01-board/03-identity.md +3 -2
  54. package/docs/02-sync/01-overview.md +2 -1
  55. package/docs/03-guides/06-sandboxed-agents.md +22 -21
  56. package/docs/04-reference/01-cli.md +10 -1
  57. package/docs/04-reference/02-board.md +6 -4
  58. package/docs/04-reference/03-http.md +4 -3
  59. package/package.json +1 -1
  60. package/dist/inspect-DnRQUmP8.mjs +0 -2
@@ -1,5 +1,5 @@
1
- import{A as e,C as t,D as n,E as r,F as i,M as a,N as o,O as s,P as c,S as l,T as u,_ as d,a as f,b as p,c as m,d as h,f as g,g as _,h as v,i as y,j as b,k as x,l as S,m as C,n as w,o as T,p as E,r as ee,s as te,t as ne,u as re,v as ie,w as D,x as O,y as k}from"./app.js";o({id:c().min(1),platform:c().min(1),key:c().min(1),...E.shape,raw:i()});const ae=o({root:a(e=>typeof e==`function`).optional(),text:c().optional(),labels:l.optional(),unset:e(O).optional(),noSync:b().optional()}).strict();function A(e){if(e&&typeof e==`object`){for(let t of Object.values(e))A(t);Object.freeze(e)}return e}const oe=o({target:c().min(1),channel:c().min(1),kind:x([`channel`,`thread`])}).strict();var j=class extends Error{code;constructor(e,t){super(t),this.code=e}};const se=e=>e instanceof j&&e.code===`channel_not_found`,ce=o({event:g,raw:i(),dedupe:c().min(1)}),M=/* @__PURE__ */ new WeakMap,le=e=>M.get(e),ue=e=>/^(```|~~~|[-*+] |\d+[.)] |#{1,6} |>|\|)/.test(e),N=/^\[vc\]: #\S*\r?\n/,P=/\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/g,F=/!\[([^\]]+)\]\(https:\/\/vercel\.com\/static\/status\/[^)]+\)\s*(?:\[[^\]]*\]\((https?:\/\/[^)\s]+)\))?/;function de(e){if(!N.test(e))return null;let t=e.search(/<details><summary>\d+ Skipped Deployments?<\/summary>/),n=[],r=0;for(let i of e.split(/\r?\n/)){let a=r;if(r=e.indexOf(`
1
+ import{A as e,C as t,D as n,E as r,F as i,M as a,N as o,O as s,P as c,S as l,T as u,_ as d,a as f,b as p,c as m,d as h,f as g,g as _,h as v,i as y,j as b,k as x,l as S,m as C,n as w,o as T,p as E,r as ee,s as te,t as ne,u as re,v as ie,w as D,x as O,y as k}from"./app.js";o({id:c().min(1),platform:c().min(1),key:c().min(1),...E.shape,raw:i()});const ae=o({root:a(e=>typeof e==`function`).optional(),text:c().optional(),labels:t.optional(),unset:e(O).optional(),noSync:b().optional()}).strict();function A(e){if(e&&typeof e==`object`){for(let t of Object.values(e))A(t);Object.freeze(e)}return e}const oe=o({target:c().min(1),channel:c().min(1),kind:x([`channel`,`thread`])}).strict();var j=class extends Error{code;constructor(e,t){super(t),this.code=e}};const se=e=>e instanceof j&&e.code===`channel_not_found`,ce=o({event:g,raw:i(),dedupe:c().min(1)}),M=/* @__PURE__ */ new WeakMap,le=e=>M.get(e),ue=e=>/^(```|~~~|[-*+] |\d+[.)] |#{1,6} |>|\|)/.test(e),N=/^\[vc\]: #\S*\r?\n/,P=/\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/g,F=/!\[([^\]]+)\]\(https:\/\/vercel\.com\/static\/status\/[^)]+\)\s*(?:\[[^\]]*\]\((https?:\/\/[^)\s]+)\))?/;function de(e){if(!N.test(e))return null;let t=e.search(/<details><summary>\d+ Skipped Deployments?<\/summary>/),n=[],r=0;for(let i of e.split(/\r?\n/)){let a=r;if(r=e.indexOf(`
2
2
  `,r)+1||e.length,!i.startsWith(`|`)||/^\|\s*(Project|Name)\s*\|/.test(i)||/^\|\s*:?-/.test(i))continue;let o=i.split(`|`).slice(1,-1).map(e=>e.trim());if(o.length<2)continue;let s=F.exec(o[1]);if(!s)continue;let c=[...o[0].matchAll(P)].at(-1),l=c?.[1]??o[0].replace(/<[^>]*>/g,``).trim();if(!l)continue;let u=o[2]?[...o[2].matchAll(P)].find(e=>/preview/i.test(e[1])):void 0,d=o[3]?.match(/<relative-time[^>]*>([^<]+)<\/relative-time>/)?.[1]?.trim()??(o[3]?.replace(/<[^>]*>/g,``).trim()||null),f=o[3]?.match(/<relative-time[^>]*\sdatetime="([^"]+)"/)?.[1]??null;n.push({project:l,projectUrl:c?.[2]??null,status:s[1].trim(),deploymentUrl:s[2]??null,previewUrl:u?.[2]??null,updated:d,updatedAt:f!==null&&!Number.isNaN(Date.parse(f))?f:null,skipped:t!==-1&&a>t})}return n.length>0?n:null}const I={ready:`✅`,building:`⏳`,queued:`⏳`,initializing:`⏳`,error:`❌`,failed:`❌`,canceled:`⚪`,ignored:`⚪`},L=(e,t)=>t?`[${e}](${t})`:e;function R(e){return e.map(e=>`- ${[`${I[e.status.toLowerCase()]??`▲`} **${L(e.project,e.projectUrl)}**`,`${L(e.status,e.deploymentUrl)}${e.skipped?` (skipped)`:``}`,...e.previewUrl?[L(`Preview`,e.previewUrl)]:[],...e.updated?[e.updated]:[]].join(` · `)}`).join(`
3
- `)}function fe(e,t){return e.by.actor===`github:user:35613825`||e.by.profile===`github:user:35613825`&&!!e.from&&t?.kind===`external`&&t.verified===!0&&t.platform===`github`}function pe(e,t){let n=t?de(e):null;return n?`**▲ Vercel**\n${R(n)}`:e}const z=(e,n=!1)=>{let r=D(e),i=r.trim()===``?n?``:`(no text)`:r;return i.length>1e4?`${i.slice(0,t-1).toWellFormed()}…`:i},B=(e,t,r=e.name??`a file`)=>`📎 ${r}${e.size===void 0?``:` (${n(e.size)})`} didn't come over: ${t}`,V=e=>e instanceof _&&e.code===`no_files`,me=(e,t)=>{let n=e.name??`a file`;if(!e.url||!/^https?:\/\//.test(e.url))return B(e,t);let r=n.replace(/[[\]\\]/g,e=>`\\${e}`),i=e.url.replace(/[ ()]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`);return B(e,t,`[${r}](${i})`)},H=(e,t)=>t.length?`${e.trim()?`${e}\n\n`:``}${t.join(`
3
+ `)}function fe(e,t){return e.by.actor===`github:user:35613825`||e.by.profile===`github:user:35613825`&&!!e.from&&t?.kind===`external`&&t.verified===!0&&t.platform===`github`}function pe(e,t){let n=t?de(e):null;return n?`**▲ Vercel**\n${R(n)}`:e}const z=(e,t=!1)=>{let n=D(e),r=n.trim()===``?t?``:`(no text)`:n;return r.length>1e4?`${r.slice(0,l-1).toWellFormed()}…`:r},B=(e,t,r=e.name??`a file`)=>`📎 ${r}${e.size===void 0?``:` (${n(e.size)})`} didn't come over: ${t}`,V=e=>e instanceof _&&e.code===`no_files`,me=(e,t)=>{let n=e.name??`a file`;if(!e.url||!/^https?:\/\//.test(e.url))return B(e,t);let r=n.replace(/[[\]\\]/g,e=>`\\${e}`),i=e.url.replace(/[ ()]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`);return B(e,t,`[${r}](${i})`)},H=(e,t)=>t.length?`${e.trim()?`${e}\n\n`:``}${t.join(`
4
4
  `)}`:e,he=e=>e.split(`
5
- `).filter(e=>/^📎 .* didn't come over: /u.test(e)),U=e=>JSON.stringify([e.url,e.message,e.snapshot,e.unavailable]),ge=(e,t)=>e.length===t.length&&e.every((e,n)=>U(e)===U(t[n])),_e=new AbortController().signal,ve=e=>{try{return JSON.parse(JSON.stringify(e??null))}catch{return null}},W=e=>typeof e==`string`?D(e):Array.isArray(e)?e.map(W):typeof e==`object`&&e?Object.fromEntries(Object.entries(e).map(([e,t])=>[D(e),W(t)])):e,G=e=>{let t=e?.data?.error,n=typeof t==`string`?t:e instanceof Error?e.message:String(e);return D(n.slice(0,500))||`unknown error`},ye=e=>e instanceof _&&e.status===404;function K(e,t,n){return n.startsWith(`${e}:`)?n:`${e}:${n.startsWith(`${t}:`)?n.slice(t.length+1):n}`}function be(e,t,n){return e===t?n:re(n,n=>n.kind===`actor`&&n.actor.startsWith(`${t}:`)?`@[${K(e,t,n.actor)}]`:null)}function xe(e,t,n){if(!(`author`in n))return n;let r={...n.author,id:K(e,t,n.author.id)};return n.kind!==`message`&&n.kind!==`edited`||e===t?{...n,author:r}:{...n,author:r,...n.mentioned?{mentioned:n.mentioned.map(n=>({...n,id:K(e,t,n.id)}))}:{},text:be(e,t,n.text)}}function q(e){let t=null,i=()=>{if(!t)throw Error(`sync used before board() bound it`);return t},a={self:`sync`,origin:{via:{kind:`engine`}}};function o(e,t,n=_e,r=a){let o=i().backend;return o[e].call(o,r,t,n)}let c=t=>{let n=e[t];if(!n)throw d(`no sync entry named ${t}`);return n},l=e=>e.slice(0,e.indexOf(`:`)),g=e=>i().syncedHere(e),b=async t=>e[l(t)]!==void 0&&await g(l(t)),x=e=>e.slice(e.indexOf(`:`)+1);async function E(e){try{return await o(`syncThread`,{thread:e})}catch(e){if(ye(e))return null;throw e}}async function D(e){try{let{message:t,replies:n}=await o(`message`,{id:e});return[t,...n]}catch(e){if(ye(e))return[];throw e}}async function O(e){return(await D(e)).find(t=>t.id===e)??null}async function M(e){return e.length===0?{}:(await o(`syncCopies`,{message:[...new Set(e)]})).copies}let N=(e,t)=>o(`syncFind`,e,t),P=null;function F(){if(P)return P;let e=o(`me`,{}).then(e=>e.principal);return P=e,e.catch(()=>{P===e&&(P=null)}),e}async function I(){let[{actors:e},t]=await Promise.all([o(`actors`,{}),F().catch(()=>null)]),n={byId:{},principal:t};for(let t of e)n.byId[t.id]={id:t.id,kind:t.kind,handle:t.handle,name:t.name,avatar:t.avatar,...t.via?{via:{...t.via}}:{},...t.platform?{platform:t.platform}:{},...t.verified?{verified:!0}:{}};return n}let L=/* @__PURE__ */ new Map;function R(e,t){let n=`${e}:${t}`,r=L.get(n);if(r&&(!r.failed||Date.now()-r.at<6e4))return r.id;let i={id:c(e).resolveChannel(t),failed:!1,at:Date.now()};return i.id.catch(r=>{i.failed=!0;let a=se(r);!a&&L.get(n)===i&&L.delete(n),console.warn(`[board] sync ${e}: ${a?`skipping`:`couldn't resolve`} ${t}: ${r.message}`)}),L.set(n,i),i.id}function U(e,t){if(!v(t))return x(t);try{let n=c(e).inboxChannel(e,t);return n===null?null:x(n)}catch{return null}}let q=/* @__PURE__ */ new Map;function Se(e,t){let n=`${e}\u001f${t.toLowerCase()}`,r=q.get(n);if(r&&Date.now()-r.at<3e5)return r.mention;q.size>=1e3&&q.clear();let i=c(e),a=i.findByEmail(t).then(e=>e?i.mention({id:e.id,kind:`external`,handle:e.handle,name:e.name,avatar:e.avatar}):null,()=>null);return q.set(n,{at:Date.now(),mention:a}),a}async function Ce(e){let t=e.indexOf(`:`);if(t<=0)throw d(`sync targets look like <key>:<channel or thread>, got: ${e}`);let n=e.slice(0,t),r=c(n);try{let i=oe.parse(await r.resolveTarget(e.slice(t+1)));if(i.kind===`channel`&&!r.canStartThreads)throw Error(`${r.platform} cannot start threads; use an existing thread`);return{target:`${n}:${i.target}`,kind:i.kind}}catch(t){throw d(`can't sync to ${e}: ${t.message}`)}}async function we(e,t){let{event:n,raw:r,dedupe:i}=ce.parse(W({...t,raw:ve(t.raw)}));for(let t of[n.channel,n.thread,`subthread`in n?n.subthread:null])if(t!==null&&!t.startsWith(`${e}:`))throw d(`provider locations must belong to sync entry ${e}`);let a=le(c(e)),s=a&&await a(x(n.channel),t=>R(e,t)).catch(async e=>{if(await Te(n.thread))return!0;throw e});(!a||s||await Te(n.thread))&&await o(`inboxPush`,{key:e,events:[{id:i,event:n,raw:r}]})}async function Te(e){try{return(await N({thread:e},AbortSignal.timeout(2e3))).thread!==null}catch(e){let t=e?.name;if(t===`TimeoutError`||t===`AbortError`)return!0;throw e}}async function Ee(t,n){let r=e[t];if(!r)throw ie(`no sync entry named ${t}`);if(!await g(t))return new Response(null,{status:200});let i;try{i=await r.receive(t,n,e=>we(t,e))}catch(e){return e instanceof _&&e.status===400?(console.error(`[board] dropped an event the board refuses`,e),new Response(null,{status:200})):(console.error(`[board] intake failed`,e),new Response(`intake failed`,{status:500}))}let a=De([t]).catch(e=>console.error(`[board] couldn't pull ${t}'s inbox:`,G(e)));return ee(a),i}async function De(t=Object.keys(e)){let n=0,r=Date.now()+24e4;for(let e of t)if(await g(e))for(;Date.now()<r;){let{items:t}=await o(`inboxNext`,{key:e,limit:10});if(t.length===0)break;await Promise.all(t.map(t=>Oe(e,t))),n+=t.length}return n}async function Oe(e,t){let n;try{await je(e,{event:t.event,raw:t.raw},{id:t.id,attempt:t.attempt+1})}catch(r){console.error(`[board] sync ${e} couldn't import ${t.id}:`,G(r)),n=G(r)}await o(`inboxAck`,{key:e,id:t.id,lease:t.lease,...n===void 0?{}:{error:n}}).catch(e=>console.error(`[board] couldn't ack an inbox event:`,G(e)))}async function ke(e,t,n,r,i=[]){if(t.length===0)return[];let a=[];for(let o of t){if(a.some(e=>e.url===o.url))continue;let t=(await N({thread:o.thread,message:o.message})).message,s=t===null?null:await O(t);if(s&&!s.deleted&&s.channel===r){a.push({url:o.url,message:s.id,unavailable:null,snapshot:{author:s.author?T(s.author):s.by.actor,text:s.text,createdAt:s.createdAt,files:s.attachments.map(e=>({name:e.name,url:null}))}});continue}if(o.snapshot){a.push({url:o.url,message:null,snapshot:o.snapshot,unavailable:null});continue}let c=i.find(e=>e.url===o.url&&e.snapshot&&e.message===null);if(c){a.push(c);continue}let l=await e.fetchLink(o,n).catch(e=>({snapshot:null,unavailable:G(e)}));a.push({url:o.url,message:null,snapshot:l.snapshot,unavailable:l.snapshot?null:(l.unavailable??`unknown`).slice(0,300)})}return W(a)}async function Ae(e,t,n){let i=[],a=[],c=null;for(let l of t.slice(0,10)){if(c!==null){a.push(me(l,c));continue}if(l.size!==void 0&&l.size>26214400){a.push(B(l,`over ${r/1024/1024} MB`));continue}let t;try{let n=await e.fetchFile(l);if(n===null){a.push(B(l,`${e.platform} can't hand it over`));continue}t=n}catch(t){if(n<3)throw t;console.warn(`[board] couldn't fetch ${l.name??`a file`} from ${e.platform}:`,G(t)),a.push(B(l,`${e.platform} wouldn't hand it over`));continue}if(t.byteLength>26214400){a.push(B(l,`over ${r/1024/1024} MB`));continue}if(t.byteLength===0){a.push(B(l,`it was empty`));continue}let d=l.name??`${l.type}`;try{i.push((await o(`upload`,{data:t,name:d,type:l.mimeType||s(d)})).attachment)}catch(e){if(e instanceof _&&(e.code===`too_large`||e.code===`no_direct_uploads`)){a.push(B(l,`over ${u/1024/1024} MB`));continue}if(!V(e))throw e;c=e.message,a.push(me(l,c))}}for(let e of t.slice(10))a.push(B(e,`a message carries at most 10`));return{attachments:i,notes:a}}async function je(e,t,n){let r=c(e),a={...t,event:xe(e,r.platform,t.event)},{event:o,raw:s}=a,l=(await N({thread:o.thread})).thread??void 0;if(o.kind===`message`){let e=(await N({thread:o.subthread??o.thread,message:o.message})).message;if(e!==null){let t=(await O(e))?.origin;if(!t||t.message!==o.message||(t.subthread??t.thread)!==(o.subthread??o.thread))return}}let u=`author`in o?o.author:{id:`${e}:system`,handle:r.platform,name:r.platform,avatar:null,isBot:!0},f,p=()=>f??=A(r.event({id:n.id,key:e,event:o,raw:s})),m,h,g=!0,_={direction:`in`,key:e,channel:x(o.channel),get event(){return p()},board:i().client({author:u,key:e,...Ne(e,o)},n.id),import(t,r={}){if(!g)throw d(`the sync function has finished`);return m??=Me(e,a,n,l,t,r),m},permalink(){let e=h??r.permalink(p());return h=e,e.catch(()=>{h===e&&(h=void 0)}),e},resolve:t=>R(e,t)};try{await r.sync(_),await m}finally{g=!1}}async function Me(e,t,n,r,i,a){let o=i??(r?(await E(r))?.channel:void 0);if(o===void 0)return{root:null,message:null};try{return await Pe(e,t,n,p.parse(o),ae.parse(a))}catch(e){if(!(e instanceof ne))throw e;let n=(await N({thread:t.event.thread})).thread;return{root:n===null?null:(await E(n))?.root??null,message:null}}}function Ne(e,t){let n=c(e),r=(`subthread`in t?t.subthread:null)??t.thread;return{via:{kind:`sync`,key:e,platform:n.platform,channel:t.channel,thread:r},respond:async e=>{await n.post(x(r),`thread`,{markdown:e})}}}async function Pe(e,t,n,r,i){let{event:a,raw:s}=t,l=Ne(e,a),u=c(e),f=(await N({thread:a.thread})).thread??void 0,p=f?await E(f):null,m=p?.root,g=e=>h(`board-inbound`,n.id,String(e)),_={key:e,channel:l.via.channel,thread:l.via.thread},v=async e=>{if(!e.dropped)return e.message;for(let t of e.dropped)await l.respond(t);throw new ne(e.dropped)},y=async({attachments:t=[],...n})=>({id:await v(await o(`syncImport`,{op:`post`,from:e,source:_,...n,origin:n.origin??null,...t.length?{attachments:t.map(e=>e.id)}:{}})),re:n.re??null}),b=e=>({root:e.re??e.id,message:e.id}),S=(e={})=>{let t={...e,...i.labels};for(let e of i.unset??[])delete t[e];return t},C=e=>{if(!i.root)return e;let t=i.root(A(structuredClone(e)));if(t&&typeof t==`object`&&`then`in t)throw d(`root overrides must be synchronous`);let n=ae.pick({text:!0,labels:!0}).parse(t);return{...e,text:n.text??e.text,labels:{...e.labels,...n.labels}}},w=(t,n,r)=>o(`syncImport`,{op:`labels`,author:t,from:e,origin:{thread:a.thread},set:n,unset:r}),T=async(e,t)=>{if(!i.labels&&!i.unset)return;let n=await O(t),r=Object.fromEntries(Object.entries(i.labels??{}).filter(([e,t])=>n?.labels[e]!==t)),a=(i.unset??[]).filter(e=>n?.labels[e]!==void 0);(Object.keys(r).length||a.length)&&await w(e,r,a)};switch(a.kind){case`message`:{let t=(await N({thread:a.subthread??a.thread,message:a.message})).message;if(t!==null)return{root:m??t,message:t};let{attachments:o,notes:c}=a.files?.length?await Ae(u,a.files,n.attempt):{attachments:[],notes:[]},l=await ke(u,a.links??[],{thread:a.subthread??a.thread,message:a.message},p?.channel??r),d={...l.length?{links:l}:{},...a.mentioned?.length?{mentioned:a.mentioned}:{},author:a.author,text:z(H(i.text??a.text,c),o.length>0),...o.length?{attachments:o}:{},origin:{channel:a.channel,thread:a.thread,subthread:a.subthread,message:a.message,context:a.context},id:await g(0)},f={...d,...i.noSync?{noSync:!0}:{}};if(m!==void 0)return await T(a.author,m),b(await y({...f,re:m}));let h=await u.fetchRoot(x(a.thread));if(h===null){let e=C({text:a.text,labels:{},author:a.author,raw:s});return b(await y({...d,channel:r,text:z(H(i.text??e.text,c),o.length>0),labels:S(e.labels)}))}let _=C({...h,raw:h.raw??null}),v=await y({author:{...h.author,id:K(e,u.platform,h.author.id)},channel:r,text:z(_.text),labels:S(_.labels),origin:{channel:a.channel,thread:a.thread,subthread:null,message:`root:${n.id}`,context:null},id:await g(1)});return b(await y({...f,re:v.id}))}case`edited`:case`deleted`:case`reaction`:{let t=(await N({thread:a.subthread??a.thread,message:a.message})).message;if(t===null)return{root:m??null,message:null};let n=`author`in a?a.author:{id:`${e}:system`,handle:u.platform,name:u.platform,avatar:null,isBot:!0},r={thread:a.subthread??a.thread,message:a.message};if(m!==void 0&&await T(n,m),a.kind===`deleted`)await o(`syncImport`,{op:`delete`,author:n,from:e,origin:r});else if(a.kind===`edited`){let s=await O(t),c=z(H(i.text??a.text,s?he(s.text):[]),(s?.attachments.length??0)>0),l=a.mentioned?.length?{mentioned:a.mentioned}:{};s&&!a.linksOnly&&s.text!==c&&await v(await o(`syncImport`,{op:`edit`,author:n,from:e,origin:r,text:c,source:_,...l}));let d=s?await ke(u,a.links??[],r,s.channel,s.links):[];s&&!ge(d,s.links)&&await o(`syncImport`,{op:`links`,author:n,from:e,origin:r,links:d})}else{if(u.singleReaction){let i=k(a.emoji),s=/* @__PURE__ */ new Set([n.id,`${await F()}+${n.id}`]);for(let[c,l]of Object.entries((await O(t))?.reactions??{}))l.some(e=>s.has(e))&&!(a.added&&c===i)&&await o(`syncImport`,{op:`react`,author:n,from:e,origin:r,emoji:c,remove:!0})}(!u.singleReaction||a.added)&&await o(`syncImport`,{op:`react`,author:n,from:e,origin:r,emoji:a.emoji,remove:!a.added})}return{root:m??null,message:t}}case`lifecycle`:{if(m!==void 0){let t=await O(m),r=t?.origin?.message===`lifecycle:${n.id}`,c=S((r?C({text:J(a),labels:a.labels,author:a.author,raw:s}):null)?.labels??a.labels),l=e=>a.owns?.some(t=>e.startsWith(t))??!1,u=Object.fromEntries(Object.entries(c).filter(([e,n])=>t?.labels[e]!==n)),d=Object.keys(t?.labels??{}).filter(e=>!(e in c)&&(a.unset.includes(e)||i.unset?.includes(e)||l(e)));if(t&&!t.deleted&&(Object.keys(u).length||d.length)&&await w(a.author,u,d),a.retitled&&t&&!t.deleted&&t.from===e&&t.origin?.thread===a.thread){let n=z(i.text??C({text:J(a),labels:t.labels,author:a.author,raw:s}).text);t.text!==n&&await v(await o(`syncImport`,{op:`edit`,author:a.author,from:e,origin:{thread:t.origin.thread,message:t.origin.message},text:n}))}return a.reply?b(await y({author:a.author,re:m,text:z(i.text??a.reply),...i.noSync?{noSync:!0}:{},id:await g(1)})):{root:m,message:r?m:null}}if(!a.createRoot)return{root:null,message:null};let t=C({text:J(a),labels:a.labels,author:a.author,raw:s}),c=await y({author:a.author,channel:r,text:z(a.reply?t.text:i.text??t.text),labels:S(t.labels),origin:{channel:a.channel,thread:a.thread,subthread:null,message:`lifecycle:${n.id}`,context:null},id:await g(0)});return a.reply?b(await y({author:a.author,re:c.id,text:z(i.text??a.reply),...i.noSync?{noSync:!0}:{},id:await g(1)})):b(c)}}}async function Fe(e,t,n){let r=m(n).flatMap(e=>e.kind===`actor`?[e.actor]:[]);if(r.length===0)return n;let i=/* @__PURE__ */ new Map;for(let n of r)!t.byId[n]&&S(n)&&i.set(n,await Se(e,n));return re(n,n=>{if(n.kind===`handle`)return null;if(i.has(n.actor))return i.get(n.actor)??n.actor;let r=Le(n.actor,t);return r?ze(e,r.id,t)??r.name:Ie(e,n.actor,t)})}function Ie(e,t,n){let r=Re(e,t,n);if(r===null)return null;let i=c(e);return i.mentionById(`${i.platform}:${r}`)}function Le(e,t){return t.byId[e]??(t.principal?t.byId[`${t.principal}+${e}`]:void 0)??null}function Re(e,t,n){let{principal:r,profile:i}=y(t),a=i===null?t:f(i)!==null&&r===n.principal?i:null;return a?.startsWith(`${e}:`)?a.slice(e.length+1):null}function ze(e,t,n){let r=n.byId[t],i=r?Re(e,t,n):null;if(i===null)return null;let a=c(e);return a.mention({...r,id:`${a.platform}:${i}`})}async function Be(t,n,r,i,a){let o=i.byId[r.by.actor],s=o?.name??r.by.actor,l=`${o?.via?` ${te(o.via)}`:``}${r.from?` (${o?.platform??e[r.from]?.platform??r.from})`:``}`,u=o?.kind===`deployment`&&!o.via?/(?:@[^@/]+| \([^()]+\))$/.exec(s)?.[0]??``:``,f=`${s}${l}`,p=`${u}${l}`,m=c(t),h=fe(r,o),g=(a??(e=>m.render(e)))(A({message:{...structuredClone(r),text:pe(r.text,h)},author:o?{...o}:null,mentionOf:e=>ze(t,e,i),label:f,target:n}));if(typeof g!=`string`)throw d(`a provider renderer must return markdown`);let _=`**${f}**: `,v=await Fe(t,i,g.startsWith(_)&&ue(g.slice(_.length))?`**${f}**:\n\n${g.slice(_.length)}`:g),y=h?de(r.text):null;return{markdown:v,...o?.verified?{as:{name:f,avatar:Ve(r,o),attribution:p}}:{},...y?{deployments:y}:{}}}function Ve(e,t){let n=e=>!e||/\/avatars\/[a-z0-9-]+$/.test(e),r=t?.avatar??null;if(!n(r))return r;let i=t?.handle.split(`/`)[0]??``,a=e.by.principal.slice(12);return!e.by.principal.startsWith(`vercel:user:`)||!i||/^user-/.test(i)||i.toLowerCase()===a.toLowerCase()?r:`https://vercel.com/api/www/avatar?u=${encodeURIComponent(i)}&s=64&format=png`}let He=e=>e.attachments.map(t=>`\n📎 ${t.name} (${n(t.size)}, on the board: #${e.id})`).join(``),Y=async(e,t,n,r=!1,i)=>{let a=l(e),{markdown:o,...s}=await Be(a,e,t,n,i);return{markdown:t.attachments.length>0&&(r||!c(a).uploadsFiles)?`${o}\n${He(t)}`:o,...s}};async function Ue(e,t,n,r,i){let a=e.replyTo===null?void 0:(await M([e.replyTo]))[e.replyTo]?.[t],o=a!==void 0&&a.thread!==n?a.thread:n,s=c(l(t)),u=await Y(t,e,r,!1,i),f,p;if(!u.markdown.trim()&&e.attachments.length&&s.uploadsFiles)try{let n=await Ke(e,t,o);p=n.message,f=n.files}catch(n){if(!s.refusesFiles(n)&&!V(n))throw n;u=await Y(t,e,r,!0,i),p=(await s.post(x(o),`thread`,u)).message,f=null}else{if(!u.markdown.trim())throw d(`a renderer must return text unless the message has media`);p=(await s.post(x(o),`thread`,u)).message}let m={thread:o,message:p,...f===void 0?{}:{files:f}};return await We(e,t,m),m}async function We(e,t,n){await o(`syncReceipt`,{kind:`message`,message:e.id,target:t,external:{thread:n.thread,message:n.message},...n.files===void 0?{}:{files:n.files}})}async function Ge(e){return Promise.all(e.attachments.map(async e=>{let{data:t}=await o(`attachment`,{id:e.id});return{data:t instanceof Uint8Array?t:new Uint8Array(await new Response(t).arrayBuffer()),filename:e.name,mimeType:e.type}}))}async function Ke(e,t,n){return c(l(t)).uploadFiles(x(n),await Ge(e))}async function X(e,t,n,r,i){let a=c(l(t));if(!a.uploadsFiles||e.attachments.length===0||n.files!==void 0)return;let s;try{s=(await Ke(e,t,n.thread)).files}catch(o){if(!a.refusesFiles(o)&&!V(o))throw Object.assign(/* @__PURE__ */ Error(`files: ${G(o)}`),{cause:o,data:{error:`files: ${G(o)}`}});console.warn(`[board] ${t} won't take #${e.id}'s files (${G(o)}); noting them in its text`),s=null,await Y(t,e,r,!0,i).then(e=>a.edit(x(n.thread),n.message,e)).catch(n=>console.warn(`[board] couldn't note #${e.id}'s files on ${t}:`,G(n)))}await o(`syncReceipt`,{kind:`files`,message:e.id,target:t,files:s})}let Z=(e,t,n,r)=>{e.some(e=>e.error===r)||e.push({id:t,target:n,error:r})};async function Q(e,t){if(t.length!==0){if(e<5||w(e))throw t[0].error;for(let{id:e,target:n,error:r}of t)console.error(`[board] gave up ${n===null?`syncing #${e}`:`delivering #${e} to ${n}`}:`,G(r)),n!==null&&await o(`syncReceipt`,{kind:`failed`,message:e,target:n,error:G(r)})}}async function $(e,t,n,r,i){let a,o=!0,s=()=>d(`the sync function has finished`),l={direction:`out`,key:e,channel:r===null?null:U(e,r),event:A(structuredClone(t)),message:A(structuredClone(n)),target:r,deliver(e={}){if(!o)throw s();return a??=r===null?Promise.resolve():i(e.render),a},start(t){if(!o)throw s();return qe(e,n,t)},resolve:t=>R(e,t)};try{await c(e).sync(l),await a}finally{o=!1}}async function qe(e,t,n){let{target:r,kind:i}=await Ce(`${e}:${n}`),a=t.re===null?t:await O(t.re);!a||a.deleted||a.noSync||r!==(a.origin?a.origin.channel??C(a.origin.thread):null)&&await o(`syncReceipt`,{kind:`thread`,message:a.id,target:r,targetKind:i,cause:`config`})}async function Je(t,n){let r=[];for(let t of Object.keys(e))e[t].canStartThreads&&await g(t)&&r.push(t);if(t.payload.noSync||r.length===0)return;let i=await O(t.message.id);if(!i||i.deleted)return;let a=[];for(let e of r)try{await $(e,t,i,null,async()=>{})}catch(e){Z(a,i.id,null,e)}await Q(n,a)}async function Ye(e,t){let{thread:n,target:r}=e.payload;if(!await b(r)||(e.payload.kind??(v(r)?`thread`:`channel`))===`thread`)return;let i=await E(n);if(!i?.targets.includes(r))return;let[a,...o]=await D(i.root);if(!a||a.id!==i.root||a.deleted)return;let s=[];try{await $(l(r),e,a,r,e=>Xe(i,a,o,r,s,e))}catch(e){Z(s,a.id,r,e)}await Q(t,s)}async function Xe(e,t,n,r,i,a){let o=await I(),s=await M([t.id,...n.map(e=>e.id)]),u=e=>(i.push({id:t.id,target:r,error:e}),e),f=e.external[r];if(f){let e=s[t.id]?.[r];if(e)try{await X(t,r,e,o,a)}catch(e){throw u(e)}}else try{let e=c(l(r)),n=await Y(r,t,o,!1,a),i=!n.markdown.trim()&&t.attachments.length>0&&e.uploadsFiles;if(!n.markdown.trim()&&!i)throw d(`a renderer must return text unless the message has media`);let s,u=await(async()=>{if(!i&&(t.attachments.length===0||!e.startsThreadsWithFiles))return e.post(x(r),`channel`,n);try{let a=await e.post(x(r),`channel`,{...n,files:await Ge(t)});return s=i?a.files??[]:a.files,a}catch(n){if(!e.refusesFiles(n)&&!V(n))throw n;return s=null,e.post(x(r),`channel`,await Y(r,t,o,!0,a))}})();f=`${l(r)}:${u.thread}`;let p={thread:f,message:u.message,...s===void 0?{}:{files:s}};await We(t,r,p),await X(t,r,p,o,a)}catch(e){throw u(e)}let p=[];for(let e of n)if(!(e.deleted||e.noSync||Ze(e,r)))try{await X(e,r,s[e.id]?.[r]??await Ue(e,r,f,o,a),o,a)}catch(t){p.push({id:e.id,target:r,error:t})}if(i.push(...p),p.length)throw p[0].error}let Ze=(e,t)=>e.origin?.thread===t||e.from!==null&&l(t)===e.from;async function Qe(e,t){if(!e.message)return;if(e.message.re===null)return Je(e,t);if(e.payload.noSync)return;let n=await E(e.payload.thread);if(!n||n.targets.length===0)return;let r=await O(e.message.id);if(!r||r.deleted)return;let i=await I(),a=[];for(let t of n.targets){let o=n.external[t];if(await b(t)&&o&&!Ze(r,t))try{await $(l(t),e,r,t,async e=>{let n=(await M([r.id]))[r.id]?.[t]??await Ue(r,t,o,i,e);await X(r,t,n,i,e)})}catch(e){Z(a,r.id,t,e)}}await Q(t,a)}async function $e(e){let t=(await M([e.payload.id]))[e.payload.id]??{};if(Object.keys(t).length===0)return;let n=e.type===`message.edited`?await O(e.payload.id):e.message??await O(e.payload.id);if(!n||e.type===`message.edited`&&n.deleted)return;let r=await I();for(let[i,a]of Object.entries(t))if(!(!await b(i)||e.payload.from!==null&&l(i)===e.payload.from))try{await $(l(i),e,n,i,async t=>{let o=c(l(i)),s=x(a.thread);e.type===`message.edited`?await o.edit(s,a.message,await Y(i,n,r,a.files===null,t)):e.type===`message.deleted`?(await o.delete(s,a.message),a.files?.length&&await o.deleteFiles(a.files)):e.type===`reaction.added`?await o.react(s,a.message,k(e.payload.emoji),!0):await o.react(s,a.message,k(e.payload.emoji),!1)})}catch(t){console.warn(`[board] skipped ${e.type} on ${i}:`,t.message)}}async function et(e){let{id:t}=e.payload,n=(await M([t]))[t]??{},r=e.message;if(!r||Object.keys(n).length===0)return;let i=await O(t);if(!i||i.deleted)return;let a=await I(),o={...i,labels:r.labels},s={...i,labels:e.before?.labels??{}};for(let[t,r]of Object.entries(n))if(await b(t))try{await $(l(t),e,o,t,async e=>{let n=await Y(t,o,a,r.files===null,e);n.markdown!==(await Y(t,s,a,r.files===null,e)).markdown&&await c(l(t)).edit(x(r.thread),r.message,n)})}catch(e){console.warn(`[board] skipped labels.changed on ${t}:`,G(e))}}async function tt(e,{attempt:t}){switch(e.type){case`thread.synced`:return Ye(e,t);case`message.posted`:return Qe(e,t);case`message.edited`:case`message.deleted`:case`reaction.added`:case`reaction.removed`:return $e(e);case`labels.changed`:return et(e)}}async function nt(e,t){let n=e[0]?await E(e[0].thread):null;if(!n)return[];let r=[];for(let e of new Set(Object.values(n.external)))await b(e)&&r.push(e);return(await Promise.all(r.map(async n=>{let r=l(n);try{let i=c(r),a=null;for(let t=e.length-1;t>=0&&a===null;t--){let r=e[t];!r.deleted&&r.origin?.thread===n&&(a=r.origin.message)}return await i.startTyping(x(n),a,t),n}catch(e){return console.warn(`[board] skipped typing on ${n}:`,G(e)),null}}))).filter(e=>e!==null)}async function rt(e,t){try{return`${e}:${await c(e).resolveChannel(t)}`}catch(e){throw d(`can't resolve inbox channel: ${e.message}`)}}let it=e=>e===`unsupported`||e===`invalid_target`?400:e===`channel_not_found`?404:e===`ratelimited`?429:[`no_client`,`list_failed`,`internal_error`,`fatal_error`,`service_unavailable`,`request_timeout`].includes(e)?502:403;async function at(e,t,n,r){let i=c(e);try{let a=await i.read(t,{limit:n,after:r});return{...a,messages:a.messages.map(t=>({...t,text:be(e,i.platform,t.text)}))}}catch(n){throw n instanceof j?new _(it(n.code),n.code,n.message):d(`can't read ${t} from ${e}: ${G(n)}`,`platform_error`)}}async function ot(e,t){let n=c(e);try{return await n.join(t)}catch(n){throw n instanceof j?new _(it(n.code),n.code,n.message):d(`can't join ${t} on ${e}: ${G(n)}`,`platform_error`)}}return{entries:e,bind(e){t=e},caller:a,deliver:tt,receive:je,pull:De,normalizeTarget:Ce,handleWebhook:Ee,inboxChannel:rt,typing:nt,readSource:at,joinSource:ot}}function J(e){let t=e.url?`${e.title}\n${e.url}`:e.title;return e.body?`${t}\n\n${e.body}`:t}export{q as createSyncEngine,K as keyedId};
5
+ `).filter(e=>/^📎 .* didn't come over: /u.test(e)),U=e=>JSON.stringify([e.url,e.message,e.snapshot,e.unavailable]),ge=(e,t)=>e.length===t.length&&e.every((e,n)=>U(e)===U(t[n])),_e=new AbortController().signal,ve=e=>{try{return JSON.parse(JSON.stringify(e??null))}catch{return null}},W=e=>typeof e==`string`?D(e):Array.isArray(e)?e.map(W):typeof e==`object`&&e?Object.fromEntries(Object.entries(e).map(([e,t])=>[D(e),W(t)])):e,G=e=>{let t=e?.data?.error,n=typeof t==`string`?t:e instanceof Error?e.message:String(e);return D(n.slice(0,500))||`unknown error`},ye=e=>e instanceof _&&e.status===404;function K(e,t,n){return n.startsWith(`${e}:`)?n:`${e}:${n.startsWith(`${t}:`)?n.slice(t.length+1):n}`}function be(e,t,n){return e===t?n:re(n,n=>n.kind===`actor`&&n.actor.startsWith(`${t}:`)?`@[${K(e,t,n.actor)}]`:null)}function xe(e,t,n){if(!(`author`in n))return n;let r={...n.author,id:K(e,t,n.author.id)};return n.kind!==`message`&&n.kind!==`edited`||e===t?{...n,author:r}:{...n,author:r,...n.mentioned?{mentioned:n.mentioned.map(n=>({...n,id:K(e,t,n.id)}))}:{},text:be(e,t,n.text)}}function q(e){let t=null,i=()=>{if(!t)throw Error(`sync used before board() bound it`);return t},a={self:`sync`,origin:{via:{kind:`engine`}}};function o(e,t,n=_e,r=a){let o=i().backend;return o[e].call(o,r,t,n)}let c=t=>{let n=e[t];if(!n)throw d(`no sync entry named ${t}`);return n},l=e=>e.slice(0,e.indexOf(`:`)),g=e=>i().syncedHere(e),b=async t=>e[l(t)]!==void 0&&await g(l(t)),x=e=>e.slice(e.indexOf(`:`)+1);async function E(e){try{return await o(`syncThread`,{thread:e})}catch(e){if(ye(e))return null;throw e}}async function D(e){try{let{message:t,replies:n}=await o(`message`,{id:e});return[t,...n]}catch(e){if(ye(e))return[];throw e}}async function O(e){return(await D(e)).find(t=>t.id===e)??null}async function M(e){return e.length===0?{}:(await o(`syncCopies`,{message:[...new Set(e)]})).copies}let N=(e,t)=>o(`syncFind`,e,t),P=null;function F(){if(P)return P;let e=o(`me`,{}).then(e=>e.principal);return P=e,e.catch(()=>{P===e&&(P=null)}),e}async function I(){let[{actors:e},t]=await Promise.all([o(`actors`,{}),F().catch(()=>null)]),n={byId:{},principal:t};for(let t of e)n.byId[t.id]={id:t.id,kind:t.kind,handle:t.handle,name:t.name,avatar:t.avatar,...t.via?{via:{...t.via}}:{},...t.platform?{platform:t.platform}:{},...t.verified?{verified:!0}:{}};return n}let L=/* @__PURE__ */ new Map;function R(e,t){let n=`${e}:${t}`,r=L.get(n);if(r&&(!r.failed||Date.now()-r.at<6e4))return r.id;let i={id:c(e).resolveChannel(t),failed:!1,at:Date.now()};return i.id.catch(r=>{i.failed=!0;let a=se(r);!a&&L.get(n)===i&&L.delete(n),console.warn(`[board] sync ${e}: ${a?`skipping`:`couldn't resolve`} ${t}: ${r.message}`)}),L.set(n,i),i.id}function U(e,t){if(!v(t))return x(t);try{let n=c(e).inboxChannel(e,t);return n===null?null:x(n)}catch{return null}}let q=/* @__PURE__ */ new Map;function Se(e,t){let n=`${e}\u001f${t.toLowerCase()}`,r=q.get(n);if(r&&Date.now()-r.at<3e5)return r.mention;q.size>=1e3&&q.clear();let i=c(e),a=i.findByEmail(t).then(e=>e?i.mention({id:e.id,kind:`external`,handle:e.handle,name:e.name,avatar:e.avatar}):null,()=>null);return q.set(n,{at:Date.now(),mention:a}),a}async function Ce(e){let t=e.indexOf(`:`);if(t<=0)throw d(`sync targets look like <key>:<channel or thread>, got: ${e}`);let n=e.slice(0,t),r=c(n);try{let i=oe.parse(await r.resolveTarget(e.slice(t+1)));if(i.kind===`channel`&&!r.canStartThreads)throw Error(`${r.platform} cannot start threads; use an existing thread`);return{target:`${n}:${i.target}`,kind:i.kind}}catch(t){throw d(`can't sync to ${e}: ${t.message}`)}}async function we(e,t){let{event:n,raw:r,dedupe:i}=ce.parse(W({...t,raw:ve(t.raw)}));for(let t of[n.channel,n.thread,`subthread`in n?n.subthread:null])if(t!==null&&!t.startsWith(`${e}:`))throw d(`provider locations must belong to sync entry ${e}`);let a=le(c(e)),s=a&&await a(x(n.channel),t=>R(e,t)).catch(async e=>{if(await Te(n.thread))return!0;throw e});(!a||s||await Te(n.thread))&&await o(`inboxPush`,{key:e,events:[{id:i,event:n,raw:r}]})}async function Te(e){try{return(await N({thread:e},AbortSignal.timeout(2e3))).thread!==null}catch(e){let t=e?.name;if(t===`TimeoutError`||t===`AbortError`)return!0;throw e}}async function Ee(t,n){let r=e[t];if(!r)throw ie(`no sync entry named ${t}`);if(!await g(t))return new Response(null,{status:200});let i;try{i=await r.receive(t,n,e=>we(t,e))}catch(e){return e instanceof _&&e.status===400?(console.error(`[board] dropped an event the board refuses`,e),new Response(null,{status:200})):(console.error(`[board] intake failed`,e),new Response(`intake failed`,{status:500}))}let a=De([t]).catch(e=>console.error(`[board] couldn't pull ${t}'s inbox:`,G(e)));return ee(a),i}async function De(t=Object.keys(e)){let n=0,r=Date.now()+24e4;for(let e of t)if(await g(e))for(;Date.now()<r;){let{items:t}=await o(`inboxNext`,{key:e,limit:10});if(t.length===0)break;await Promise.all(t.map(t=>Oe(e,t))),n+=t.length}return n}async function Oe(e,t){let n;try{await je(e,{event:t.event,raw:t.raw},{id:t.id,attempt:t.attempt+1})}catch(r){console.error(`[board] sync ${e} couldn't import ${t.id}:`,G(r)),n=G(r)}await o(`inboxAck`,{key:e,id:t.id,lease:t.lease,...n===void 0?{}:{error:n}}).catch(e=>console.error(`[board] couldn't ack an inbox event:`,G(e)))}async function ke(e,t,n,r,i=[]){if(t.length===0)return[];let a=[];for(let o of t){if(a.some(e=>e.url===o.url))continue;let t=(await N({thread:o.thread,message:o.message})).message,s=t===null?null:await O(t);if(s&&!s.deleted&&s.channel===r){a.push({url:o.url,message:s.id,unavailable:null,snapshot:{author:s.author?T(s.author):s.by.actor,text:s.text,createdAt:s.createdAt,files:s.attachments.map(e=>({name:e.name,url:null}))}});continue}if(o.snapshot){a.push({url:o.url,message:null,snapshot:o.snapshot,unavailable:null});continue}let c=i.find(e=>e.url===o.url&&e.snapshot&&e.message===null);if(c){a.push(c);continue}let l=await e.fetchLink(o,n).catch(e=>({snapshot:null,unavailable:G(e)}));a.push({url:o.url,message:null,snapshot:l.snapshot,unavailable:l.snapshot?null:(l.unavailable??`unknown`).slice(0,300)})}return W(a)}async function Ae(e,t,n){let i=[],a=[],c=null;for(let l of t.slice(0,10)){if(c!==null){a.push(me(l,c));continue}if(l.size!==void 0&&l.size>26214400){a.push(B(l,`over ${r/1024/1024} MB`));continue}let t;try{let n=await e.fetchFile(l);if(n===null){a.push(B(l,`${e.platform} can't hand it over`));continue}t=n}catch(t){if(n<3)throw t;console.warn(`[board] couldn't fetch ${l.name??`a file`} from ${e.platform}:`,G(t)),a.push(B(l,`${e.platform} wouldn't hand it over`));continue}if(t.byteLength>26214400){a.push(B(l,`over ${r/1024/1024} MB`));continue}if(t.byteLength===0){a.push(B(l,`it was empty`));continue}let d=l.name??`${l.type}`;try{i.push((await o(`upload`,{data:t,name:d,type:l.mimeType||s(d)})).attachment)}catch(e){if(e instanceof _&&(e.code===`too_large`||e.code===`no_direct_uploads`)){a.push(B(l,`over ${u/1024/1024} MB`));continue}if(!V(e))throw e;c=e.message,a.push(me(l,c))}}for(let e of t.slice(10))a.push(B(e,`a message carries at most 10`));return{attachments:i,notes:a}}async function je(e,t,n){let r=c(e),a={...t,event:xe(e,r.platform,t.event)},{event:o,raw:s}=a,l=(await N({thread:o.thread})).thread??void 0;if(o.kind===`message`){let e=(await N({thread:o.subthread??o.thread,message:o.message})).message;if(e!==null){let t=(await O(e))?.origin;if(!t||t.message!==o.message||(t.subthread??t.thread)!==(o.subthread??o.thread))return}}let u=`author`in o?o.author:{id:`${e}:system`,handle:r.platform,name:r.platform,avatar:null,isBot:!0},f,p=()=>f??=A(r.event({id:n.id,key:e,event:o,raw:s})),m,h,g=!0,_={direction:`in`,key:e,channel:x(o.channel),get event(){return p()},board:i().client({author:u,key:e,...Ne(e,o)},n.id),import(t,r={}){if(!g)throw d(`the sync function has finished`);return m??=Me(e,a,n,l,t,r),m},permalink(){let e=h??r.permalink(p());return h=e,e.catch(()=>{h===e&&(h=void 0)}),e},resolve:t=>R(e,t)};try{await r.sync(_),await m}finally{g=!1}}async function Me(e,t,n,r,i,a){let o=i??(r?(await E(r))?.channel:void 0);if(o===void 0)return{root:null,message:null};try{return await Pe(e,t,n,p.parse(o),ae.parse(a))}catch(e){if(!(e instanceof ne))throw e;let n=(await N({thread:t.event.thread})).thread;return{root:n===null?null:(await E(n))?.root??null,message:null}}}function Ne(e,t){let n=c(e),r=(`subthread`in t?t.subthread:null)??t.thread;return{via:{kind:`sync`,key:e,platform:n.platform,channel:t.channel,thread:r},respond:async e=>{await n.post(x(r),`thread`,{markdown:e})}}}async function Pe(e,t,n,r,i){let{event:a,raw:s}=t,l=Ne(e,a),u=c(e),f=(await N({thread:a.thread})).thread??void 0,p=f?await E(f):null,m=p?.root,g=e=>h(`board-inbound`,n.id,String(e)),_={key:e,channel:l.via.channel,thread:l.via.thread},v=async e=>{if(!e.dropped)return e.message;for(let t of e.dropped)await l.respond(t);throw new ne(e.dropped)},y=async({attachments:t=[],...n})=>({id:await v(await o(`syncImport`,{op:`post`,from:e,source:_,...n,origin:n.origin??null,...t.length?{attachments:t.map(e=>e.id)}:{}})),re:n.re??null}),b=e=>({root:e.re??e.id,message:e.id}),S=(e={})=>{let t={...e,...i.labels};for(let e of i.unset??[])delete t[e];return t},C=e=>{if(!i.root)return e;let t=i.root(A(structuredClone(e)));if(t&&typeof t==`object`&&`then`in t)throw d(`root overrides must be synchronous`);let n=ae.pick({text:!0,labels:!0}).parse(t);return{...e,text:n.text??e.text,labels:{...e.labels,...n.labels}}},w=(t,n,r)=>o(`syncImport`,{op:`labels`,author:t,from:e,origin:{thread:a.thread},set:n,unset:r}),T=async(e,t)=>{if(!i.labels&&!i.unset)return;let n=await O(t),r=Object.fromEntries(Object.entries(i.labels??{}).filter(([e,t])=>n?.labels[e]!==t)),a=(i.unset??[]).filter(e=>n?.labels[e]!==void 0);(Object.keys(r).length||a.length)&&await w(e,r,a)};switch(a.kind){case`message`:{let t=(await N({thread:a.subthread??a.thread,message:a.message})).message;if(t!==null)return{root:m??t,message:t};let{attachments:o,notes:c}=a.files?.length?await Ae(u,a.files,n.attempt):{attachments:[],notes:[]},l=await ke(u,a.links??[],{thread:a.subthread??a.thread,message:a.message},p?.channel??r),d={...l.length?{links:l}:{},...a.mentioned?.length?{mentioned:a.mentioned}:{},author:a.author,text:z(H(i.text??a.text,c),o.length>0),...o.length?{attachments:o}:{},origin:{channel:a.channel,thread:a.thread,subthread:a.subthread,message:a.message,context:a.context},id:await g(0)},f={...d,...i.noSync?{noSync:!0}:{}};if(m!==void 0)return await T(a.author,m),b(await y({...f,re:m}));let h=await u.fetchRoot(x(a.thread));if(h===null){let e=C({text:a.text,labels:{},author:a.author,raw:s});return b(await y({...d,channel:r,text:z(H(i.text??e.text,c),o.length>0),labels:S(e.labels)}))}let _=C({...h,raw:h.raw??null}),v=await y({author:{...h.author,id:K(e,u.platform,h.author.id)},channel:r,text:z(_.text),labels:S(_.labels),origin:{channel:a.channel,thread:a.thread,subthread:null,message:`root:${n.id}`,context:null},id:await g(1)});return b(await y({...f,re:v.id}))}case`edited`:case`deleted`:case`reaction`:{let t=(await N({thread:a.subthread??a.thread,message:a.message})).message;if(t===null)return{root:m??null,message:null};let n=`author`in a?a.author:{id:`${e}:system`,handle:u.platform,name:u.platform,avatar:null,isBot:!0},r={thread:a.subthread??a.thread,message:a.message};if(m!==void 0&&await T(n,m),a.kind===`deleted`)await o(`syncImport`,{op:`delete`,author:n,from:e,origin:r});else if(a.kind===`edited`){let s=await O(t),c=z(H(i.text??a.text,s?he(s.text):[]),(s?.attachments.length??0)>0),l=a.mentioned?.length?{mentioned:a.mentioned}:{};s&&!a.linksOnly&&s.text!==c&&await v(await o(`syncImport`,{op:`edit`,author:n,from:e,origin:r,text:c,source:_,...l}));let d=s?await ke(u,a.links??[],r,s.channel,s.links):[];s&&!ge(d,s.links)&&await o(`syncImport`,{op:`links`,author:n,from:e,origin:r,links:d})}else{if(u.singleReaction){let i=k(a.emoji),s=/* @__PURE__ */ new Set([n.id,`${await F()}+${n.id}`]);for(let[c,l]of Object.entries((await O(t))?.reactions??{}))l.some(e=>s.has(e))&&!(a.added&&c===i)&&await o(`syncImport`,{op:`react`,author:n,from:e,origin:r,emoji:c,remove:!0})}(!u.singleReaction||a.added)&&await o(`syncImport`,{op:`react`,author:n,from:e,origin:r,emoji:a.emoji,remove:!a.added})}return{root:m??null,message:t}}case`lifecycle`:{if(m!==void 0){let t=await O(m),r=t?.origin?.message===`lifecycle:${n.id}`,c=S((r?C({text:J(a),labels:a.labels,author:a.author,raw:s}):null)?.labels??a.labels),l=e=>a.owns?.some(t=>e.startsWith(t))??!1,u=Object.fromEntries(Object.entries(c).filter(([e,n])=>t?.labels[e]!==n)),d=Object.keys(t?.labels??{}).filter(e=>!(e in c)&&(a.unset.includes(e)||i.unset?.includes(e)||l(e)));if(t&&!t.deleted&&(Object.keys(u).length||d.length)&&await w(a.author,u,d),a.retitled&&t&&!t.deleted&&t.from===e&&t.origin?.thread===a.thread){let n=z(i.text??C({text:J(a),labels:t.labels,author:a.author,raw:s}).text);t.text!==n&&await v(await o(`syncImport`,{op:`edit`,author:a.author,from:e,origin:{thread:t.origin.thread,message:t.origin.message},text:n}))}return a.reply?b(await y({author:a.author,re:m,text:z(i.text??a.reply),...i.noSync?{noSync:!0}:{},id:await g(1)})):{root:m,message:r?m:null}}if(!a.createRoot)return{root:null,message:null};let t=C({text:J(a),labels:a.labels,author:a.author,raw:s}),c=await y({author:a.author,channel:r,text:z(a.reply?t.text:i.text??t.text),labels:S(t.labels),origin:{channel:a.channel,thread:a.thread,subthread:null,message:`lifecycle:${n.id}`,context:null},id:await g(0)});return a.reply?b(await y({author:a.author,re:c.id,text:z(i.text??a.reply),...i.noSync?{noSync:!0}:{},id:await g(1)})):b(c)}}}async function Fe(e,t,n){let r=m(n).flatMap(e=>e.kind===`actor`?[e.actor]:[]);if(r.length===0)return n;let i=/* @__PURE__ */ new Map;for(let n of r)!t.byId[n]&&S(n)&&i.set(n,await Se(e,n));return re(n,n=>{if(n.kind===`handle`)return null;if(i.has(n.actor))return i.get(n.actor)??n.actor;let r=Le(n.actor,t);return r?ze(e,r.id,t)??r.name:Ie(e,n.actor,t)})}function Ie(e,t,n){let r=Re(e,t,n);if(r===null)return null;let i=c(e);return i.mentionById(`${i.platform}:${r}`)}function Le(e,t){return t.byId[e]??(t.principal?t.byId[`${t.principal}+${e}`]:void 0)??null}function Re(e,t,n){let{principal:r,profile:i}=y(t),a=i===null?t:f(i)!==null&&r===n.principal?i:null;return a?.startsWith(`${e}:`)?a.slice(e.length+1):null}function ze(e,t,n){let r=n.byId[t],i=r?Re(e,t,n):null;if(i===null)return null;let a=c(e);return a.mention({...r,id:`${a.platform}:${i}`})}async function Be(t,n,r,i,a){let o=i.byId[r.by.actor],s=o?.name??r.by.actor,l=`${o?.via?` ${te(o.via)}`:``}${r.from?` (${o?.platform??e[r.from]?.platform??r.from})`:``}`,u=o?.kind===`deployment`&&!o.via?/(?:@[^@/]+| \([^()]+\))$/.exec(s)?.[0]??``:``,f=`${s}${l}`,p=`${u}${l}`,m=c(t),h=fe(r,o),g=(a??(e=>m.render(e)))(A({message:{...structuredClone(r),text:pe(r.text,h)},author:o?{...o}:null,mentionOf:e=>ze(t,e,i),label:f,target:n}));if(typeof g!=`string`)throw d(`a provider renderer must return markdown`);let _=`**${f}**: `,v=await Fe(t,i,g.startsWith(_)&&ue(g.slice(_.length))?`**${f}**:\n\n${g.slice(_.length)}`:g),y=h?de(r.text):null;return{markdown:v,...o?.verified?{as:{name:f,avatar:Ve(r,o),attribution:p}}:{},...y?{deployments:y}:{}}}function Ve(e,t){let n=e=>!e||/\/avatars\/[a-z0-9-]+$/.test(e),r=t?.avatar??null;if(!n(r))return r;let i=t?.handle.split(`/`)[0]??``,a=e.by.principal.slice(12);return!e.by.principal.startsWith(`vercel:user:`)||!i||/^user-/.test(i)||i.toLowerCase()===a.toLowerCase()?r:`https://vercel.com/api/www/avatar?u=${encodeURIComponent(i)}&s=64&format=png`}let He=e=>e.attachments.map(t=>`\n📎 ${t.name} (${n(t.size)}, on the board: #${e.id})`).join(``),Y=async(e,t,n,r=!1,i)=>{let a=l(e),{markdown:o,...s}=await Be(a,e,t,n,i);return{markdown:t.attachments.length>0&&(r||!c(a).uploadsFiles)?`${o}\n${He(t)}`:o,...s}};async function Ue(e,t,n,r,i){let a=e.replyTo===null?void 0:(await M([e.replyTo]))[e.replyTo]?.[t],o=a!==void 0&&a.thread!==n?a.thread:n,s=c(l(t)),u=await Y(t,e,r,!1,i),f,p;if(!u.markdown.trim()&&e.attachments.length&&s.uploadsFiles)try{let n=await Ke(e,t,o);p=n.message,f=n.files}catch(n){if(!s.refusesFiles(n)&&!V(n))throw n;u=await Y(t,e,r,!0,i),p=(await s.post(x(o),`thread`,u)).message,f=null}else{if(!u.markdown.trim())throw d(`a renderer must return text unless the message has media`);p=(await s.post(x(o),`thread`,u)).message}let m={thread:o,message:p,...f===void 0?{}:{files:f}};return await We(e,t,m),m}async function We(e,t,n){await o(`syncReceipt`,{kind:`message`,message:e.id,target:t,external:{thread:n.thread,message:n.message},...n.files===void 0?{}:{files:n.files}})}async function Ge(e){return Promise.all(e.attachments.map(async e=>{let{data:t}=await o(`attachment`,{id:e.id});return{data:t instanceof Uint8Array?t:new Uint8Array(await new Response(t).arrayBuffer()),filename:e.name,mimeType:e.type}}))}async function Ke(e,t,n){return c(l(t)).uploadFiles(x(n),await Ge(e))}async function X(e,t,n,r,i){let a=c(l(t));if(!a.uploadsFiles||e.attachments.length===0||n.files!==void 0)return;let s;try{s=(await Ke(e,t,n.thread)).files}catch(o){if(!a.refusesFiles(o)&&!V(o))throw Object.assign(/* @__PURE__ */ Error(`files: ${G(o)}`),{cause:o,data:{error:`files: ${G(o)}`}});console.warn(`[board] ${t} won't take #${e.id}'s files (${G(o)}); noting them in its text`),s=null,await Y(t,e,r,!0,i).then(e=>a.edit(x(n.thread),n.message,e)).catch(n=>console.warn(`[board] couldn't note #${e.id}'s files on ${t}:`,G(n)))}await o(`syncReceipt`,{kind:`files`,message:e.id,target:t,files:s})}let Z=(e,t,n,r)=>{e.some(e=>e.error===r)||e.push({id:t,target:n,error:r})};async function Q(e,t){if(t.length!==0){if(e<5||w(e))throw t[0].error;for(let{id:e,target:n,error:r}of t)console.error(`[board] gave up ${n===null?`syncing #${e}`:`delivering #${e} to ${n}`}:`,G(r)),n!==null&&await o(`syncReceipt`,{kind:`failed`,message:e,target:n,error:G(r)})}}async function $(e,t,n,r,i){let a,o=!0,s=()=>d(`the sync function has finished`),l={direction:`out`,key:e,channel:r===null?null:U(e,r),event:A(structuredClone(t)),message:A(structuredClone(n)),target:r,deliver(e={}){if(!o)throw s();return a??=r===null?Promise.resolve():i(e.render),a},start(t){if(!o)throw s();return qe(e,n,t)},resolve:t=>R(e,t)};try{await c(e).sync(l),await a}finally{o=!1}}async function qe(e,t,n){let{target:r,kind:i}=await Ce(`${e}:${n}`),a=t.re===null?t:await O(t.re);!a||a.deleted||a.noSync||r!==(a.origin?a.origin.channel??C(a.origin.thread):null)&&await o(`syncReceipt`,{kind:`thread`,message:a.id,target:r,targetKind:i,cause:`config`})}async function Je(t,n){let r=[];for(let t of Object.keys(e))e[t].canStartThreads&&await g(t)&&r.push(t);if(t.payload.noSync||r.length===0)return;let i=await O(t.message.id);if(!i||i.deleted)return;let a=[];for(let e of r)try{await $(e,t,i,null,async()=>{})}catch(e){Z(a,i.id,null,e)}await Q(n,a)}async function Ye(e,t){let{thread:n,target:r}=e.payload;if(!await b(r)||(e.payload.kind??(v(r)?`thread`:`channel`))===`thread`)return;let i=await E(n);if(!i?.targets.includes(r))return;let[a,...o]=await D(i.root);if(!a||a.id!==i.root||a.deleted||a.noSync)return;let s=[];try{await $(l(r),e,a,r,e=>Xe(i,a,o,r,s,e))}catch(e){Z(s,a.id,r,e)}await Q(t,s)}async function Xe(e,t,n,r,i,a){let o=await I(),s=await M([t.id,...n.map(e=>e.id)]),u=e=>(i.push({id:t.id,target:r,error:e}),e),f=e.external[r];if(f){let e=s[t.id]?.[r];if(e)try{await X(t,r,e,o,a)}catch(e){throw u(e)}}else try{let e=c(l(r)),n=await Y(r,t,o,!1,a),i=!n.markdown.trim()&&t.attachments.length>0&&e.uploadsFiles;if(!n.markdown.trim()&&!i)throw d(`a renderer must return text unless the message has media`);let s,u=await(async()=>{if(!i&&(t.attachments.length===0||!e.startsThreadsWithFiles))return e.post(x(r),`channel`,n);try{let a=await e.post(x(r),`channel`,{...n,files:await Ge(t)});return s=i?a.files??[]:a.files,a}catch(n){if(!e.refusesFiles(n)&&!V(n))throw n;return s=null,e.post(x(r),`channel`,await Y(r,t,o,!0,a))}})();f=`${l(r)}:${u.thread}`;let p={thread:f,message:u.message,...s===void 0?{}:{files:s}};await We(t,r,p),await X(t,r,p,o,a)}catch(e){throw u(e)}let p=[];for(let e of n)if(!(e.deleted||e.noSync||Ze(e,r)))try{await X(e,r,s[e.id]?.[r]??await Ue(e,r,f,o,a),o,a)}catch(t){p.push({id:e.id,target:r,error:t})}if(i.push(...p),p.length)throw p[0].error}let Ze=(e,t)=>e.origin?.thread===t||e.from!==null&&l(t)===e.from;async function Qe(e,t){if(!e.message)return;if(e.message.re===null)return Je(e,t);if(e.payload.noSync)return;let n=await E(e.payload.thread);if(!n||n.targets.length===0)return;let r=await D(n.root);if(r[0]?.id!==n.root||r[0].noSync)return;let i=r.find(t=>t.id===e.message.id);if(!i||i.deleted)return;let a=await I(),o=[];for(let t of n.targets){let r=n.external[t];if(await b(t)&&r&&!Ze(i,t))try{await $(l(t),e,i,t,async e=>{let n=(await M([i.id]))[i.id]?.[t]??await Ue(i,t,r,a,e);await X(i,t,n,a,e)})}catch(e){Z(o,i.id,t,e)}}await Q(t,o)}async function $e(e){let t=(await M([e.payload.id]))[e.payload.id]??{};if(Object.keys(t).length===0)return;let n=e.type===`message.edited`?await O(e.payload.id):e.message??await O(e.payload.id);if(!n||e.type===`message.edited`&&n.deleted)return;let r=await I();for(let[i,a]of Object.entries(t))if(!(!await b(i)||e.payload.from!==null&&l(i)===e.payload.from))try{await $(l(i),e,n,i,async t=>{let o=c(l(i)),s=x(a.thread);e.type===`message.edited`?await o.edit(s,a.message,await Y(i,n,r,a.files===null,t)):e.type===`message.deleted`?(await o.delete(s,a.message),a.files?.length&&await o.deleteFiles(a.files)):e.type===`reaction.added`?await o.react(s,a.message,k(e.payload.emoji),!0):await o.react(s,a.message,k(e.payload.emoji),!1)})}catch(t){console.warn(`[board] skipped ${e.type} on ${i}:`,t.message)}}async function et(e){let{id:t}=e.payload,n=(await M([t]))[t]??{},r=e.message;if(!r||Object.keys(n).length===0)return;let i=await O(t);if(!i||i.deleted)return;let a=await I(),o={...i,labels:r.labels},s={...i,labels:e.before?.labels??{}};for(let[t,r]of Object.entries(n))if(await b(t))try{await $(l(t),e,o,t,async e=>{let n=await Y(t,o,a,r.files===null,e);n.markdown!==(await Y(t,s,a,r.files===null,e)).markdown&&await c(l(t)).edit(x(r.thread),r.message,n)})}catch(e){console.warn(`[board] skipped labels.changed on ${t}:`,G(e))}}async function tt(e,{attempt:t}){switch(e.type){case`thread.synced`:return Ye(e,t);case`message.posted`:return Qe(e,t);case`message.edited`:case`message.deleted`:case`reaction.added`:case`reaction.removed`:return $e(e);case`labels.changed`:return et(e)}}async function nt(e,t){let n=e[0]?await E(e[0].thread):null;if(!n)return[];let r=[];for(let e of new Set(Object.values(n.external)))await b(e)&&r.push(e);return(await Promise.all(r.map(async n=>{let r=l(n);try{let i=c(r),a=null;for(let t=e.length-1;t>=0&&a===null;t--){let r=e[t];!r.deleted&&r.origin?.thread===n&&(a=r.origin.message)}return await i.startTyping(x(n),a,t),n}catch(e){return console.warn(`[board] skipped typing on ${n}:`,G(e)),null}}))).filter(e=>e!==null)}async function rt(e,t){try{return`${e}:${await c(e).resolveChannel(t)}`}catch(e){throw d(`can't resolve inbox channel: ${e.message}`)}}let it=e=>e===`unsupported`||e===`invalid_target`?400:e===`channel_not_found`?404:e===`ratelimited`?429:[`no_client`,`list_failed`,`internal_error`,`fatal_error`,`service_unavailable`,`request_timeout`].includes(e)?502:403;async function at(e,t,n,r){let i=c(e);try{let a=await i.read(t,{limit:n,after:r});return{...a,messages:a.messages.map(t=>({...t,text:be(e,i.platform,t.text)}))}}catch(n){throw n instanceof j?new _(it(n.code),n.code,n.message):d(`can't read ${t} from ${e}: ${G(n)}`,`platform_error`)}}async function ot(e,t){let n=c(e);try{return await n.join(t)}catch(n){throw n instanceof j?new _(it(n.code),n.code,n.message):d(`can't join ${t} on ${e}: ${G(n)}`,`platform_error`)}}return{entries:e,bind(e){t=e},caller:a,deliver:tt,receive:je,pull:De,normalizeTarget:Ce,handleWebhook:Ee,inboxChannel:rt,typing:nt,readSource:at,joinSource:ot}}function J(e){let t=e.url?`${e.title}\n${e.url}`:e.title;return e.body?`${t}\n\n${e.body}`:t}export{q as createSyncEngine,K as keyedId};
@@ -1,7 +1,7 @@
1
1
  import { i as ATTACHMENT_BYTES_MAX, r as parseProfileHeader, t as InvalidProfileHeader } from "./profile-header-Cj0Cb1cf.mjs";
2
- import "./schemas-TeVe4Udh.mjs";
3
- import { t as Failed, u as who } from "./main-CqX7JqzE.mjs";
4
- import { n as relative, r as shell, t as CSP } from "./shell-BLHZoP-x.mjs";
2
+ import "./schemas-CUSTEFIy.mjs";
3
+ import { t as Failed, u as who } from "./main-B016auoG.mjs";
4
+ import { n as relative, r as shell, t as CSP } from "./shell-DmpmgOPC.mjs";
5
5
  import { t as page } from "./page-7KWSGxyC.mjs";
6
6
  import { randomBytes, timingSafeEqual } from "node:crypto";
7
7
  import { createServer } from "node:http";
@@ -0,0 +1,2 @@
1
+ import { n as inspect } from "./inspect-CZeoSm7E.mjs";
2
+ export { inspect };
package/dist/inspect.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { i as ATTACHMENT_BYTES_MAX, r as parseProfileHeader, t as InvalidProfileHeader } from "./profile-header-Cj0Cb1cf.mjs";
2
- import "./schemas-TeVe4Udh.mjs";
3
- import { n as relative, r as shell, t as CSP } from "./shell-BLHZoP-x.mjs";
2
+ import "./schemas-CUSTEFIy.mjs";
3
+ import { n as relative, r as shell, t as CSP } from "./shell-DmpmgOPC.mjs";
4
4
  import { t as page } from "./page-7KWSGxyC.mjs";
5
5
  //#region src/inspect/handler.ts
6
6
  /**
@@ -1,20 +1,20 @@
1
1
  import { a as DIRECT_UPLOAD_BYTES_MAX, i as ATTACHMENT_BYTES_MAX, l as mediaType, o as IMPORT_BYTES_MAX, s as fileName } from "./profile-header-Cj0Cb1cf.mjs";
2
- import { A as authorView, D as TaskNote, E as TaskHoldKind, M as storable, T as TASK_NOTE_MAX, _ as OPEN_TASK_STATES, a as CAN_MAX, b as SeenActorKind, c as EDITED_HOLD, d as LabelKey, g as MessageText, h as MessageId, i as Author, j as platformAvatar, k as actorKind, l as Emoji, n as Attachment, o as CHANNEL_PATTERN_MAX, p as Labels, s as ChannelPath, t as ActorId, u as Handle, w as TASK_LABEL, y as RemoteWatcherId } from "./schemas-TeVe4Udh.mjs";
3
- import { a as Link, i as ExternalTarget, n as ExternalEvent, o as Origin } from "./external-BLI4W_-V.mjs";
4
- import "./routes-qS92xz8U.mjs";
5
- import { a as duplicateId, c as notFound, f as BoardError, i as batchTooLarge, l as textTooLong, m as duration, o as forbidden$1, r as badRequest, t as HttpError, u as toErrorResponse } from "./errors-DwV7I0g4.mjs";
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-ysFm2S4v.mjs";
2
+ import { A as actorKind, D as TaskHoldKind, E as TASK_NOTE_MAX, M as platformAvatar, N as storable, O as TaskNote, T as TASK_LABEL, a as CAN_MAX, b as RemoteWatcherId, c as EDITED_HOLD, d as LabelKey, g as MessageText, h as MessageId, i as Author, j as authorView, l as Emoji, n as Attachment, o as CHANNEL_PATTERN_MAX, p as Labels, s as ChannelPath, t as ActorId, u as Handle, v as OPEN_TASK_STATES, x as SeenActorKind } from "./schemas-CUSTEFIy.mjs";
3
+ import { a as Link, i as ExternalTarget, n as ExternalEvent, o as Origin } from "./external-D2jq_DEQ.mjs";
4
+ import "./routes-BE0y6wCk.mjs";
5
+ import { a as duplicateId, c as notFound, f as BoardError, i as batchTooLarge, l as textTooLong, m as duration, o as forbidden$1, r as badRequest, t as HttpError, u as toErrorResponse } from "./errors-DYF4hhIc.mjs";
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-DUKIITFZ.mjs";
7
7
  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";
8
8
  import { a as replaceMentions, i as mentionTerms, n as isEmail, r as mentionTerm, t as extractMentions } from "./mentions-CnWt9Z5b.mjs";
9
- import { t as VERSION } from "./version-BCoWGLEW.mjs";
10
- import { c as compileAccess, i as authorize, o as checkGrantChange, t as FULL_ACCESS, u as parseCan } from "./access-B8DnrnHa.mjs";
11
- import { a as runMatch, h as SYNC, i as canonicalWatchers, l as METHODS, n as SYNC_ACTOR, o as compileWatcher, r as syncTarget, s as hasCriteria, t as batchPlan } from "./task-batch-CujTLmTB.mjs";
12
- import { T as wroteAs, b as removes, c as checkCan, g as joined, h as issuerName, l as checkGrant, n as GITHUB_ISSUER, p as grantIssuers, s as authenticates, u as checkPrincipal, w as workflowPath } from "./auth-CEU06Nyp.mjs";
9
+ import { t as VERSION } from "./version-C70RLVEK.mjs";
10
+ import { c as compileAccess, i as authorize, o as checkGrantChange, t as FULL_ACCESS, u as parseCan } from "./access-BbgmsAFF.mjs";
11
+ import { a as runMatch, h as SYNC, i as canonicalWatchers, l as METHODS, n as SYNC_ACTOR, o as compileWatcher, r as syncTarget, s as hasCriteria, t as batchPlan } from "./task-batch-9lVDG3d-.mjs";
12
+ import { T as wroteAs, b as removes, c as checkCan, g as joined, h as issuerName, l as checkGrant, n as GITHUB_ISSUER, p as grantIssuers, s as authenticates, u as checkPrincipal, w as workflowPath } from "./auth-DJDTfgAL.mjs";
13
13
  import { n as setOwn, t as own } from "./own-OwgPWdmh.mjs";
14
- import { i as ownedActor, n as actorSeen, o as viaOf } from "./actors-DewJKyqy.mjs";
14
+ import { i as ownedActor, n as actorSeen, o as viaOf } from "./actors-CX2D22hL.mjs";
15
15
  import { C as sessionClearedError, a as SOCKET_TIMINGS, c as drainSettledHooks, d as nullProtoRecord, f as runtimeConsumerFactory, g as A2Error, h as stateTailReaders, i as RESERVED_PARTICIPANT_IDS, l as failedPreviousAttempt, m as serverInternals, n as POLL_TIMINGS, o as STATE_CACHE, p as runtimeConsumers, r as PRESENCE_TIMINGS, s as STREAM_TIMINGS, t as DRAIN_TIMINGS, u as markSchedulerSendFailure, v as NonRetriableError, x as isSessionCleared, y as asStoreUnavailable } from "./internal-CvsrprnU-CEPOUpAv.mjs";
16
16
  import { i as streamActivities, n as defaultSleep, t as createStreamActivity } from "./store-polling-BZt2Rf3D-oh3aU_An.mjs";
17
- import { a as foldActors, i as concernedMessageId, o as foldMessages, s as iso, t as TABLES_CONSUMER } from "./sql-DIKQd5Me.mjs";
17
+ import { a as foldActors, i as concernedMessageId, o as foldMessages, s as iso, t as TABLES_CONSUMER } from "./sql-iABdyCiz.mjs";
18
18
  import { z } from "zod";
19
19
  import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
20
20
  import { mkdir, readFile, writeFile } from "node:fs/promises";
@@ -5197,6 +5197,7 @@ async function writePost(ctx, input) {
5197
5197
  if (input.sync?.length) throw badRequest("sync attaches whole threads: use `board sync <id> <target>`");
5198
5198
  } else {
5199
5199
  if (!channel) throw badRequest("a post needs a channel");
5200
+ if (input.noSync && input.sync?.length) throw badRequest("`noSync` and `sync` contradict each other");
5200
5201
  if (input.after !== void 0) throw badRequest("`after` is for replies", "invalid_after");
5201
5202
  thread = id;
5202
5203
  }
@@ -5273,7 +5274,6 @@ async function commitPost(ctx, input, placed) {
5273
5274
  const targets = [];
5274
5275
  if (re === null) for (const requested of input.sync ?? []) {
5275
5276
  const target = syncTarget(requested);
5276
- await unclaimed(ctx, target, thread, identity.principal.access);
5277
5277
  if (!targets.some((t) => t.target === target.target)) targets.push({
5278
5278
  ...target,
5279
5279
  cause: "request"
@@ -5324,6 +5324,7 @@ async function commitPost(ctx, input, placed) {
5324
5324
  const before = events.findIndex((event) => event.type === "message.posted");
5325
5325
  rows = await appendFrom(ctx, async () => {
5326
5326
  const { position, events: more } = await along();
5327
+ for (const target of targets) await unclaimed(ctx, target, thread, identity.principal.access);
5327
5328
  const came = more({
5328
5329
  id: position + 1 + before,
5329
5330
  thread
@@ -5339,7 +5340,8 @@ async function commitPost(ctx, input, placed) {
5339
5340
  } : event), ...came]
5340
5341
  };
5341
5342
  });
5342
- } else rows = input.after === void 0 || re === null ? await ctx.session.append(...events) : await appendWhile(ctx, nothingAfter(ctx, re, input.after), events);
5343
+ } else if (targets.some((target) => target.kind === "thread")) rows = await appendWhile(ctx, unclaimedAt(ctx, targets, thread, identity.principal.access), events);
5344
+ else rows = input.after === void 0 || re === null ? await ctx.session.append(...events) : await appendWhile(ctx, nothingAfter(ctx, re, input.after), events);
5343
5345
  } catch (error) {
5344
5346
  const replayed = error instanceof HttpError && error.code === "newer_message" || input.with !== void 0 && duplicateEvent(error) ? await replayOf(ctx, input, {
5345
5347
  channel,
@@ -5490,12 +5492,12 @@ const readerFor = (ctx, access, message) => ctx.reads.reader(access, [message]);
5490
5492
  * Refuses an external thread another board thread is synced with: taking it
5491
5493
  * over would send its replies away from that thread, to a caller who may not
5492
5494
  * read it. A reader of that thread's channel learns which thread it is. It
5493
- * reads the tables once they've applied the whole log, so a sync just made
5494
- * counts.
5495
+ * reads the tables as they are: it runs inside an append's look, whose
5496
+ * `appendFrom` has them apply the log first, and whose append lands only if
5497
+ * nothing, another claim included, landed since.
5495
5498
  */
5496
5499
  async function unclaimed(ctx, target, thread, access) {
5497
5500
  if (target.kind !== "thread") return;
5498
- await ctx.reads.ensure();
5499
5501
  const owner = await ctx.reads.tables.threadOf(target.target);
5500
5502
  if (owner === null || owner === thread) return;
5501
5503
  const synced = await ctx.reads.tables.syncOf(owner);
@@ -5503,6 +5505,16 @@ async function unclaimed(ctx, target, thread, access) {
5503
5505
  throw new HttpError(409, "already_synced", `${target.target} is already synced with ${which}`);
5504
5506
  }
5505
5507
  /**
5508
+ * An append's condition that none of `targets` is another thread's, as `unclaimed` refuses: it
5509
+ * returns the index its reads reflect at least, so the append lands only if nothing, another
5510
+ * claim included, landed since.
5511
+ */
5512
+ const unclaimedAt = (ctx, targets, thread, access) => async () => {
5513
+ const position = await ctx.reads.tables.position();
5514
+ for (const target of targets) await unclaimed(ctx, target, thread, access);
5515
+ return position;
5516
+ };
5517
+ /**
5506
5518
  * Waits until the tables hold a write, so any read after it includes it. Most often
5507
5519
  * nothing was written in between, and the writer applies its own events itself; else
5508
5520
  * it waits for the tables' consumer. The write landed either way: if the tables are
@@ -5774,10 +5786,7 @@ const labelsAre = (ctx, id, expected) => async () => {
5774
5786
  async function writeAttach(ctx, input) {
5775
5787
  const message = spent(input.authorized, "sync");
5776
5788
  const { target, kind } = input.target;
5777
- await ctx.reads.ensure();
5778
- if ((await ctx.reads.tables.syncOf(message.thread))?.targets.includes(target)) return { attached: false };
5779
- await unclaimed(ctx, input.target, message.thread, input.identity.principal.access);
5780
- await untilApplied(ctx, await ctx.session.append({
5789
+ const event = {
5781
5790
  type: "thread.synced",
5782
5791
  id: await derivedId("board", message.thread, "sync", target),
5783
5792
  payload: {
@@ -5787,8 +5796,21 @@ async function writeAttach(ctx, input) {
5787
5796
  cause: input.cause,
5788
5797
  by: input.identity.author
5789
5798
  }
5790
- }));
5791
- return { attached: true };
5799
+ };
5800
+ const rows = await appendFrom(ctx, async () => {
5801
+ const position = await ctx.reads.tables.position();
5802
+ if ((await ctx.reads.tables.syncOf(message.thread))?.targets.includes(target)) return {
5803
+ position,
5804
+ events: []
5805
+ };
5806
+ await unclaimed(ctx, input.target, message.thread, input.identity.principal.access);
5807
+ return {
5808
+ position,
5809
+ events: [event]
5810
+ };
5811
+ });
5812
+ await untilApplied(ctx, rows);
5813
+ return { attached: rows.length > 0 };
5792
5814
  }
5793
5815
  /**
5794
5816
  * A channel made before anything posts to it, or the one that's there, made by a post or another
@@ -10470,10 +10492,10 @@ function local(options = {}) {
10470
10492
  opening ??= (async () => {
10471
10493
  const file = localFile(bound.name);
10472
10494
  let store;
10473
- if (options.memory) store = (await import("./memory-DzqkXIB-.mjs")).memory();
10495
+ if (options.memory) store = (await import("./memory-C2lzMV_t.mjs")).memory();
10474
10496
  else {
10475
10497
  const { mkdir } = await import("node:fs/promises");
10476
- const { sqlite } = await import("./sqlite-BF9kBDh1.mjs");
10498
+ const { sqlite } = await import("./sqlite-28EMrmk7.mjs");
10477
10499
  const path = join(dir, `${file}.db`);
10478
10500
  try {
10479
10501
  await mkdir(dir, {
@@ -1,18 +1,18 @@
1
1
  import { a as DIRECT_UPLOAD_BYTES_MAX, c as fileSize } from "./profile-header-Cj0Cb1cf.mjs";
2
- import { m as MESSAGE_TEXT_MAX, r as AttachmentId } from "./schemas-TeVe4Udh.mjs";
3
- import "./routes-qS92xz8U.mjs";
2
+ import { m as MESSAGE_TEXT_MAX, r as AttachmentId } from "./schemas-CUSTEFIy.mjs";
3
+ import "./routes-BE0y6wCk.mjs";
4
4
  import { n as displayEmoji, r as normalizeEmoji } from "./emoji-CTLpvH-A.mjs";
5
- import { f as BoardError } from "./errors-DwV7I0g4.mjs";
6
- import { l as shownName } from "./middleware-ysFm2S4v.mjs";
5
+ import { f as BoardError } from "./errors-DYF4hhIc.mjs";
6
+ import { l as shownName } from "./middleware-DUKIITFZ.mjs";
7
7
  import { d as parseSchemaId, r as findBlocks, t as block } from "./blocks-CVoBC7ur.mjs";
8
8
  import { a as replaceMentions, n as isEmail, t as extractMentions } from "./mentions-CnWt9Z5b.mjs";
9
- import { t as VERSION } from "./version-BCoWGLEW.mjs";
10
- import { r as PERMISSIONS } from "./access-B8DnrnHa.mjs";
11
- import { c as withMentions } from "./task-batch-CujTLmTB.mjs";
12
- import { i as isBoardName, n as createTasksInChunks, s as isApiMessageId, t as TasksInChunksError } from "./exports-DLzyKwEp.mjs";
9
+ import { t as VERSION } from "./version-C70RLVEK.mjs";
10
+ import { r as PERMISSIONS } from "./access-BbgmsAFF.mjs";
11
+ import { c as withMentions } from "./task-batch-9lVDG3d-.mjs";
12
+ import { i as isBoardName, n as createTasksInChunks, s as isApiMessageId, t as TasksInChunksError } from "./exports-CuD-Mxkw.mjs";
13
13
  import { i as groups, n as filters$1, o as options, r as globalOptions, s as usage$1, t as commands } from "./commands-nN8WpvCe.mjs";
14
- import { a as vercel, c as configDir, d as handFetch, f as handLogin, h as vercelProjectFile, i as handTeam, l as connect, n as credentialSource, o as http, r as credentialed, s as boardUrl, t as board, u as environmentProfile } from "./server-V7qyVUiJ.mjs";
15
- import { t as conformance } from "./conformance-0xONNKcB.mjs";
14
+ import { _ as vercelProjectFile, a as vercel, c as boardUrl, d as environmentProfile, f as handFetch, i as handTeam, l as configDir, m as handToken, n as credentialSource, o as http, p as handLogin, r as credentialed, t as board, u as connect } from "./server-ViWNvg5q.mjs";
15
+ import { t as conformance } from "./conformance-Cr-umDl0.mjs";
16
16
  import { n as displayText, t as byVercelBot } from "./bots-CqPYxkqK.mjs";
17
17
  import { spawn } from "node:child_process";
18
18
  import { createHash, randomUUID } from "node:crypto";
@@ -287,6 +287,8 @@ const terminalText = (text) => text.replace(/\r\n/g, "\n").replace(/[\u0000-\u00
287
287
  const code = char.charCodeAt(0);
288
288
  return code < 32 ? String.fromCharCode(9216 + code) : code === 127 ? "␡" : "�";
289
289
  });
290
+ /** As `terminalText`, for what shows within one line: tab and newline show as their pictures too. */
291
+ const lineText = (text) => terminalText(text).replace(/[\t\n]/g, (char) => String.fromCharCode(9216 + char.charCodeAt(0)));
290
292
  /** Who you are, as your messages show you: `claude via julian` with a profile, your name otherwise. */
291
293
  const who = (me) => shownName(me);
292
294
  /**
@@ -307,7 +309,7 @@ function ago(iso, now = Date.now()) {
307
309
  const indent = (text, prefix) => text.split("\n").map((line) => `${prefix}${line}`).join("\n");
308
310
  function labels(message) {
309
311
  const entries = Object.entries(message.labels);
310
- return entries.length ? ` [${entries.map(([k, v]) => `${k}=${v}`).join(" ")}]` : "";
312
+ return entries.length ? ` [${entries.map(([k, v]) => `${k}=${lineText(v)}`).join(" ")}]` : "";
311
313
  }
312
314
  function reactions(message, names) {
313
315
  const groups = Object.entries(message.reactions);
@@ -423,7 +425,7 @@ function taskNote(message, task, room) {
423
425
  if (task.state === "completed" && task.result) return noteLine(task.result, room);
424
426
  if ((task.state === "failed" || task.state === "canceled") && task.reason) return noteLine(task.reason, room);
425
427
  if (task.state === "blocked" && task.blocked) return noteLine(task.blocked.reason, room);
426
- return [Object.entries(message.labels).filter(([key]) => !key.startsWith("board.")).map(([key, value]) => `${key}=${value}`).join(" "), task.state === "waiting" && task.needs.length ? `needs ${task.needs.map((id) => `#${id}`).join(" ")}` : ""].filter(Boolean).join(" ");
428
+ return [Object.entries(message.labels).filter(([key]) => !key.startsWith("board.")).map(([key, value]) => `${key}=${lineText(value)}`).join(" "), task.state === "waiting" && task.needs.length ? `needs ${task.needs.map((id) => `#${id}`).join(" ")}` : ""].filter(Boolean).join(" ");
427
429
  }
428
430
  /** The widest a task's state is (`completed`), and how wide its first line's column is at least and at most. */
429
431
  const STATE_WIDTH = 9;
@@ -1391,6 +1393,8 @@ let typed = [];
1391
1393
  let warnings = [];
1392
1394
  /** The board this run reached by its URL, for a failure to name. */
1393
1395
  let reached = null;
1396
+ /** Where the credential this run sent came from, as `whoami` says it, for a refusal to say which to replace. */
1397
+ let sent = () => null;
1394
1398
  /** How long the message text this run sends is, for a backend's refusal of it to say what to do instead. */
1395
1399
  let sentLength = 0;
1396
1400
  /** The help `words` ask for: a command's page when they name one (`read`, `sources read`), or else every command. */
@@ -2157,7 +2161,7 @@ function failureOf(error) {
2157
2161
  details: []
2158
2162
  };
2159
2163
  if (status === 400) return theirs("usage", specific("invalid_arguments"), `Can't ${doing()}.`);
2160
- if (status === 401) return theirs("auth", "login_required", "The board didn't accept your credentials.", process.env.BOARD_TOKEN && (reached && !vercelBoard(reached) || credentialSource() === "BOARD_TOKEN") ? [{ instruction: "Pass a token it accepts in BOARD_TOKEN, or unset it" }] : [{
2164
+ if (status === 401) return theirs("auth", "login_required", "The board didn't accept your credentials.", sent() === "the token you passed" ? [{ instruction: "Pass a token it accepts" }] : process.env.BOARD_TOKEN && (reached && !vercelBoard(reached) || credentialSource() === "BOARD_TOKEN") ? [{ instruction: "Pass a token it accepts in BOARD_TOKEN, or unset it" }] : [{
2161
2165
  instruction: "Log in again",
2162
2166
  argv: ["vercel", "login"]
2163
2167
  }]);
@@ -2276,6 +2280,7 @@ function connection(url = flags.url, options = {}) {
2276
2280
  ensure: flags.ensure === true
2277
2281
  } : {}
2278
2282
  });
2283
+ sent = credentialSource;
2279
2284
  return {
2280
2285
  url: null,
2281
2286
  transport: { source: credentialSource },
@@ -2290,6 +2295,7 @@ function connection(url = flags.url, options = {}) {
2290
2295
  ...onVercel,
2291
2296
  ...sending(options.token, options.can, options.headers)
2292
2297
  }) });
2298
+ sent = credentialSource;
2293
2299
  return {
2294
2300
  url: at,
2295
2301
  transport: { source: credentialSource },
@@ -2305,6 +2311,7 @@ function connection(url = flags.url, options = {}) {
2305
2311
  ...Object.keys(extra).length > 0 ? { fetch: withHeaders(extra) } : {}
2306
2312
  });
2307
2313
  const board$2 = board({ backend: http(at, { fetch: transport.fetch }) });
2314
+ sent = transport.source;
2308
2315
  return {
2309
2316
  url: at,
2310
2317
  transport,
@@ -4284,12 +4291,14 @@ const context = () => ({
4284
4291
  */
4285
4292
  async function main(argv, options) {
4286
4293
  handLogin(options.login ?? null);
4294
+ handToken(options.token ?? null);
4287
4295
  handTeam(options.team ?? null);
4288
4296
  handFetch(options.fetch ?? null);
4289
4297
  try {
4290
4298
  return await runOnce(argv, options);
4291
4299
  } finally {
4292
4300
  handLogin(null);
4301
+ handToken(null);
4293
4302
  handTeam(null);
4294
4303
  handFetch(null);
4295
4304
  }
@@ -4301,6 +4310,7 @@ async function runOnce(argv, options) {
4301
4310
  positionals = [];
4302
4311
  warnings = [];
4303
4312
  reached = null;
4313
+ sent = () => null;
4304
4314
  sentLength = 0;
4305
4315
  self = null;
4306
4316
  try {
@@ -1,6 +1,6 @@
1
- import { r as sqlTables } from "./sql-DIKQd5Me.mjs";
1
+ import { r as sqlTables } from "./sql-iABdyCiz.mjs";
2
2
  import { t as memory$1 } from "./store-memory-CKQVEzXN.mjs";
3
- import { t as sqliteDb } from "./sqlite-db-CSYwiZ4E.mjs";
3
+ import { t as sqliteDb } from "./sqlite-db-Ckd-ceNe.mjs";
4
4
  //#region src/store/memory.ts
5
5
  /**
6
6
  * A board that lives in memory, for tests: its log in A2's memory store, its
@@ -1,5 +1,5 @@
1
- import { m as MESSAGE_TEXT_MAX, p as Labels } from "./schemas-TeVe4Udh.mjs";
2
- import { t as HttpError } from "./errors-DwV7I0g4.mjs";
1
+ import { _ as NewLabels, m as MESSAGE_TEXT_MAX } from "./schemas-CUSTEFIy.mjs";
2
+ import { t as HttpError } from "./errors-DYF4hhIc.mjs";
3
3
  import { z } from "zod";
4
4
  //#region src/client/ids.ts
5
5
  const hex = (bytes) => Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
@@ -130,7 +130,7 @@ var DroppedError = class extends HttpError {
130
130
  };
131
131
  const Patch = z.object({
132
132
  text: z.string().max(MESSAGE_TEXT_MAX).optional(),
133
- labels: Labels.optional()
133
+ labels: NewLabels.optional()
134
134
  }).strict();
135
135
  const MIDDLEWARE_ACTOR = "board:middleware";
136
136
  /**
@@ -1,6 +1,6 @@
1
1
  import { a as DIRECT_UPLOAD_BYTES_MAX } from "./profile-header-Cj0Cb1cf.mjs";
2
- import { C as SentText, M as storable, O as TaskState, S as SentTaskNote, c as EDITED_HOLD, d as LabelKey, f as LabelValue, g as MessageText, j as platformAvatar, l as Emoji, m as MESSAGE_TEXT_MAX, o as CHANNEL_PATTERN_MAX, p as Labels, r as AttachmentId, s as ChannelPath, t as ActorId, x as SentTaskHoldKind } from "./schemas-TeVe4Udh.mjs";
3
- import { a as Link, i as ExternalTarget, n as ExternalEvent, o as Origin, t as ExternalAuthor } from "./external-BLI4W_-V.mjs";
2
+ import { C as SentTaskNote, M as platformAvatar, N as storable, S as SentTaskHoldKind, _ as NewLabels, c as EDITED_HOLD, d as LabelKey, f as LabelValue, g as MessageText, k as TaskState, l as Emoji, m as MESSAGE_TEXT_MAX, o as CHANNEL_PATTERN_MAX, p as Labels, r as AttachmentId, s as ChannelPath, t as ActorId, w as SentText } from "./schemas-CUSTEFIy.mjs";
3
+ import { a as Link, i as ExternalTarget, n as ExternalEvent, o as Origin, t as ExternalAuthor } from "./external-D2jq_DEQ.mjs";
4
4
  import { z } from "zod";
5
5
  //#region src/api/routes.ts
6
6
  /**
@@ -75,7 +75,7 @@ const PostBody = z.object({
75
75
  re: Ref.optional(),
76
76
  /** May be empty when the message has attachments. */
77
77
  text: z.string().default(""),
78
- labels: Labels.optional(),
78
+ labels: NewLabels.optional(),
79
79
  noSync: z.boolean().optional(),
80
80
  /**
81
81
  * External targets a new thread starts with: `slack:#incidents`, `github:owner/repo:12`. The
@@ -110,7 +110,7 @@ const ScheduleBody = z.object({
110
110
  channel: ChannelPath.optional(),
111
111
  re: Ref.optional(),
112
112
  text: z.string().default(""),
113
- labels: Labels.optional(),
113
+ labels: NewLabels.optional(),
114
114
  noSync: z.boolean().optional(),
115
115
  attachments: z.array(AttachmentId).optional(),
116
116
  in: Duration.optional(),
@@ -160,7 +160,7 @@ const CreateTaskBody = z.object({
160
160
  re: Ref.optional(),
161
161
  /** As long as a post's text may be: the backend says how long that is. */
162
162
  text: z.string().optional(),
163
- labels: Labels.optional(),
163
+ labels: NewLabels.optional(),
164
164
  noSync: z.boolean().optional(),
165
165
  /** IDs from `POST /attachments`, as a post takes them. */
166
166
  attachments: z.array(AttachmentId).optional(),
@@ -197,7 +197,7 @@ const CreateTasksBody = z.object({
197
197
  key: TaskKey.optional(),
198
198
  /** May be empty when the task's root has attachments. As long as a post's text may be: the backend says how long that is. */
199
199
  text: z.string(),
200
- labels: Labels.optional(),
200
+ labels: NewLabels.optional(),
201
201
  noSync: z.boolean().optional(),
202
202
  /** IDs from `POST /attachments`, as a post takes them. */
203
203
  attachments: z.array(AttachmentId).optional(),
@@ -517,7 +517,7 @@ const SyncImportBody = z.discriminatedUnion("op", [
517
517
  channel: ChannelPath.optional(),
518
518
  re: Ref.optional(),
519
519
  text: z.string().max(MESSAGE_TEXT_MAX).default(""),
520
- labels: Labels.optional(),
520
+ labels: NewLabels.optional(),
521
521
  noSync: z.boolean().optional(),
522
522
  attachments: z.array(AttachmentId).max(10).optional(),
523
523
  links: z.array(ImportLink).max(10).optional(),
@@ -552,7 +552,7 @@ const SyncImportBody = z.discriminatedUnion("op", [
552
552
  op: z.literal("labels"),
553
553
  ...Imported,
554
554
  ...Changed,
555
- set: Labels.optional(),
555
+ set: NewLabels.optional(),
556
556
  unset: z.array(LabelKey).optional(),
557
557
  /** As a label write's: what the labels must be now, a value or null for none. */
558
558
  if: z.record(LabelKey, LabelValue.nullable()).optional()
@@ -647,7 +647,7 @@ const ReactBody = z.object({
647
647
  */
648
648
  const CreateChannelBody = z.strictObject({ path: ChannelPath });
649
649
  const LabelBody = z.object({
650
- set: Labels.optional(),
650
+ set: NewLabels.optional(),
651
651
  unset: z.array(LabelKey).optional(),
652
652
  /**
653
653
  * What the message's labels must be now: a key's value, or null for one that mustn't be set.
@@ -39,6 +39,12 @@ const notALabelKey = (issue) => `${JSON.stringify(String(issue.input))} isn't a
39
39
  const LabelKey = z.string().max(64, { error: notALabelKey }).regex(/^[a-z0-9][a-z0-9_.-]*$/, { error: notALabelKey }).refine(notInherited, "label key is a reserved name");
40
40
  const LabelValue = z.string().max(256, { error: (issue) => `a label value is at most 256 characters, and this one has ${String(issue.input).length}` }).refine(storable, "label value has a NUL character or a lone surrogate");
41
41
  const Labels = z.record(LabelKey, LabelValue);
42
+ /**
43
+ * A label value as a write sets it: no control characters either, so a value can't break the line
44
+ * a reader shows it on (`vb read` prints labels inline). Labels already in a log keep what they have.
45
+ */
46
+ const NewLabelValue = LabelValue.refine((value) => !/\p{Cc}/u.test(value), "label value has a control character");
47
+ const NewLabels = z.record(LabelKey, NewLabelValue);
42
48
  /** Normalized short names, as Chat SDK names them: `eyes`, `check`, `thumbs_up`. */
43
49
  const Emoji = z.string().max(64).regex(/^[a-z0-9_+-]+$/, "invalid emoji name").refine(notInherited, "emoji name is a reserved name");
44
50
  /** `vercel:user:u_abc123`, or `vercel:user:u_abc123+claude` for a profile. */
@@ -115,4 +121,4 @@ const TaskHoldKind = z.string().regex(/^[a-z0-9][a-z0-9_.-]{0,63}$/, "a kind is
115
121
  /** A registered watcher's ID: a profile name, since its writes are by that profile. */
116
122
  const RemoteWatcherId = z.string().regex(/^[A-Za-z][A-Za-z0-9-]{0,31}$/, "ids start with a letter and use up to 32 letters, numbers, and hyphens");
117
123
  //#endregion
118
- export { authorView as A, SentText as C, TaskNote as D, TaskHoldKind as E, storable as M, toStorable as N, TaskState as O, SentTaskNote as S, TASK_NOTE_MAX as T, OPEN_TASK_STATES as _, CAN_MAX as a, SeenActorKind as b, EDITED_HOLD as c, LabelKey as d, LabelValue as f, MessageText as g, MessageId as h, Author as i, platformAvatar as j, actorKind as k, Emoji as l, MESSAGE_TEXT_MAX as m, Attachment as n, CHANNEL_PATTERN_MAX as o, Labels as p, AttachmentId as r, ChannelPath as s, ActorId as t, Handle as u, RESERVED_LABEL_PREFIX as v, TASK_LABEL as w, SentTaskHoldKind as x, RemoteWatcherId as y };
124
+ export { actorKind as A, SentTaskNote as C, TaskHoldKind as D, TASK_NOTE_MAX as E, platformAvatar as M, storable as N, TaskNote as O, toStorable as P, SentTaskHoldKind as S, TASK_LABEL as T, NewLabels as _, CAN_MAX as a, RemoteWatcherId as b, EDITED_HOLD as c, LabelKey as d, LabelValue as f, MessageText as g, MessageId as h, Author as i, authorView as j, TaskState as k, Emoji as l, MESSAGE_TEXT_MAX as m, Attachment as n, CHANNEL_PATTERN_MAX as o, Labels as p, AttachmentId as r, ChannelPath as s, ActorId as t, Handle as u, OPEN_TASK_STATES as v, SentText as w, SeenActorKind as x, RESERVED_LABEL_PREFIX as y };
@@ -1,8 +1,8 @@
1
- import { f as BoardError, p as createBoardClient, t as HttpError } from "./errors-DwV7I0g4.mjs";
2
- import { i as LOGINS, r as LOGIN } from "./auth-CEU06Nyp.mjs";
3
- import { p as localTokenFile, t as board } from "./server-V7qyVUiJ.mjs";
4
- import { t as oidcTokens } from "./tokens-BmCDAT4N.mjs";
5
- import { t as local } from "./local-DPpSEq2_.mjs";
1
+ import { f as BoardError, p as createBoardClient, t as HttpError } from "./errors-DYF4hhIc.mjs";
2
+ import { i as LOGINS, r as LOGIN } from "./auth-DJDTfgAL.mjs";
3
+ import { h as localTokenFile, t as board } from "./server-ViWNvg5q.mjs";
4
+ import { t as oidcTokens } from "./tokens-C-iK0Cku.mjs";
5
+ import { t as local } from "./local-BVSFSSYf.mjs";
6
6
  import { mkdir, rename, rm, stat, writeFile } from "node:fs/promises";
7
7
  import { userInfo } from "node:os";
8
8
  import { dirname, join, resolve } from "node:path";