@vercel/board 0.46.0 → 0.47.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 (82) hide show
  1. package/dist/{access-Crbvd2Dm.mjs → access-C06pIr0M.mjs} +1 -1
  2. package/dist/access.d.mts +2 -2
  3. package/dist/access.mjs +4 -4
  4. package/dist/{actors-BBphaJ_G.mjs → actors-Dkyg-oo0.mjs} +2 -2
  5. package/dist/{auth-C-pFnJBA.mjs → auth-B9-wXQ-x.mjs} +29 -9
  6. package/dist/{auth-CkNXnQno.d.mts → auth-li3lKwJG.d.mts} +1 -1
  7. package/dist/{backend-D3p8gjba.d.mts → backend-i_esjwUS.d.mts} +21 -4
  8. package/dist/backend-local.d.mts +1 -1
  9. package/dist/backend-local.mjs +1 -1
  10. package/dist/{chat-provider-Bn33acHd.d.mts → chat-provider-BWBGZOZY.d.mts} +4 -2
  11. package/dist/{chat-provider-1zpY6Qo_.mjs → chat-provider-CD7jskh7.mjs} +7 -4
  12. package/dist/cli-commands.d.mts +1 -1
  13. package/dist/cli-commands.mjs +1 -1
  14. package/dist/cli-embedded.d.mts +2 -2
  15. package/dist/cli-embedded.mjs +2 -2
  16. package/dist/cli.mjs +46 -15
  17. package/dist/{commands-CSZPQ38I.d.mts → commands-CJsOA-hf.d.mts} +6 -0
  18. package/dist/{commands-D0lyo8O8.mjs → commands-Dk6_cHLS.mjs} +6 -0
  19. package/dist/{conformance-Blzd4CXG.mjs → conformance-CDP8y2Zm.mjs} +94 -3
  20. package/dist/conformance.d.mts +1 -1
  21. package/dist/conformance.mjs +1 -1
  22. package/dist/{engine-C_SlBihU.mjs → engine-j2VeNuKG.mjs} +43 -50
  23. package/dist/{errors-DZ1tbwSM.mjs → errors-QhkdzI-o.mjs} +27 -8
  24. package/dist/{events-mGuhF4i5.mjs → events-MOcxGpOQ.mjs} +1 -1
  25. package/dist/{exports-DQauuHrc.mjs → exports-CEqS-IPP.mjs} +205 -56
  26. package/dist/{exports-DUX_Yzo7.d.mts → exports-CF9rKCXd.d.mts} +4 -4
  27. package/dist/{external-BVr1Sq0y.mjs → external-BuVTXT1R.mjs} +6 -2
  28. package/dist/{index-BHXg4Xdo.d.mts → index-ttfx1TZ6.d.mts} +2 -2
  29. package/dist/index.d.mts +6 -6
  30. package/dist/index.mjs +4 -4
  31. package/dist/index.node.d.mts +7 -7
  32. package/dist/index.node.mjs +4 -4
  33. package/dist/inspect/app.js +44 -44
  34. package/dist/inspect/engine.js +1 -1
  35. package/dist/inspect-8YAhl_h3.mjs +2 -0
  36. package/dist/{inspect-2OIjv2lW.mjs → inspect-vOSrW_g6.mjs} +82 -32
  37. package/dist/{local-11FMUJrU.mjs → local-0ajWOVhN.mjs} +92 -50
  38. package/dist/{main-BYmbTDgo.mjs → main-B8Zkd4Pm.mjs} +127 -46
  39. package/dist/{memory-CZBdVNn8.mjs → memory-CMm-Fk_A.mjs} +2 -2
  40. package/dist/{mentions-DfZGp3B-.mjs → mentions-CnWt9Z5b.mjs} +34 -1
  41. package/dist/{middleware-BKsTcMAv.mjs → middleware-CT6vMNUc.mjs} +1 -1
  42. package/dist/{provider-D3bfHRHA.d.mts → provider-Bc3xI90K.d.mts} +82 -5
  43. package/dist/{routes-B2HHHD_C.mjs → routes-ABXf3CKq.mjs} +17 -4
  44. package/dist/{routes-NEc6w3QC.d.mts → routes-CjA6Mp4D.d.mts} +70 -0
  45. package/dist/serve-BepKXDH3.mjs +285 -0
  46. package/dist/{server-Ch3tuK2k.mjs → server-4rQL3xuH.mjs} +38 -19
  47. package/dist/{serving-9riPNrHk.mjs → serving-BNdiReQT.mjs} +1 -1
  48. package/dist/{sql-Bml29DpM.mjs → sql-IEbO5vXs.mjs} +2 -2
  49. package/dist/{sqlite-4C5u7-ag.mjs → sqlite-CVG8XKHm.mjs} +2 -2
  50. package/dist/{sqlite-db-eVb9v3zc.mjs → sqlite-db-BJjPQYx4.mjs} +1 -1
  51. package/dist/sync-chat-sdk.d.mts +16 -2
  52. package/dist/sync-chat-sdk.mjs +2 -2
  53. package/dist/sync-github.d.mts +16 -2
  54. package/dist/sync-github.mjs +3 -3
  55. package/dist/sync-linear.d.mts +17 -3
  56. package/dist/sync-linear.mjs +2 -2
  57. package/dist/sync-slack.d.mts +17 -3
  58. package/dist/sync-slack.mjs +106 -14
  59. package/dist/sync.d.mts +2 -2
  60. package/dist/sync.mjs +2 -2
  61. package/dist/{task-batch-BJcLiYe1.mjs → task-batch-BZXm6kOE.mjs} +6 -6
  62. package/dist/{tokens-DPKF_cb5.mjs → tokens-BCp4EWTQ.mjs} +2 -2
  63. package/docs/01-board/01-mounting.md +7 -4
  64. package/docs/01-board/03-identity.md +43 -23
  65. package/docs/01-board/04-messages.md +3 -2
  66. package/docs/01-board/06-watchers.md +3 -3
  67. package/docs/01-board/07-schedules.md +2 -2
  68. package/docs/01-board/09-access.md +6 -4
  69. package/docs/01-board/10-local.md +4 -1
  70. package/docs/02-sync/01-overview.md +4 -5
  71. package/docs/02-sync/02-functions.md +2 -2
  72. package/docs/02-sync/03-slack.md +8 -5
  73. package/docs/02-sync/06-providers.md +8 -0
  74. package/docs/03-guides/02-inspector.md +17 -1
  75. package/docs/03-guides/06-sandboxed-agents.md +2 -2
  76. package/docs/03-guides/08-tailnet.md +123 -0
  77. package/docs/04-reference/01-cli.md +56 -15
  78. package/docs/04-reference/02-board.md +10 -5
  79. package/docs/04-reference/03-http.md +24 -3
  80. package/package.json +1 -1
  81. package/dist/inspect-F-b4GPXX.mjs +0 -2
  82. package/dist/serve-DS2T2iWI.mjs +0 -181
@@ -2,4 +2,4 @@ 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 a
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
3
  `)}function fe(e,t){let n=t===`github:user:35613825`?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`,pe=(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,me=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]),he=(e,t)=>e.length===t.length&&e.every((e,n)=>U(e)===U(t[n])),ge=new AbortController().signal,_e=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`},ve=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 ye(e,t,n){return`author`in n?{...n,author:{...n.author,id:K(e,t,n.author.id)}}:n}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=ge,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(ve(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(ve(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 be(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 xe(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 Se(e,t){let{event:n,raw:r,dedupe:i}=ce.parse(W({...t,raw:_e(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 Ce(n.thread))return!0;throw e});(!a||s||await Ce(n.thread))&&await o(`inboxPush`,{key:e,events:[{id:i,event:n,raw:r}]})}async function Ce(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 we(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=>Se(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=Te([t]).catch(e=>console.error(`[board] couldn't pull ${t}'s inbox:`,G(e)));return ee(a),i}async function Te(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=>Ee(e,t))),n+=t.length}return n}async function Ee(e,t){let n;try{await ke(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 De(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 Oe(e,t,n){let i=[],a=[],c=null;for(let l of t.slice(0,10)){if(c!==null){a.push(pe(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(pe(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 ke(e,t,n){let r=c(e),a={...t,event:ye(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,...je(e,o)},n.id),import(t,r={}){if(!g)throw d(`the sync function has finished`);return m??=Ae(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 Ae(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 Me(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 je(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 Me(e,t,n,r,i){let{event:a,raw:s}=t,l=je(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 Oe(u,a.files,n.attempt):{attachments:[],notes:[]},l=await De(u,a.links??[],{thread:a.subthread??a.thread,message:a.message},p?.channel??r),d={...l.length?{links:l}:{},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?me(s.text):[]),(s?.attachments.length??0)>0);s&&!a.linksOnly&&s.text!==c&&await v(await o(`syncImport`,{op:`edit`,author:n,from:e,origin:r,text:c,source:_}));let l=s?await De(u,a.links??[],r,s.channel,s.links):[];s&&!he(l,s.links)&&await o(`syncImport`,{op:`links`,author:n,from:e,origin:r,links:l})}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 Ne(e,t,n,r){let i=m(r);if(i.length===0)return r;let a=/* @__PURE__ */ new Map;for(let t of i)t.kind===`actor`&&!n.byId[t.actor]&&S(t.actor)&&a.set(t.actor,await be(e,t.actor));let o=/* @__PURE__ */ new Map;for(let t of i){if(t.kind!==`handle`)continue;let r=Object.values(n.byId).filter(e=>{let n=e.handle.toLowerCase();return n===t.handle||!t.handle.includes(`/`)&&n.slice(n.indexOf(`/`)+1)===t.handle});o.set(t.handle,r.flatMap(t=>{let r=Y(e,t.id,n);return r===null?[]:[{id:t.id,mention:r}]}))}let s=[...o.values()].some(e=>new Set(e.map(e=>e.mention)).size>1)?new Set((await D(t.re??t.id)).map(e=>e.by.actor)):null,c=e=>{let t=new Set(e.map(e=>e.mention));return t.size===1?[...t][0]:null};return re(r,t=>{if(t.kind===`handle`){let e=o.get(t.handle)??[];return c(e)??(s?c(e.filter(e=>s.has(e.id))):null)}if(a.has(t.actor))return a.get(t.actor)??t.actor;let r=Pe(t.actor,n);return r?Y(e,r.id,n)??r.name:null})}function Pe(e,t){return t.byId[e]??(t.principal?t.byId[`${t.principal}+${e}`]:void 0)??null}function Fe(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 Y(e,t,n){let r=n.byId[t],i=r?Fe(e,t,n):null;if(i===null)return null;let a=c(e);return a.mention({...r,id:`${a.platform}:${i}`})}async function Ie(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=(a??(e=>m.render(e)))(A({message:{...structuredClone(r),text:fe(r.text,r.by.actor)},author:o?{...o}:null,mentionOf:e=>Y(t,e,i),label:f,target:n}));if(typeof h!=`string`)throw d(`a provider renderer must return markdown`);let g=`**${f}**: `,_=await Ne(t,r,i,h.startsWith(g)&&ue(h.slice(g.length))?`**${f}**:\n\n${h.slice(g.length)}`:h),v=r.by.actor===`github:user:35613825`?de(r.text):null;return{markdown:_,...o?.verified?{as:{name:f,avatar:Le(r,o),attribution:p}}:{},...v?{deployments:v}:{}}}function Le(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 Re=e=>e.attachments.map(t=>`\n📎 ${t.name} (${n(t.size)}, on the board: #${e.id})`).join(``),X=async(e,t,n,r=!1,i)=>{let a=l(e),{markdown:o,...s}=await Ie(a,e,t,n,i);return{markdown:t.attachments.length>0&&(r||!c(a).uploadsFiles)?`${o}\n${Re(t)}`:o,...s}};async function ze(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 X(t,e,r,!1,i),f,p;if(!u.markdown.trim()&&e.attachments.length&&s.uploadsFiles)try{let n=await He(e,t,o);p=n.message,f=n.files}catch(n){if(!s.refusesFiles(n)&&!V(n))throw n;u=await X(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 Be(e,t,m),m}async function Be(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 Ve(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 He(e,t,n){return c(l(t)).uploadFiles(x(n),await Ve(e))}async function Z(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 He(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 X(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 Q=(e,t,n,r)=>{e.some(e=>e.error===r)||e.push({id:t,target:n,error:r})};async function Ue(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 We(e,n,t)},resolve:t=>R(e,t)};try{await c(e).sync(l),await a}finally{o=!1}}async function We(e,t,n){let{target:r,kind:i}=await xe(`${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 Ge(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){Q(a,i.id,null,e)}await Ue(n,a)}async function Ke(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=>qe(i,a,o,r,s,e))}catch(e){Q(s,a.id,r,e)}await Ue(t,s)}async function qe(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 Z(t,r,e,o,a)}catch(e){throw u(e)}}else try{let e=c(l(r)),n=await X(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 Ve(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 X(r,t,o,!0,a))}})();f=`${l(r)}:${u.thread}`;let p={thread:f,message:u.message,...s===void 0?{}:{files:s}};await Be(t,r,p),await Z(t,r,p,o,a)}catch(e){throw u(e)}let p=[];for(let e of n)if(!(e.deleted||e.noSync||Je(e,r)))try{await Z(e,r,s[e.id]?.[r]??await ze(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 Je=(e,t)=>e.origin?.thread===t||e.from!==null&&l(t)===e.from;async function Ye(e,t){if(!e.message)return;if(e.message.re===null)return Ge(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&&!Je(r,t))try{await $(l(t),e,r,t,async e=>{let n=(await M([r.id]))[r.id]?.[t]??await ze(r,t,o,i,e);await Z(r,t,n,i,e)})}catch(e){Q(a,r.id,t,e)}}await Ue(t,a)}async function Xe(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 X(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 Ze(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 X(t,o,a,r.files===null,e);n.markdown!==(await X(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 Qe(e,{attempt:t}){switch(e.type){case`thread.synced`:return Ke(e,t);case`message.posted`:return Ye(e,t);case`message.edited`:case`message.deleted`:case`reaction.added`:case`reaction.removed`:return Xe(e);case`labels.changed`:return Ze(e)}}async function $e(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 et(e,t){try{return`${e}:${await c(e).resolveChannel(t)}`}catch(e){throw d(`can't resolve inbox channel: ${e.message}`)}}let tt=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 nt(e,t,n,r){let i=c(e);try{return await i.read(t,{limit:n,after:r})}catch(n){throw n instanceof j?new _(tt(n.code),n.code,n.message):d(`can't read ${t} from ${e}: ${G(n)}`,`platform_error`)}}async function rt(e,t){let n=c(e);try{return await n.join(t)}catch(n){throw n instanceof j?new _(tt(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:Qe,receive:ke,pull:Te,normalizeTarget:xe,handleWebhook:we,inboxChannel:et,typing:$e,readSource:nt,joinSource:rt}}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]),he=(e,t)=>e.length===t.length&&e.every((e,n)=>U(e)===U(t[n])),ge=new AbortController().signal,_e=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`},ve=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 ye(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:re(n.text,n=>n.kind===`actor`&&n.actor.startsWith(`${t}:`)?`@[${K(e,t,n.actor)}]`:null)}}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=ge,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(ve(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(ve(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 be(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 xe(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 Se(e,t){let{event:n,raw:r,dedupe:i}=ce.parse(W({...t,raw:_e(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 Ce(n.thread))return!0;throw e});(!a||s||await Ce(n.thread))&&await o(`inboxPush`,{key:e,events:[{id:i,event:n,raw:r}]})}async function Ce(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 we(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=>Se(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=Te([t]).catch(e=>console.error(`[board] couldn't pull ${t}'s inbox:`,G(e)));return ee(a),i}async function Te(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=>Ee(e,t))),n+=t.length}return n}async function Ee(e,t){let n;try{await ke(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 De(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 Oe(e,t,n){let i=[],a=[],c=null;for(let l of t.slice(0,10)){if(c!==null){a.push(pe(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(pe(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 ke(e,t,n){let r=c(e),a={...t,event:ye(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,...je(e,o)},n.id),import(t,r={}){if(!g)throw d(`the sync function has finished`);return m??=Ae(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 Ae(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 Me(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 je(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 Me(e,t,n,r,i){let{event:a,raw:s}=t,l=je(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 Oe(u,a.files,n.attempt):{attachments:[],notes:[]},l=await De(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?me(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 De(u,a.links??[],r,s.channel,s.links):[];s&&!he(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 Ne(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 be(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=Pe(n.actor,t);return r?Ie(e,r.id,t)??r.name:null})}function Pe(e,t){return t.byId[e]??(t.principal?t.byId[`${t.principal}+${e}`]:void 0)??null}function Fe(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 Ie(e,t,n){let r=n.byId[t],i=r?Fe(e,t,n):null;if(i===null)return null;let a=c(e);return a.mention({...r,id:`${a.platform}:${i}`})}async function Le(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=(a??(e=>m.render(e)))(A({message:{...structuredClone(r),text:fe(r.text,r.by.actor)},author:o?{...o}:null,mentionOf:e=>Ie(t,e,i),label:f,target:n}));if(typeof h!=`string`)throw d(`a provider renderer must return markdown`);let g=`**${f}**: `,_=await Ne(t,i,h.startsWith(g)&&ue(h.slice(g.length))?`**${f}**:\n\n${h.slice(g.length)}`:h),v=r.by.actor===`github:user:35613825`?de(r.text):null;return{markdown:_,...o?.verified?{as:{name:f,avatar:Re(r,o),attribution:p}}:{},...v?{deployments:v}:{}}}function Re(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 ze=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 Le(a,e,t,n,i);return{markdown:t.attachments.length>0&&(r||!c(a).uploadsFiles)?`${o}\n${ze(t)}`:o,...s}};async function Be(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 Ue(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 Ve(e,t,m),m}async function Ve(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 He(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 Ue(e,t,n){return c(l(t)).uploadFiles(x(n),await He(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 Ue(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 We(e,n,t)},resolve:t=>R(e,t)};try{await c(e).sync(l),await a}finally{o=!1}}async function We(e,t,n){let{target:r,kind:i}=await xe(`${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 Ge(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 Ke(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=>qe(i,a,o,r,s,e))}catch(e){Z(s,a.id,r,e)}await Q(t,s)}async function qe(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 He(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 Ve(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||Je(e,r)))try{await X(e,r,s[e.id]?.[r]??await Be(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 Je=(e,t)=>e.origin?.thread===t||e.from!==null&&l(t)===e.from;async function Ye(e,t){if(!e.message)return;if(e.message.re===null)return Ge(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&&!Je(r,t))try{await $(l(t),e,r,t,async e=>{let n=(await M([r.id]))[r.id]?.[t]??await Be(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 Xe(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 Ze(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 Qe(e,{attempt:t}){switch(e.type){case`thread.synced`:return Ke(e,t);case`message.posted`:return Ye(e,t);case`message.edited`:case`message.deleted`:case`reaction.added`:case`reaction.removed`:return Xe(e);case`labels.changed`:return Ze(e)}}async function $e(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 et(e,t){try{return`${e}:${await c(e).resolveChannel(t)}`}catch(e){throw d(`can't resolve inbox channel: ${e.message}`)}}let tt=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 nt(e,t,n,r){let i=c(e);try{return await i.read(t,{limit:n,after:r})}catch(n){throw n instanceof j?new _(tt(n.code),n.code,n.message):d(`can't read ${t} from ${e}: ${G(n)}`,`platform_error`)}}async function rt(e,t){let n=c(e);try{return await n.join(t)}catch(n){throw n instanceof j?new _(tt(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:Qe,receive:ke,pull:Te,normalizeTarget:xe,handleWebhook:we,inboxChannel:et,typing:$e,readSource:nt,joinSource:rt}}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};
@@ -0,0 +1,2 @@
1
+ import { n as inspect } from "./inspect-vOSrW_g6.mjs";
2
+ export { inspect };
@@ -1,6 +1,6 @@
1
- import { g as InvalidProfileHeader, v as parseProfileHeader, y as ATTACHMENT_BYTES_MAX } from "./errors-DZ1tbwSM.mjs";
1
+ import { g as InvalidProfileHeader, v as parseProfileHeader, y as ATTACHMENT_BYTES_MAX } from "./errors-QhkdzI-o.mjs";
2
2
  import "./schemas-7VFdomFB.mjs";
3
- import { t as Failed, u as who } from "./main-BYmbTDgo.mjs";
3
+ import { t as Failed, u as who } from "./main-B8Zkd4Pm.mjs";
4
4
  import { t as page } from "./page-D-OzDOAX.mjs";
5
5
  import { randomBytes, timingSafeEqual } from "node:crypto";
6
6
  import { createServer } from "node:http";
@@ -625,6 +625,14 @@ button.file:hover { background: var(--shade-hover); color: var(--bright); }
625
625
  .toasts { position: fixed; right: 16px; bottom: 16px; display: grid; gap: 8px; z-index: 60; }
626
626
  .toast { max-width: 420px; padding: 8px 12px; border: 1px solid var(--dim); background: var(--bg); color: var(--bright); }
627
627
  `;
628
+ /** What a proxy adds to a request it forwards: Tailscale's sets `X-Forwarded-Host`, most others `X-Forwarded-For`. */
629
+ const FORWARDED = [
630
+ "forwarded",
631
+ "x-forwarded-for",
632
+ "x-forwarded-host",
633
+ "x-forwarded-proto",
634
+ "x-real-ip"
635
+ ];
628
636
  /** The prebuilt UI where board is installed, read only when an inspector starts without one. */
629
637
  const bundle = async () => (await import("./page-Dr9Aqlej.mjs")).page();
630
638
  const attribute = (value) => value.replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`);
@@ -656,14 +664,18 @@ const CSP = [
656
664
  "frame-ancestors 'none'"
657
665
  ].join("; ");
658
666
  /**
659
- * Serves the UI, and a proxy for the board's API that adds your credentials, on
660
- * 127.0.0.1. Because the proxy acts as you, it answers only its own page: every
661
- * request must name this server's host (no DNS rebinding) and carry the per-run
662
- * token that only the page has, and writes must also come from its origin. Your
663
- * credential for the board never leaves this process. `hosts` adds names a proxy in
664
- * front of it serves the page on: whoever reaches the page there acts as you.
667
+ * The UI, and a proxy for the board's API that adds your credentials, for a server
668
+ * on 127.0.0.1 to answer with. Because the proxy acts as you, it answers only its
669
+ * own page: every request must name the server's host (no DNS rebinding) and carry
670
+ * the per-run token that only the page has, and writes must also come from its
671
+ * origin. Your credential for the board never leaves this process. `hosts` adds
672
+ * names a proxy in front of it serves the page on: whoever reaches the page there
673
+ * acts as you, unless `visitor` says who a request is: a client that acts as them,
674
+ * or null for one it can't name, which the proxy then refuses. A request a proxy
675
+ * forwarded must name one of them: the server's own name is this machine's alone,
676
+ * and a caller behind a proxy can send it too.
665
677
  */
666
- async function startInspector(options) {
678
+ async function createInspector(options) {
667
679
  const { client } = options;
668
680
  const me = await client.me();
669
681
  const started = me.profile === null ? null : me.avatar ? {
@@ -673,7 +685,9 @@ async function startInspector(options) {
673
685
  const board = (await client.discovery().catch(() => null))?.url ?? client.url;
674
686
  const app = options.page ?? await bundle();
675
687
  const token = randomBytes(24).toString("base64url");
688
+ const allowed = new Set((options.hosts ?? []).map((host) => host.toLowerCase()));
676
689
  let hosts = /* @__PURE__ */ new Set();
690
+ let proxied = /* @__PURE__ */ new Set();
677
691
  let origins = /* @__PURE__ */ new Set();
678
692
  const streams = /* @__PURE__ */ new Set();
679
693
  async function proxy(request, response, url) {
@@ -693,6 +707,12 @@ async function startInspector(options) {
693
707
  code: "bad_path",
694
708
  message: "no relative paths"
695
709
  } });
710
+ const visiting = options.visitor?.(request);
711
+ if (visiting === null) return json(response, 401, { error: {
712
+ code: "unauthorized",
713
+ message: "the proxy in front of this page names no one for this request, so there's no one to act as"
714
+ } });
715
+ const acting = visiting ?? client;
696
716
  const controller = new AbortController();
697
717
  streams.add(controller);
698
718
  response.on("close", () => controller.abort());
@@ -713,7 +733,7 @@ async function startInspector(options) {
713
733
  message: error.message
714
734
  } });
715
735
  }
716
- const upstream = await client.request(`${path}${url.search}`, {
736
+ const upstream = await acting.request(`${path}${url.search}`, {
717
737
  as,
718
738
  method: request.method ?? "GET",
719
739
  headers: {
@@ -741,32 +761,54 @@ async function startInspector(options) {
741
761
  streams.delete(controller);
742
762
  }
743
763
  }
744
- const server = createServer((request, response) => {
745
- const url = new URL(request.url ?? "/", "http://inspector");
746
- if (!hosts.has(String(request.headers.host).toLowerCase())) return send(response, 421, "text/plain; charset=utf-8", "wrong host");
764
+ function handle(request, response) {
765
+ let url;
766
+ try {
767
+ url = new URL(request.url ?? "/", "http://inspector");
768
+ } catch {
769
+ return send(response, 400, "text/plain; charset=utf-8", "bad request");
770
+ }
771
+ const named = String(request.headers.host).toLowerCase();
772
+ if (!(FORWARDED.some((header) => request.headers[header] !== void 0) ? proxied : hosts).has(named)) return send(response, 421, "text/plain; charset=utf-8", "wrong host");
747
773
  if (url.pathname === "/board" || url.pathname.startsWith("/board/")) return void proxy(request, response, url).catch(() => response.headersSent ? response.end() : send(response, 500, "text/plain; charset=utf-8", "error"));
748
774
  if (request.method !== "GET") return send(response, 405, "text/plain; charset=utf-8", "method not allowed");
749
775
  if (url.pathname === "/app.js") return app ? send(response, 200, "text/javascript; charset=utf-8", app) : send(response, 503, "text/plain; charset=utf-8", "the inspector's UI isn't built: run `pnpm --filter @vercel/board build`");
750
776
  send(response, 200, "text/html; charset=utf-8", shell(token, started), { "content-security-policy": CSP });
751
- });
752
- const port = await listen(server, options.port ?? 4747, options.port === void 0);
753
- const allowed = (options.hosts ?? []).map((host) => host.toLowerCase());
754
- hosts = /* @__PURE__ */ new Set([
755
- `127.0.0.1:${port}`,
756
- `localhost:${port}`,
757
- ...allowed
758
- ]);
759
- origins = /* @__PURE__ */ new Set([
760
- `http://127.0.0.1:${port}`,
761
- `http://localhost:${port}`,
762
- ...allowed.flatMap((host) => [`http://${host}`, `https://${host}`])
763
- ]);
777
+ }
764
778
  return {
765
- url: `http://127.0.0.1:${port}`,
766
779
  board,
767
780
  me,
781
+ at(port) {
782
+ const own = [`127.0.0.1:${port}`, `localhost:${port}`];
783
+ hosts = /* @__PURE__ */ new Set([...own, ...allowed]);
784
+ proxied = new Set([...allowed].filter((host) => !own.includes(host)));
785
+ origins = /* @__PURE__ */ new Set([
786
+ `http://127.0.0.1:${port}`,
787
+ `http://localhost:${port}`,
788
+ ...[...allowed].flatMap((host) => [`http://${host}`, `https://${host}`])
789
+ ]);
790
+ return {
791
+ handle,
792
+ close() {
793
+ for (const stream of streams) stream.abort();
794
+ }
795
+ };
796
+ }
797
+ };
798
+ }
799
+ /** The inspector on a server of its own, on 127.0.0.1: `port`, or 4747, or any free one when that's taken. */
800
+ async function startInspector(options) {
801
+ const inspector = await createInspector(options);
802
+ let page = null;
803
+ const server = createServer((request, response) => page ? page.handle(request, response) : void response.writeHead(503).end());
804
+ const port = await listen(server, options.port ?? 4747, options.port === void 0);
805
+ const serving = page = inspector.at(port);
806
+ return {
807
+ url: `http://127.0.0.1:${port}`,
808
+ board: inspector.board,
809
+ me: inspector.me,
768
810
  close: () => new Promise((resolve) => {
769
- for (const stream of streams) stream.abort();
811
+ serving.close();
770
812
  server.close(() => resolve());
771
813
  server.closeAllConnections();
772
814
  })
@@ -850,11 +892,19 @@ async function pageOf() {
850
892
  });
851
893
  return found;
852
894
  }
895
+ /** The hosts `--allow-host`, or `--tailscale`, names: each a host, with its port when that isn't its scheme's default. */
896
+ function allowedHosts({ flags, usage }, flag = "allow-host") {
897
+ const hosts = flags[flag] ?? [];
898
+ const bad = hosts.find((host) => !/^[a-z0-9.-]+(:\d+)?$/i.test(host));
899
+ if (bad !== void 0) throw usage(`--${flag} takes a host, with a port if it isn't the default, like box.tailnet.ts.net: not ${bad}.`);
900
+ return [...new Set(hosts.flatMap((host) => [host, host.replace(/:(443|80)$/, "")]))];
901
+ }
853
902
  async function inspect({ flags, out, usage, portFlag, client, openBrowser }) {
854
903
  const port = portFlag();
855
- const hosts = flags["allow-host"] ?? [];
856
- const bad = hosts.find((host) => !/^[a-z0-9.-]+(:\d+)?$/i.test(host));
857
- if (bad !== void 0) throw usage(`--allow-host takes a host, with a port if it isn't the default, like box.tailnet.ts.net: not ${bad}.`);
904
+ const hosts = allowedHosts({
905
+ flags,
906
+ usage
907
+ });
858
908
  const page = await pageOf();
859
909
  const inspector = await startInspector({
860
910
  client: client(),
@@ -869,4 +919,4 @@ async function inspect({ flags, out, usage, portFlag, client, openBrowser }) {
869
919
  return 0;
870
920
  }
871
921
  //#endregion
872
- export { stopped as n, startInspector as r, inspect as t };
922
+ export { createInspector as i, inspect as n, stopped as r, allowedHosts as t };
@@ -1,18 +1,18 @@
1
- import { S as fileName, a as duplicateId, b as DIRECT_UPLOAD_BYTES_MAX, 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, w as mediaType, x as IMPORT_BYTES_MAX, y as ATTACHMENT_BYTES_MAX } from "./errors-DZ1tbwSM.mjs";
1
+ import { S as fileName, a as duplicateId, b as DIRECT_UPLOAD_BYTES_MAX, 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, w as mediaType, x as IMPORT_BYTES_MAX, y as ATTACHMENT_BYTES_MAX } from "./errors-QhkdzI-o.mjs";
2
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-7VFdomFB.mjs";
3
- import { a as Link, i as ExternalTarget, n as ExternalEvent, o as Origin } from "./external-BVr1Sq0y.mjs";
4
- import "./routes-B2HHHD_C.mjs";
5
- 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-BKsTcMAv.mjs";
3
+ import { a as Link, i as ExternalTarget, n as ExternalEvent, o as Origin } from "./external-BuVTXT1R.mjs";
4
+ import "./routes-ABXf3CKq.mjs";
5
+ 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-CT6vMNUc.mjs";
6
6
  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";
7
- import { a as replaceMentions, i as mentionTerms, n as isEmail, r as mentionTerm, t as extractMentions } from "./mentions-DfZGp3B-.mjs";
8
- import { a as runMatch, g as VERSION, 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-BJcLiYe1.mjs";
9
- import { c as compileAccess, i as authorize, o as checkGrantChange, t as FULL_ACCESS, u as parseCan } from "./access-Crbvd2Dm.mjs";
10
- 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-C-pFnJBA.mjs";
7
+ import { a as replaceMentions, i as mentionTerms, n as isEmail, r as mentionTerm, t as extractMentions } from "./mentions-CnWt9Z5b.mjs";
8
+ import { a as runMatch, g as VERSION, 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-BZXm6kOE.mjs";
9
+ import { c as compileAccess, i as authorize, o as checkGrantChange, t as FULL_ACCESS, u as parseCan } from "./access-C06pIr0M.mjs";
10
+ 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-B9-wXQ-x.mjs";
11
11
  import { n as setOwn, t as own } from "./own-OwgPWdmh.mjs";
12
- import { i as ownedActor, n as actorSeen, o as viaOf } from "./actors-BBphaJ_G.mjs";
12
+ import { i as ownedActor, n as actorSeen, o as viaOf } from "./actors-Dkyg-oo0.mjs";
13
13
  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";
14
14
  import { i as streamActivities, n as defaultSleep, t as createStreamActivity } from "./store-polling-BZt2Rf3D-oh3aU_An.mjs";
15
- import { a as foldActors, i as concernedMessageId, o as foldMessages, s as iso, t as TABLES_CONSUMER } from "./sql-Bml29DpM.mjs";
15
+ import { a as foldActors, i as concernedMessageId, o as foldMessages, s as iso, t as TABLES_CONSUMER } from "./sql-IEbO5vXs.mjs";
16
16
  import { z } from "zod";
17
17
  import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
18
18
  import { mkdir, readFile, writeFile } from "node:fs/promises";
@@ -5065,6 +5065,20 @@ function seenFor(identity, actors) {
5065
5065
  } : actor, actors, identity.principal.facts?.issuer === "host");
5066
5066
  }
5067
5067
  /**
5068
+ * The `actor.seen` of each platform user an import's text mentions that the board hasn't met: who
5069
+ * they are, as the import names them. One it knows keeps its record, which their own writes keep
5070
+ * current: a mention only introduces.
5071
+ */
5072
+ function metBy(introduces, actors, author) {
5073
+ const met = /* @__PURE__ */ new Set([author]);
5074
+ return (introduces ?? []).flatMap((actor) => {
5075
+ if (met.has(actor.id) || own(actors.byId, actor.id)) return [];
5076
+ met.add(actor.id);
5077
+ const seen = actorSeen(actor, actors);
5078
+ return seen ? [seen] : [];
5079
+ });
5080
+ }
5081
+ /**
5068
5082
  * Whether the board checked who a write is by, as it shows them: a principal a credential named (an
5069
5083
  * OIDC token it trusts, or a host's verifier; never the board's own code), shown as
5070
5084
  * that principal names it: its handle and name, and for an agent, that principal after `via`, its
@@ -5277,6 +5291,7 @@ async function commitPost(ctx, input, placed) {
5277
5291
  })));
5278
5292
  const events = [
5279
5293
  ...seen ? [seen] : [],
5294
+ ...metBy(input.introduces, actors, identity.actor.id),
5280
5295
  {
5281
5296
  type: "message.posted",
5282
5297
  ...id ? { id } : {},
@@ -5584,16 +5599,20 @@ async function writeEdit(ctx, input) {
5584
5599
  async function commitEdit(ctx, input, message) {
5585
5600
  const { state: actors } = await ctx.session.state(actorsReducer);
5586
5601
  const seen = seenFor(input.identity, actors);
5587
- const events = [...seen ? [seen] : [], {
5588
- type: "message.edited",
5589
- payload: {
5590
- id: message.id,
5591
- thread: message.thread,
5592
- text: input.text,
5593
- by: input.identity.author,
5594
- from: input.from ?? null
5602
+ const events = [
5603
+ ...seen ? [seen] : [],
5604
+ ...metBy(input.introduces, actors, input.identity.actor.id),
5605
+ {
5606
+ type: "message.edited",
5607
+ payload: {
5608
+ id: message.id,
5609
+ thread: message.thread,
5610
+ text: input.text,
5611
+ by: input.identity.author,
5612
+ from: input.from ?? null
5613
+ }
5595
5614
  }
5596
- }];
5615
+ ];
5597
5616
  const { revision } = input;
5598
5617
  await untilApplied(ctx, message.re === null ? await appendFrom(ctx, async () => {
5599
5618
  const { position, found } = await asOfNow(ctx, message.id);
@@ -5970,9 +5989,17 @@ const storedGrant = (row) => ({
5970
5989
  * repository's run with what it says of its workflow, branch (main unless it says), and event, or an issuer's token with
5971
5990
  * its claims. A board that verifies tokens itself looks no names up, so a name is a 400.
5972
5991
  */
5973
- function principalNamed(query, team) {
5992
+ function principalNamed(query, team, logins) {
5974
5993
  if (query.user !== void 0) {
5975
- if (query.user.includes("@")) throw badRequest(`this board can't look up ${query.user}: it verifies tokens itself, so name the user by ID`);
5994
+ if (query.user.includes("@")) {
5995
+ if (!logins) throw badRequest(`this board can't look up ${query.user}: it verifies tokens itself, so name the user by ID`);
5996
+ const login = query.user.toLowerCase();
5997
+ return {
5998
+ id: `vercel:user:${login}`,
5999
+ kind: "person",
6000
+ handle: login
6001
+ };
6002
+ }
5976
6003
  return {
5977
6004
  id: `vercel:user:${query.user}`,
5978
6005
  kind: "person",
@@ -6118,7 +6145,7 @@ const namesIssuer = (principals) => principals.some((principal) => principal.kin
6118
6145
  * name an oidc issuer. A removal goes by who a principal is; an add joins one the grant names
6119
6146
  * already. `issuers` are the ones the board's rules trust.
6120
6147
  */
6121
- async function updated(identity, state, { id, add, remove, can }, issuers, accessIn, team) {
6148
+ async function updated(identity, state, { id, add, remove, can }, issuers, accessIn, team, logins) {
6122
6149
  const index = indexOf(id);
6123
6150
  const row = index === null ? void 0 : state.grants[index];
6124
6151
  if (!row) {
@@ -6130,7 +6157,7 @@ async function updated(identity, state, { id, add, remove, can }, issuers, acces
6130
6157
  const others = grantIssuers(Object.values(state.grants).filter((other) => other.id !== row.id).map(storedGrant));
6131
6158
  let principals = [...row.principals];
6132
6159
  for (const input of remove ?? []) {
6133
- const removal = checkPrincipal(input, [...issuers, ...others], true);
6160
+ const removal = checkPrincipal(input, [...issuers, ...others], true, null, logins);
6134
6161
  const kept = principals.filter((principal) => !removes(removal, principal));
6135
6162
  if (kept.length === principals.length) throw badRequest(`${id} doesn't name that ${removal.kind} principal`, "not_in_grant");
6136
6163
  principals = kept;
@@ -6140,7 +6167,7 @@ async function updated(identity, state, { id, add, remove, can }, issuers, acces
6140
6167
  ...issuers,
6141
6168
  ...others,
6142
6169
  ...grantIssuers([{ principals }])
6143
- ], false, team);
6170
+ ], false, team, logins);
6144
6171
  const at = principals.findIndex((principal) => joined(added, principal) !== null);
6145
6172
  if (at === -1) principals.push(added);
6146
6173
  else principals[at] = joined(added, principals[at]);
@@ -6173,6 +6200,7 @@ async function updated(identity, state, { id, add, remove, can }, issuers, acces
6173
6200
  * defaults and the grants.
6174
6201
  */
6175
6202
  function createTrust(options) {
6203
+ const logins = () => options.logins?.() ?? false;
6176
6204
  const accessIn = (principal, grants) => options.accessNow(principal, grants);
6177
6205
  const session = createServer({
6178
6206
  contract: accessContract,
@@ -6193,7 +6221,7 @@ function createTrust(options) {
6193
6221
  const team = await options.team();
6194
6222
  const [row] = await whileHeadMoves(async () => {
6195
6223
  const { state, index } = await latest();
6196
- const checked = checkGrant(body, grantIssuers(Object.values(state.grants).map(storedGrant)), team);
6224
+ const checked = checkGrant(body, grantIssuers(Object.values(state.grants).map(storedGrant)), team, logins());
6197
6225
  const before = Object.values(state.grants).map(storedGrant);
6198
6226
  const after = [...before, checked];
6199
6227
  await mayGrant(identity, { changed: checked }, before, after, accessIn);
@@ -6215,7 +6243,7 @@ function createTrust(options) {
6215
6243
  const team = await options.team();
6216
6244
  const id = await whileHeadMoves(async () => {
6217
6245
  const { state, index } = await latest();
6218
- const event = await updated(identity, state, input, [], accessIn, team);
6246
+ const event = await updated(identity, state, input, [], accessIn, team, logins());
6219
6247
  await session.append.ifLastIndex(index, event);
6220
6248
  return event.payload.id;
6221
6249
  });
@@ -6234,7 +6262,7 @@ function createTrust(options) {
6234
6262
  can: []
6235
6263
  };
6236
6264
  const { id, kind, handle, facts, scope } = identity.principal;
6237
- const principal = named ? principalNamed(query, await options.team()) : {
6265
+ const principal = named ? principalNamed(query, await options.team(), logins()) : {
6238
6266
  id,
6239
6267
  kind,
6240
6268
  handle,
@@ -8953,7 +8981,8 @@ function build(options, binding) {
8953
8981
  store: log,
8954
8982
  accessNow: (principal, grants) => binding.accessNow(principal, grants),
8955
8983
  explain: (principal, channel) => binding.explain(principal, channel),
8956
- team: async () => (await binding.project()).teamId
8984
+ team: async () => (await binding.project()).teamId,
8985
+ logins: () => binding.logins
8957
8986
  });
8958
8987
  const schemaRegistry = createSchemas({ store: log });
8959
8988
  const inboxes = inboxServer.session(INBOXES_SESSION);
@@ -9661,11 +9690,17 @@ function build(options, binding) {
9661
9690
  },
9662
9691
  async syncImport(caller, body, signal) {
9663
9692
  const { principal } = await needSync(caller, "import", true);
9664
- const platform = await speaksFor(caller, principal.id, body.author, body.from);
9693
+ const mentioned = body.op === "post" || body.op === "edit" ? body.mentioned ?? [] : [];
9694
+ const [platform, ...platforms] = await speaksFor(caller, principal.id, [body.author, ...mentioned], body.from);
9665
9695
  const author = externalIdentity(body.author, ownSync(caller) ? null : principal, platform);
9666
9696
  const may = (channel) => principal.access.can("sync", channel);
9667
9697
  const keys = ownSync(caller) ? [] : (await entriesOf(caller, principal.id)).map(({ key }) => key);
9668
- const asNamed = (text) => keys.length === 0 ? text : replaceMentions(text, (token) => token.kind === "actor" && keys.some((key) => token.actor.startsWith(`${key}:`)) ? `@[${principal.id}+${token.actor}]` : null);
9698
+ const asNamed = (text) => {
9699
+ if (keys.length === 0) return text;
9700
+ const named = replaceMentions(text, (token) => token.kind === "actor" && keys.some((key) => token.actor.startsWith(`${key}:`)) ? `@[${principal.id}+${token.actor}]` : null);
9701
+ return named.length > 1e4 ? text : named;
9702
+ };
9703
+ const introduces = mentioned.map((user, at) => externalIdentity(user, ownSync(caller) ? null : principal, platforms[at]).actor);
9669
9704
  if (body.op === "post") {
9670
9705
  if (body.channel === void 0 === (body.re === void 0)) throw badRequest("an import needs `channel`; a reply needs `re`");
9671
9706
  let re;
@@ -9700,7 +9735,8 @@ function build(options, binding) {
9700
9735
  ...body.origin && !ownSync(caller) ? { importedBy: principal.id } : {},
9701
9736
  after: afterAt(body.after),
9702
9737
  attachments,
9703
- links: await linksOf(principal, body.links)
9738
+ links: await linksOf(principal, body.links),
9739
+ introduces
9704
9740
  })).id;
9705
9741
  };
9706
9742
  const write = {
@@ -9727,7 +9763,8 @@ function build(options, binding) {
9727
9763
  text: asNamed(text),
9728
9764
  from: body.from,
9729
9765
  asAuthor,
9730
- revision: body.revision
9766
+ revision: body.revision,
9767
+ introduces
9731
9768
  });
9732
9769
  return ref(found.id);
9733
9770
  };
@@ -10020,35 +10057,40 @@ function build(options, binding) {
10020
10057
  return [...found.values()];
10021
10058
  }
10022
10059
  /**
10023
- * Whether a caller may write as `author`, and the platform of the sync key they're a user of: a
10024
- * platform user, never anyone this board signs in, named under a key it syncs (`slack-eu:…`):
10025
- * entry `from`, when it names one.
10060
+ * Whether a caller may write as each of `users`, and the platform of the sync key each is a user
10061
+ * of: a platform user, never anyone this board signs in, named under a key it syncs
10062
+ * (`slack-eu:…`): entry `from`, when it names one. An import's author, and who its text mentions.
10026
10063
  */
10027
- async function speaksFor(caller, principal, author, from) {
10028
- if (authenticates(author.id) || await signedIn(author.id)) throw forbidden$1(`${author.id} is someone this board signs in, not a platform user: sync can't write as them`);
10064
+ async function speaksFor(caller, principal, users, from) {
10065
+ const signs = await signedIn();
10066
+ for (const { id } of users) if (authenticates(id) || signs(id)) throw forbidden$1(`${id} is someone this board signs in, not a platform user: sync can't write as them`);
10029
10067
  const entries = await entriesOf(caller, principal);
10030
10068
  const keys = from === null ? entries : entries.filter((entry) => entry.key === from);
10031
10069
  if (from !== null && keys.length === 0) throw forbidden$1(`this token doesn't sync ${from} here: its board registers its sync entries`);
10032
- const entry = keys.find(({ key }) => author.id.startsWith(`${key}:`));
10033
- if (!entry) throw forbidden$1(`${author.id} isn't a user of ${keys.length ? keys.map(({ key }) => key).join(" or ") : "a sync key this token has"}: their ID starts with its key`);
10034
- return entry.platform;
10070
+ return users.map(({ id }) => {
10071
+ const entry = keys.find(({ key }) => id.startsWith(`${key}:`));
10072
+ if (!entry) throw forbidden$1(`${id} isn't a user of ${keys.length ? keys.map(({ key }) => key).join(" or ") : "a sync key this token has"}: their ID starts with its key`);
10073
+ return entry.platform;
10074
+ });
10035
10075
  }
10036
10076
  /**
10037
- * Whether `id` is someone this board signs in that `authenticates` can't tell by its shape: a
10077
+ * Whether an ID is someone this board signs in that `authenticates` can't tell by its shape: a
10038
10078
  * host's principal, which may take any ID and kind, and their agents (`<principal>+<profile>`).
10039
10079
  * It is once it has registered (its watchers write as `<principal>+<id>`, which never wakes
10040
10080
  * them), or written: the board records a host's principals and their profiles as the host's,
10041
10081
  * whatever their kind, and anything else that writes as other than a platform user.
10042
10082
  */
10043
- async function signedIn(id) {
10044
- const plus = id.indexOf("+");
10083
+ async function signedIn() {
10045
10084
  const owners = (await registry.state()).byOwner;
10046
- if (owners[id] || plus > 0 && owners[id.slice(0, plus)]) return true;
10047
10085
  const { state: actors } = await session.state(actorsReducer);
10048
- return [id, plus > 0 ? id.slice(0, plus) : null].some((known) => {
10049
- const actor = known === null ? void 0 : actors.byId[known];
10050
- return actor !== void 0 && (actor.kind !== "external" || actor.host === true);
10051
- });
10086
+ return (id) => {
10087
+ const plus = id.indexOf("+");
10088
+ if (owners[id] || plus > 0 && owners[id.slice(0, plus)]) return true;
10089
+ return [id, plus > 0 ? id.slice(0, plus) : null].some((known) => {
10090
+ const actor = known === null ? void 0 : actors.byId[known];
10091
+ return actor !== void 0 && (actor.kind !== "external" || actor.host === true);
10092
+ });
10093
+ };
10052
10094
  }
10053
10095
  /**
10054
10096
  * Refuses a caller narrowed with `x-board-can` (a sandboxed agent, say): its principal's
@@ -10346,10 +10388,10 @@ function local(options = {}) {
10346
10388
  opening ??= (async () => {
10347
10389
  const file = localFile(bound.name);
10348
10390
  let store;
10349
- if (options.memory) store = (await import("./memory-CZBdVNn8.mjs")).memory();
10391
+ if (options.memory) store = (await import("./memory-CMm-Fk_A.mjs")).memory();
10350
10392
  else {
10351
10393
  const { mkdir } = await import("node:fs/promises");
10352
- const { sqlite } = await import("./sqlite-4C5u7-ag.mjs");
10394
+ const { sqlite } = await import("./sqlite-CVG8XKHm.mjs");
10353
10395
  const path = join(dir, `${file}.db`);
10354
10396
  try {
10355
10397
  await mkdir(dir, {