@popmelt.com/core 0.28.1 → 0.28.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -2
- package/claude-plugin/.claude-plugin/plugin.json +1 -1
- package/codex-plugin/.codex-plugin/plugin.json +1 -1
- package/dist/{ParticipantRuntime-JUOBT3CY.mjs → ParticipantRuntime-SYIF75DS.mjs} +1 -1
- package/dist/bridge-entry.mjs +1 -1
- package/dist/{browser-runtime-6KNOQXAJ.mjs → browser-runtime-7YSJ2DPK.mjs} +1 -1
- package/dist/browser.mjs +1 -1
- package/dist/{chunk-3THBMCJW.mjs → chunk-264MDJPC.mjs} +2 -2
- package/dist/{chunk-VRFM3TLR.mjs → chunk-DZI4H523.mjs} +1 -1
- package/dist/{chunk-W4VRK56P.mjs → chunk-MIGCFNL4.mjs} +1 -1
- package/dist/{chunk-35UEAIRA.mjs → chunk-TP3COBHM.mjs} +25 -25
- package/dist/cli.mjs +2 -2
- package/dist/index.mjs +1 -1
- package/dist/plugin-astro.mjs +1 -1
- package/dist/plugin-nuxt.mjs +1 -1
- package/dist/plugin-vite.mjs +1 -1
- package/dist/server.mjs +1 -1
- package/package.json +1 -1
- /package/dist/{chunk-3NTTM74X.mjs → chunk-VKFM7ZBT.mjs} +0 -0
package/README.md
CHANGED
|
@@ -17,9 +17,11 @@ Runs locally, learns naturally. Your annotations, screenshots, threads, and Impr
|
|
|
17
17
|
- A local web project: React is the established integration; vanilla HTML/JS with Vite, Vue, Nuxt, Svelte/SvelteKit, and Astro have experimental DOM integrations
|
|
18
18
|
- Node.js 18 or newer, or a newer version required by your framework
|
|
19
19
|
- React 18 or newer for a React host; non-React integrations still require the renderer peers listed in their setup instructions
|
|
20
|
-
- The Codex CLI or Claude Code CLI installed, available in your terminal, and
|
|
20
|
+
- The Codex CLI or Claude Code CLI installed, available in your terminal, and authenticated
|
|
21
21
|
|
|
22
|
-
The Codex and Claude Code desktop apps work too. Open your local app in their built-in browser and use Popmelt there just as you would in any other browser. The corresponding CLI still needs to be installed and
|
|
22
|
+
The Codex and Claude Code desktop apps work too. Open your local app in their built-in browser and use Popmelt there just as you would in any other browser. The corresponding CLI still needs to be installed and authenticated because it runs the threads.
|
|
23
|
+
|
|
24
|
+
Claude thread runs use Claude Code's authentication configuration, including API keys. Popmelt inherits `ANTHROPIC_API_KEY` from the environment of its local bridge and leaves Claude's credential/helper configuration intact; it does not store keys or select a separate billing mode. Claude's non-interactive runs use an API key when one is present, subject to its authentication precedence and managed policies. To use subscription authentication, remove the API key from that environment and configure Claude Code accordingly. Launch the app/bridge from the intended environment; an already-running bridge does not pick up later shell changes, so restart it only after active runs finish. See [Claude Code authentication](https://code.claude.com/docs/en/authentication).
|
|
23
25
|
|
|
24
26
|
## Install with your coding agent
|
|
25
27
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{a as Wt}from"./chunk-SWTSMLHA.mjs";import{vb as Ut,bb as _t,Eb as gt,Oa as qt,Va as zt,ab as tt,Ra as $t,Ua as Ft,Sa as Vt,K as Ht,Qa as Xt,Ta as Kt,ub as Bt,qb as Yt,Xa as Zt,nb as Gt,pb as Qt,rb as er,tb as tr,sb as yt,Na as vt,Pa as rr,Ia as nr,$a as ir,Wa as ar,Nb as or,b as sr}from"./chunk-W4VRK56P.mjs";import"./chunk-JQHZFDY5.mjs";import{Ta as lr,Ra as rt,e as dr,sa as $e,va as cr,Q as ur,N as pr,_a as fr,cb as hr,ba as mr,g as wt}from"./chunk-A2UXK7AS.mjs";import{a as je}from"./chunk-MP7S5ALD.mjs";import"./chunk-XTOCFTVW.mjs";import"./chunk-LVEMYZOA.mjs";import"./chunk-XOGBFVWI.mjs";import{v as gr,o as bt}from"./chunk-HGW2U6PD.mjs";import{useState as _,useSyncExternalStore as It,useEffect as ee,useRef as K,useCallback as We,useMemo as nt,useId as yr,useLayoutEffect as St}from"react";import{Link2 as vr,Ban as wr,Clock as br,X as Ir,Hand as Sr,SendHorizontal as kr,LoaderCircle as Er,RotateCcw as Pr,Check as xr,Copy as Ar}from"lucide-react";import{jsxs as Y,jsx as S,Fragment as Ue}from"react/jsx-runtime";var Cr=class extends Error{constructor(){super("The saved draft changed in another runtime. Your local changes are preserved.")}},it=(e,t)=>e.revision===t.revision&&JSON.stringify(e.source)===JSON.stringify(t.source)&&JSON.stringify(e.state)===JSON.stringify(t.state);function Tr(e){let t=structuredClone(e.draft.state??je),r=structuredClone(e.source),i=e.draft.revision,n=0,a=0,s=null,d=!1,o=structuredClone(e.draft),f=null,l=null,u=!1,w=new Set,I=new Set,y=()=>{for(let c of[...I])c()},b={getSnapshot:()=>t,subscribe:c=>(w.add(c),()=>{w.delete(c)}),dispatch:c=>{if(u)throw new Error("Participant runtime is disposed");let p=wt(t,c);if(p!==t){t=p,n++;for(let x of[...w])x();y()}}},g=()=>u?Promise.reject(new Error("Participant runtime is disposed")):l||(s||d?Promise.reject(s??new Error("Draft sync paused")):n===a?Promise.resolve():(l=Promise.resolve().then(async()=>{for(;!u&&!d&&n!==a;){let c=n,p=structuredClone(r),x=structuredClone(t);f={generation:c,draft:{revision:i+1,source:p,state:x}};let A=await e.save(i,p,x);if(!it(A,f.draft))throw new Error("Unexpected saved draft revision; reconnect before writing");i=A.revision,a=c,o=structuredClone(A),f=null}}).catch(c=>{throw s=c instanceof Error?c:new Error(String(c)),s}).finally(()=>{l=null,y()}),l));return{binding:b,flush:g,getStatus:()=>({revision:i,unsaved:n!==a,error:s,disposed:u}),subscribeStatus(c){return I.add(c),()=>{I.delete(c)}},pause(c){d=!0,s=c,y()},async whenSettled(){await l?.catch(()=>{})},reconcile(c){if(u)throw new Error("Participant runtime is disposed");if(l)throw new Error("Wait for the pending save before reconciling");if(!it(c,o)){if(!f||!it(c,f.draft))throw new Cr;i=c.revision,a=f.generation,o=structuredClone(c)}f=null,s=null,d=!1,y()},retry(){return s=null,d=!1,g()},setSource(c){if(u)throw new Error("Participant runtime is disposed");if(c.sourceId!==r.sourceId)throw new Error("Changing source worlds requires a new participant runtime");c.revision!==r.revision&&(r=structuredClone(c),n++,y())},async revoke(){u=!0,d=!0,await l?.catch(()=>{}),t=structuredClone(je),f=null,o={revision:i,source:null,state:null};for(let c of[...w])c();y()},dispose(){u=!0,w.clear(),I.clear()}}}var kt=8192,at=8*1024*1024,jr=256,Fe=100,Ae=(...e)=>JSON.stringify(e),Ve=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Re=e=>structuredClone(e),Or=class extends Error{constructor(){super("This edit predates retained synchronization history"),this.name="PlaneHistoryExpiredError"}},Et=(e,t)=>Pt(e.stamp,t.stamp)||(e.id<t.id?-1:e.id>t.id?1:0);function He(e,t){let r=new Map([...e.checkpoint?.receipts??[],...e.events].map(a=>[a.id,a])),i=[],n=[];for(let a of t){let s=r.get(a.id);if(s){if(!Ve(s,a))throw new Error("Plane event identity was reused");continue}e.checkpoint&&Et(a,e.checkpoint.through)<=0?n.push(a):i.push(a)}return{pending:i,superseded:n}}function Mr(e,t){let r=He(e,t);if(r.superseded.length)throw new Or;return r.pending}function Pt(e,t){return e.time-t.time||e.counter-t.counter||(e.actor<t.actor?-1:e.actor>t.actor?1:0)}function Nr(e,t,r,i){let n=r.reduce((s,d)=>!s||Pt(d.stamp,s)>0?d.stamp:s,t),a=Math.max(Math.floor(i),n?.time??0);return{actor:e,time:a,counter:a===n?.time?n.counter+1:0}}function ot(e){let t=new Map;for(let r of e.annotations){t.set(Ae("annotation",r.id),!0);for(let[i,n]of Object.entries(r))i!=="id"&&n!==void 0&&t.set(Ae("annotation",r.id,i),n)}for(let r of e.styleModifications){let i=Ae(r.pathname??"/",r.selector),{changes:n,...a}=r;t.set(Ae("styleMeta",i),a);for(let s of n)t.set(Ae("style",i,s.property),s)}for(let r of e.textModifications)t.set(Ae("text",Ae(r.pathname??"/",r.selector,JSON.stringify(r.textNodePath))),r);for(let r of e.domModifications)t.set(Ae("dom",r.id),r);for(let r of e.spacingTokenChanges)t.set(Ae("spacing",r.tokenPath),r);for(let r of e.spacingTokenMods)t.set(Ae("spacingMod",r.tokenPath),r);return t}function st(e,t){let r=ot(e),i=ot(t);return[...new Set([...r.keys(),...i.keys()])].filter(n=>!(JSON.parse(n)[0]==="styleMeta"&&!i.has(n))).filter(n=>!Ve(r.get(n),i.get(n))).map(n=>({key:n,...i.has(n)?{value:Re(i.get(n))}:{}}))}function xt(e,t){let r={...t,annotations:[],styleModifications:[],textModifications:[],domModifications:[],spacingTokenChanges:[],spacingTokenMods:[]},i=new Map;for(let[a,s]of e){let[d,o,f]=JSON.parse(a);d==="annotation"&&!f&&s===!0&&i.set(o,{id:o})}let n=new Map;for(let[a,s]of e){let[d,o,f]=JSON.parse(a);if(d==="annotation"&&f&&i.has(o)&&Object.defineProperty(i.get(o),f,{value:s,enumerable:!0,configurable:!0,writable:!0}),d==="style"){let l=n.get(o),u=e.get(Ae("styleMeta",o));if(!u)continue;l||(l={...u,changes:[]},n.set(o,l)),l.changes.push(s)}d==="text"&&r.textModifications.push(s),d==="dom"&&r.domModifications.push(s),d==="spacing"&&r.spacingTokenChanges.push(s),d==="spacingMod"&&r.spacingTokenMods.push(s)}return r.annotations=[...i.values()],r.styleModifications=[...n.values()],r.selectedAnnotationIds=t.selectedAnnotationIds.filter(a=>i.has(a)),r.lastSelectedId=r.selectedAnnotationIds.includes(t.lastSelectedId??"")?t.lastSelectedId:null,r}var At=e=>({annotations:e.annotations,styleModifications:e.styleModifications,textModifications:e.textModifications,domModifications:e.domModifications,spacingTokenChanges:e.spacingTokenChanges,spacingTokenMods:e.spacingTokenMods});function lt(e=je){let t=[...e.undoStack.slice(-Fe),At(e)],r={...Re(e),...Re(t[0]),undoStack:[],redoStack:[]},i=[];for(let s=1;s<t.length;s++){let d=`migration:${s}`;i.push({id:d,stamp:{time:0,counter:s,actor:"migration"},kind:"edit",group:d,changes:st({...r,...t[s-1]},{...r,...t[s]})})}let n=e,a=[];for(let s of[...e.redoStack].reverse().slice(0,Fe)){let d=`migration:${i.length+1}`,o={...r,...s};i.push({id:d,stamp:{time:0,counter:i.length+1,actor:"migration"},kind:"edit",group:d,changes:st(n,o)}),a.push(d),n=o}for(let s of a.reverse()){let d=`migration:${i.length+1}`;i.push({id:d,stamp:{time:0,counter:i.length+1,actor:"migration"},kind:"undo",target:s})}return{version:1,base:r,events:i}}function dt(e){if(!Array.isArray(e)||e.length>kt||JSON.stringify(e).length>at)throw new Error("Plane history exceeds the local session limit");for(let t of e){let r=n=>typeof n=="string"&&n.length>0&&n.length<=256;if(!t||!r(t.id)||!t.stamp||!r(t.stamp.actor)||!Number.isSafeInteger(t.stamp.time)||t.stamp.time<0||!Number.isSafeInteger(t.stamp.counter)||t.stamp.counter<0||!["edit","undo","redo"].includes(t.kind))throw new Error("Invalid plane event");if(t.kind!=="edit"){if(!r(t.target))throw new Error("Invalid history target");continue}if(t.group!==void 0&&!r(t.group)||t.reset!==void 0&&typeof t.reset!="boolean"||!Array.isArray(t.changes)||t.changes.length>1e4)throw new Error("Invalid plane edit");let i=new Set;for(let n of t.changes){if(!n||typeof n.key!="string"||n.key.length>8192)throw new Error("Invalid property key");let a=JSON.parse(n.key);if(!Array.isArray(a)||a.length<2||a.length>3||a.some(s=>typeof s!="string"||!s.length)||!["annotation","style","styleMeta","text","dom","spacing","spacingMod"].includes(a[0])||a[0]==="style"&&a.length!==3||!["style","annotation"].includes(a[0])&&a.length!==2||a[0]==="annotation"&&a.length===2&&n.value!==void 0&&n.value!==!0||i.has(n.key))throw new Error("Invalid property key");i.add(n.key)}}return Re(e)}function ct(e,t){let r=new Map(e.events.map(i=>[i.id,i]));for(let i of Mr(e,t)){let n=r.get(i.id);if(n&&!Ve(n,i))throw new Error("Plane event identity was reused");r.set(i.id,i)}if(r.size>kt)throw new Error("Plane history exceeds the local session limit");return{...e,events:[...r.values()].sort(Et)}}function Rr(e){if(e.version!==1&&e.version!==2)throw new Error("Unsupported plane history version");if(e.version===2&&!e.checkpoint)throw new Error("Missing plane history checkpoint");let t=e.checkpoint,r=t?new Map(Re(t.cells)):ot(e.base),i=new Map(t?.writers??[]),n=Re(t?.undo??[]),a=Re(t?.redo??[]),s=(d,o)=>{let f=[],l=[...d].sort((u,w)=>JSON.parse(u.key).length-JSON.parse(w.key).length);for(let u of l){let[w,I,y]=JSON.parse(u.key);if(w==="styleMeta"&&u.value===void 0)continue;let b=i.get(u.key)??"base";if(u.guard!==void 0&&b!==u.guard||w==="annotation"&&y&&!r.has(Ae(w,I)))continue;let g=r.get(u.key);u.value===void 0?r.delete(u.key):r.set(u.key,u.value);let c=u.restoreWriter??o;if(i.set(u.key,c),f.push({key:u.key,before:g,after:u.value,beforeWriter:b,afterWriter:c}),w==="annotation"&&!y&&u.value===void 0)for(let p of[...r.keys()]){let[x,A]=JSON.parse(p);x===w&&A===I&&(f.push({key:p,before:r.get(p),after:void 0,beforeWriter:i.get(p)??"base",afterWriter:c}),r.delete(p),i.set(p,c))}}return f};for(let d of e.events)if(d.kind==="edit"){let o=s(d.changes,d.group??d.id);if(d.reset&&(n.length=0,a.length=0),!d.group||!o.length)continue;let f=n.find(l=>l.id===d.group);if(f)for(let l of o){let u=f.changes.find(w=>w.key===l.key);u?(u.after=l.after,u.afterWriter=l.afterWriter):f.changes.push(l)}else n.push({id:d.group,writer:d.group,changes:o});a.length=0,n.length>Fe&&n.shift()}else{let o=d.kind==="undo"?n:a,f=d.kind==="undo"?a:n,l=o.findIndex(I=>I.id===d.target);if(l<0)continue;let u=o.splice(l,1)[0],w=s(u.changes.map(I=>({key:I.key,value:I.before,guard:I.afterWriter,restoreWriter:I.beforeWriter})),d.id);w.length&&f.push({id:d.id,writer:d.id,changes:w}),f.length>Fe&&f.shift()}return{cells:r,writers:i,undo:n,redo:a}}function ut(e,t=e.base,r=!0){let{cells:i,writers:n,undo:a,redo:s}=Rr(e),d=xt(i,t);d.styleModifications=d.styleModifications.filter(I=>!e.hostStyleDeletions?.some(y=>sr(I,y)));let o=new Set(Object.keys(e.hostDeletions??{}));d.annotations=d.annotations.filter(I=>!o.has(I.id)),d.selectedAnnotationIds=d.selectedAnnotationIds.filter(I=>!o.has(I));let f=I=>{let y=new Map(i);for(let b of I.changes)(n.get(b.key)??"base")===b.afterWriter&&(b.before===void 0?y.delete(b.key):y.set(b.key,b.before));return At(xt(y,t))},l=I=>I.filter(y=>y.changes.some(b=>JSON.parse(b.key)[0]!=="styleMeta"&&(n.get(b.key)??"base")===b.afterWriter&&!Ve(b.before,i.get(b.key)))),u=l(a),w=l(s);return d.undoStack=r?u.map(f):[],d.redoStack=r?w.map(f):[],{state:Re(d),undo:u.map(I=>I.id),redo:w.map(I=>I.id)}}function Lr(e){let t=structuredClone(e.draft.history??lt(e.draft.state??je)),r=He(t,e.pendingEvents??[]);t=ct(t,r.pending);let i=ut(t,{...structuredClone(e.draft.state??je),...e.view}),n=i.state,a=structuredClone(e.source),s=e.draft.revision,d=r.pending,o=structuredClone(e.draft),f=null,l=!!e.persist,u=0,w=0,I=Promise.resolve(),y=!1,b,g,c=null,p=null,x=!1,A=!1,P=new Set,C=new Set,O=()=>{for(let v of[...P])v()},M=()=>{for(let v of[...C])v()},j=()=>{i=ut(t,n),n=i.state},J=()=>{if(!e.persist||!l)return Promise.resolve();let v=structuredClone(o),te=structuredClone(a),$=structuredClone(d),F=u;return w++,I=I.then(()=>e.persist(v,te,$)).then(()=>{F===u&&(f=null)}).catch(R=>{F===u&&(f=R instanceof Error?R:new Error(String(R)))}).finally(()=>{F===u&&(w--,M())}),I},q=async()=>{do await I;while(w>0);if(f)throw f},ie=v=>{if(v.revision<s)return;if(v.source&&v.source.sourceId!==a.sourceId)throw new Error("Draft source world mismatch");if(!v.history)throw new Error("Shared history is unavailable; reconnect to an updated bridge");let te=He(v.history,d),$=ct(structuredClone(v.history),te.pending),F=JSON.stringify($.hostStyleDeletions)!==JSON.stringify(t.hostStyleDeletions)||JSON.stringify($.hostDeletions)!==JSON.stringify(t.hostDeletions)||$.checkpoint?.through.id!==t.checkpoint?.through.id||$.events.length!==t.events.length||$.events.some((R,L)=>R.id!==t.events[L]?.id);d=te.pending,te.superseded.length&&(g=void 0),t=$,s=v.revision,o=structuredClone(v),F&&j(),J()},H={getSnapshot:()=>n,subscribe(v){return P.add(v),()=>{P.delete(v)}},dispatch(v){if(A)throw new Error("Participant runtime is disposed");let te=n,$,F=()=>(b=Nr(e.actor,b,t.events,(e.now??Date.now)()),b),R=()=>crypto.randomUUID();if(v.type==="UNDO"||v.type==="REDO"){let L=(v.type==="UNDO"?i.undo:i.redo).at(-1);if(!L)return;$={id:R(),stamp:F(),kind:v.type==="UNDO"?"undo":"redo",target:L},g=void 0}else{let L=wt(n,v);if(L===n)return;let D=v.type==="UPDATE_LINKED_POSITIONS"?[]:st(n,L),oe=L.undoStack.length>n.undoStack.length,me=["MODIFY_STYLE","MOVE_ANNOTATION","RESIZE_ANNOTATION","UPDATE_TEXT_SIZE","UPDATE_ANNOTATION_COLOR"].includes(v.type);if(D.length){let be=R(),pe=oe||me?!oe&&g&&g===i.undo.at(-1)?g:be:void 0;$={id:be,stamp:F(),kind:"edit",changes:D,...pe?{group:pe}:{},...v.type==="CLEAR"?{reset:!0}:{}},g=pe}n=L}if($){try{t=ct(t,[$])}catch(L){n=te,p=L instanceof Error?L:new Error(String(L)),x=!0,g=void 0,O(),M();return}d.push($),j(),J()}O(),M(),e.saveView?.(n)}},ae=()=>A?Promise.reject(new Error("Participant runtime is disposed")):c||(p||x?Promise.reject(p??new Error("Draft sync paused")):!d.length&&!y&&!w&&!f?Promise.resolve():(c=Promise.resolve().then(async()=>{for(f&&await J(),await q();!A&&!x&&(d.length||y);){await q();let v=structuredClone(d.slice(0,jr)),te=structuredClone(a),$=await e.save(s,te,n,v);if(A)return;ie($),await q(),a.revision===te.revision&&(y=!1),O()}}).catch(v=>{throw p=v instanceof Error?v:new Error(String(v)),p}).finally(()=>{c=null,M()}),c));return{binding:H,flush:ae,getStatus:()=>({revision:s,unsaved:d.length>0||y,error:p,localError:f,memoryOnly:!l,savingLocally:w>0,disposed:A}),subscribeStatus(v){return C.add(v),()=>{C.delete(v)}},pause(v){x=!0,p=v,M()},async whenSettled(){await c?.catch(()=>{}),await q().catch(()=>{})},whenDurable:q,async retryLocalSave(){if(A)throw new Error("Participant runtime is disposed");await J(),await q()},async clearLocalSpace(){if(x=!0,await c?.catch(()=>{}),await q().catch(()=>{}),A)throw new Error("Participant runtime is disposed");l=!1,d=[],y=!1,g=void 0,t=structuredClone(o.history??lt(o.state??je)),i=ut(t,{...structuredClone(je),activeColor:n.activeColor,isAnnotating:n.isAnnotating}),n=i.state,s=o.revision,f=null,p=null,O(),M()},async resumeLocalSaving(){if(!e.persist||A)return!1;l=!0;let v;try{return await Promise.race([J().then(q),new Promise((te,$)=>{v=setTimeout(()=>$(new Error("Local saving timed out")),2e3)})]),!A}catch{return u++,l=!1,w=0,I=Promise.resolve(),f=null,M(),!1}finally{clearTimeout(v)}},reconcile(v){if(A)throw new Error("Participant runtime is disposed");if(c)throw new Error("Wait for the pending save before reconciling");ie(v),p=null,x=!1,O(),M()},receive(v){A||x||c||v.revision<=s||(ie(v),O(),M())},retry(){return x=!1,p=null,ae()},setSource(v){if(v.sourceId!==a.sourceId)throw new Error("Changing source worlds requires a new participant runtime");v.revision===a.revision&&o.source?.revision===v.revision||(a=structuredClone(v),y=!0,M())},async revoke(){A=!0,x=!0,await c?.catch(()=>{}),await q().catch(()=>{}),d=[],t=lt(je),n=structuredClone(je),o={revision:s,source:null,state:null},O(),M()},dispose(){A=!0,P.clear(),C.clear()}}}function Dr(e,t){if(!t.reference.draft.history||t.reference.draft.source&&t.basis.sourceId!==t.reference.draft.source.sourceId)throw new Error("Offline recovery requires a matching shared-history source");if(e&&(e.version!==1||e.reference.author.id!==t.reference.author.id||e.reference.planeId!==t.reference.planeId||e.basis.sourceId!==t.basis.sourceId))throw new Error("Offline recovery belongs to a different plane");let r=e&&e.reference.draft.revision>t.reference.draft.revision?e.reference:t.reference,i=new Map;for(let o of[...dt(e?.pending??[]),...dt(t.pending)]){let f=i.get(o.id);if(f&&JSON.stringify(f)!==JSON.stringify(o))throw new Error("Offline operation identity was reused");i.set(o.id,o)}let n=He(r.draft.history,[...i.values()]),a=new Set(n.pending.map(o=>o.id)),s=e?.pending.some(o=>a.has(o.id)),d={version:1,reference:r,basis:s?e.basis:t.basis,pending:n.pending,...e?.superseded?{superseded:e.superseded}:{}};if(n.superseded.length){let o=n.superseded.slice(-128);for(;o.length&&new TextEncoder().encode(JSON.stringify(o)).length>256*1024;)o.shift();d.superseded={revision:r.draft.revision,events:o,omitted:n.superseded.length-o.length}}if(dt(d.pending),d.superseded&&new TextEncoder().encode(JSON.stringify(d)).length>at&&delete d.superseded,new TextEncoder().encode(JSON.stringify(d)).length>at)throw new Error("Offline recovery storage limit reached; pending work is preserved");return structuredClone(d)}function Jr(e,t,r,i=indexedDB){let n=JSON.stringify([new URL(e).origin,t,r]),a=!1,s=new Promise((o,f)=>{let l=i.open("popmelt-plane-recovery",1);l.onupgradeneeded=()=>l.result.createObjectStore("planes"),l.onerror=()=>f(new Error("Could not open local draft recovery",{cause:l.error})),l.onblocked=()=>f(new Error("Local draft recovery is blocked by another browser view")),l.onsuccess=()=>{if(a){l.result.close(),f(new Error("Local draft recovery is closed"));return}l.result.onversionchange=()=>l.result.close(),o(l.result)}});s.catch(()=>{});let d=async o=>{let f=await s;if(a)throw new Error("Local draft recovery is closed");return new Promise((l,u)=>{let w=f.transaction("planes",o?"readwrite":"readonly"),I=w.objectStore("planes"),y=null,b,g=I.get(n);g.onsuccess=()=>{try{if(y=g.result??null,y&&(y.version!==1||y.reference.author.id!==r||y.basis.sourceId!==t))throw new Error("Invalid local recovery record; it has been preserved");o&&(y=Dr(y,o),I.put(y,n))}catch(c){b=c,w.abort()}},w.oncomplete=()=>l(y),w.onabort=()=>u(b??new Error("Could not save local draft recovery",{cause:w.error})),w.onerror=()=>{}})};return{read:()=>d(),update:o=>d(structuredClone(o)),async clear(){let o=await s;if(a)throw new Error("Local draft recovery is closed");await new Promise((f,l)=>{let u=o.transaction("planes","readwrite");u.objectStore("planes").delete(n),u.oncomplete=()=>f(),u.onabort=()=>l(u.error??new Error("Could not clear local draft recovery"))})},close(){a=!0,s.then(o=>o.close()).catch(()=>{})}}}var ke=class extends Error{constructor(e,t,r){super(t),this.status=e,this.code=r}},Ct=class{constructor(e,t,r,i=(...n)=>fetch(...n)){this.projectId=t,this.transport=i;let n=new URL(e);if(n.protocol!=="http:"||!["localhost","127.0.0.1","[::1]"].includes(n.hostname)||n.username||n.password||n.search||n.hash||n.pathname!=="/")throw new Error("Participant transport requires a local bridge origin");if(!t)throw new Error("Project identity required");this.base=n.origin,this.credential=r?{...r}:void 0}moderateStyles(e,t,r=!1){return this.rpc("moderate-styles",{participantId:e,styleModifications:t,restore:r})}moderateAnnotations(e,t,r=!1,i){return this.rpc("moderate-annotations",{participantId:e,annotationIds:t,restore:r,threadId:i})}async request(e,t,r={},i){let n=t instanceof FormData,a=await this.transport(this.base+e,{method:"POST",redirect:"error",credentials:"omit",signal:i??AbortSignal.timeout(3e4),headers:{...n?{}:{"Content-Type":"application/json"},"X-Popmelt-Project-Id":this.projectId,...this.credential?{"X-Popmelt-Participant-Id":this.credential.participantId,"X-Popmelt-Participant-Token":this.credential.token}:{},...r},body:n?t:JSON.stringify(t)}),s=await a.json().catch(()=>null);if(!a.ok)throw new ke(a.status,typeof s?.error=="string"?s.error:"Participant request failed",typeof s?.code=="string"?s.code:void 0);if(s===null)throw new Error("Invalid participant response");return{data:s,status:a.status}}async rpc(e,t={},r){return(await this.request("/participants/"+e,t,{},r)).data}mountRequestScope(e){if(!this.credential)throw new Error("Join before mounting a canvas");return ur(this.base,{"X-Popmelt-Project-Id":this.projectId,"X-Popmelt-Participant-Id":this.credential.participantId,"X-Popmelt-Participant-Token":this.credential.token,...e?{"X-Popmelt-Source-Revision":e.revision}:{}})}source(){return this.rpc("source")}snapshot(){return this.rpc("snapshot")}setHostModelSelection(e){return this.rpc("model-selection",{selection:e})}reserveAdmissionColor(e){return this.rpc("access-color",{receipt:e})}requestAdmission(e,t,r){return this.rpc("access-request",{receipt:e,name:t,colorIdentity:r})}admissionStatus(e){return this.rpc("access-status",{receipt:e})}cancelAdmission(e){return this.rpc("access-cancel",{receipt:e})}admissions(){return this.rpc("access-list")}decideAdmission(e,t){return this.rpc("access-decide",{id:e,decision:t})}attention(){return this.rpc("attention-read")}async reportAttention(e,t,r,i,n){return(await this.request("/participants/attention",{runtime:e,phase:t,operationId:r,location:i},{},n??AbortSignal.timeout(1500))).data}invite(){return this.rpc("invite")}revokeInvite(e){return this.rpc("revoke-invite",{invitation:e})}join(e,t,r){return this.rpc("join",{invitation:e,name:t,...r?{colorIdentity:r}:{}})}joinOrRequestAdmission(e,t,r){return this.rpc("join-or-request",{invitation:e,name:t,colorIdentity:r})}read(e,t){return this.rpc("read",{participantId:e,historyVersion:2},t)}connect(e,t){return this.rpc("connect",{runtimeId:e,previousToken:t})}renew(e,t){return this.rpc("renew",{runtime:e,activeColor:t})}disconnect(e){return this.rpc("disconnect",{runtime:e})}publish(e,t,r,i){return r.sourceId!==this.projectId?Promise.reject(new Error("Source world mismatch")):this.rpc("publish",{runtime:e,expectedRevision:t,sourceRevision:r.revision,state:i})}merge(e,t,r,i){return r.sourceId!==this.projectId?Promise.reject(new Error("Source world mismatch")):this.rpc("merge",{runtime:e,expectedRevision:t,sourceRevision:r.revision,events:i,historyVersion:2})}rename(e){return this.rpc("rename",{name:e})}setPermission(e,t){return this.rpc("permission",{participantId:e,permission:t})}revokeAccess(e){return this.rpc("revoke-access",{participantId:e})}pending(){return this.rpc("pending")}preview(e){return this.rpc("preview-read",{participantId:e})}previewWanted(e){return this.rpc("preview-demand",{runtime:e})}publishPreview(e,t,r){return this.rpc("preview-publish",{runtime:e,image:t,geometry:r})}review(e){return this.rpc("review",{id:e})}discard(e){return this.rpc("discard",{id:e})}submission(e,t){if(t===202&&e.pendingApproval===!0&&typeof e.submissionId=="string")return{status:"pending-approval",submissionId:e.submissionId,threadId:typeof e.threadId=="string"?e.threadId:void 0};if(t===200&&typeof e.jobId=="string"&&typeof e.threadId=="string"&&typeof e.position=="number")return{...e,status:"queued",jobId:e.jobId,threadId:e.threadId,position:e.position};throw new Error("Unexpected participant submission response")}async send(e,t,r){if(r.sourceId!==this.projectId)throw new Error("Source world mismatch");let i=await this.request("/send",e,{"X-Popmelt-Draft-Revision":String(t),"X-Popmelt-Source-Revision":r.revision});return this.submission(i.data,i.status)}contribute(e,t){return this.rpc("contribute",{threadId:e,text:t})}async approve(e,t){let r=await this.request("/participants/approve",{id:e,revision:t});return this.submission(r.data,r.status)}};function Wr(e){return[...new Set([...e.annotations.map(t=>t.linkedSelector),...e.styleModifications.map(t=>t.selector),...e.textModifications.map(t=>t.selector)].filter(t=>!!t))].slice(0,200)}function Ur(e,t,r){let i=Math.min(r.width/t.width,r.height/t.height),n=t.width*i,a=t.height*i;return{left:r.left+(r.width-n)/2+e.left*n,top:r.top+(r.height-a)/2+e.top*a,width:e.width*n,height:e.height*a}}function Xe(e){return e instanceof ke?e.status>=500||e.status===408||e.status===429||e.status===409&&(e.code==="runtime_expired"||e.code==="draft_conflict"):e instanceof TypeError||typeof e=="object"&&e!==null&&"name"in e&&(e.name==="TimeoutError"||e.name==="AbortError")}function pt(e,t=8e3){return Math.min(1e3*2**Math.min(Math.max(0,e-1),10),t)*(.5+Math.random()*.5)}function _r(e,t,r){let i={selectedId:r};try{let a=JSON.parse(e.getItem(t)??"null");a?.version===1&&typeof a.selectedId=="string"&&a.selectedId&&(i={selectedId:a.selectedId,...typeof a.threadId=="string"&&a.threadId?{threadId:a.threadId}:{}})}catch{}let n=a=>{if(!(a.selectedId===i.selectedId&&a.threadId===i.threadId)){i=a;try{e.setItem(t,JSON.stringify({version:1,...i}))}catch{}}};return{read:()=>i,select(a){a!==i.selectedId&&n({selectedId:a})},rememberThread(a,s){a===i.selectedId&&n({selectedId:a,...s?{threadId:s}:{}})},clear(){i={selectedId:r};try{e.removeItem(t)}catch{}}}}async function qr(e){let{projectId:t,runtimeStorage:r}=e,i={...e.credential},n={...e.observedSource};if(n.sourceId!==t)throw new Error("The loaded source does not match this participant session");let a=new Ct(e.bridgeUrl,t,i),s=`popmelt-runtime:${t}:${i.participantId}`,d=`popmelt-view:${t}:${i.participantId}`,o=_r(r,`popmelt-navigation:${t}:${i.participantId}`,i.participantId),f=ar(r,`popmelt-suggestion-views:${t}:${i.participantId}`),l;try{let h=JSON.parse(r.getItem(d)??"null");typeof h?.isAnnotating=="boolean"&&typeof h?.activeColor=="string"&&(l={isAnnotating:h.isAnnotating,activeColor:h.activeColor})}catch{}let u=null;try{u=JSON.parse(r.getItem(s)??"null"),(u?.participantId!==i.participantId||typeof u?.runtimeId!="string"||typeof u?.token!="string")&&(u=null)}catch{}let w=a.mountRequestScope(n),I=`popmelt-recovery-reset:${new URL(e.bridgeUrl).origin}:${t}:${i.participantId}`,y=!1;try{y=r.getItem(I)==="1"}catch{}let b=y?null:e.recoveryStore!==void 0?e.recoveryStore:typeof indexedDB<"u"?Jr(e.bridgeUrl,t,i.participantId):null,g=null,c=null,p,x;try{g=await b?.read()??null;try{x=await a.read(),p=await a.connect(x.draft.history?crypto.randomUUID():u?.runtimeId??crypto.randomUUID(),x.draft.history?void 0:u?.token),r.setItem(s,JSON.stringify(p))}catch(h){if(h instanceof ke&&h.status===403&&(await a.snapshot().catch(()=>[])).find(W=>W.identity.id===i.participantId)?.revokedAt!==void 0)throw await b?.clear?.(),new ke(403,"Your access was removed by the host","access_removed");if(!g||!(h instanceof Error)||!Xe(h))throw h;x=g.reference,p={participantId:i.participantId,runtimeId:crypto.randomUUID(),token:"",expiresAt:0},c=h}x.draft.history&&b&&(g=await b.update({reference:x,basis:n,pending:[]}),g&&(x=g.reference))}catch(h){throw b?.close(),w(),h}let A;try{A=x.draft.history?Lr({draft:x.draft,source:n,actor:p.runtimeId,view:l,pendingEvents:g?.pending,persist:b?async(h,W,T)=>{await b.update({reference:{...x,draft:h},basis:W,pending:T})}:void 0,saveView:h=>{try{r.setItem(d,JSON.stringify({isAnnotating:h.isAnnotating,activeColor:h.activeColor}))}catch{}},save:(h,W,T,Q)=>a.merge(p,h,W,Q)}):null}catch(h){throw b?.close(),w(),h}let P=A??Tr({draft:x.draft,source:n,save:(h,W,T)=>a.publish(p,h,W,T)}),C=!1,O=!1,M=null,j="connected",J=null,q=null,ie=0,H,ae=1e3,v=-1,te=!1,$=!1,F=new Set,R=()=>{for(let h of F)h()},L=()=>{C||H||J||j!=="reconnecting"||(H=setTimeout(()=>{H=void 0,oe()},ae),ae=Math.min(ae*2,3e4))},D=h=>{if(!C){if(M=h instanceof Error?h:new Error(String(h)),P.pause(M),M instanceof ke&&M.status===401){j="paused",$=!0,ie++,clearTimeout(H),H=void 0,R();return}j=Xe(M)?"reconnecting":"paused",j==="paused"&&(ie++,clearTimeout(H),H=void 0),L(),R()}},oe=(h=!1)=>{if(C)return Promise.reject(new Error("Participant runtime is closed"));if(q&&!h)return q;if(J)return J;let W=++ie,T=()=>!C&&W===ie;return clearTimeout(H),H=void 0,j="reconnecting",P.pause(M??new Error("Reconnecting to the participant session")),R(),J=(async()=>{if(await P.whenSettled(),!T())return;let Q=await a.connect(p.runtimeId,p.token);if(C)return;p=Q;try{r.setItem(s,JSON.stringify(p))}catch(Oe){if(!A?.getStatus().memoryOnly)throw Oe}if(!T())return;let Te=await a.read();T()&&(P.reconcile(Te.draft),await P.flush(),T()&&(M=null,j="connected",ae=1e3,R()))})().catch(Q=>{T()&&D(Q)}).finally(()=>{J=null,L()}),J},me=P.binding.subscribe(()=>{j==="connected"&&P.flush().catch(D)}),be=A?.subscribeStatus(()=>{let h=A.getStatus().localError;h&&h!==M?D(h):R()}),pe,he=setInterval(()=>{if(C||O||j!=="connected")return;O=!0;let h=p,W=P.binding.getSnapshot().activeColor;a.renew(p,W!==pe?W:void 0).then(T=>{!C&&p===h&&(p=T,pe=W,r.setItem(s,JSON.stringify(T)))}).catch(T=>{pe=void 0,!(p!==h||j!=="connected")&&(D(T),T instanceof ke&&T.status===409&&T.code==="runtime_expired"&&oe())}).finally(()=>{O=!1})},4e3),de=!1,se=0,Ee=async h=>{if(C||j!=="connected"||!A||!h)return;let W=ie;if(h.draftRevision>P.getStatus().revision){let T=await a.read();!C&&j==="connected"&&W===ie&&A.receive(T.draft)}},ce=setInterval(()=>{C||de||j!=="connected"||!A||se||(de=!0,a.snapshot().then(async h=>{let W=h.find(T=>T.identity.id===i.participantId);await Ee(W)}).catch(D).finally(()=>{de=!1}))},1e3),ge=0,G=!1,z=()=>{let h=P.binding.getSnapshot();return JSON.stringify({annotations:h.annotations.map(W=>({...W,status:void 0})),styles:h.styleModifications,text:h.textModifications,dom:h.domModifications,spacing:h.spacingTokenChanges})},le=null,Ce=null,B=!1,Le=setInterval(()=>{if(C||!le||B||j!=="connected")return;let h=le,W=p;B=!0,a.previewWanted(p).then(async({wanted:T})=>{if(!T||le!==h||C||j!=="connected")return;await P.flush();let Q=P.binding.getSnapshot(),Te=P.getStatus().revision,Oe=await h.frame(Wr(Q));Oe&&le===h&&!C&&j==="connected"&&W.token===p.token&&Q===P.binding.getSnapshot()&&await a.publishPreview(p,Oe.image,{draftRevision:Te,targets:Oe.targets})}).catch(T=>{if(!(C||j!=="connected")){if(T instanceof Error&&Xe(T)){D(T);return}le===h&&(Ce=T instanceof Error?T.message:"Preview unavailable",h.stop(),le=null,R())}}).finally(()=>{B=!1})},1e3);c?D(c):g?.pending.length&&P.flush().catch(D);let re;return{client:a,credential:i,navigation:o,state:P,readViewedSuggestions:f.read,markSuggestionViewed:f.mark,markSuggestionsViewed:f.markMany,captureVersion:z,reportAttention(h,W,T,Q){return C||j!=="connected"?Promise.resolve(!1):a.reportAttention(p,h,W,T,Q)},bindSubjects(h){return re=h,()=>{re===h&&(re=void 0)}},getSubjects:()=>re,getStatus:()=>({error:M,phase:j,pendingCount:ge,sending:G,sharing:!!le,previewError:Ce,accessRemoved:$}),reconnect:()=>oe(),retainExternalMembershipPolling(){se++;let h=!1;return()=>{h||(h=!0,se--)}},async retryLocalSave(){if(q)return q;await A?.retryLocalSave(),await oe()},clearLocalSpace(){return q||(C||!A?Promise.reject(new Error("Local space is unavailable")):(q=Promise.resolve().then(async()=>{let h=J;if(ie++,clearTimeout(H),H=void 0,j="paused",P.pause(new Error("Clearing local space")),R(),await h,C)throw new Error("Participant runtime is closed");try{r.setItem(I,"1")}catch{}await A.clearLocalSpace();let W;try{if(await Promise.race([b?.clear?b.clear():Promise.reject(new Error("Local storage cannot be cleared")),new Promise((T,Q)=>{W=setTimeout(()=>Q(new Error("Local clear timed out")),2e3)})]),C)throw new Error("Participant runtime is closed");if(await A.resumeLocalSaving())try{r.removeItem(I)}catch{}}catch{}finally{clearTimeout(W)}if(C)throw new Error("Participant runtime is closed");if(await oe(!0),j!=="connected")throw M??new Error("Session remains unavailable")}).finally(()=>{q=null}),q))},observeMembership(h){if(!(C||h.identity.id!==i.participantId)){if(h.revokedAt!==void 0&&!te){te=!0,D(new ke(403,"Your access was removed by the host")),le?.stop(),le=null,r.removeItem(s),r.removeItem(d),o.clear(),P.revoke().then(()=>b?.clear?.()).then(()=>{$=!0,R()}).catch(W=>{M=W instanceof Error?W:new Error("Could not clear local draft"),R()});return}if(!te){if(h.permission!=="blocked"&&!de&&(de=!0,Ee(h).catch(D).finally(()=>{de=!1})),h.permission==="blocked")v=h.permissionEpoch,M instanceof ke&&M.status===403||D(new ke(403,"Participant access is blocked"));else if(j==="paused"&&M instanceof ke&&M.status===403&&h.permissionEpoch>v){v=h.permissionEpoch;let W=()=>{!C&&j==="paused"&&v===h.permissionEpoch&&M instanceof ke&&M.status===403&&oe()};J?J.then(W):W()}}}},sharePreview(h){if(C){h?.stop();return}le?.stop(),le=h,Ce=null,h||a.publishPreview(p,null).catch(()=>{}),R()},subscribe:h=>(F.add(h),()=>{F.delete(h)}),async send(h,W){if(C||j!=="connected")throw M??new Error("Participant runtime is closed");if(G)throw new Error("A submission is already in progress");G=!0,R();try{if(P.setSource(n),await P.flush(),j!=="connected")throw M??new Error("Draft sync paused");if(z()!==W)throw new Error("Draft changed during capture; send again to include your latest changes");let T=await a.send(mr(h),P.getStatus().revision,n);return T.status==="pending-approval"?(ge++,R(),{pendingApproval:!0,submissionId:T.submissionId,threadId:T.threadId}):T}finally{G=!1,R()}},dispose(){C||(C=!0,re=void 0,j="closed",clearTimeout(H),clearInterval(he),clearInterval(ce),clearInterval(Le),le?.stop(),le=null,a.publishPreview(p,null).catch(()=>{}),me(),be?.(),w(),P.dispose(),P.whenSettled().finally(()=>b?.close()),F.clear())}}}function zr(e,t){e.removeItem(`popmelt-participant:${t}`);let r=`popmelt-admission:${t}`,i;try{i=JSON.parse(e.getItem(r)??"null")}catch{e.removeItem(r);return}i&&typeof i=="object"&&e.setItem(r,JSON.stringify({name:i.name,colorIdentity:i.colorIdentity??i.receipt}))}var ft="popmelt-join",Tt=/^[A-Za-z0-9_-]{43}$/;function $r(e,t){let r=new URL(e);if(!["http:","https:"].includes(r.protocol)||!["localhost","127.0.0.1","[::1]"].includes(r.hostname)||!Tt.test(t))throw new Error("A local page and valid invitation are required");let i=jt(r.href).cleanUrl,n=new URL(i);return n.hash=`${n.hash.slice(1)}${n.hash?"&":""}${ft}=${t}`,n.href}function jt(e){let t=new URL(e),r=null,i=t.hash.slice(1).split("&").filter(n=>{if(!n.startsWith(`${ft}=`))return!0;let a=n.slice(ft.length+1);return Tt.test(a)&&(r=a),!1});return t.hash=i.join("&"),{token:r,cleanUrl:t.href}}function Fr(e){let t={phase:"starting"},r=0,i=!1,n=!1,a=0,s,d=new Set,o=`popmelt-participant:${e.projectId}`,f=new Ct(e.url,e.projectId),l=g=>{if(!n){t=g;for(let c of d)c()}},u=async(g={})=>{let c=await fetch("/__popmelt/host",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify(g),redirect:"error"});if(c.status===403)return null;if(!c.ok)throw new Error(`Host entry unavailable (${c.status}).`);let p=`popmelt-before-participants:${e.projectId}`;return localStorage.getItem(p)===null&&localStorage.setItem(p,JSON.stringify(Object.fromEntries(Object.values(nr(e.projectId)).map(x=>[x,localStorage.getItem(x)])))),await c.json()},w=g=>qr({bridgeUrl:e.url,projectId:e.projectId,credential:g,runtimeStorage:sessionStorage,observedSource:{sourceId:e.projectId,revision:e.revision}}),I=async(g,c=a)=>{if(n||c!==a)return;let p=await w(g);if(n||c!==a){p.dispose();return}try{localStorage.setItem(o,JSON.stringify(g))}catch(x){throw p.dispose(),x}s?.dispose(),s=p,l({phase:"connected",connection:p}),u({credential:g}).catch(()=>{})},y=()=>{a++,s?.dispose(),s=void 0,zr(localStorage,e.projectId),l({phase:"entry",invitation:null})},b=async()=>{let g=jt(location.href),c=new URL(g.cleanUrl),p=new URLSearchParams(c.hash.slice(1)),x=p.get("popmelt-host");p.delete("popmelt-host"),x&&(c.hash=p.toString()),c.href!==location.href&&history.replaceState(history.state,"",c);let A=null;if(x){if(A=await u({token:x}),!A)throw new Error("Host entry expired. Use the current private host link.")}else if(!g.token){try{A=JSON.parse(localStorage.getItem(o)??"null")}catch{}A??(A=await u())}if(!n){if(!A){l({phase:"entry",invitation:g.token??null});return}try{await I(A)}catch(P){if(n)return;if(P.code==="access_removed"){y();return}if(P.status!==401)throw P;let C=await u();C?await I(C):y()}}};return{client:f,getSnapshot:()=>t,subscribe(g){return d.add(g),()=>{d.delete(g)}},retain(){if(n)throw new Error("Participant lifecycle is disposed");r++,i||(i=!0,b().catch(c=>l({phase:"error",message:c.message})));let g=!1;return()=>{g||(g=!0,r--,queueMicrotask(()=>{r||n||(n=!0,a++,s?.dispose(),s=void 0,d.clear())}))}},removed:y,async join(g,c){if(t.phase!=="entry"||!t.invitation||n)throw new Error("No active invitation");if(!c)throw new Error("Peer identity is not ready");let p=a,x=await f.joinOrRequestAdmission(t.invitation,g,c);if(!(n||p!==a)){if("admission"in x){localStorage.setItem(`popmelt-admission:${e.projectId}`,JSON.stringify({name:x.admission.name,receipt:c,colorIdentity:c})),l({phase:"entry",invitation:null});return}await I(x.joined.credential,p)}},admit:g=>I(g)}}function Ke(){let e=crypto.getRandomValues(new Uint8Array(32));return{id:crypto.randomUUID(),token:Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}}var _e=360,qe=120,Be=180,Ot=260;function Vr({client:e,storage:t,storageKey:r,onAdmitted:i,theme:n="light",themePreference:a=n,onThemePreferenceChange:s,onJoin:d}){let o=K(null),f=K(!1);if(!f.current){f.current=!0;try{o.current=JSON.parse(t.getItem(r)??"null")}catch{}}let[l,u]=_(o.current?.name??""),[w,I]=_(d?void 0:o.current?.receipt),[y,b]=_(null),[g,c]=_(),[p,x]=_(),A=K(null),[P,C]=_(!!d),[O,M]=_(!1),[j,J]=_(0),[q,ie]=_(),[H,ae]=_("idle"),[v,te]=_(),[$,F]=_(),R=K(!1),[L,D]=_(""),oe=K(null),me=K(null),be=K(null),pe=K(null),he=K(!1),de=K(0),se=K(!1),Ee=yr(),ce=K(!1),ge=K(0),G=K(i);G.current=i;let z=K(!1),le=K(null),Ce=K(()=>{});le.current||(le.current=new Promise(k=>{Ce.current=k}));let B=rt[n],Le=P&&!g;ee(()=>{let k=!1,Z,X,V=()=>{k||(k=!0,z.current=!0,Ce.current())};typeof requestAnimationFrame=="function"&&(Z=requestAnimationFrame(()=>{X=requestAnimationFrame(V)}));let Ie=window.setTimeout(V,64);return()=>{Z!==void 0&&cancelAnimationFrame(Z),X!==void 0&&cancelAnimationFrame(X),window.clearTimeout(Ie),V()}},[]),ee(()=>cr(document),[]),St(()=>{let k=!0,Z=()=>{if(!k||!be.current)return;let X=getComputedStyle(be.current),V=document.createElement("span");Object.assign(V.style,{position:"fixed",visibility:"hidden",pointerEvents:"none",whiteSpace:"nowrap",fontFamily:X.fontFamily,fontSize:X.fontSize,fontWeight:X.fontWeight,lineHeight:X.lineHeight}),document.body.append(V);let Ie=Number.parseFloat(X.paddingLeft)+Number.parseFloat(X.paddingRight);V.textContent="Ask for access";let Pe=Ie+12+3+V.getBoundingClientRect().width;V.textContent="Request pending";let ye=Ie+12+3+V.getBoundingClientRect().width;V.textContent="Request declined";let Me=Ie+12+3+V.getBoundingClientRect().width;if(V.remove(),Pe>15&&ye>15&&Me>15&&te({ask:Math.ceil(Pe),pending:Math.ceil(ye),declined:Math.ceil(Me)}),pe.current){let xe=getComputedStyle(pe.current),ve=document.createElement("span");Object.assign(ve.style,{position:"fixed",visibility:"hidden",pointerEvents:"none",whiteSpace:"nowrap",fontFamily:xe.fontFamily,fontSize:xe.fontSize,fontWeight:xe.fontWeight,lineHeight:xe.lineHeight}),ve.textContent="Sending...",document.body.append(ve);let we=Number.parseFloat(xe.paddingLeft)+Number.parseFloat(xe.paddingRight);F({idle:Math.ceil(we+14),sending:Math.ceil(we+ve.getBoundingClientRect().width)}),ve.remove()}};return Z(),document.fonts?.ready.then(Z),()=>{k=!1}},[n,P]),ee(()=>{if(!j)return;let k=setTimeout(()=>J(0),_e);return()=>clearTimeout(k)},[j]),ee(()=>{if(!q)return;let k=setTimeout(()=>ie(void 0),_e);return()=>clearTimeout(k)},[q]),ee(()=>{if(H!=="in")return;let k=setTimeout(()=>ae("idle"),Be);return()=>clearTimeout(k)},[H]),ee(()=>{o.current&&delete o.current.color;try{let k=JSON.parse(t.getItem(r)??"null");k&&typeof k=="object"&&"color"in k&&(delete k.color,t.setItem(r,JSON.stringify(k)))}catch{}},[t,r]);let re=!!(w&&(!y||y.status==="pending"||y.status==="granted")),h=(k,Z)=>{o.current={...o.current,name:k,receipt:Z},t.setItem(r,JSON.stringify(o.current))};ee(()=>{if(y?.status==="cancelled"){o.current={...o.current,name:l,receipt:void 0};try{t.setItem(r,JSON.stringify(o.current))}catch{}I(void 0),b(null)}},[y,l,t,r]);let W=()=>{if(A.current)return A.current;let k=async()=>{let Z=JSON.parse(t.getItem(r)??"null"),X=Z?.colorIdentity??Z?.receipt??Ke();o.current={name:l,receipt:Z?.receipt,colorIdentity:X},t.setItem(r,JSON.stringify(o.current));let V;try{V=await e.reserveAdmissionColor(X)}catch(Ie){let Pe=Ie.status;if(Pe!==400&&Pe!==401)throw Ie;X=Ke(),o.current={...o.current,colorIdentity:X},t.setItem(r,JSON.stringify(o.current)),V=await e.reserveAdmissionColor(X)}return c(V.color),x(ir(V)),X};return A.current=k().finally(()=>{A.current=null}),A.current},T=()=>{C(!P),P||D("")},Q=K(W);Q.current=W;let Te=!!d;ee(()=>{if(!P||g)return;let k=!1,Z,X=0,V=async()=>{try{await Q.current()}catch{if(k)return;Z=setTimeout(()=>{V()},pt(++X))}};return V(),()=>{k=!0,clearTimeout(Z)}},[P,g,t,r]),ee(()=>{if(!P)return;me.current?.focus();let k=Z=>{Z.composedPath().includes(oe.current)||C(!1)};return document.addEventListener("pointerdown",k),()=>document.removeEventListener("pointerdown",k)},[P]),ee(()=>{if(!w)return;let k=!0,Z=!1,X=!1,V,Ie,Pe=()=>{ge.current+=1,o.current={...o.current,name:l,receipt:void 0};try{t.setItem(r,JSON.stringify(o.current))}catch{}I(void 0),b(null),C(!1),D("")},ye=()=>{X=!0;let ve=Ke(),we=0,De=async()=>{if(k)try{let Je=await Q.current();o.current={...o.current,name:l,receipt:ve,colorIdentity:Je},t.setItem(r,JSON.stringify(o.current));let ze=await e.requestAdmission(ve,l,Je);if(!k)return;ge.current+=1,I(ve),b(ze),D("")}catch{if(!k)return;Ie=setTimeout(()=>{De()},pt(++we))}};De()},Me=async()=>{if(Z||X||se.current||ce.current)return;Z=!0;let ve=ge.current;try{let we=await e.admissionStatus(w);if(!k||ve!==ge.current)return;if(we.status==="declined"){if(z.current||await le.current,!k||ve!==ge.current)return;X=!0;let De=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches,Je=()=>{k&&(ae("rejected"),J(ze=>ze+1),V=setTimeout(()=>{if(k){if(De){Pe(),ae("idle");return}ae("rejected-out"),V=setTimeout(()=>{k&&(Pe(),ae("in"))},qe)}},_e))};De?Je():(ae("pending-out"),V=setTimeout(Je,qe));return}if(we.status==="expired"){ye();return}if(b(we),X=we.status==="cancelled",D(""),we.credential){se.current=!0;try{await G.current(we.credential),X=!0}finally{se.current=!1}}}catch(we){if(!k||ve!==ge.current)return;we.status===401&&ye()}finally{Z=!1}};Me();let xe=setInterval(Me,1500);return()=>{k=!1,clearInterval(xe),clearTimeout(V),clearTimeout(Ie)}},[e,w,l,t,r]);let Oe=async()=>{if(!(!w||O||ce.current)){ce.current=!0,ge.current+=1,M(!0),D("");try{let k=await e.cancelAdmission(w);b(k),C(!1)}catch{J(k=>k+1)}finally{ce.current=!1,M(!1)}}},et=async k=>{if(!l.trim()||O||re||R.current)return;if(R.current=!0,M(!0),D(""),ie(void 0),d){try{let X=await W();h(l.trim()),await d(l.trim(),X)}catch(X){D(X instanceof Error?X.message:"Could not join. Please try again.")}finally{R.current=!1,M(!1)}return}try{o.current=JSON.parse(t.getItem(r)??"null")}catch{}let Z=!y&&o.current?.receipt?o.current.receipt:Ke();try{let X=await W();h(l,Z),o.current={...o.current,name:l,receipt:Z};let V=await e.requestAdmission(Z,l.trim(),X);I(Z),u(V.name),b(V),C(!1)}catch{o.current={...o.current,name:l,receipt:Z},ie({target:k,pulse:++de.current})}finally{R.current=!1,M(!1)}};return Y("div",{ref:oe,"data-devtools":"participant-admission","data-popmelt-font":"sans","data-popmelt-theme":n,style:{display:"contents"},onKeyDown:k=>{k.key==="Escape"&&(C(!1),k.stopPropagation())},children:[S("style",{children:`
|
|
2
|
+
import{a as Wt}from"./chunk-SWTSMLHA.mjs";import{vb as Ut,bb as _t,Eb as gt,Oa as qt,Va as zt,ab as tt,Ra as $t,Ua as Ft,Sa as Vt,K as Ht,Qa as Xt,Ta as Kt,ub as Bt,qb as Yt,Xa as Zt,nb as Gt,pb as Qt,rb as er,tb as tr,sb as yt,Na as vt,Pa as rr,Ia as nr,$a as ir,Wa as ar,Nb as or,b as sr}from"./chunk-MIGCFNL4.mjs";import"./chunk-JQHZFDY5.mjs";import{Ta as lr,Ra as rt,e as dr,sa as $e,va as cr,Q as ur,N as pr,_a as fr,cb as hr,ba as mr,g as wt}from"./chunk-A2UXK7AS.mjs";import{a as je}from"./chunk-MP7S5ALD.mjs";import"./chunk-XTOCFTVW.mjs";import"./chunk-LVEMYZOA.mjs";import"./chunk-XOGBFVWI.mjs";import{v as gr,o as bt}from"./chunk-HGW2U6PD.mjs";import{useState as _,useSyncExternalStore as It,useEffect as ee,useRef as K,useCallback as We,useMemo as nt,useId as yr,useLayoutEffect as St}from"react";import{Link2 as vr,Ban as wr,Clock as br,X as Ir,Hand as Sr,SendHorizontal as kr,LoaderCircle as Er,RotateCcw as Pr,Check as xr,Copy as Ar}from"lucide-react";import{jsxs as Y,jsx as S,Fragment as Ue}from"react/jsx-runtime";var Cr=class extends Error{constructor(){super("The saved draft changed in another runtime. Your local changes are preserved.")}},it=(e,t)=>e.revision===t.revision&&JSON.stringify(e.source)===JSON.stringify(t.source)&&JSON.stringify(e.state)===JSON.stringify(t.state);function Tr(e){let t=structuredClone(e.draft.state??je),r=structuredClone(e.source),i=e.draft.revision,n=0,a=0,s=null,d=!1,o=structuredClone(e.draft),f=null,l=null,u=!1,w=new Set,I=new Set,y=()=>{for(let c of[...I])c()},b={getSnapshot:()=>t,subscribe:c=>(w.add(c),()=>{w.delete(c)}),dispatch:c=>{if(u)throw new Error("Participant runtime is disposed");let p=wt(t,c);if(p!==t){t=p,n++;for(let x of[...w])x();y()}}},g=()=>u?Promise.reject(new Error("Participant runtime is disposed")):l||(s||d?Promise.reject(s??new Error("Draft sync paused")):n===a?Promise.resolve():(l=Promise.resolve().then(async()=>{for(;!u&&!d&&n!==a;){let c=n,p=structuredClone(r),x=structuredClone(t);f={generation:c,draft:{revision:i+1,source:p,state:x}};let A=await e.save(i,p,x);if(!it(A,f.draft))throw new Error("Unexpected saved draft revision; reconnect before writing");i=A.revision,a=c,o=structuredClone(A),f=null}}).catch(c=>{throw s=c instanceof Error?c:new Error(String(c)),s}).finally(()=>{l=null,y()}),l));return{binding:b,flush:g,getStatus:()=>({revision:i,unsaved:n!==a,error:s,disposed:u}),subscribeStatus(c){return I.add(c),()=>{I.delete(c)}},pause(c){d=!0,s=c,y()},async whenSettled(){await l?.catch(()=>{})},reconcile(c){if(u)throw new Error("Participant runtime is disposed");if(l)throw new Error("Wait for the pending save before reconciling");if(!it(c,o)){if(!f||!it(c,f.draft))throw new Cr;i=c.revision,a=f.generation,o=structuredClone(c)}f=null,s=null,d=!1,y()},retry(){return s=null,d=!1,g()},setSource(c){if(u)throw new Error("Participant runtime is disposed");if(c.sourceId!==r.sourceId)throw new Error("Changing source worlds requires a new participant runtime");c.revision!==r.revision&&(r=structuredClone(c),n++,y())},async revoke(){u=!0,d=!0,await l?.catch(()=>{}),t=structuredClone(je),f=null,o={revision:i,source:null,state:null};for(let c of[...w])c();y()},dispose(){u=!0,w.clear(),I.clear()}}}var kt=8192,at=8*1024*1024,jr=256,Fe=100,Ae=(...e)=>JSON.stringify(e),Ve=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Re=e=>structuredClone(e),Or=class extends Error{constructor(){super("This edit predates retained synchronization history"),this.name="PlaneHistoryExpiredError"}},Et=(e,t)=>Pt(e.stamp,t.stamp)||(e.id<t.id?-1:e.id>t.id?1:0);function He(e,t){let r=new Map([...e.checkpoint?.receipts??[],...e.events].map(a=>[a.id,a])),i=[],n=[];for(let a of t){let s=r.get(a.id);if(s){if(!Ve(s,a))throw new Error("Plane event identity was reused");continue}e.checkpoint&&Et(a,e.checkpoint.through)<=0?n.push(a):i.push(a)}return{pending:i,superseded:n}}function Mr(e,t){let r=He(e,t);if(r.superseded.length)throw new Or;return r.pending}function Pt(e,t){return e.time-t.time||e.counter-t.counter||(e.actor<t.actor?-1:e.actor>t.actor?1:0)}function Nr(e,t,r,i){let n=r.reduce((s,d)=>!s||Pt(d.stamp,s)>0?d.stamp:s,t),a=Math.max(Math.floor(i),n?.time??0);return{actor:e,time:a,counter:a===n?.time?n.counter+1:0}}function ot(e){let t=new Map;for(let r of e.annotations){t.set(Ae("annotation",r.id),!0);for(let[i,n]of Object.entries(r))i!=="id"&&n!==void 0&&t.set(Ae("annotation",r.id,i),n)}for(let r of e.styleModifications){let i=Ae(r.pathname??"/",r.selector),{changes:n,...a}=r;t.set(Ae("styleMeta",i),a);for(let s of n)t.set(Ae("style",i,s.property),s)}for(let r of e.textModifications)t.set(Ae("text",Ae(r.pathname??"/",r.selector,JSON.stringify(r.textNodePath))),r);for(let r of e.domModifications)t.set(Ae("dom",r.id),r);for(let r of e.spacingTokenChanges)t.set(Ae("spacing",r.tokenPath),r);for(let r of e.spacingTokenMods)t.set(Ae("spacingMod",r.tokenPath),r);return t}function st(e,t){let r=ot(e),i=ot(t);return[...new Set([...r.keys(),...i.keys()])].filter(n=>!(JSON.parse(n)[0]==="styleMeta"&&!i.has(n))).filter(n=>!Ve(r.get(n),i.get(n))).map(n=>({key:n,...i.has(n)?{value:Re(i.get(n))}:{}}))}function xt(e,t){let r={...t,annotations:[],styleModifications:[],textModifications:[],domModifications:[],spacingTokenChanges:[],spacingTokenMods:[]},i=new Map;for(let[a,s]of e){let[d,o,f]=JSON.parse(a);d==="annotation"&&!f&&s===!0&&i.set(o,{id:o})}let n=new Map;for(let[a,s]of e){let[d,o,f]=JSON.parse(a);if(d==="annotation"&&f&&i.has(o)&&Object.defineProperty(i.get(o),f,{value:s,enumerable:!0,configurable:!0,writable:!0}),d==="style"){let l=n.get(o),u=e.get(Ae("styleMeta",o));if(!u)continue;l||(l={...u,changes:[]},n.set(o,l)),l.changes.push(s)}d==="text"&&r.textModifications.push(s),d==="dom"&&r.domModifications.push(s),d==="spacing"&&r.spacingTokenChanges.push(s),d==="spacingMod"&&r.spacingTokenMods.push(s)}return r.annotations=[...i.values()],r.styleModifications=[...n.values()],r.selectedAnnotationIds=t.selectedAnnotationIds.filter(a=>i.has(a)),r.lastSelectedId=r.selectedAnnotationIds.includes(t.lastSelectedId??"")?t.lastSelectedId:null,r}var At=e=>({annotations:e.annotations,styleModifications:e.styleModifications,textModifications:e.textModifications,domModifications:e.domModifications,spacingTokenChanges:e.spacingTokenChanges,spacingTokenMods:e.spacingTokenMods});function lt(e=je){let t=[...e.undoStack.slice(-Fe),At(e)],r={...Re(e),...Re(t[0]),undoStack:[],redoStack:[]},i=[];for(let s=1;s<t.length;s++){let d=`migration:${s}`;i.push({id:d,stamp:{time:0,counter:s,actor:"migration"},kind:"edit",group:d,changes:st({...r,...t[s-1]},{...r,...t[s]})})}let n=e,a=[];for(let s of[...e.redoStack].reverse().slice(0,Fe)){let d=`migration:${i.length+1}`,o={...r,...s};i.push({id:d,stamp:{time:0,counter:i.length+1,actor:"migration"},kind:"edit",group:d,changes:st(n,o)}),a.push(d),n=o}for(let s of a.reverse()){let d=`migration:${i.length+1}`;i.push({id:d,stamp:{time:0,counter:i.length+1,actor:"migration"},kind:"undo",target:s})}return{version:1,base:r,events:i}}function dt(e){if(!Array.isArray(e)||e.length>kt||JSON.stringify(e).length>at)throw new Error("Plane history exceeds the local session limit");for(let t of e){let r=n=>typeof n=="string"&&n.length>0&&n.length<=256;if(!t||!r(t.id)||!t.stamp||!r(t.stamp.actor)||!Number.isSafeInteger(t.stamp.time)||t.stamp.time<0||!Number.isSafeInteger(t.stamp.counter)||t.stamp.counter<0||!["edit","undo","redo"].includes(t.kind))throw new Error("Invalid plane event");if(t.kind!=="edit"){if(!r(t.target))throw new Error("Invalid history target");continue}if(t.group!==void 0&&!r(t.group)||t.reset!==void 0&&typeof t.reset!="boolean"||!Array.isArray(t.changes)||t.changes.length>1e4)throw new Error("Invalid plane edit");let i=new Set;for(let n of t.changes){if(!n||typeof n.key!="string"||n.key.length>8192)throw new Error("Invalid property key");let a=JSON.parse(n.key);if(!Array.isArray(a)||a.length<2||a.length>3||a.some(s=>typeof s!="string"||!s.length)||!["annotation","style","styleMeta","text","dom","spacing","spacingMod"].includes(a[0])||a[0]==="style"&&a.length!==3||!["style","annotation"].includes(a[0])&&a.length!==2||a[0]==="annotation"&&a.length===2&&n.value!==void 0&&n.value!==!0||i.has(n.key))throw new Error("Invalid property key");i.add(n.key)}}return Re(e)}function ct(e,t){let r=new Map(e.events.map(i=>[i.id,i]));for(let i of Mr(e,t)){let n=r.get(i.id);if(n&&!Ve(n,i))throw new Error("Plane event identity was reused");r.set(i.id,i)}if(r.size>kt)throw new Error("Plane history exceeds the local session limit");return{...e,events:[...r.values()].sort(Et)}}function Rr(e){if(e.version!==1&&e.version!==2)throw new Error("Unsupported plane history version");if(e.version===2&&!e.checkpoint)throw new Error("Missing plane history checkpoint");let t=e.checkpoint,r=t?new Map(Re(t.cells)):ot(e.base),i=new Map(t?.writers??[]),n=Re(t?.undo??[]),a=Re(t?.redo??[]),s=(d,o)=>{let f=[],l=[...d].sort((u,w)=>JSON.parse(u.key).length-JSON.parse(w.key).length);for(let u of l){let[w,I,y]=JSON.parse(u.key);if(w==="styleMeta"&&u.value===void 0)continue;let b=i.get(u.key)??"base";if(u.guard!==void 0&&b!==u.guard||w==="annotation"&&y&&!r.has(Ae(w,I)))continue;let g=r.get(u.key);u.value===void 0?r.delete(u.key):r.set(u.key,u.value);let c=u.restoreWriter??o;if(i.set(u.key,c),f.push({key:u.key,before:g,after:u.value,beforeWriter:b,afterWriter:c}),w==="annotation"&&!y&&u.value===void 0)for(let p of[...r.keys()]){let[x,A]=JSON.parse(p);x===w&&A===I&&(f.push({key:p,before:r.get(p),after:void 0,beforeWriter:i.get(p)??"base",afterWriter:c}),r.delete(p),i.set(p,c))}}return f};for(let d of e.events)if(d.kind==="edit"){let o=s(d.changes,d.group??d.id);if(d.reset&&(n.length=0,a.length=0),!d.group||!o.length)continue;let f=n.find(l=>l.id===d.group);if(f)for(let l of o){let u=f.changes.find(w=>w.key===l.key);u?(u.after=l.after,u.afterWriter=l.afterWriter):f.changes.push(l)}else n.push({id:d.group,writer:d.group,changes:o});a.length=0,n.length>Fe&&n.shift()}else{let o=d.kind==="undo"?n:a,f=d.kind==="undo"?a:n,l=o.findIndex(I=>I.id===d.target);if(l<0)continue;let u=o.splice(l,1)[0],w=s(u.changes.map(I=>({key:I.key,value:I.before,guard:I.afterWriter,restoreWriter:I.beforeWriter})),d.id);w.length&&f.push({id:d.id,writer:d.id,changes:w}),f.length>Fe&&f.shift()}return{cells:r,writers:i,undo:n,redo:a}}function ut(e,t=e.base,r=!0){let{cells:i,writers:n,undo:a,redo:s}=Rr(e),d=xt(i,t);d.styleModifications=d.styleModifications.filter(I=>!e.hostStyleDeletions?.some(y=>sr(I,y)));let o=new Set(Object.keys(e.hostDeletions??{}));d.annotations=d.annotations.filter(I=>!o.has(I.id)),d.selectedAnnotationIds=d.selectedAnnotationIds.filter(I=>!o.has(I));let f=I=>{let y=new Map(i);for(let b of I.changes)(n.get(b.key)??"base")===b.afterWriter&&(b.before===void 0?y.delete(b.key):y.set(b.key,b.before));return At(xt(y,t))},l=I=>I.filter(y=>y.changes.some(b=>JSON.parse(b.key)[0]!=="styleMeta"&&(n.get(b.key)??"base")===b.afterWriter&&!Ve(b.before,i.get(b.key)))),u=l(a),w=l(s);return d.undoStack=r?u.map(f):[],d.redoStack=r?w.map(f):[],{state:Re(d),undo:u.map(I=>I.id),redo:w.map(I=>I.id)}}function Lr(e){let t=structuredClone(e.draft.history??lt(e.draft.state??je)),r=He(t,e.pendingEvents??[]);t=ct(t,r.pending);let i=ut(t,{...structuredClone(e.draft.state??je),...e.view}),n=i.state,a=structuredClone(e.source),s=e.draft.revision,d=r.pending,o=structuredClone(e.draft),f=null,l=!!e.persist,u=0,w=0,I=Promise.resolve(),y=!1,b,g,c=null,p=null,x=!1,A=!1,P=new Set,C=new Set,O=()=>{for(let v of[...P])v()},M=()=>{for(let v of[...C])v()},j=()=>{i=ut(t,n),n=i.state},J=()=>{if(!e.persist||!l)return Promise.resolve();let v=structuredClone(o),te=structuredClone(a),$=structuredClone(d),F=u;return w++,I=I.then(()=>e.persist(v,te,$)).then(()=>{F===u&&(f=null)}).catch(R=>{F===u&&(f=R instanceof Error?R:new Error(String(R)))}).finally(()=>{F===u&&(w--,M())}),I},q=async()=>{do await I;while(w>0);if(f)throw f},ie=v=>{if(v.revision<s)return;if(v.source&&v.source.sourceId!==a.sourceId)throw new Error("Draft source world mismatch");if(!v.history)throw new Error("Shared history is unavailable; reconnect to an updated bridge");let te=He(v.history,d),$=ct(structuredClone(v.history),te.pending),F=JSON.stringify($.hostStyleDeletions)!==JSON.stringify(t.hostStyleDeletions)||JSON.stringify($.hostDeletions)!==JSON.stringify(t.hostDeletions)||$.checkpoint?.through.id!==t.checkpoint?.through.id||$.events.length!==t.events.length||$.events.some((R,L)=>R.id!==t.events[L]?.id);d=te.pending,te.superseded.length&&(g=void 0),t=$,s=v.revision,o=structuredClone(v),F&&j(),J()},H={getSnapshot:()=>n,subscribe(v){return P.add(v),()=>{P.delete(v)}},dispatch(v){if(A)throw new Error("Participant runtime is disposed");let te=n,$,F=()=>(b=Nr(e.actor,b,t.events,(e.now??Date.now)()),b),R=()=>crypto.randomUUID();if(v.type==="UNDO"||v.type==="REDO"){let L=(v.type==="UNDO"?i.undo:i.redo).at(-1);if(!L)return;$={id:R(),stamp:F(),kind:v.type==="UNDO"?"undo":"redo",target:L},g=void 0}else{let L=wt(n,v);if(L===n)return;let D=v.type==="UPDATE_LINKED_POSITIONS"?[]:st(n,L),oe=L.undoStack.length>n.undoStack.length,me=["MODIFY_STYLE","MOVE_ANNOTATION","RESIZE_ANNOTATION","UPDATE_TEXT_SIZE","UPDATE_ANNOTATION_COLOR"].includes(v.type);if(D.length){let be=R(),pe=oe||me?!oe&&g&&g===i.undo.at(-1)?g:be:void 0;$={id:be,stamp:F(),kind:"edit",changes:D,...pe?{group:pe}:{},...v.type==="CLEAR"?{reset:!0}:{}},g=pe}n=L}if($){try{t=ct(t,[$])}catch(L){n=te,p=L instanceof Error?L:new Error(String(L)),x=!0,g=void 0,O(),M();return}d.push($),j(),J()}O(),M(),e.saveView?.(n)}},ae=()=>A?Promise.reject(new Error("Participant runtime is disposed")):c||(p||x?Promise.reject(p??new Error("Draft sync paused")):!d.length&&!y&&!w&&!f?Promise.resolve():(c=Promise.resolve().then(async()=>{for(f&&await J(),await q();!A&&!x&&(d.length||y);){await q();let v=structuredClone(d.slice(0,jr)),te=structuredClone(a),$=await e.save(s,te,n,v);if(A)return;ie($),await q(),a.revision===te.revision&&(y=!1),O()}}).catch(v=>{throw p=v instanceof Error?v:new Error(String(v)),p}).finally(()=>{c=null,M()}),c));return{binding:H,flush:ae,getStatus:()=>({revision:s,unsaved:d.length>0||y,error:p,localError:f,memoryOnly:!l,savingLocally:w>0,disposed:A}),subscribeStatus(v){return C.add(v),()=>{C.delete(v)}},pause(v){x=!0,p=v,M()},async whenSettled(){await c?.catch(()=>{}),await q().catch(()=>{})},whenDurable:q,async retryLocalSave(){if(A)throw new Error("Participant runtime is disposed");await J(),await q()},async clearLocalSpace(){if(x=!0,await c?.catch(()=>{}),await q().catch(()=>{}),A)throw new Error("Participant runtime is disposed");l=!1,d=[],y=!1,g=void 0,t=structuredClone(o.history??lt(o.state??je)),i=ut(t,{...structuredClone(je),activeColor:n.activeColor,isAnnotating:n.isAnnotating}),n=i.state,s=o.revision,f=null,p=null,O(),M()},async resumeLocalSaving(){if(!e.persist||A)return!1;l=!0;let v;try{return await Promise.race([J().then(q),new Promise((te,$)=>{v=setTimeout(()=>$(new Error("Local saving timed out")),2e3)})]),!A}catch{return u++,l=!1,w=0,I=Promise.resolve(),f=null,M(),!1}finally{clearTimeout(v)}},reconcile(v){if(A)throw new Error("Participant runtime is disposed");if(c)throw new Error("Wait for the pending save before reconciling");ie(v),p=null,x=!1,O(),M()},receive(v){A||x||c||v.revision<=s||(ie(v),O(),M())},retry(){return x=!1,p=null,ae()},setSource(v){if(v.sourceId!==a.sourceId)throw new Error("Changing source worlds requires a new participant runtime");v.revision===a.revision&&o.source?.revision===v.revision||(a=structuredClone(v),y=!0,M())},async revoke(){A=!0,x=!0,await c?.catch(()=>{}),await q().catch(()=>{}),d=[],t=lt(je),n=structuredClone(je),o={revision:s,source:null,state:null},O(),M()},dispose(){A=!0,P.clear(),C.clear()}}}function Dr(e,t){if(!t.reference.draft.history||t.reference.draft.source&&t.basis.sourceId!==t.reference.draft.source.sourceId)throw new Error("Offline recovery requires a matching shared-history source");if(e&&(e.version!==1||e.reference.author.id!==t.reference.author.id||e.reference.planeId!==t.reference.planeId||e.basis.sourceId!==t.basis.sourceId))throw new Error("Offline recovery belongs to a different plane");let r=e&&e.reference.draft.revision>t.reference.draft.revision?e.reference:t.reference,i=new Map;for(let o of[...dt(e?.pending??[]),...dt(t.pending)]){let f=i.get(o.id);if(f&&JSON.stringify(f)!==JSON.stringify(o))throw new Error("Offline operation identity was reused");i.set(o.id,o)}let n=He(r.draft.history,[...i.values()]),a=new Set(n.pending.map(o=>o.id)),s=e?.pending.some(o=>a.has(o.id)),d={version:1,reference:r,basis:s?e.basis:t.basis,pending:n.pending,...e?.superseded?{superseded:e.superseded}:{}};if(n.superseded.length){let o=n.superseded.slice(-128);for(;o.length&&new TextEncoder().encode(JSON.stringify(o)).length>256*1024;)o.shift();d.superseded={revision:r.draft.revision,events:o,omitted:n.superseded.length-o.length}}if(dt(d.pending),d.superseded&&new TextEncoder().encode(JSON.stringify(d)).length>at&&delete d.superseded,new TextEncoder().encode(JSON.stringify(d)).length>at)throw new Error("Offline recovery storage limit reached; pending work is preserved");return structuredClone(d)}function Jr(e,t,r,i=indexedDB){let n=JSON.stringify([new URL(e).origin,t,r]),a=!1,s=new Promise((o,f)=>{let l=i.open("popmelt-plane-recovery",1);l.onupgradeneeded=()=>l.result.createObjectStore("planes"),l.onerror=()=>f(new Error("Could not open local draft recovery",{cause:l.error})),l.onblocked=()=>f(new Error("Local draft recovery is blocked by another browser view")),l.onsuccess=()=>{if(a){l.result.close(),f(new Error("Local draft recovery is closed"));return}l.result.onversionchange=()=>l.result.close(),o(l.result)}});s.catch(()=>{});let d=async o=>{let f=await s;if(a)throw new Error("Local draft recovery is closed");return new Promise((l,u)=>{let w=f.transaction("planes",o?"readwrite":"readonly"),I=w.objectStore("planes"),y=null,b,g=I.get(n);g.onsuccess=()=>{try{if(y=g.result??null,y&&(y.version!==1||y.reference.author.id!==r||y.basis.sourceId!==t))throw new Error("Invalid local recovery record; it has been preserved");o&&(y=Dr(y,o),I.put(y,n))}catch(c){b=c,w.abort()}},w.oncomplete=()=>l(y),w.onabort=()=>u(b??new Error("Could not save local draft recovery",{cause:w.error})),w.onerror=()=>{}})};return{read:()=>d(),update:o=>d(structuredClone(o)),async clear(){let o=await s;if(a)throw new Error("Local draft recovery is closed");await new Promise((f,l)=>{let u=o.transaction("planes","readwrite");u.objectStore("planes").delete(n),u.oncomplete=()=>f(),u.onabort=()=>l(u.error??new Error("Could not clear local draft recovery"))})},close(){a=!0,s.then(o=>o.close()).catch(()=>{})}}}var ke=class extends Error{constructor(e,t,r){super(t),this.status=e,this.code=r}},Ct=class{constructor(e,t,r,i=(...n)=>fetch(...n)){this.projectId=t,this.transport=i;let n=new URL(e);if(n.protocol!=="http:"||!["localhost","127.0.0.1","[::1]"].includes(n.hostname)||n.username||n.password||n.search||n.hash||n.pathname!=="/")throw new Error("Participant transport requires a local bridge origin");if(!t)throw new Error("Project identity required");this.base=n.origin,this.credential=r?{...r}:void 0}moderateStyles(e,t,r=!1){return this.rpc("moderate-styles",{participantId:e,styleModifications:t,restore:r})}moderateAnnotations(e,t,r=!1,i){return this.rpc("moderate-annotations",{participantId:e,annotationIds:t,restore:r,threadId:i})}async request(e,t,r={},i){let n=t instanceof FormData,a=await this.transport(this.base+e,{method:"POST",redirect:"error",credentials:"omit",signal:i??AbortSignal.timeout(3e4),headers:{...n?{}:{"Content-Type":"application/json"},"X-Popmelt-Project-Id":this.projectId,...this.credential?{"X-Popmelt-Participant-Id":this.credential.participantId,"X-Popmelt-Participant-Token":this.credential.token}:{},...r},body:n?t:JSON.stringify(t)}),s=await a.json().catch(()=>null);if(!a.ok)throw new ke(a.status,typeof s?.error=="string"?s.error:"Participant request failed",typeof s?.code=="string"?s.code:void 0);if(s===null)throw new Error("Invalid participant response");return{data:s,status:a.status}}async rpc(e,t={},r){return(await this.request("/participants/"+e,t,{},r)).data}mountRequestScope(e){if(!this.credential)throw new Error("Join before mounting a canvas");return ur(this.base,{"X-Popmelt-Project-Id":this.projectId,"X-Popmelt-Participant-Id":this.credential.participantId,"X-Popmelt-Participant-Token":this.credential.token,...e?{"X-Popmelt-Source-Revision":e.revision}:{}})}source(){return this.rpc("source")}snapshot(){return this.rpc("snapshot")}setHostModelSelection(e){return this.rpc("model-selection",{selection:e})}reserveAdmissionColor(e){return this.rpc("access-color",{receipt:e})}requestAdmission(e,t,r){return this.rpc("access-request",{receipt:e,name:t,colorIdentity:r})}admissionStatus(e){return this.rpc("access-status",{receipt:e})}cancelAdmission(e){return this.rpc("access-cancel",{receipt:e})}admissions(){return this.rpc("access-list")}decideAdmission(e,t){return this.rpc("access-decide",{id:e,decision:t})}attention(){return this.rpc("attention-read")}async reportAttention(e,t,r,i,n){return(await this.request("/participants/attention",{runtime:e,phase:t,operationId:r,location:i},{},n??AbortSignal.timeout(1500))).data}invite(){return this.rpc("invite")}revokeInvite(e){return this.rpc("revoke-invite",{invitation:e})}join(e,t,r){return this.rpc("join",{invitation:e,name:t,...r?{colorIdentity:r}:{}})}joinOrRequestAdmission(e,t,r){return this.rpc("join-or-request",{invitation:e,name:t,colorIdentity:r})}read(e,t){return this.rpc("read",{participantId:e,historyVersion:2},t)}connect(e,t){return this.rpc("connect",{runtimeId:e,previousToken:t})}renew(e,t){return this.rpc("renew",{runtime:e,activeColor:t})}disconnect(e){return this.rpc("disconnect",{runtime:e})}publish(e,t,r,i){return r.sourceId!==this.projectId?Promise.reject(new Error("Source world mismatch")):this.rpc("publish",{runtime:e,expectedRevision:t,sourceRevision:r.revision,state:i})}merge(e,t,r,i){return r.sourceId!==this.projectId?Promise.reject(new Error("Source world mismatch")):this.rpc("merge",{runtime:e,expectedRevision:t,sourceRevision:r.revision,events:i,historyVersion:2})}rename(e){return this.rpc("rename",{name:e})}setPermission(e,t){return this.rpc("permission",{participantId:e,permission:t})}revokeAccess(e){return this.rpc("revoke-access",{participantId:e})}pending(){return this.rpc("pending")}preview(e){return this.rpc("preview-read",{participantId:e})}previewWanted(e){return this.rpc("preview-demand",{runtime:e})}publishPreview(e,t,r){return this.rpc("preview-publish",{runtime:e,image:t,geometry:r})}review(e){return this.rpc("review",{id:e})}discard(e){return this.rpc("discard",{id:e})}submission(e,t){if(t===202&&e.pendingApproval===!0&&typeof e.submissionId=="string")return{status:"pending-approval",submissionId:e.submissionId,threadId:typeof e.threadId=="string"?e.threadId:void 0};if(t===200&&typeof e.jobId=="string"&&typeof e.threadId=="string"&&typeof e.position=="number")return{...e,status:"queued",jobId:e.jobId,threadId:e.threadId,position:e.position};throw new Error("Unexpected participant submission response")}async send(e,t,r){if(r.sourceId!==this.projectId)throw new Error("Source world mismatch");let i=await this.request("/send",e,{"X-Popmelt-Draft-Revision":String(t),"X-Popmelt-Source-Revision":r.revision});return this.submission(i.data,i.status)}contribute(e,t){return this.rpc("contribute",{threadId:e,text:t})}async approve(e,t){let r=await this.request("/participants/approve",{id:e,revision:t});return this.submission(r.data,r.status)}};function Wr(e){return[...new Set([...e.annotations.map(t=>t.linkedSelector),...e.styleModifications.map(t=>t.selector),...e.textModifications.map(t=>t.selector)].filter(t=>!!t))].slice(0,200)}function Ur(e,t,r){let i=Math.min(r.width/t.width,r.height/t.height),n=t.width*i,a=t.height*i;return{left:r.left+(r.width-n)/2+e.left*n,top:r.top+(r.height-a)/2+e.top*a,width:e.width*n,height:e.height*a}}function Xe(e){return e instanceof ke?e.status>=500||e.status===408||e.status===429||e.status===409&&(e.code==="runtime_expired"||e.code==="draft_conflict"):e instanceof TypeError||typeof e=="object"&&e!==null&&"name"in e&&(e.name==="TimeoutError"||e.name==="AbortError")}function pt(e,t=8e3){return Math.min(1e3*2**Math.min(Math.max(0,e-1),10),t)*(.5+Math.random()*.5)}function _r(e,t,r){let i={selectedId:r};try{let a=JSON.parse(e.getItem(t)??"null");a?.version===1&&typeof a.selectedId=="string"&&a.selectedId&&(i={selectedId:a.selectedId,...typeof a.threadId=="string"&&a.threadId?{threadId:a.threadId}:{}})}catch{}let n=a=>{if(!(a.selectedId===i.selectedId&&a.threadId===i.threadId)){i=a;try{e.setItem(t,JSON.stringify({version:1,...i}))}catch{}}};return{read:()=>i,select(a){a!==i.selectedId&&n({selectedId:a})},rememberThread(a,s){a===i.selectedId&&n({selectedId:a,...s?{threadId:s}:{}})},clear(){i={selectedId:r};try{e.removeItem(t)}catch{}}}}async function qr(e){let{projectId:t,runtimeStorage:r}=e,i={...e.credential},n={...e.observedSource};if(n.sourceId!==t)throw new Error("The loaded source does not match this participant session");let a=new Ct(e.bridgeUrl,t,i),s=`popmelt-runtime:${t}:${i.participantId}`,d=`popmelt-view:${t}:${i.participantId}`,o=_r(r,`popmelt-navigation:${t}:${i.participantId}`,i.participantId),f=ar(r,`popmelt-suggestion-views:${t}:${i.participantId}`),l;try{let h=JSON.parse(r.getItem(d)??"null");typeof h?.isAnnotating=="boolean"&&typeof h?.activeColor=="string"&&(l={isAnnotating:h.isAnnotating,activeColor:h.activeColor})}catch{}let u=null;try{u=JSON.parse(r.getItem(s)??"null"),(u?.participantId!==i.participantId||typeof u?.runtimeId!="string"||typeof u?.token!="string")&&(u=null)}catch{}let w=a.mountRequestScope(n),I=`popmelt-recovery-reset:${new URL(e.bridgeUrl).origin}:${t}:${i.participantId}`,y=!1;try{y=r.getItem(I)==="1"}catch{}let b=y?null:e.recoveryStore!==void 0?e.recoveryStore:typeof indexedDB<"u"?Jr(e.bridgeUrl,t,i.participantId):null,g=null,c=null,p,x;try{g=await b?.read()??null;try{x=await a.read(),p=await a.connect(x.draft.history?crypto.randomUUID():u?.runtimeId??crypto.randomUUID(),x.draft.history?void 0:u?.token),r.setItem(s,JSON.stringify(p))}catch(h){if(h instanceof ke&&h.status===403&&(await a.snapshot().catch(()=>[])).find(W=>W.identity.id===i.participantId)?.revokedAt!==void 0)throw await b?.clear?.(),new ke(403,"Your access was removed by the host","access_removed");if(!g||!(h instanceof Error)||!Xe(h))throw h;x=g.reference,p={participantId:i.participantId,runtimeId:crypto.randomUUID(),token:"",expiresAt:0},c=h}x.draft.history&&b&&(g=await b.update({reference:x,basis:n,pending:[]}),g&&(x=g.reference))}catch(h){throw b?.close(),w(),h}let A;try{A=x.draft.history?Lr({draft:x.draft,source:n,actor:p.runtimeId,view:l,pendingEvents:g?.pending,persist:b?async(h,W,T)=>{await b.update({reference:{...x,draft:h},basis:W,pending:T})}:void 0,saveView:h=>{try{r.setItem(d,JSON.stringify({isAnnotating:h.isAnnotating,activeColor:h.activeColor}))}catch{}},save:(h,W,T,Q)=>a.merge(p,h,W,Q)}):null}catch(h){throw b?.close(),w(),h}let P=A??Tr({draft:x.draft,source:n,save:(h,W,T)=>a.publish(p,h,W,T)}),C=!1,O=!1,M=null,j="connected",J=null,q=null,ie=0,H,ae=1e3,v=-1,te=!1,$=!1,F=new Set,R=()=>{for(let h of F)h()},L=()=>{C||H||J||j!=="reconnecting"||(H=setTimeout(()=>{H=void 0,oe()},ae),ae=Math.min(ae*2,3e4))},D=h=>{if(!C){if(M=h instanceof Error?h:new Error(String(h)),P.pause(M),M instanceof ke&&M.status===401){j="paused",$=!0,ie++,clearTimeout(H),H=void 0,R();return}j=Xe(M)?"reconnecting":"paused",j==="paused"&&(ie++,clearTimeout(H),H=void 0),L(),R()}},oe=(h=!1)=>{if(C)return Promise.reject(new Error("Participant runtime is closed"));if(q&&!h)return q;if(J)return J;let W=++ie,T=()=>!C&&W===ie;return clearTimeout(H),H=void 0,j="reconnecting",P.pause(M??new Error("Reconnecting to the participant session")),R(),J=(async()=>{if(await P.whenSettled(),!T())return;let Q=await a.connect(p.runtimeId,p.token);if(C)return;p=Q;try{r.setItem(s,JSON.stringify(p))}catch(Oe){if(!A?.getStatus().memoryOnly)throw Oe}if(!T())return;let Te=await a.read();T()&&(P.reconcile(Te.draft),await P.flush(),T()&&(M=null,j="connected",ae=1e3,R()))})().catch(Q=>{T()&&D(Q)}).finally(()=>{J=null,L()}),J},me=P.binding.subscribe(()=>{j==="connected"&&P.flush().catch(D)}),be=A?.subscribeStatus(()=>{let h=A.getStatus().localError;h&&h!==M?D(h):R()}),pe,he=setInterval(()=>{if(C||O||j!=="connected")return;O=!0;let h=p,W=P.binding.getSnapshot().activeColor;a.renew(p,W!==pe?W:void 0).then(T=>{!C&&p===h&&(p=T,pe=W,r.setItem(s,JSON.stringify(T)))}).catch(T=>{pe=void 0,!(p!==h||j!=="connected")&&(D(T),T instanceof ke&&T.status===409&&T.code==="runtime_expired"&&oe())}).finally(()=>{O=!1})},4e3),de=!1,se=0,Ee=async h=>{if(C||j!=="connected"||!A||!h)return;let W=ie;if(h.draftRevision>P.getStatus().revision){let T=await a.read();!C&&j==="connected"&&W===ie&&A.receive(T.draft)}},ce=setInterval(()=>{C||de||j!=="connected"||!A||se||(de=!0,a.snapshot().then(async h=>{let W=h.find(T=>T.identity.id===i.participantId);await Ee(W)}).catch(D).finally(()=>{de=!1}))},1e3),ge=0,G=!1,z=()=>{let h=P.binding.getSnapshot();return JSON.stringify({annotations:h.annotations.map(W=>({...W,status:void 0})),styles:h.styleModifications,text:h.textModifications,dom:h.domModifications,spacing:h.spacingTokenChanges})},le=null,Ce=null,B=!1,Le=setInterval(()=>{if(C||!le||B||j!=="connected")return;let h=le,W=p;B=!0,a.previewWanted(p).then(async({wanted:T})=>{if(!T||le!==h||C||j!=="connected")return;await P.flush();let Q=P.binding.getSnapshot(),Te=P.getStatus().revision,Oe=await h.frame(Wr(Q));Oe&&le===h&&!C&&j==="connected"&&W.token===p.token&&Q===P.binding.getSnapshot()&&await a.publishPreview(p,Oe.image,{draftRevision:Te,targets:Oe.targets})}).catch(T=>{if(!(C||j!=="connected")){if(T instanceof Error&&Xe(T)){D(T);return}le===h&&(Ce=T instanceof Error?T.message:"Preview unavailable",h.stop(),le=null,R())}}).finally(()=>{B=!1})},1e3);c?D(c):g?.pending.length&&P.flush().catch(D);let re;return{client:a,credential:i,navigation:o,state:P,readViewedSuggestions:f.read,markSuggestionViewed:f.mark,markSuggestionsViewed:f.markMany,captureVersion:z,reportAttention(h,W,T,Q){return C||j!=="connected"?Promise.resolve(!1):a.reportAttention(p,h,W,T,Q)},bindSubjects(h){return re=h,()=>{re===h&&(re=void 0)}},getSubjects:()=>re,getStatus:()=>({error:M,phase:j,pendingCount:ge,sending:G,sharing:!!le,previewError:Ce,accessRemoved:$}),reconnect:()=>oe(),retainExternalMembershipPolling(){se++;let h=!1;return()=>{h||(h=!0,se--)}},async retryLocalSave(){if(q)return q;await A?.retryLocalSave(),await oe()},clearLocalSpace(){return q||(C||!A?Promise.reject(new Error("Local space is unavailable")):(q=Promise.resolve().then(async()=>{let h=J;if(ie++,clearTimeout(H),H=void 0,j="paused",P.pause(new Error("Clearing local space")),R(),await h,C)throw new Error("Participant runtime is closed");try{r.setItem(I,"1")}catch{}await A.clearLocalSpace();let W;try{if(await Promise.race([b?.clear?b.clear():Promise.reject(new Error("Local storage cannot be cleared")),new Promise((T,Q)=>{W=setTimeout(()=>Q(new Error("Local clear timed out")),2e3)})]),C)throw new Error("Participant runtime is closed");if(await A.resumeLocalSaving())try{r.removeItem(I)}catch{}}catch{}finally{clearTimeout(W)}if(C)throw new Error("Participant runtime is closed");if(await oe(!0),j!=="connected")throw M??new Error("Session remains unavailable")}).finally(()=>{q=null}),q))},observeMembership(h){if(!(C||h.identity.id!==i.participantId)){if(h.revokedAt!==void 0&&!te){te=!0,D(new ke(403,"Your access was removed by the host")),le?.stop(),le=null,r.removeItem(s),r.removeItem(d),o.clear(),P.revoke().then(()=>b?.clear?.()).then(()=>{$=!0,R()}).catch(W=>{M=W instanceof Error?W:new Error("Could not clear local draft"),R()});return}if(!te){if(h.permission!=="blocked"&&!de&&(de=!0,Ee(h).catch(D).finally(()=>{de=!1})),h.permission==="blocked")v=h.permissionEpoch,M instanceof ke&&M.status===403||D(new ke(403,"Participant access is blocked"));else if(j==="paused"&&M instanceof ke&&M.status===403&&h.permissionEpoch>v){v=h.permissionEpoch;let W=()=>{!C&&j==="paused"&&v===h.permissionEpoch&&M instanceof ke&&M.status===403&&oe()};J?J.then(W):W()}}}},sharePreview(h){if(C){h?.stop();return}le?.stop(),le=h,Ce=null,h||a.publishPreview(p,null).catch(()=>{}),R()},subscribe:h=>(F.add(h),()=>{F.delete(h)}),async send(h,W){if(C||j!=="connected")throw M??new Error("Participant runtime is closed");if(G)throw new Error("A submission is already in progress");G=!0,R();try{if(P.setSource(n),await P.flush(),j!=="connected")throw M??new Error("Draft sync paused");if(z()!==W)throw new Error("Draft changed during capture; send again to include your latest changes");let T=await a.send(mr(h),P.getStatus().revision,n);return T.status==="pending-approval"?(ge++,R(),{pendingApproval:!0,submissionId:T.submissionId,threadId:T.threadId}):T}finally{G=!1,R()}},dispose(){C||(C=!0,re=void 0,j="closed",clearTimeout(H),clearInterval(he),clearInterval(ce),clearInterval(Le),le?.stop(),le=null,a.publishPreview(p,null).catch(()=>{}),me(),be?.(),w(),P.dispose(),P.whenSettled().finally(()=>b?.close()),F.clear())}}}function zr(e,t){e.removeItem(`popmelt-participant:${t}`);let r=`popmelt-admission:${t}`,i;try{i=JSON.parse(e.getItem(r)??"null")}catch{e.removeItem(r);return}i&&typeof i=="object"&&e.setItem(r,JSON.stringify({name:i.name,colorIdentity:i.colorIdentity??i.receipt}))}var ft="popmelt-join",Tt=/^[A-Za-z0-9_-]{43}$/;function $r(e,t){let r=new URL(e);if(!["http:","https:"].includes(r.protocol)||!["localhost","127.0.0.1","[::1]"].includes(r.hostname)||!Tt.test(t))throw new Error("A local page and valid invitation are required");let i=jt(r.href).cleanUrl,n=new URL(i);return n.hash=`${n.hash.slice(1)}${n.hash?"&":""}${ft}=${t}`,n.href}function jt(e){let t=new URL(e),r=null,i=t.hash.slice(1).split("&").filter(n=>{if(!n.startsWith(`${ft}=`))return!0;let a=n.slice(ft.length+1);return Tt.test(a)&&(r=a),!1});return t.hash=i.join("&"),{token:r,cleanUrl:t.href}}function Fr(e){let t={phase:"starting"},r=0,i=!1,n=!1,a=0,s,d=new Set,o=`popmelt-participant:${e.projectId}`,f=new Ct(e.url,e.projectId),l=g=>{if(!n){t=g;for(let c of d)c()}},u=async(g={})=>{let c=await fetch("/__popmelt/host",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify(g),redirect:"error"});if(c.status===403)return null;if(!c.ok)throw new Error(`Host entry unavailable (${c.status}).`);let p=`popmelt-before-participants:${e.projectId}`;return localStorage.getItem(p)===null&&localStorage.setItem(p,JSON.stringify(Object.fromEntries(Object.values(nr(e.projectId)).map(x=>[x,localStorage.getItem(x)])))),await c.json()},w=g=>qr({bridgeUrl:e.url,projectId:e.projectId,credential:g,runtimeStorage:sessionStorage,observedSource:{sourceId:e.projectId,revision:e.revision}}),I=async(g,c=a)=>{if(n||c!==a)return;let p=await w(g);if(n||c!==a){p.dispose();return}try{localStorage.setItem(o,JSON.stringify(g))}catch(x){throw p.dispose(),x}s?.dispose(),s=p,l({phase:"connected",connection:p}),u({credential:g}).catch(()=>{})},y=()=>{a++,s?.dispose(),s=void 0,zr(localStorage,e.projectId),l({phase:"entry",invitation:null})},b=async()=>{let g=jt(location.href),c=new URL(g.cleanUrl),p=new URLSearchParams(c.hash.slice(1)),x=p.get("popmelt-host");p.delete("popmelt-host"),x&&(c.hash=p.toString()),c.href!==location.href&&history.replaceState(history.state,"",c);let A=null;if(x){if(A=await u({token:x}),!A)throw new Error("Host entry expired. Use the current private host link.")}else if(!g.token){try{A=JSON.parse(localStorage.getItem(o)??"null")}catch{}A??(A=await u())}if(!n){if(!A){l({phase:"entry",invitation:g.token??null});return}try{await I(A)}catch(P){if(n)return;if(P.code==="access_removed"){y();return}if(P.status!==401)throw P;let C=await u();C?await I(C):y()}}};return{client:f,getSnapshot:()=>t,subscribe(g){return d.add(g),()=>{d.delete(g)}},retain(){if(n)throw new Error("Participant lifecycle is disposed");r++,i||(i=!0,b().catch(c=>l({phase:"error",message:c.message})));let g=!1;return()=>{g||(g=!0,r--,queueMicrotask(()=>{r||n||(n=!0,a++,s?.dispose(),s=void 0,d.clear())}))}},removed:y,async join(g,c){if(t.phase!=="entry"||!t.invitation||n)throw new Error("No active invitation");if(!c)throw new Error("Peer identity is not ready");let p=a,x=await f.joinOrRequestAdmission(t.invitation,g,c);if(!(n||p!==a)){if("admission"in x){localStorage.setItem(`popmelt-admission:${e.projectId}`,JSON.stringify({name:x.admission.name,receipt:c,colorIdentity:c})),l({phase:"entry",invitation:null});return}await I(x.joined.credential,p)}},admit:g=>I(g)}}function Ke(){let e=crypto.getRandomValues(new Uint8Array(32));return{id:crypto.randomUUID(),token:Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}}var _e=360,qe=120,Be=180,Ot=260;function Vr({client:e,storage:t,storageKey:r,onAdmitted:i,theme:n="light",themePreference:a=n,onThemePreferenceChange:s,onJoin:d}){let o=K(null),f=K(!1);if(!f.current){f.current=!0;try{o.current=JSON.parse(t.getItem(r)??"null")}catch{}}let[l,u]=_(o.current?.name??""),[w,I]=_(d?void 0:o.current?.receipt),[y,b]=_(null),[g,c]=_(),[p,x]=_(),A=K(null),[P,C]=_(!!d),[O,M]=_(!1),[j,J]=_(0),[q,ie]=_(),[H,ae]=_("idle"),[v,te]=_(),[$,F]=_(),R=K(!1),[L,D]=_(""),oe=K(null),me=K(null),be=K(null),pe=K(null),he=K(!1),de=K(0),se=K(!1),Ee=yr(),ce=K(!1),ge=K(0),G=K(i);G.current=i;let z=K(!1),le=K(null),Ce=K(()=>{});le.current||(le.current=new Promise(k=>{Ce.current=k}));let B=rt[n],Le=P&&!g;ee(()=>{let k=!1,Z,X,V=()=>{k||(k=!0,z.current=!0,Ce.current())};typeof requestAnimationFrame=="function"&&(Z=requestAnimationFrame(()=>{X=requestAnimationFrame(V)}));let Ie=window.setTimeout(V,64);return()=>{Z!==void 0&&cancelAnimationFrame(Z),X!==void 0&&cancelAnimationFrame(X),window.clearTimeout(Ie),V()}},[]),ee(()=>cr(document),[]),St(()=>{let k=!0,Z=()=>{if(!k||!be.current)return;let X=getComputedStyle(be.current),V=document.createElement("span");Object.assign(V.style,{position:"fixed",visibility:"hidden",pointerEvents:"none",whiteSpace:"nowrap",fontFamily:X.fontFamily,fontSize:X.fontSize,fontWeight:X.fontWeight,lineHeight:X.lineHeight}),document.body.append(V);let Ie=Number.parseFloat(X.paddingLeft)+Number.parseFloat(X.paddingRight);V.textContent="Ask for access";let Pe=Ie+12+3+V.getBoundingClientRect().width;V.textContent="Request pending";let ye=Ie+12+3+V.getBoundingClientRect().width;V.textContent="Request declined";let Me=Ie+12+3+V.getBoundingClientRect().width;if(V.remove(),Pe>15&&ye>15&&Me>15&&te({ask:Math.ceil(Pe),pending:Math.ceil(ye),declined:Math.ceil(Me)}),pe.current){let xe=getComputedStyle(pe.current),ve=document.createElement("span");Object.assign(ve.style,{position:"fixed",visibility:"hidden",pointerEvents:"none",whiteSpace:"nowrap",fontFamily:xe.fontFamily,fontSize:xe.fontSize,fontWeight:xe.fontWeight,lineHeight:xe.lineHeight}),ve.textContent="Sending...",document.body.append(ve);let we=Number.parseFloat(xe.paddingLeft)+Number.parseFloat(xe.paddingRight);F({idle:Math.ceil(we+14),sending:Math.ceil(we+ve.getBoundingClientRect().width)}),ve.remove()}};return Z(),document.fonts?.ready.then(Z),()=>{k=!1}},[n,P]),ee(()=>{if(!j)return;let k=setTimeout(()=>J(0),_e);return()=>clearTimeout(k)},[j]),ee(()=>{if(!q)return;let k=setTimeout(()=>ie(void 0),_e);return()=>clearTimeout(k)},[q]),ee(()=>{if(H!=="in")return;let k=setTimeout(()=>ae("idle"),Be);return()=>clearTimeout(k)},[H]),ee(()=>{o.current&&delete o.current.color;try{let k=JSON.parse(t.getItem(r)??"null");k&&typeof k=="object"&&"color"in k&&(delete k.color,t.setItem(r,JSON.stringify(k)))}catch{}},[t,r]);let re=!!(w&&(!y||y.status==="pending"||y.status==="granted")),h=(k,Z)=>{o.current={...o.current,name:k,receipt:Z},t.setItem(r,JSON.stringify(o.current))};ee(()=>{if(y?.status==="cancelled"){o.current={...o.current,name:l,receipt:void 0};try{t.setItem(r,JSON.stringify(o.current))}catch{}I(void 0),b(null)}},[y,l,t,r]);let W=()=>{if(A.current)return A.current;let k=async()=>{let Z=JSON.parse(t.getItem(r)??"null"),X=Z?.colorIdentity??Z?.receipt??Ke();o.current={name:l,receipt:Z?.receipt,colorIdentity:X},t.setItem(r,JSON.stringify(o.current));let V;try{V=await e.reserveAdmissionColor(X)}catch(Ie){let Pe=Ie.status;if(Pe!==400&&Pe!==401)throw Ie;X=Ke(),o.current={...o.current,colorIdentity:X},t.setItem(r,JSON.stringify(o.current)),V=await e.reserveAdmissionColor(X)}return c(V.color),x(ir(V)),X};return A.current=k().finally(()=>{A.current=null}),A.current},T=()=>{C(!P),P||D("")},Q=K(W);Q.current=W;let Te=!!d;ee(()=>{if(!P||g)return;let k=!1,Z,X=0,V=async()=>{try{await Q.current()}catch{if(k)return;Z=setTimeout(()=>{V()},pt(++X))}};return V(),()=>{k=!0,clearTimeout(Z)}},[P,g,t,r]),ee(()=>{if(!P)return;me.current?.focus();let k=Z=>{Z.composedPath().includes(oe.current)||C(!1)};return document.addEventListener("pointerdown",k),()=>document.removeEventListener("pointerdown",k)},[P]),ee(()=>{if(!w)return;let k=!0,Z=!1,X=!1,V,Ie,Pe=()=>{ge.current+=1,o.current={...o.current,name:l,receipt:void 0};try{t.setItem(r,JSON.stringify(o.current))}catch{}I(void 0),b(null),C(!1),D("")},ye=()=>{X=!0;let ve=Ke(),we=0,De=async()=>{if(k)try{let Je=await Q.current();o.current={...o.current,name:l,receipt:ve,colorIdentity:Je},t.setItem(r,JSON.stringify(o.current));let ze=await e.requestAdmission(ve,l,Je);if(!k)return;ge.current+=1,I(ve),b(ze),D("")}catch{if(!k)return;Ie=setTimeout(()=>{De()},pt(++we))}};De()},Me=async()=>{if(Z||X||se.current||ce.current)return;Z=!0;let ve=ge.current;try{let we=await e.admissionStatus(w);if(!k||ve!==ge.current)return;if(we.status==="declined"){if(z.current||await le.current,!k||ve!==ge.current)return;X=!0;let De=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches,Je=()=>{k&&(ae("rejected"),J(ze=>ze+1),V=setTimeout(()=>{if(k){if(De){Pe(),ae("idle");return}ae("rejected-out"),V=setTimeout(()=>{k&&(Pe(),ae("in"))},qe)}},_e))};De?Je():(ae("pending-out"),V=setTimeout(Je,qe));return}if(we.status==="expired"){ye();return}if(b(we),X=we.status==="cancelled",D(""),we.credential){se.current=!0;try{await G.current(we.credential),X=!0}finally{se.current=!1}}}catch(we){if(!k||ve!==ge.current)return;we.status===401&&ye()}finally{Z=!1}};Me();let xe=setInterval(Me,1500);return()=>{k=!1,clearInterval(xe),clearTimeout(V),clearTimeout(Ie)}},[e,w,l,t,r]);let Oe=async()=>{if(!(!w||O||ce.current)){ce.current=!0,ge.current+=1,M(!0),D("");try{let k=await e.cancelAdmission(w);b(k),C(!1)}catch{J(k=>k+1)}finally{ce.current=!1,M(!1)}}},et=async k=>{if(!l.trim()||O||re||R.current)return;if(R.current=!0,M(!0),D(""),ie(void 0),d){try{let X=await W();h(l.trim()),await d(l.trim(),X)}catch(X){D(X instanceof Error?X.message:"Could not join. Please try again.")}finally{R.current=!1,M(!1)}return}try{o.current=JSON.parse(t.getItem(r)??"null")}catch{}let Z=!y&&o.current?.receipt?o.current.receipt:Ke();try{let X=await W();h(l,Z),o.current={...o.current,name:l,receipt:Z};let V=await e.requestAdmission(Z,l.trim(),X);I(Z),u(V.name),b(V),C(!1)}catch{o.current={...o.current,name:l,receipt:Z},ie({target:k,pulse:++de.current})}finally{R.current=!1,M(!1)}};return Y("div",{ref:oe,"data-devtools":"participant-admission","data-popmelt-font":"sans","data-popmelt-theme":n,style:{display:"contents"},onKeyDown:k=>{k.key==="Escape"&&(C(!1),k.stopPropagation())},children:[S("style",{children:`
|
|
3
3
|
${Bt}
|
|
4
4
|
[data-popmelt-admission-ask] {
|
|
5
5
|
transition: box-shadow 120ms ease, width ${Be}ms ease;
|
package/dist/bridge-entry.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{j as n}from"./chunk-
|
|
1
|
+
import{j as n}from"./chunk-TP3COBHM.mjs";import"./chunk-GL4I4MI6.mjs";import"./chunk-QXVMGZFP.mjs";import{mkdir as d,unlink as l,writeFile as P}from"fs/promises";import{join as r}from"path";var u=parseInt(process.env.POPMELT_PORT||"1111",10),s=process.env.POPMELT_PROJECT_ROOT||process.cwd(),w=process.env.POPMELT_DEV_ORIGIN||void 0,m=process.env.POPMELT_COPILOT_PATH||void 0,O=process.env.POPMELT_CDP_URL||void 0,c=r(s,".popmelt"),i=r(c,"bridge.lock");async function f(e){await d(c,{recursive:!0}),await P(i,JSON.stringify({pid:process.pid,port:e,startedAt:Date.now()})+`
|
|
2
2
|
`)}async function a(){try{await l(i)}catch{}}async function T(){let e=await n({port:u,projectRoot:s,devOrigin:w,copilotPath:m,nativeCaptureUrl:O,restartMode:"detached"});await f(e.port),await new Promise(p=>{let t=!1,o=async()=>{t||(t=!0,await e.close(),await a(),p(),process.exit(0))};process.on("SIGTERM",o),process.on("SIGINT",o)})}T().catch(e=>{console.error("[popmelt bridge-entry] Fatal:",e),a().finally(()=>process.exit(1))});
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{b as m,a as i}from"./chunk-
|
|
2
|
+
import{b as m,a as i}from"./chunk-264MDJPC.mjs";import"./chunk-MIGCFNL4.mjs";import"./chunk-JQHZFDY5.mjs";import"./chunk-EX63NVDN.mjs";import"./chunk-N2ZEZCHO.mjs";import"./chunk-J3UIBBU2.mjs";import"./chunk-3LBOX7HQ.mjs";import"./chunk-QUNV5PNI.mjs";import"./chunk-A2UXK7AS.mjs";import"./chunk-MP7S5ALD.mjs";import"./chunk-XTOCFTVW.mjs";import"./chunk-LVEMYZOA.mjs";import"./chunk-XOGBFVWI.mjs";import"./chunk-HGW2U6PD.mjs";import{createElement as p}from"react";import{createRoot as e}from"react-dom/client";function n(o,t){let r=e(o);return r.render(p(m,t)),()=>{r.unmount(),i()}}export{n as mountBrowserRuntime};
|
package/dist/browser.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
export{a as isPopmeltPreview}from"./chunk-EX63NVDN.mjs";var m={unmount(){}},u="[data-popmelt-browser-host]";async function p(o={}){if(!o.enabled||typeof document>"u")return m;if(document.querySelector(`${u}, [data-popmelt-top-layer-host]`))throw new Error("Popmelt is already mounted. Unmount it before mounting again.");let e=document.createElement("div");e.setAttribute("data-popmelt-browser-host",""),e.setAttribute("data-devtools",""),document.documentElement.appendChild(e);let d=[["__POPMELT_PROJECT_ID__",o.projectId],["__POPMELT_BRIDGE_URL__",o.bridgeUrl]].flatMap(([t,r])=>{if(r===void 0)return[];let n=Object.prototype.hasOwnProperty.call(window,t),l=window[t],i=r??void 0;return window[t]=i,[()=>{window[t]===i&&(n?window[t]=l:delete window[t])}]}),a=()=>{e.remove();for(let t of d)t()};try{let{mountBrowserRuntime:t}=await import("./browser-runtime-
|
|
2
|
+
export{a as isPopmeltPreview}from"./chunk-EX63NVDN.mjs";var m={unmount(){}},u="[data-popmelt-browser-host]";async function p(o={}){if(!o.enabled||typeof document>"u")return m;if(document.querySelector(`${u}, [data-popmelt-top-layer-host]`))throw new Error("Popmelt is already mounted. Unmount it before mounting again.");let e=document.createElement("div");e.setAttribute("data-popmelt-browser-host",""),e.setAttribute("data-devtools",""),document.documentElement.appendChild(e);let d=[["__POPMELT_PROJECT_ID__",o.projectId],["__POPMELT_BRIDGE_URL__",o.bridgeUrl]].flatMap(([t,r])=>{if(r===void 0)return[];let n=Object.prototype.hasOwnProperty.call(window,t),l=window[t],i=r??void 0;return window[t]=i,[()=>{window[t]===i&&(n?window[t]=l:delete window[t])}]}),a=()=>{e.remove();for(let t of d)t()};try{let{mountBrowserRuntime:t}=await import("./browser-runtime-7YSJ2DPK.mjs");if(!e.isConnected)throw new Error("Popmelt mount was removed before startup.");let r=t(e,o),n=!0;return{unmount(){if(n){n=!1;try{r()}finally{a()}}}}}catch(t){throw a(),t}}export{p as mountPopmelt};
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{K as Za,Sa as tc,d as Xf,c as nc,vb as us,a as Vf,zb as rc,Ab as oc,yb as ic,hb as Qf,ib as Gf,Ha as ji,ha as Zf,Fb as eh,Gb as ac,ga as th,Mb as nh,Ib as rh,Jb as oh,Kb as ih,Ya as ah,ia as lh,Ba as sh,xa as lc,_a as dh,$ as ch,aa as ps,ba as uh,ca as ph,Za as fh,Da as hh,fa as mh,mb as fs,lb as gh,kb as hs,Hb as yh,ja as vh,Ma as sc,za as dc,Ka as cc,La as bh,Ja as uc,Ia as xh,Ea as ms,L as wh,Eb as Sh,n as pc,wa as Ih,wb as fc,Pa as kh,Oa as Eh,Ra as Th,Na as Ch,Qa as Ah,Aa as Mh,B as Rh,C as Lh,j as $h,pa as Zt,sa as jh,va as Ph,Fa as zh,qa as hc,la as Pi,R as Dh,ka as Oh,P as mc,W as Hh,db as ci,Ob as Nh,Lb as _h,cb as gc,eb as yc,ob as gs,qb as Fh,Cb as Wh,Db as Jh,jb as qh,fb as Bh,gb as Yh,ya as Uh,Ca as ys,O as Kh,A as vc,D as bc,J as xc,I as wc,m as ui,E as Sc,H as zi,N as Xh,ta as vs,oa as Vh,na as bs,ma as xs,M as Qh,ea as Gh,da as Zh,Ga as em,ra as Ic,ua as kc,o as tm,U as Ec,S as Tc,T as Cc,V as nm,X as Ac,Z as Mc,_ as rm,Q as om,xb as Rc,Bb as Lc,k as Di,y as ws,p as pi,G as el,s as $c,e as im,Y as am,r as tl,f as jc,w as lm,h as $r,t as Ss,q as pa,g as Is,i as sm,x as dm,v as cm,F as ks,u as Pc,l as zc,z as um}from"./chunk-
|
|
2
|
+
import{K as Za,Sa as tc,d as Xf,c as nc,vb as us,a as Vf,zb as rc,Ab as oc,yb as ic,hb as Qf,ib as Gf,Ha as ji,ha as Zf,Fb as eh,Gb as ac,ga as th,Mb as nh,Ib as rh,Jb as oh,Kb as ih,Ya as ah,ia as lh,Ba as sh,xa as lc,_a as dh,$ as ch,aa as ps,ba as uh,ca as ph,Za as fh,Da as hh,fa as mh,mb as fs,lb as gh,kb as hs,Hb as yh,ja as vh,Ma as sc,za as dc,Ka as cc,La as bh,Ja as uc,Ia as xh,Ea as ms,L as wh,Eb as Sh,n as pc,wa as Ih,wb as fc,Pa as kh,Oa as Eh,Ra as Th,Na as Ch,Qa as Ah,Aa as Mh,B as Rh,C as Lh,j as $h,pa as Zt,sa as jh,va as Ph,Fa as zh,qa as hc,la as Pi,R as Dh,ka as Oh,P as mc,W as Hh,db as ci,Ob as Nh,Lb as _h,cb as gc,eb as yc,ob as gs,qb as Fh,Cb as Wh,Db as Jh,jb as qh,fb as Bh,gb as Yh,ya as Uh,Ca as ys,O as Kh,A as vc,D as bc,J as xc,I as wc,m as ui,E as Sc,H as zi,N as Xh,ta as vs,oa as Vh,na as bs,ma as xs,M as Qh,ea as Gh,da as Zh,Ga as em,ra as Ic,ua as kc,o as tm,U as Ec,S as Tc,T as Cc,V as nm,X as Ac,Z as Mc,_ as rm,Q as om,xb as Rc,Bb as Lc,k as Di,y as ws,p as pi,G as el,s as $c,e as im,Y as am,r as tl,f as jc,w as lm,h as $r,t as Ss,q as pa,g as Is,i as sm,x as dm,v as cm,F as ks,u as Pc,l as zc,z as um}from"./chunk-MIGCFNL4.mjs";import{c as pm,a as Dc,b as fa}from"./chunk-JQHZFDY5.mjs";import{a as Oc,b as fm}from"./chunk-EX63NVDN.mjs";import{d as hm,g as mm,m as gm,l as ym}from"./chunk-N2ZEZCHO.mjs";import{a as vm}from"./chunk-J3UIBBU2.mjs";import{b as bm,f as Oi,h as xm,g as Es,a as Hc,d as Nc,c as _c}from"./chunk-3LBOX7HQ.mjs";import{a as wm}from"./chunk-QUNV5PNI.mjs";import{sa as Ts,R as Fc,T as Kt,h as Sm,Ua as Wc,X as Jc,V as qc,W as Cs,Y as Im,Z as ha,$ as Bc,aa as Yc,fa as km,ha as Em,ga as Tm,da as Cm,ia as Am,cb as Uc,ka as Hi,La as Mm,N as Rm,H as Kc,A as io,Ka as nl,Ja as Lm,P as $m,D as Xc,O as jm,Ca as In,ra as As,za as lr,Ea as Ms,ya as ma,Ga as Pm,la as rl,Xa as Vc,xa as ao,ab as zm,bb as Qc,va as Dm,ua as Om,Ta as Rs,Ra as Ls,Wa as Gc,_ as Hm,U as Nm,J as $s,v as Zc,u as ga,r as ol,w as Ni,wa as eu,ja as tu,I as _m,K as Fm,M as Wm,f as Jm,Aa as qm,Ba as Bm,ta as Ym,Za as Um,Ya as nu,$a as Km,_a as Xm,Va as ru,z as ou,t as js,g as Vm,Da as Ps,C as Qm,E as iu,G as Gm,F as Zm,Fa as au,Ha as lu,B as eg,s as il,L as tg,y as zs,S as ng,q as su,x as rg}from"./chunk-A2UXK7AS.mjs";import{i as du,k as og,m as ig,h as cu,g as ag,a as al,e as lg,b as jr,d as sg,f as ot,c as dg}from"./chunk-MP7S5ALD.mjs";import{a as cg}from"./chunk-LVEMYZOA.mjs";import{c as ln,a as Ro,i as yn,j as _i,d as ug,e as pg,b as uu,l as fg,m as hg,k as mg}from"./chunk-XOGBFVWI.mjs";import{d as vn,o as ya,n as Fi,a as pu,i as fu,v as hu,u as mu,h as ll,k as gg,f as yg,c as Ds,m as gu,l as Os}from"./chunk-HGW2U6PD.mjs";import{lazy as yu,memo as vg,useContext as Pr,useState as $,Fragment as bg,useRef as q,useEffect as _,useCallback as B,useMemo as Se,Suspense as vu,cloneElement as xg,useSyncExternalStore as wg,useLayoutEffect as Tt,useId as Sg}from"react";import{jsx as u,jsxs as C,Fragment as it}from"react/jsx-runtime";import{Fingerprint as lo,Component as sl,Ban as dl,Terminal as bu,PenLine as xu,ImageIcon as Ig,Plug as kg,SquareMousePointer as Eg,ChevronRight as Hs,FilePenLine as Tg,ChevronDown as Wi,Check as Lo,ChevronLeft as Cg,X as cl,Send as wu,Clock as Su,Lock as Ag,ArrowDown as Mg,OctagonAlert as Iu,MessageCircleQuestionMark as Rg,Reply as Lg,TriangleAlert as $g,Command as ku,CornerDownLeft as Ns,EyeOff as jg,Trash2 as Pg}from"lucide-react";import{createPortal as Eu}from"react-dom";function zg(e){return Fc(e)?new Dg(e):new EventSource(e)}var Dg=class{constructor(e){this.readyState=0,this.onerror=null,this.controller=new AbortController,this.listeners=new Map,this.read(e)}addEventListener(e,t){let n=this.listeners.get(e)??new Set;n.add(t),this.listeners.set(e,n)}close(){this.readyState=2,this.controller.abort(),this.listeners.clear()}emit(e,t){let n=new MessageEvent(e,{data:t});for(let r of this.listeners.get(e)??[])r(n)}async read(e){try{let t=await fetch(e,ng(e,{signal:this.controller.signal}));if(!t.ok||!t.body||!t.headers.get("content-type")?.includes("text/event-stream"))throw new Error("Event stream unavailable");if(this.controller.signal.aborted)return;this.readyState=1;let n=t.body.getReader(),r=new TextDecoder,o="",i="message",a=[],l=0;try{for(;!this.controller.signal.aborted;){let s=await n.read();if(s.done)throw new Error("Event stream ended");if(o+=r.decode(s.value,{stream:!0}),o.length>2*1024*1024)throw new Error("Event frame too large");let d;for(;(d=o.indexOf(`
|
|
3
3
|
`))!==-1;){let c=o.slice(0,d).replace(/\r$/,"");if(o=o.slice(d+1),!c)a.length&&this.emit(i,a.join(`
|
|
4
4
|
`)),i="message",a=[],l=0;else if(c.startsWith("event:"))i=c.slice(6).trimStart();else if(c.startsWith("data:")&&(a.push(c.slice(5).replace(/^ /,"")),l+=c.length,l>2*1024*1024))throw new Error("Event frame too large")}}}finally{await n.cancel().catch(()=>{})}}catch{if(this.controller.signal.aborted)return;this.readyState=2,this.emit("error",""),this.onerror?.call(this,new Event("error"))}}};function Og(e,t,n){return[...e].reverse().find(o=>o.type==="done"||o.type==="error")||(t?void 0:n)}function Tu(e,t,n){let r=new Set(t.map(s=>s.id)),o=new Map(n.map(s=>[s.id,s])),i=e.flatMap(s=>{let d=o.get(s);return d?.status==="done"||d?.status==="error"?[d]:[]}),a=new Set(i.map(s=>s.id)),l=e.filter(s=>!a.has(s));for(let s of r)l.includes(s)||l.push(s);return{serverActiveIds:r,terminalJobs:i,reconciledActiveIds:l}}function Cu(e,t){return e.store===void 0&&(e.store=t),e.store}function Hg(e,t){let n=e.listeners??(e.listeners=new Set);return n.add(t),()=>n.delete(t)}function Ng(e,t,n){let r=n(Cu(e,t));e.store=r;for(let o of e.listeners??[])o();return r}var Ze=globalThis.__POPMELT_BRIDGE_CONNECTION__??(globalThis.__POPMELT_BRIDGE_CONNECTION__={}),ul=Ze.sourceId??(typeof localStorage<"u"?localStorage.getItem("popmelt-source-id"):null)??(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():Math.random().toString(36).slice(2));Ze.sourceId=ul;try{typeof localStorage<"u"&&localStorage.setItem("popmelt-source-id",ul)}catch{}function _s(){return ul}var pl={isConnected:!1,status:"disconnected",jobResponses:{},jobThinking:{},activeJobIds:[],activeJobThreads:{},currentResponse:"",currentThinking:"",events:[],activeJobId:null,lastCompletedJobId:null,lastResponseText:null,lastThreadId:null,lastErrorByJob:{},pendingQuestions:[],incrementalResolutions:[],capabilitiesVersion:0};Ze.store??(Ze.store={...pl}),Ze.listeners??(Ze.listeners=new Set);var zr=Ze.activeEs??null,fl=Ze.activeBridgeUrl??null,Dr=null,Xn=Ze.connectionGeneration??0,hl=new Set,Ji=new Map,$o={},Fs=new Set;function Pn(e,t){if(!e)return!1;if(Fs.has(e))return!0;if(hl.has(e)){let r=Ji.get(e);return r||(r=[],Ji.set(e,r)),r.push({type:t.type??"",data:t}),!0}let n=$o[e];return n!==void 0&&typeof t.seq=="number"&&t.seq<=n}async function Au(e,t,n,r=new Map){let o=()=>n!==(Ze.connectionGeneration??0);for(let i of t){if(o())return;hl.add(i),Ji.set(i,[])}await Promise.all(t.map(async i=>{try{let a=await Bc(e,i);if(o())return;let l=Ji.get(i)??[];if(a){ut(c=>{let f={...c.jobResponses,[i]:a.accumulated.response},p={...c.jobThinking,[i]:a.accumulated.thinking},h=[...c.events];for(let g of a.events)g.type==="done"||g.type==="error"||h.push({type:g.type,data:g,timestamp:Date.now()});return{...c,jobResponses:f,jobThinking:p,currentResponse:i===c.activeJobId?a.accumulated.response:c.currentResponse,currentThinking:i===c.activeJobId?a.accumulated.thinking:c.currentThinking,events:h}}),$o[i]=a.currentSeq;let s=[...a.events].reverse().find(c=>c.type==="job_started"||c.type==="job_parked");s?.type==="job_parked"&&qi("job_parked",s,i);let d=Og(a.events,a.jobActive,r.get(i));d&&qi(d.type,d,i);for(let c of l)typeof c.data.seq=="number"&&c.data.seq<=a.currentSeq||qi(c.type,c.data,i)}else{let s=!1;for(let c of l)qi(c.type,c.data,i),(c.type==="done"||c.type==="error")&&(s=!0);let d=r.get(i);!s&&d&&qi(d.type,d,i)}}finally{hl.delete(i),Ji.delete(i)}}))}function qi(e,t,n){if(e==="job_parked")ut(r=>{let o=r.activeJobIds.filter(i=>i!==n);return{...r,activeJobIds:o,activeJobId:o.at(-1)??null,events:[...r.events,{type:e,data:t,timestamp:Date.now()}]}});else if(e==="job_started")ut(r=>({...r,status:"streaming",activeJobId:n,activeJobIds:[...new Set([...r.activeJobIds,n])],activeJobThreads:typeof t.threadId=="string"?{...r.activeJobThreads,[n]:t.threadId}:r.activeJobThreads,events:[...r.events,{type:e,data:t,timestamp:Date.now()}]}));else if(e==="delta"){let r=t.text||"";ut(o=>({...o,jobResponses:{...o.jobResponses,[n]:(o.jobResponses[n]||"")+r},currentResponse:n===o.activeJobId?o.currentResponse+r:o.currentResponse,events:[...o.events,{type:"delta",data:t,timestamp:Date.now()}]}))}else if(e==="thinking"){let r=t.text||"";ut(o=>({...o,jobThinking:{...o.jobThinking,[n]:(o.jobThinking[n]||"")+r},currentThinking:n===o.activeJobId?o.currentThinking+r:o.currentThinking,events:[...o.events,{type:"thinking",data:t,timestamp:Date.now()}]}))}else if(e==="status")ut(r=>({...r,events:[...r.events,{type:"status",data:t,timestamp:Date.now()}]}));else if(e==="done")delete $o[n],ut(r=>{let o=r.activeJobIds.filter(d=>d!==n),i={...r.jobResponses},a={...r.jobThinking},l=i[n];delete i[n],delete a[n];let s=n===r.activeJobId?o.length>0?o[o.length-1]:null:r.activeJobId;return{...r,activeJobIds:o,activeJobId:s,jobResponses:i,jobThinking:a,lastCompletedJobId:n,lastResponseText:t.responseText||l||r.currentResponse||null,lastThreadId:t.threadId??null,...n===r.activeJobId?{currentResponse:s&&i[s]||"",currentThinking:s&&a[s]||""}:{},events:[...r.events,{type:"done",data:t,timestamp:Date.now()}]}});else if(e==="error"){delete $o[n];let r=t.message??"";ut(o=>{let i=o.activeJobIds.filter(l=>l!==n),a=i.length>0?o.status:"error";return{...o,status:a,activeJobIds:i,lastCompletedJobId:n,lastErrorByJob:r?{...o.lastErrorByJob,[n]:r}:o.lastErrorByJob,events:[...o.events,{type:"error",data:t,timestamp:Date.now()}]}})}else ut(e==="question"?r=>{let o=typeof t.threadId=="string"?t.threadId:"",i=typeof t.question=="string"?t.question:"",a=Array.isArray(t.annotationIds)?t.annotationIds.filter(s=>typeof s=="string"):void 0,l=r.pendingQuestions.some(s=>s.jobId===n);return{...r,pendingQuestions:i&&o&&!l?[...r.pendingQuestions,{jobId:n,threadId:o,question:i,annotationIds:a,timestamp:Date.now()}]:r.pendingQuestions,events:[...r.events,{type:e,data:t,timestamp:Date.now()}]}}:r=>({...r,events:[...r.events,{type:e,data:t,timestamp:Date.now()}]}))}var Vn=Ze.discoveredBridgeUrl??null,zn=Ze.discoveredBridgeProjectId??null,jo=null,Bi=null;function Mu(e,t=!1){let n=e??null;if(!(!t&&(Ze.expectedProjectId??null)===n)){zr&&(zr.close(),zr=null,Ze.activeEs=null),Dr&&(clearTimeout(Dr),Dr=null),fl=null,Ze.activeBridgeUrl=null,Vn=null,zn=null,Ze.discoveredBridgeUrl=null,Ze.discoveredBridgeProjectId=null,jo=null,Bi=null,hl.clear(),Ji.clear(),Fs.clear();for(let r of Object.keys($o))delete $o[r];Ze.expectedProjectId=n,Xn=(Ze.connectionGeneration??Xn)+1,Ze.connectionGeneration=Xn,ut(()=>({...pl}))}}function _g(){Ze.listeners?.size||Mu(null,!0)}async function Ru(e,t){if(Vn&&(t?zn===t:!zn))return Vn;if(!t&&zn&&(Vn=null,zn=null,Ze.discoveredBridgeUrl=Vn,Ze.discoveredBridgeProjectId=zn),t&&zn&&zn!==t&&(Vn=null,zn=null,Ze.discoveredBridgeUrl=Vn,Ze.discoveredBridgeProjectId=zn),jo&&Bi===(t??null))return jo;let n=Xn;return Bi=t??null,jo=Hm(e,t).then(r=>n!==Xn?null:(Vn=r?.url??null,zn=r?.projectId??t??null,Ze.discoveredBridgeUrl=Vn,Ze.discoveredBridgeProjectId=zn,jo=null,Bi=null,Vn)).catch(()=>(n!==Xn||(jo=null,Bi=null),null)),jo}function Fg(){return Vn}async function Wg(e,t){Vn=null,zn=null,Ze.discoveredBridgeUrl=null,Ze.discoveredBridgeProjectId=null,jo=null,Bi=null;let n=Xn,r=await Ru(e,t);return r&&n===Xn&&Ws(r),r}function va(){return Cu(Ze,{...pl})}function Jg(e){return Hg(Ze,e)}function ut(e){Ng(Ze,{...pl},t=>{let n=e(t),r=new Set(n.activeJobIds),o=n.activeJobId&&r.has(n.activeJobId)?n.activeJobId:n.activeJobIds.at(-1)??null;return{...n,activeJobId:o,activeJobThreads:Object.keys(n.activeJobThreads).some(i=>!r.has(i))?Object.fromEntries(Object.entries(n.activeJobThreads).filter(([i])=>r.has(i))):n.activeJobThreads,status:n.status==="streaming"&&r.size===0?"idle":n.status}})}function qg(){return typeof window<"u"?window.__POPMELT_PROJECT_ID__??null:null}function Ws(e){if(zr&&zr.readyState!==EventSource.CLOSED&&fl===e)return;zr&&(zr.close(),zr=null,Ze.activeEs=null),Dr&&(clearTimeout(Dr),Dr=null),fl=e,Ze.activeBridgeUrl=fl,Xn=(Ze.connectionGeneration??Xn)+1;let t=Xn;Ze.connectionGeneration=Xn;let n=new URLSearchParams({sourceId:ul}),r=qg();r&&n.set("projectId",r);let o=zg(`${e}/events?${n.toString()}`);zr=o,Ze.activeEs=zr;let i=()=>t!==(Ze.connectionGeneration??0);o.addEventListener("connected",()=>{i()||ha(e).then(a=>{if(i())return;let l=[...a?.activeJobs??(a?.activeJob?[a.activeJob]:[]),...a?.queuedJobs?.filter(m=>m.parked)??[]],s=a?.recentJobs??[],d=Tu(va().activeJobIds,l,s),{serverActiveIds:c,terminalJobs:f}=d,p=f.map(m=>m.id),h=new Map;for(let m of f)h.set(m.id,m.status==="error"?{type:"error",jobId:m.id,message:m.error??"The agent run failed.",threadId:m.threadId,annotationIds:m.annotationIds}:{type:"done",jobId:m.id,success:!0,threadId:m.threadId,annotationIds:m.annotationIds});ut(m=>{let x={...m.lastErrorByJob};for(let A of f)A?.status==="error"&&A.error&&(x[A.id]=A.error);let w=Tu(m.activeJobIds,l,s).reconciledActiveIds,z={};for(let A of l)A.threadId&&(z[A.id]=A.threadId);return{...m,isConnected:!0,status:w.length>0?"streaming":p.length>0||m.status==="disconnected"?"idle":m.status,activeJobId:w.length>0?w[w.length-1]:null,activeJobIds:w,activeJobThreads:z,lastErrorByJob:x,workspaceGeneration:a?.workspaceGeneration}});let g=[...new Set([...Array.from(c),...p])];g.length>0&&Au(e,g,t,h).catch(()=>{})})}),o.addEventListener("job_parked",a=>{if(i())return;let l=JSON.parse(a.data);Pn(l.jobId,l)||qi("job_parked",l,l.jobId)}),o.addEventListener("thread_changed",a=>{if(i())return;let l=JSON.parse(a.data);ut(s=>({...s,events:[...s.events,{type:"thread_changed",data:l,timestamp:Date.now()}]}))}),o.addEventListener("job_started",a=>{if(i())return;let l=JSON.parse(a.data),s=l.jobId;if(Pn(s,l))return;let d=l.threadId;ut(c=>({...c,status:"streaming",activeJobId:s,activeJobIds:c.activeJobIds.includes(s)?c.activeJobIds:[...c.activeJobIds,s],activeJobThreads:d?{...c.activeJobThreads,[s]:d}:c.activeJobThreads,jobResponses:{...c.jobResponses,[s]:c.jobResponses[s]??""},jobThinking:{...c.jobThinking,[s]:c.jobThinking[s]??""},currentResponse:c.jobResponses[s]??"",currentThinking:c.jobThinking[s]??"",lastResponseText:null,lastThreadId:null,events:[...c.events,{type:"job_started",data:l,timestamp:Date.now()}]}))}),o.addEventListener("delta",a=>{if(i())return;let l=JSON.parse(a.data),s=l.jobId;if(Pn(s,l))return;let d=l.text||"";ut(c=>({...c,jobResponses:s?{...c.jobResponses,[s]:(c.jobResponses[s]||"")+d}:c.jobResponses,currentResponse:!s||s===c.activeJobId?c.currentResponse+d:c.currentResponse,events:[...c.events,{type:"delta",data:l,timestamp:Date.now()}]}))}),o.addEventListener("thinking",a=>{if(i())return;let l=JSON.parse(a.data),s=l.jobId;if(Pn(s,l))return;let d=l.text||"";ut(c=>({...c,jobThinking:s?{...c.jobThinking,[s]:(c.jobThinking[s]||"")+d}:c.jobThinking,currentThinking:!s||s===c.activeJobId?c.currentThinking+d:c.currentThinking,events:[...c.events,{type:"thinking",data:l,timestamp:Date.now()}]}))}),o.addEventListener("status",a=>{if(i())return;let l=JSON.parse(a.data),s=l.jobId;Pn(s,l)||ut(d=>({...d,events:[...d.events,{type:"status",data:l,timestamp:Date.now()}]}))}),o.addEventListener("orientation",a=>{if(i())return;let l=JSON.parse(a.data),s=l.jobId;Pn(s,l)||ut(d=>({...d,events:[...d.events,{type:"orientation",data:l,timestamp:Date.now()}]}))}),o.addEventListener("approval",a=>{if(i())return;let l=JSON.parse(a.data);Pn(l.jobId,l)||ut(s=>({...s,events:[...s.events,{type:"approval",data:l,timestamp:Date.now()}]}))}),o.addEventListener("imprint_used",a=>{if(i())return;let l=JSON.parse(a.data),s=l.jobId;Pn(s,l)||ut(d=>({...d,events:[...d.events,{type:"imprint_used",data:l,timestamp:Date.now()}]}))}),o.addEventListener("tool_use",a=>{if(i())return;let l=JSON.parse(a.data),s=l.jobId;Pn(s,l)||ut(d=>({...d,events:[...d.events,{type:"tool_use",data:l,timestamp:Date.now()}]}))});for(let a of["image_generation","image_ready"])o.addEventListener(a,l=>{if(i())return;let s=JSON.parse(l.data),d=s.jobId;Pn(d,s)||ut(c=>({...c,events:[...c.events,{type:a,data:s,timestamp:Date.now()}]}))});o.addEventListener("done",a=>{if(i())return;let l=JSON.parse(a.data),s=l.jobId;Pn(s,l)||(s&&delete $o[s],ut(d=>{let c=s?d.activeJobIds.filter(x=>x!==s):d.activeJobIds,f={...d.jobResponses},p={...d.jobThinking},h={...d.activeJobThreads},g=s?f[s]:void 0;s&&(delete f[s],delete p[s],delete h[s]);let m=s===d.activeJobId?c.length>0?c[c.length-1]:null:d.activeJobId;return{...d,activeJobIds:c,activeJobId:m,jobResponses:f,jobThinking:p,lastCompletedJobId:s??d.activeJobId,lastResponseText:l.responseText||g||d.currentResponse||null,lastThreadId:l.threadId??null,...s===d.activeJobId?{currentResponse:m&&f[m]||"",currentThinking:m&&p[m]||""}:{},events:[...d.events,{type:"done",data:l,timestamp:Date.now()}]}}))}),o.addEventListener("question",a=>{if(i())return;let l=JSON.parse(a.data),s=l.jobId;Pn(s,l)||ut(d=>({...d,pendingQuestions:[...d.pendingQuestions,{jobId:l.jobId,threadId:l.threadId,question:l.question,annotationIds:l.annotationIds,timestamp:Date.now()}],events:[...d.events,{type:"question",data:l,timestamp:Date.now()}]}))}),o.addEventListener("capabilities_changed",()=>{i()||ut(a=>({...a,capabilitiesVersion:a.capabilitiesVersion+1}))}),o.addEventListener("workspace_cleared",a=>{if(i())return;let l=JSON.parse(a.data);typeof l.workspaceGeneration!="number"||!Number.isInteger(l.workspaceGeneration)||l.workspaceGeneration<0||ut(s=>{for(let d of s.activeJobIds)Fs.add(d);return{...s,workspaceGeneration:l.workspaceGeneration,status:"idle",activeJobId:null,activeJobIds:[],activeJobThreads:{},jobResponses:{},jobThinking:{},currentResponse:"",currentThinking:"",events:[],lastCompletedJobId:null,lastResponseText:null,lastThreadId:null,lastErrorByJob:{},pendingQuestions:[],incrementalResolutions:[]}})}),o.addEventListener("queue_drained",()=>{if(i())return;let a=[...va().activeJobIds];if(a.length===0){ut(l=>({...l,status:l.status==="error"?"error":"idle",incrementalResolutions:[]}));return}Au(e,a,t).then(()=>{i()||ut(l=>({...l,status:l.activeJobIds.length>0?l.status:l.status==="error"?"error":"idle",incrementalResolutions:l.activeJobIds.length>0?l.incrementalResolutions:[]}))})}),o.addEventListener("error",a=>{if(!i()){if(o.readyState===EventSource.CLOSED){ut(s=>({...s,isConnected:!1,status:"disconnected"})),Dr&&(clearTimeout(Dr),Dr=null);let l=t;Dr=setTimeout(()=>{l===(Ze.connectionGeneration??0)&&ha(e).then(s=>{s&&l===(Ze.connectionGeneration??0)&&Ws(e)})},5e3)}else if(a instanceof MessageEvent){let l=JSON.parse(a.data),s=l.jobId??null;if(Pn(s??void 0,l))return;s&&delete $o[s];let d=l.message??"";ut(c=>{let f=s?c.activeJobIds.filter(h=>h!==s):c.activeJobIds,p=f.length>0?c.status:"error";return{...c,status:p,activeJobIds:f,lastCompletedJobId:s??c.activeJobId,lastErrorByJob:s&&d?{...c.lastErrorByJob,[s]:d}:c.lastErrorByJob,events:[...c.events,{type:"error",data:l,timestamp:Date.now()}]}})}}}),o.onerror=()=>{i()||o.readyState===EventSource.CLOSED&&ut(a=>({...a,isConnected:!1,status:"disconnected"}))}}function Bg(e="http://localhost:1111",t=!0,n){let r=wg(Jg,va,va);_(()=>{if(Mu(n),!t)return;let a=!1;return Ru(e,n).then(l=>{!l||a||ha(l).then(s=>{!a&&s&&(!n||s.projectId===n)&&Ws(l)})}),()=>{a=!0}},[e,t,n]);let o=B(()=>{ut(()=>({...va(),events:[],currentResponse:"",currentThinking:"",jobResponses:{},jobThinking:{},lastResponseText:null,lastThreadId:null,lastErrorByJob:{},incrementalResolutions:[]}))},[]),i=B(a=>{ut(l=>({...l,pendingQuestions:l.pendingQuestions.filter(s=>s.threadId!==a)}))},[]);return{...r,clearEvents:o,dismissQuestion:i}}var Lu="devtools-model-id:codex";function Yg(e,t,n){let[r,o]=$(()=>typeof window>"u"?"":localStorage.getItem(Lu)??""),i=e.findIndex(s=>s.id===r),a=i>=0?i:Math.max(0,e.findIndex(s=>s.id==="")),l=B(s=>{o(s),localStorage.setItem(Lu,s)},[]);return _(()=>{n&&t&&r&&i<0&&e.some(s=>s.id)&&l("")},[n,t,r,i,e,l]),{index:a,select:l}}function Ug(e,t,n){let r=e.flatMap(({requestedAt:a,resolvedAt:l})=>Number.isFinite(a)&&Number.isFinite(l)?[[Math.max(t,a),Math.min(n,l)]]:[]).sort((a,l)=>a[0]-l[0]),o=t,i=0;for(let[a,l]of r)i+=Math.max(0,l-Math.max(o,a)),o=Math.max(o,l);return i}function $u(e){let t=new Map,n=new Set;for(let r of e)if(r.type==="approval"){let o=r.data.approval;t.set(o.id,o)}else(r.type==="done"||r.type==="error")&&n.add(String(r.data.jobId));return new Set([...t.values()].filter(r=>r.status==="pending"&&!n.has(r.jobId)).map(r=>r.jobId))}function ju(e){let t=new MutationObserver(n=>{let r=n.filter(o=>document.body.contains(o.target)||o.target===document.documentElement&&[...o.addedNodes,...o.removedNodes].some(i=>i instanceof Element&&i.tagName==="BODY"));r.length&&e(r)});return t.observe(document.documentElement,{childList:!0,subtree:!0}),t}function Kg(e,t,n,r=8*1024*1024){let o=d=>JSON.stringify({id:e,clientId:t,result:d}),i=d=>new TextEncoder().encode(d).length<=r,a=o(n);if(i(a))return a;let l=Array.isArray(n.images)?n.images:[],s=[l.filter(d=>d.kind==="annotated-viewport"),l.filter(d=>d.kind!=="annotated-viewport"),[]];for(let d of s){let c=o({...n,images:d,visualEvidence:{status:"partial",reason:"response_size_limit",omitted:l.filter(f=>!d.includes(f)).map(f=>f.kind)}});if(i(c))return c}return o({status:"context_too_large",targetKey:n.targetKey,images:[],warning:"Context exceeds the response limit even without images."})}function Xg(e,t,n){let r=q(n);r.current=n;let[o,i]=$([]),a=p=>i(p?[p]:[]),l=q(null),s=q(null),d=q(null),c=B(()=>d.current?.(),[]),f=B(p=>{l.current=p,s.current?.(p)},[]);return _(()=>{if(!e)return;let p={clientId:crypto.randomUUID(),sequence:0,page:location.origin+location.pathname,title:document.title,active:!0,windowFocused:document.hasFocus(),lastInteractionAt:0,blurredAt:0,hover:null,pinned:null,history:[]},h=null,g=new WeakMap,m=new Map,x,w=!1,z=!1,A,S,H=0,R=()=>{let O=location.origin+location.pathname;p.page!==O&&(p.page=O,p.title=document.title,p.hover=null,p.pinned=null,p.history=[],p.recent=null,p.selected=null,m.clear(),h=null,p.lastInteractionAt=0),p.sequence++,A=JSON.stringify(p),!z&&(z=!0,(async()=>{for(;A;){let j=A;A=void 0;try{await Kt(`${t}/focus`,{method:"POST",headers:{"Content-Type":"application/json"},body:j,signal:AbortSignal.timeout(3e3)})}catch{}}z=!1})())},K=(O,j)=>{g.has(O)||g.set(O,crypto.randomUUID());let P=yn(O),L=vn(O),E=getComputedStyle(O),Z={...j?{subject:j}:{},key:g.get(O),capturedAt:Date.now(),selector:P.selector,tagName:P.tagName,text:P.textContent?.slice(0,200),component:P.reactComponent,source:P.reactSource,rect:{x:L.x,y:L.y,width:L.width,height:L.height},styles:Object.fromEntries(["color","background-color","font-size","font-family","display","padding","border-radius"].map(re=>[re,E.getPropertyValue(re)]))};if(m.set(Z.key,{element:O,target:Z}),m.size>32){let re=[...m.keys()].find(ee=>ee!==p.pinned?.key);re&&m.delete(re)}return Z},G=O=>{let j=O?.element??null,P=O?.selection==="selected",L=p.selected??p.hover;j===h&&!!p.selected===P&&L?.subject?.key===O?.subject?.key||(h=j,clearTimeout(x),x=setTimeout(()=>{if(w)return;let E=j?.isConnected&&!ya(j,"input, textarea, select, [contenteditable], [data-popmelt-private], [data-popmelt-canvas-block], [data-devtools]")?K(j,O?.subject):null;p.selected=P?E:null,p.hover=P?null:E,P&&(p.recent=null),p.hover&&(p.history=[...p.history,p.hover].slice(-8)),p.windowFocused&&(p.recent=null),R()},j&&!P?120:0))};s.current=G,d.current=()=>{w||document.visibilityState!=="visible"||(p.lastInteractionAt=Date.now(),p.windowFocused=document.hasFocus(),!S&&(S=setTimeout(()=>{S=void 0,H=Date.now(),R()},Math.max(0,250-(Date.now()-H)))))},G(l.current);let N=()=>{p.windowFocused=document.hasFocus(),p.blurredAt=p.windowFocused?0:Date.now(),p.recent=p.windowFocused?null:p.hover,R()},V=()=>{p.active=document.visibilityState==="visible",p.active?G(l.current):(clearTimeout(x),p.hover=null,p.history=[],p.recent=null,p.selected=null,m.clear(),h=null,p.lastInteractionAt=0),R()};document.addEventListener("visibilitychange",V),window.addEventListener("focus",N),window.addEventListener("blur",N);let Y=setInterval(R,1e4),I=!1,X,te=new Set,D=setInterval(async()=>{if(!(w||I||document.visibilityState!=="visible")){I=!0;try{let O=await Kt(`${t}/focus/requests?clientId=${p.clientId}`,{signal:AbortSignal.timeout(3e3)});if(!O.ok)return;let j=await O.json();for(let P of j){if(te.has(P.id)||w||P.expiresAt<Date.now())continue;te.add(P.id),te.size>64&&te.delete(te.values().next().value);let L=m.get(P.targetKey),E={status:"target_unavailable"};if(P.tasteProposal){let{tasteProposalSession:Z}=await import("./taste-proposal-session-XU4N7RUV.mjs");if(w||P.expiresAt<Date.now())continue;let re=document.activeElement;for(;re?.shadowRoot?.activeElement;)re=re.shadowRoot.activeElement;E=re?.matches("input, textarea, select, [contenteditable]")&&ya(re,"[data-taste-editor]")&&P.tasteProposal.action!=="inspect"?{status:"busy",reason:"The human is editing a proposal field. Retry after editing ends."}:Z.command(P.tasteProposal)}else if(P.workspace){let{collectWorkspaceSnapshot:Z,workspaceAttentionTarget:re}=await import("./workspace-snapshot-EJQHHDQ4.mjs");if(w||P.expiresAt<Date.now())continue;E=Z(r.current.state,P.workspace);let ee=P.workspace.entryId?[P.workspace.entryId]:"entries"in E?E.entries.map(U=>U.id):[],ie=[...new Set(ee.map(U=>re(r.current.state,U,r.current.registry)).filter(U=>!!U))];i(ie);for(let U of ie)U instanceof HTMLElement&&U.hasAttribute("data-popmelt-thread-header")&&cg(U,U);if(ie.length&&(clearTimeout(X),X=setTimeout(()=>a(null),Math.max(0,P.expiresAt-Date.now())),await new Promise(U=>requestAnimationFrame(()=>setTimeout(U,0))),w))break;E.attention=P.workspace.entryId?ie.length?"shown":re(r.current.state,P.workspace.entryId,r.current.registry,!0)?"target_offscreen":"target_missing_hidden_or_ambiguous":{shown:ie.length,requested:ee.length}}else if(L?.element.isConnected&&p.page===location.origin+location.pathname&&!ya(L.element,"[data-popmelt-private], input, textarea, select, [contenteditable]"))try{let Z=P.attentionOnly?null:(await import("./focus-inspection-2FPCQIN2.mjs")).inspectFocusElement;if(w||P.expiresAt<Date.now()||!L.element.isConnected||p.page!==location.origin+location.pathname)continue;if(a(L.element),clearTimeout(X),X=setTimeout(()=>a(null),Math.max(0,P.expiresAt-Date.now())),await new Promise(re=>requestAnimationFrame(()=>setTimeout(re,0))),w)break;E=Z?await Z(L.element,L.target,P.screenshot,r.current):{status:"ok",attention:"shown"}}catch{E={status:"capture_failed"}}if(w||document.visibilityState!=="visible")break;(await Kt(`${t}/focus/response`,{method:"POST",headers:{"Content-Type":"application/json"},body:Kg(P.id,p.clientId,E),signal:AbortSignal.timeout(3e3)})).ok||await Kt(`${t}/focus/response`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:P.id,clientId:p.clientId,result:{status:"response_rejected"}}),signal:AbortSignal.timeout(3e3)}),clearTimeout(X),a(null)}}catch{}finally{clearTimeout(X),w||a(null),I=!1}}},1e3);return V(),()=>{w=!0,clearTimeout(x),clearTimeout(S),clearInterval(Y),clearInterval(D),clearTimeout(X),a(null),document.removeEventListener("visibilitychange",V),window.removeEventListener("focus",N),window.removeEventListener("blur",N),s.current=null,d.current=null,m.clear(),p.hover=null,p.selected=null,p.history=[],p.active=!1,R()}},[e,t]),{onCanvasFocusChange:f,onCanvasActivity:c,inspectingElement:e?o[0]??null:null,inspectingElements:e?o:[]}}function Vg(e,t,n,r){let[o,i]=$(null),[a,l]=$(null),s=q(0),d=q(Promise.resolve(!0)),c=B(()=>{s.current=Date.now()},[]),f=B(h=>{s.current=Date.now(),i(h)},[]),p=B(h=>l(g=>JSON.stringify(g)===JSON.stringify(h)?g:h),[]);return _(()=>{if(!e||!r)return;let h=o?.element;if(h&&ya(h,"[data-private], [data-sensitive]"))return;let g=a?.targets??(h?[{selector:o?.subject?Dc(o.subject):Ro(h),...o?.subject?{subject:o.subject}:{}}]:[]);if(!g.length)return;let m={pathname:window.location.pathname,ownerId:t,color:n,targets:g,activity:"looking",...a?{threadId:a.threadId}:{}},x=!1,w=null,z=!1,A=(N,V,Y)=>{let I=d.current.then(()=>N!=="finish"&&(x||w!==V)?!1:e(N,V,Y));return d.current=I.catch(()=>!1),I},S=()=>{let N=w;w=null,N&&A("finish",N).catch(()=>{})},H=async()=>{if(x||z)return;if(!(document.visibilityState!=="hidden"&&document.hasFocus()&&m.pathname===window.location.pathname&&(a||h?.isConnected&&(o?.selection==="selected"||Date.now()-s.current<5e3)))){S();return}z=!0;let N=w?"renew":"start",V=w??crypto.randomUUID();w=V;try{!await A(N,V,m)&&w===V&&(w=null),x&&S()}catch{w===V&&(w=null)}finally{z=!1}},R=setTimeout(H,120),K=setInterval(H,1e3),G=()=>S();return window.addEventListener("blur",G),window.addEventListener("focus",H),document.addEventListener("visibilitychange",H),()=>{x=!0,clearTimeout(R),clearInterval(K),S(),window.removeEventListener("blur",G),window.removeEventListener("focus",H),document.removeEventListener("visibilitychange",H)}},[e,r,t,n,o,a]),{onFocus:f,onActivity:c,onThread:p}}var ml="data-popmelt-preview-target",Pu="script,iframe,object,embed,link,meta,base,style,template";function Qg({root:e,targets:t,revision:n,width:r,height:o,cleanClone:i}){let a=e.cloneNode(!0),l=[e,...e.querySelectorAll("*")],s=[a,...a.querySelectorAll("*")],d=new Set,c=new Map;for(let[p,h]of t){if(!p||!l.includes(h))throw new Error("Target is outside the preview root");if(c.has(h))throw new Error("Target has multiple identities");c.set(h,p)}l.forEach((p,h)=>{let g=s[h];(p.shadowRoot||p.matches("canvas,video"))&&d.add("Shadow DOM, canvas and video state are not mirrored");for(let x of[...g.attributes])(/^on/i.test(x.name)||["src","srcset","href","xlink:href","action","formaction","autofocus","contenteditable",ml].includes(x.name))&&g.removeAttribute(x.name);p instanceof HTMLInputElement&&(p.type==="password"||p.type==="file"?g.removeAttribute("value"):g.setAttribute("value",p.value),g.toggleAttribute("checked",p.checked)),p instanceof HTMLTextAreaElement&&(g.textContent=p.value),p instanceof HTMLOptionElement&&g.toggleAttribute("selected",p.selected);let m=c.get(p);m&&g.setAttribute(ml,m),i?.(p,g)});for(let p of a.querySelectorAll(Pu))p.remove();for(let p of a.querySelectorAll("[data-devtools], [data-popmelt-peer-surface], [data-popmelt-root], popmelt-root"))p.remove();if(a.matches(Pu))throw new Error("Unsupported preview root");let f="";for(let p of e.ownerDocument.styleSheets)if(!(p.ownerNode instanceof Element&&p.ownerNode.closest("[data-devtools], [data-popmelt-top-layer-host]")))try{f+=[...p.cssRules].map(h=>h.cssText).join(`
|
|
5
5
|
`)+`
|
|
6
|
-
`}catch{d.add("An inaccessible stylesheet was omitted")}return d.add("Static snapshot: no scripts, external assets, event handlers or application runtime"),{revision:n,html:e.tagName==="BODY"?a.innerHTML:a.outerHTML,...e.tagName==="BODY"?{bodyAttributes:Object.fromEntries([...a.attributes].map(p=>[p.name,p.value]))}:{},css:f,width:r,height:o,warnings:[...d]}}function zu(e,t){let n=[...e.querySelectorAll(`[${ml}]`)].filter(r=>r.getAttribute(ml)===t);return n.length===1?n[0]:null}var Gg=class{constructor(e){this.generation=0,this.cancelPending=null,this.current=null,this.disposed=!1,this.frame=e.ownerDocument.createElement("iframe"),this.frame.setAttribute("sandbox","allow-same-origin"),this.frame.title="Peer plane preview",this.frame.style.cssText="border:0;display:block;pointer-events:none;",this.frame.tabIndex=-1,e.append(this.frame)}async render(e,t,n){if(this.disposed)throw new Error("Preview surface was disposed");this.cancelPending?.();let r=++this.generation;this.current=null,this.frame.width=String(e.width),this.frame.height=String(e.height);let o=this.frame.ownerDocument.implementation.createHTMLDocument("Peer preview"),i=o.createElement("meta");i.httpEquiv="Content-Security-Policy",i.content="default-src 'none'; style-src 'unsafe-inline'; form-action 'none'; base-uri 'none'; script-src 'none'",o.head.prepend(i);let a=o.createElement("style");a.textContent=e.css.replace(/<\/style/gi,"<\\/style"),o.head.append(a),o.body.innerHTML=e.html;for(let[s,d]of Object.entries(e.bodyAttributes??{}))o.body.setAttribute(s,d);let l=o.createElement("style");return l.textContent="*,*::before,*::after{animation:none!important;transition:none!important;caret-color:transparent!important}",o.head.append(l),o.documentElement.dataset.previewGeneration=String(r),new Promise(s=>{let d=h=>{clearTimeout(p),this.frame.removeEventListener("load",f),this.cancelPending===c&&(this.cancelPending=null),s(h)},c=()=>d(!1),f=()=>{if(r!==this.generation||this.frame.contentDocument?.documentElement.dataset.previewGeneration!==String(r))return;let h=this.frame.contentDocument;n?.(h);for(let g of t.artifacts)g.kind==="style"&&zu(h,g.targetKey)?.style.setProperty(g.property,g.value,"important");this.current={baseline:e,plane:{...t}},d(!0)},p=setTimeout(c,5e3);this.cancelPending=c,this.frame.addEventListener("load",f),queueMicrotask(()=>{!this.disposed&&r===this.generation&&(this.frame.srcdoc="<!doctype html>"+o.documentElement.outerHTML)})})}inspect(e,t){let n=this.current,r=this.frame.contentDocument;if(!n||!r)return null;let o=zu(r,e);if(!o)return null;let i=this.frame.contentWindow.getComputedStyle(o),a=o.getBoundingClientRect();return{planeId:n.plane.id,planeRevision:n.plane.revision,sourceRevision:n.baseline.revision,targetKey:e,styles:Object.fromEntries(t.map(l=>[l,i.getPropertyValue(l)])),rect:{x:a.x,y:a.y,width:a.width,height:a.height}}}dispose(){this.disposed=!0,++this.generation,this.cancelPending?.(),this.current=null,this.frame.remove()}};function Zg(e,t){return{id:e,ownerId:t,revision:0,artifacts:[],undo:[],redo:[],attention:null}}function Js(e){return tl(e).flatMap(t=>t==="color"?[...jc]:[t])}function ey(e,t){if(e===void 0)return{families:Di.map(n=>({family:n,label:ws(n)}))};if(!Di.includes(e))throw new Error("Unknown omnidial family");if(!t)return{family:e,subproperties:Js(e)};if(!Js(e).includes(t))throw new Error("Unknown omnidial subproperty");return{family:e,subproperty:t,...e==="transform"&&t==="translate"?{composedToken:"translate-x-<xStep>-y-<yStep>",axisSteps:pi(e,t)}:{},tokens:pi(e,t).map(n=>({token:el(e,n,t),value:zi(e,n,t)}))}}function ty(e,t){if(t!==void 0&&!Di.includes(t))throw new Error("Unknown omnidial family");let n=/^translate-x-(-?\d+)-y-(-?\d+)$/.exec(e);if(n&&(!t||t==="transform")){let o=pi("transform","translate"),i=o.find(l=>String(l)===n[1]),a=o.find(l=>String(l)===n[2]);if(i!==void 0&&a!==void 0)return{family:"transform",subproperty:"translate",step:i,axisSteps:{x:i,y:a}}}let r=[];for(let o of t?[t]:Di)for(let i of Js(o))for(let a of pi(o,i))el(o,a,i)===e&&r.push({family:o,subproperty:i,step:a});if(r.length>1)throw new Error("Ambiguous omnidial token; include its family (for example stack or grid)");if(!r.length)throw new Error("Unknown omnidial token; discover available tokens or use an explicit custom property/value");return r[0]}function Du(e,t,n,r){let o=e.ownerDocument.defaultView.getComputedStyle(e),i=vc(t,r),a=zi(t,n,r),l=xc(t),s=wc(t,r,n),d=t==="border"&&!ui(t,r)&&typeof n=="number"&&n>0?Sc(r):null,c={family:t,subproperty:$c(t,r),step:n},f=[{property:i,original:o.getPropertyValue(i).trim()||"0px",modified:a,token:el(t,n,r),sticker:c}];l&&f.unshift({property:"display",original:o.getPropertyValue("display").trim()||"block",modified:l,token:l,sticker:c});for(let p of s)f.push({property:p.property,original:o.getPropertyValue(p.property).trim(),modified:p.value,token:p.token,sticker:c});if(d){let p=o.getPropertyValue(d).trim();(!p||p==="none")&&f.push({property:d,original:p||"none",modified:"solid",token:el(t,n,r),sticker:c})}return{alreadyApplied:bc(t,n,r,p=>o.getPropertyValue(p)),changes:f}}function Ou(e,t,n){let r=e.ownerDocument.defaultView.getComputedStyle(e),o="translate",i=`${Number(t)*4}px ${Number(n)*4}px`,a={family:"transform",subproperty:"translate",step:t,axisSteps:{x:t,y:n}};return{alreadyApplied:r.getPropertyValue(o).trim()===i,changes:[{property:o,original:r.getPropertyValue(o).trim()||"none",modified:i,token:`translate-x-${t}-y-${n}`,sticker:a}]}}function ny(e,t){for(let n of t.changes)ot(e,n.property,n.modified)}var ry=new Set(["text","transform","opacity"]),oy=new Set(["padding","margin","border","radius","color"]);function iy(e){return e instanceof SVGSVGElement&&!(e.parentElement instanceof SVGElement)}function ay(e){return e!=="text-align"}function gl(e,t,n){return jr(e)?e instanceof HTMLElement?!0:t==="text"&&!ay(n)?!1:ry.has(t)||iy(e)&&oy.has(t):!1}function ba(e){return[...new Set([...e?.annotations.flatMap(t=>t.linkedSelector?[t.linkedSelector]:[])??[],...e?.styleModifications.map(t=>t.selector)??[],...e?.textModifications.map(t=>t.selector)??[]])]}function ly(e,t){return Object.keys(t).filter(n=>e[n]!==void 0&&e[n]!==t[n])}function Hu(e,t){return Object.keys(e).length===Object.keys(t).length&&Object.keys(t).every(n=>e[n]===t[n])}function qs(e,t,n,r){let o={...e};for(let i of r){if(n[i]===void 0){delete o[i];continue}o[i]=t[i]??e[i]??n[i]}return o}function sy(e){let t=e.ownerDocument.defaultView.getComputedStyle(e),n=Array.from(t).filter(i=>!i.startsWith("--")).map(i=>`${i}:${t.getPropertyValue(i)}`).join(";"),r=e.outerHTML+n,o=2166136261;for(let i=0;i<r.length;i++)o=Math.imul(o^r.charCodeAt(i),16777619);return`target-v2:${(o>>>0).toString(16)}`}var sr=()=>location.origin+location.pathname;function yl(e){let t=document.querySelectorAll(e),n=t[0];if(t.length!==1||!(n instanceof HTMLElement||n instanceof SVGElement)||n.closest("[data-devtools], [data-popmelt-peer-surface], [data-popmelt-canvas-block]"))throw new Error("Target must resolve to exactly one app element");if(n.matches("input,textarea,select,[contenteditable],script,style")||n.closest("[data-private], [data-sensitive]"))throw new Error("Private/editable controls are outside the peer preview");return n}var Nu=class{constructor(){this.sources={},this.changed=[],this.container=document.createElement("div"),this.container.dataset.popmeltPeerSurface="",this.container.setAttribute("aria-hidden","true"),this.container.style.cssText="position:fixed;left:-100000px;top:0;pointer-events:none;",document.body.append(this.container),this.surface=new Gg(this.container)}async render(e,t,n,r=!1){if(t.domModifications.length||t.spacingTokenChanges.length)throw new Error("Independent previews do not yet support staged structure or spacing-token edits; your draft is preserved");let o=e.state??al,i=new Set([...n?[n]:[],...ba(o)]),a=new Map;for(let c of i)a.set(c,yl(c));let l=new Map;for(let c of t.textModifications){let f=document.querySelector(c.selector);f&&l.set(f,[...l.get(f)??[],c])}let s=Qg({root:document.body,targets:a,revision:sr(),width:innerWidth,height:innerHeight,cleanClone:(c,f)=>{if(!r){dg(c,f);for(let p of l.get(c)??[]){let h=f;for(let g of p.textNodePath)h=h?.childNodes[g];h?.nodeType===Node.TEXT_NODE&&(h.nodeValue=p.original)}}}}),d=Zg(e.identity.id,e.identity.id);if(d.revision=e.revision,r||(d.artifacts=o.styleModifications.flatMap(c=>c.changes.map(f=>({kind:"style",id:c.selector+f.property,targetKey:c.selector,property:f.property,value:f.modified})))),!await this.surface.render(s,d,c=>{this.sources=Object.fromEntries([...i].map(f=>[f,sy(c.querySelector(`[data-popmelt-preview-target="${CSS.escape(f)}"]`))])),this.changed=ly(e.basis??{},this.sources)}))throw new Error("Preview superseded or unavailable");return this.surface.frame.contentWindow?.scrollTo(scrollX,scrollY),s.warnings}async execute(e,t){let{action:n}=e,r=structuredClone(e.peer);if(n.type==="prepare-send"){if(!ba(r.state).length)throw new Error("There are no peer changes to send");if(await this.render(r,t),!e.observedSources||Object.keys(this.sources).some(s=>e.observedSources[s]!==this.sources[s]))throw new Error("Source changed since the last preview. Take another look, then send again.");return this.changed.length&&r.revision++,r.basis={...this.sources},delete r.pendingRevision,{peer:r,sources:this.sources}}if(n.type==="check-source"){let s={...r,state:{...structuredClone(al),annotations:Object.keys(n.sources).map((d,c)=>({id:`source-${c}`,type:"text",text:"",points:[],strokeWidth:1,color:r.color,timestamp:0,linkedSelector:d}))}};if(await this.render(s,t),!Hu(n.sources,this.sources))throw new Error("Source changed since Send. Preview the current source and send again.");return{peer:r,evidence:{status:"source-current"}}}if(n.type==="tokens")return{peer:r,evidence:ey(n.family,n.subproperty)};let o=r.state??{...structuredClone(al),isAnnotating:!0,activeColor:r.color},i=o,a,l=s=>{i=Vm(i,s)};if(n.type==="send")throw new Error("Send requires the implementation bridge");if(n.type==="rebase")await this.render(r,t),r.basis={...this.sources},r.revision++,delete r.pendingRevision,a={status:"rebased",note:"Draft preserved against current source; Send requires a new approval if in Suggest."};else if(n.type==="undo"||n.type==="redo"){l({type:n.type==="undo"?"UNDO":"REDO"}),await this.render({...r,state:i},t);let s=[...new Set([...ba(o),...ba(i)])].filter(d=>{let c=f=>JSON.stringify([f.annotations.filter(p=>p.linkedSelector===d),f.styleModifications.filter(p=>p.selector===d)]);return c(o)!==c(i)});r.basis=qs(r.basis??{},e.observedSources??{},this.sources,s)}else if(n.type==="attention"&&!n.selector)r.attention=null;else if(n.type==="clear"){let s=n.kind!=="style"&&o.annotations.some(c=>c.linkedSelector===n.selector),d=n.kind!=="comment"&&o.styleModifications.some(c=>c.selector===n.selector);if(!s&&!d)return{peer:r,evidence:{status:"nothing-to-clear"}};i={...o,annotations:n.kind==="style"?o.annotations:o.annotations.filter(c=>c.linkedSelector!==n.selector),styleModifications:n.kind==="comment"?o.styleModifications:o.styleModifications.filter(c=>c.selector!==n.selector),undoStack:[...o.undoStack,{annotations:o.annotations,styleModifications:o.styleModifications,textModifications:o.textModifications,domModifications:o.domModifications,spacingTokenChanges:o.spacingTokenChanges,spacingTokenMods:o.spacingTokenMods}],redoStack:[]},await this.render({...r,state:i},t),r.basis=qs(r.basis??{},e.observedSources??{},this.sources,[n.selector])}else if("selector"in n&&n.selector){let s=yl(n.selector),d=yn(s),c=n.selector;if(n.type==="inspect"){let f=await this.render(r,t,c,n.plane==="host");a={...this.surface.inspect(c,n.properties??[]),element:d,warnings:f,view:n.plane??"own",url:sr(),changedSourceTargets:n.plane==="host"?void 0:this.changed}}else if(n.type==="style")if("token"in n){let f=ty(n.token,n.family);if(!gl(s,f.family,f.subproperty))throw new Error("This omnidial token does not support the target");await this.render(r,t,c);let p=this.surface.frame.contentDocument?.querySelector(c);if(!p)throw new Error("Could not inspect original style");let h=f.axisSteps?Ou(p,f.axisSteps.x,f.axisSteps.y):Du(p,f.family,f.step,f.subproperty);h.alreadyApplied||l({type:"MODIFY_STYLES_BATCH",payload:{selector:c,element:{...d,selector:c},changes:h.changes}}),a={token:n.token,selection:f,alreadyApplied:h.alreadyApplied}}else{if(!CSS.supports(n.property,n.value))throw new Error("Unsupported CSS property/value");await this.render(r,t,c);let f=this.surface.inspect(c,[n.property])?.styles[n.property];if(f===void 0)throw new Error("Could not inspect original style");l({type:"MODIFY_STYLES_BATCH",payload:{selector:c,element:{...d,selector:c},changes:[{property:n.property,original:f,modified:n.value}]}})}else if(n.type==="comment"){await this.render(r,t,c);let f=s.getBoundingClientRect();l({type:"ADD_TEXT",payload:{id:`peer-note-${e.id}`,point:{x:f.x+scrollX,y:f.y+scrollY-26},text:n.text,linkedSelector:c,elements:[{...d,selector:c}]}})}r.attention=null,(n.type==="comment"||n.type==="style")&&(r.basis=qs(r.basis??{},e.observedSources??{},this.sources,[c]))}if(i!==o){if(i.annotations.length+i.styleModifications.length>100)throw new Error("Peer draft is full; submit or undo before adding more");i={...i,undoStack:i.undoStack.slice(-50),redoStack:i.redoStack.slice(-50)},r.state=i,r.revision++,r.url=sr(),delete r.pendingRevision}return{peer:r,evidence:a,...["inspect","style","comment","clear","undo","redo","rebase"].includes(n.type)&&!(n.type==="inspect"&&n.plane==="host")?{sources:this.sources}:{}}}dispose(){this.surface.dispose(),this.container.remove()}};async function dy(e,t,n){let r=!0,o,i=new Set,a=async c=>{let f=new AbortController;i.add(f);let p=setTimeout(()=>f.abort(),1500);try{return await e(c,f.signal)}catch{return!1}finally{clearTimeout(p),i.delete(f)}},l=()=>{r=!1,clearTimeout(o);for(let c of i)c.abort()},s=()=>{l(),a("finish")},d=async()=>{if(!r)return;let c=await a("renew");r&&c&&(o=setTimeout(()=>{d()},1e3))};n.addEventListener("abort",s,{once:!0});try{if(n.aborted)throw new Error("Canvas disconnected before action");let c=await a("start");if(n.aborted)throw new Error("Canvas disconnected before action");return r&&c&&(o=setTimeout(()=>{d()},1e3)),await t()}finally{l(),n.removeEventListener("abort",s),await a("finish")}}function cy(e){let t=`popmelt-peer-seen:${e}`,[n,r]=$({key:"",revisions:{}});return _(()=>{let o={};try{let i=JSON.parse(localStorage.getItem(t)??"{}");i&&typeof i=="object"&&!Array.isArray(i)&&(o=Object.fromEntries(Object.entries(i).filter(([,a])=>Number.isSafeInteger(a)&&a>=0)))}catch{}r({key:t,revisions:o})},[t]),{markSeen:B((o,i)=>{r(a=>{if(a.key!==t||(a.revisions[o]??0)>=i)return a;let l={key:t,revisions:{...a.revisions,[o]:i}};try{localStorage.setItem(t,JSON.stringify(l.revisions))}catch{}return l})},[t]),isUnseen:(o,i)=>n.key===t&&i>(n.revisions[o]??0)}}function uy(e,t){let n,r=l=>(l instanceof Element?l:l.parentElement)?.closest("[data-devtools], [data-popmelt-peer-surface], [data-popmelt-root], popmelt-root"),o=()=>{n===void 0&&(n=setTimeout(()=>{n=void 0,t()},400))},i=new MutationObserver(l=>{document.hidden||!e.length||l.some(s=>{if(r(s.target)||s.type==="childList"&&[...s.addedNodes,...s.removedNodes].every(c=>r(c)))return!1;let d=s.target instanceof Element?s.target:s.target.parentElement;return d?.closest("style,head")?!0:e.some(c=>{let f=document.querySelector(c);return!f||f.contains(s.target)||d?.contains(f)})})&&o()});i.observe(document.documentElement,{subtree:!0,attributes:!0,childList:!0,characterData:!0}),window.addEventListener("resize",o);let a=()=>{document.hidden||o()};return document.addEventListener("visibilitychange",a),()=>{i.disconnect(),clearTimeout(n),window.removeEventListener("resize",o),document.removeEventListener("visibilitychange",a)}}function _u(e){if(!e)return 0;let t=Uh(e.annotations);return lc({annotations:e.annotations.filter(n=>!n.captured&&!t.has(n)),styleModifications:e.styleModifications.filter(n=>!n.captured),textModifications:e.textModifications.filter(n=>!n.captured)}).count}function py(e,t,n,r,o){let[i,a]=$([]),[l,s]=$([]),d=kh(l,e&&r.isAnnotating),c=Eh(e&&r.isAnnotating),{viewedId:f,isPeeking:p}=c,[h,g]=$(),[m,x]=$(),[w,z]=$([]),A=q(null),{markSeen:S,isUnseen:H}=cy(n),R=Se(()=>new Map(i.map(U=>[U.identity.id,_u(U.state)])),[i]),{annotations:K,styleModifications:G,textModifications:N}=r,V=Se(()=>_u({annotations:K,styleModifications:G,textModifications:N}),[K,G,N]),[Y,I]=$(null),X=q(null),te=q({human:r,settings:o});te.current={human:r,settings:o};let D=q({clientId:crypto.randomUUID()}),O=q(async()=>{throw new Error("Canvas is disconnected")}),j=e?i.find(U=>U.identity.id===f):void 0,P=i.find(U=>U.identity.id===c.selectedId)?.state,L=Se(()=>Th(P),[P]);_(()=>{if(!e||!n)return;D.current.token||(D.current={clientId:crypto.randomUUID()});let U=!1,me,le=-1,oe=-1,Me=new AbortController,Te="",Ce=!1,J=new Nu,ve=new Map,$e=ge=>{U||typeof ge.presenceVersion!="number"||ge.presenceVersion<=oe||!Array.isArray(ge.presence)||(oe=ge.presenceVersion,s(ge.presence))},De=async(ge,pe={},Fe=AbortSignal.any([Me.signal,AbortSignal.timeout(5e4)]))=>{let Be=D.current.token,st=await Kt(`${t}/peers/${ge}`,{method:"POST",headers:{"Content-Type":"application/json","X-Popmelt-Project-Id":n},body:JSON.stringify({...D.current,...pe}),signal:Fe}),Ve=await st.json();if(ge!=="host"&&Be!==D.current.token)throw new Error("Canvas session changed during request");if(!st.ok||Ve.error)throw new Error(Ve.error??`Peer request failed (${st.status})`);return Ve};O.current=De;async function et(ge){if(ge.url&&ge.url!==sr())throw new Error("Canvas navigated before the operation could run");if(ge.action.type!=="send"){let Je=im(ge.action);return Je?(yl(Je.selector),dy(async(pt,kn)=>{let Xt=await De("activity",{id:ge.id,phase:pt},kn);return $e(Xt),Xt.accepted===!0},()=>J.execute(ge,te.current.human),Me.signal)):J.execute(ge,te.current.human)}if(!ge.grant)throw new Error("No host-approved Send grant");let pe=structuredClone(ge.peer);if(pe.url!==sr())throw new Error("Return to the proposal\u2019s page before sending");let Fe=pe.state;if(!Fe||!Fe.annotations.length&&!Fe.styleModifications.length)throw new Error("There are no peer changes to send");await J.render(pe,te.current.human);let Be={...J.sources};if(!ge.observedSources||Object.keys(Be).some(Je=>ge.observedSources[Je]!==Be[Je]))throw new Error("Source changed since the last preview. Take another look, then send again.");let st=J.surface.frame.contentDocument;if(!st)throw new Error("Peer preview is unavailable");let[Ve]=await Oi(st.body,null,[],{viewportOnly:!0});if(!Ve)throw new Error("Could not capture the peer preview");if(await J.render(pe,te.current.human),!Hu(Be,J.sources))throw new Error("Source changed while preparing Send. Take another look, then send again.");await De("source",{grant:ge.grant,sources:Be});let ke=Nc(Fe.annotations,Fe.styleModifications,void 0,void 0,Fe.textModifications),{provider:Ue,model:mt,agentSettings:_t}=te.current.settings,yt=await Yc(Ve,JSON.stringify(ke),t,pe.color,Ue,mt,void 0,void 0,_t,void 0,void 0,void 0,ge.grant);return pe.state={...structuredClone(al),isAnnotating:!0,activeColor:pe.color},pe.revision++,pe.basis={},delete pe.pendingRevision,pe.lastJob={jobId:yt.jobId,threadId:yt.threadId},{peer:pe,evidence:{status:"submitted",...yt}}}async function rt(){try{if(!D.current.token||Te!==sr()){let pe=await De("host",{url:sr()});if(U)return;D.current.token=String(pe.token),Te=sr()}let ge=await De("poll",{version:le,presenceVersion:oe});if(U)return;$e(ge),ge.peers&&(a(ge.peers),Ce=ge.peers.length>0,le=Number(ge.version));for(let pe of ge.requests){let Fe=ve.get(pe.id);if(!Fe){try{Fe=await et(pe)}catch(Be){Fe={error:Be instanceof Error?Be.message:String(Be)}}ve.set(pe.id,Fe),ve.size>100&&ve.delete(ve.keys().next().value)}await De("response",{id:pe.id,result:Fe})}}catch(ge){!U&&ge instanceof Error&&ge.message.includes("Host capability")&&(D.current.token=void 0,le=-1,oe=-1,U||s([]))}finally{U||(me=setTimeout(()=>{rt()},document.hidden||!Ce?2e3:600))}}return rt(),()=>{U=!0,Me.abort(),clearTimeout(me),J.dispose(),a([]),s([]),O.current=async()=>{throw new Error("Canvas is disconnected")}}},[e,t,n]),_(()=>{if(x(void 0),z([]),A.current=null,!j||!r.isAnnotating||!X.current){I(null);return}let U=new Nu;X.current.append(U.container),I(null),U.container.removeAttribute("aria-hidden"),U.container.style.cssText="position:absolute;inset:0;pointer-events:none;";let me=!1;j.url&&j.url!==sr()&&x("This draft belongs to another page. Return to it to preview.");let le=!1,oe=!1,Me=()=>{if(!me){if(le){oe=!0;return}le=!0,U.render(j,te.current.human).then(()=>{me||(x(void 0),z(U.changed),A.current={id:j.identity.id,revision:j.revision,values:{...U.sources}},I(U.surface.frame),S(j.identity.id,j.revision))}).catch(ve=>{me||(A.current=null,I(null),x(ve.message))}).finally(()=>{le=!1,oe&&(oe=!1,Me())})}},Te=!j.url||j.url===sr();Te&&Me();let Ce=Te?uy(ba(j.state),Me):()=>{},J=()=>U.surface.frame.contentWindow?.scrollTo(scrollX,scrollY);return window.addEventListener("scroll",J,{passive:!0}),()=>{me=!0,Ce(),window.removeEventListener("scroll",J),U.dispose()}},[j,r.isAnnotating,S]);let E=async U=>{try{return await U(),g(void 0),!0}catch(me){return g(me instanceof Error?me.message:String(me)),!1}},Z=e&&i.length?{peers:[{identity:{id:"host",name:"You",kind:"human",relationship:"host"},permission:"direct",color:r.activeColor,stagedCount:V},...i.map(U=>({...U,stagedCount:R.get(U.identity.id)??0,unseenActivity:H(U.identity.id,U.revision)}))],viewedPeerId:f,selectedPeerId:c.selectedId,onPeek:c.peek,onPeekEnd:c.leave,onPreview:U=>{c.select(U),g(void 0)},onPermissionChange:(U,me)=>E(()=>O.current("permission",{peerId:U,permission:me}))}:null,re=j?.pendingRevision!==void 0?()=>E(()=>{let U=A.current;if(!U||U.id!==f||U.revision!==j.revision)throw new Error("Wait for this draft\u2019s preview before sending.");return O.current("approve",{peerId:f,revision:j.pendingRevision,sources:U.values})}):void 0,ee=!!(j&&r.isAnnotating),ie=e&&(h??(ee?m:void 0));return _(()=>{if(!ee)return;let U=me=>{me.composedPath().some(le=>le instanceof Element&&le.hasAttribute("data-devtools"))||(me.metaKey||me.ctrlKey)&&me.key==="Enter"||(me.key.length===1||["Backspace","Delete","Enter"].includes(me.key))&&(me.preventDefault(),me.stopPropagation())};return window.addEventListener("keydown",U,!0),()=>window.removeEventListener("keydown",U,!0)},[ee]),{toolbar:Z,selectedId:c.selectedId,threadAnnotationNumbers:L,activePreview:ee,isPeeking:p,viewed:j,approve:re,overlay:C(it,{children:[ee&&u("div",{ref:X,"data-devtools":"peer-preview","data-peer-revision":j?.revision,"data-pending-revision":j?.pendingRevision,"data-popmelt-peer-surface":!0,style:{position:"fixed",inset:0,zIndex:1e4,background:"#111",pointerEvents:"auto"}}),d.map(({presence:U,engaged:me})=>{if(p)return null;let le=i.find(Me=>Me.identity.id===U.peerId);if(!le||U.clientId!==D.current.clientId||U.url!==sr()||ee&&le.identity.id!==f)return null;let oe=null;try{oe=ee?Y?.contentDocument?.querySelector(U.selector)??null:yl(U.selector)}catch{}return u(Uc,{element:oe,engaged:me,label:`${le.identity.name} is looking at this element`},`${le.identity.id}:${U.operationId}`)}),!p&&ee&&j&&Y?.contentDocument&&u(Ch,{peer:j,targetDocument:Y.contentDocument,onApprove:re?()=>{re()}:void 0}),ee&&j&&f===c.selectedId&&u("div",{"data-devtools":"peer-plane-border","data-plane-owner":j.identity.id,"aria-hidden":"true",style:{position:"fixed",inset:0,border:`2px solid ${j.color}`,boxSizing:"border-box",pointerEvents:"none",zIndex:10002}}),ee&&j&&f===c.selectedId&&u(Ah,{name:j.identity.name,isOwnPlane:j.identity.id==="host",color:j.color,changed:w.length>0}),ie&&u("div",{"data-devtools":"peer-error",role:"status",style:{position:"fixed",bottom:100,right:24,maxWidth:360,padding:12,background:"#222",color:"#ddd",borderRadius:12,fontFamily:Ts,fontSize:12,lineHeight:1.4,zIndex:10002},children:ie})]})}}function fy(e,t,n,r,o,i,a){let[l,s]=$(),d=q({navigation:e,selectedId:t});_(()=>{if(!e||!n||l?.navigation===e)return;let c=e.read(),f=o.current,p=!1;if(!c.threadId||c.selectedId!==t){s({navigation:e});return}return i(c.threadId).then(h=>{if(!p){if(f===o.current&&e.read()===c)if(h>=200&&h<300)a(c.threadId);else if(h===403||h===404||h===410)e.rememberThread(t,null);else{s({navigation:e,unresolvedRevision:f});return}s({navigation:e})}}).catch(()=>{p||s({navigation:e,unresolvedRevision:f})}),()=>{p=!0}},[e,t,n,l,o,i,a]),_(()=>{let c=d.current.navigation!==e||d.current.selectedId!==t;d.current={navigation:e,selectedId:t},!(!e||l?.navigation!==e||c)&&(l.unresolvedRevision===o.current&&!r||e.rememberThread(t,r))},[e,t,r,l,o])}var hy=yu(()=>import("./ParticipantRuntime-JUOBT3CY.mjs")),my=yu(()=>import("./PreviewRuntime-JAZLAGQE.mjs"));function gy({children:e,projectId:t,adapters:n,multiplayer:r=!1}){let[o,i]=$(!1);if(_(()=>{i(!0)},[]),!o)return null;let a=window.__POPMELT_PARTICIPANTS__;if(!r)return Oc()?null:a?u("p",{role:"status","data-devtools":"participant-disabled",children:"Multiplayer is disabled. Enable the multiplayer option in your Popmelt integration to use this participant page."}):e;if(a)try{fm(a,t)}catch(l){return u("p",{role:"alert","data-devtools":"participant-error",children:l.message})}return Oc()?a?u(vu,{fallback:null,children:u(my,{config:a,adapters:n})}):null:a?u(vu,{fallback:null,children:u(hy,{config:a,children:xg(e,{bridgeUrl:a.url,projectId:a.projectId})},a.projectId)}):e}function yy(e,t,n,r){let o=q(e);o.current=e;let[i,a]=$([]),l=q(null),[s,d]=$(null),[c,f]=$(null),p=i.filter(x=>x.scope===e),h=x=>a(w=>w.filter(z=>z.id!==x)),g=(x,w)=>{let z=Symbol(x);f(null);let A=t(x).then(()=>!0,()=>(o.current===e&&(w(),f({scope:e,message:"Could not dismiss thread. Please try again."})),h(z),!1));a(S=>[...S.filter(H=>H.scope===e),{id:z,threadId:x,rollback:w,saved:A,scope:e,undoHead:r}])},m=async()=>{let x=p.at(-1);if(!(!x||l.current===e)){l.current=e,d(e),f(null);try{if(!await x.saved||o.current!==e||(await n(x.threadId),o.current!==e))return;x.rollback(),h(x.id)}catch{o.current===e&&f({scope:e,message:"Could not restore thread. Try Undo again."})}finally{l.current===e&&(l.current=null,d(null))}}};return{dismiss:g,undo:m,tryUndo:()=>{let x=p.at(-1);return!x||x.undoHead!==r?!1:(m(),!0)},busy:s===e,count:p.length,error:c?.scope===e?c.message:null}}function vy({enabled:e,active:t,configuration:n=!0,adapters:r}){let[o,i]=$(!1),[a,l]=$(null),s=Se(()=>hm(),[]),{recognition:d,selector:c,root:f,observe:p,store:h,imageHasher:g,onError:m}=typeof n=="object"?n:{},x=r.some(S=>S.surfaceKind==="image"||S.id==="see:image"),w=e&&n!==!1&&!x,z=t||o,A=z?d:void 0;return _(()=>{e?t&&i(!0):i(!1)},[e,t]),_(()=>{if(!w)return;let S=mm({recognition:A?{cacheKey:A.cacheKey,configurationKey:A.configurationKey,detect:H=>A.detect(H),reconcile:(...H)=>A.reconcile(...H)}:void 0,hydrateOnly:!z,selector:c,root:f,observe:p,store:h??s,imageHasher:g,onError:m});return l(S),()=>{l(null),S.destroy()}},[w,A,z,c,f,p,h,s,g,m]),Se(()=>w&&a?[a,...r]:r,[w,a,r])}function by({enabled:e,configuration:t=!0,adapters:n}){let[r,o]=$(null),i=Se(()=>gm(),[]),{segmentation:a,tracking:l,selector:s,root:d,observe:c,store:f,onError:p}=typeof t=="object"?t:{},h=n.some(m=>m.surfaceKind==="video"||m.id==="see:video"),g=e&&t!==!1&&!h;return _(()=>{if(!g)return;let m=ym({tracking:l,segmentation:a,selector:s,root:d,observe:c,store:f??i,onError:p});return o(m),()=>{o(null),m.destroy()}},[g,l,a,s,d,c,f,i,p]),Se(()=>g&&r?[r,...n]:n,[g,r,n])}function Fu(e,t){return JSON.stringify([e,t.adapter,t.key])}async function Wu(e,t,n,r){for(let o of t){if(!o.target)continue;let i=Fu(n,o.target);if(!r.has(i))try{r.set(i,await e.captureFeedback(o.target))}catch{r.set(i,null)}}}function xy(e,t,n){let r=new Map;for(let o of e.annotations){let i=t.find(l=>l.id===o.id),a=(i?.groupId?t.filter(l=>l.groupId===i.groupId):t.filter(l=>l.id===o.id)).flatMap(l=>n.get(l.id)??[]);a.length&&r.set(o.id,a)}return r}function wy(e,t,n,r){for(let o of e.annotations){if(!o.target)continue;let i=n.get(Fu(o.pathname||r,o.target));if(!i){o.subjectFeedback={warning:"Live object unavailable; the following object context is the draft-time snapshot, not a refreshed detection. No object crop is attached."};continue}if(o.elements=[i.elementInfo],o.subjectFeedback=i.warning?{warning:i.warning}:void 0,i.crop){let a=t.get(o.id)??[];o.subjectFeedback={...o.subjectFeedback,cropImageIndex:a.length},t.set(o.id,[...a,i.crop])}}}function Sy(e){let t=e?.requestItems?.flatMap(r=>r.kind==="annotation"&&r.text.trim()?[r.text.trim()]:[]);if(t?.length)return t.join("; ");let n=e?.requestItems?.flatMap(r=>r.kind==="changes"?[`${r.elementLabel} [${r.changes.join(", ")}]`]:[]);return n?.length?n.join("; "):e?.requestText?.trim()||void 0}function Iy(e,t){if(!e?.frames?.length)return[];let n=new Map;for(let r of e.steps){let o=r.visuals?.afterFrameId;o&&!n.has(o)&&n.set(o,r.action?.label?`After ${r.action.label}`:"Resulting state")}return e.frames.flatMap((r,o)=>{let i=t[r.imageIndex];return i?[{id:r.id,imageIndex:r.imageIndex,label:o===0?"Initial state":n.get(r.id)??"State",url:i}]:[]})}function Ju(e){let t=e.instruction?.trim();return t?e.attachments?.some(n=>n.name?.trim()===t)?null:t:null}function ky(e,t){let n=e?.tagName?.toLowerCase(),r=e?.id?`#${e.id}`:"",o=e?.className?`.${e.className.trim().split(/\s+/).slice(0,2).join(".")}`:"",i=n?`${n}${r}${o}`:t;return e?.reactComponent?`<${e.reactComponent}> ${i}`:i}function Ey(e){let t=e.elements?.[0]?.reactComponent||e.elements?.[0]?.tagName||e.linkedSelector,n=e.type&&e.type!=="annotation"?`${e.type} annotation`:"Annotation";return t?`${n} on ${t}`:n}function Ty(e){let t=e.annotations.map(o=>{let i=o.interactionEpisode?.steps.length??0;return{kind:"annotation",annotationId:o.id,pathname:o.pathname,text:Ju(o)??Ey(o),...i>0?{interactionEpisodeStepCount:i}:{}}}),n=new Map,r=o=>{let i=`${o.pathname??""}:${o.durableSelector??o.selector}`,a=n.get(i);if(a){a.changes.push(o.text),o.annotationNumber!==void 0&&(a.annotationNumber===void 0||o.annotationNumber<a.annotationNumber)&&(a.annotationNumber=o.annotationNumber);return}let l={kind:"changes",elementKey:i,elementLabel:ky(o.element,o.selector),...o.annotationNumber!==void 0?{annotationNumber:o.annotationNumber}:{},pathname:o.pathname,changes:[o.text]};n.set(i,l),t.push(l)};for(let o of e.styleModifications??[])for(let i of o.changes)r({...o,text:`${i.property}: ${i.original||"unset"} \u2192 ${i.modified||"unset"}${i.token?` (${i.token})`:""}`});for(let o of e.textModifications??[])r({...o,text:`Text: ${o.original||"empty"} \u2192 ${o.modified||"empty"}`});for(let o of e.domModifications??[])r({...o,text:o.operation==="copy"?"Copied element":"Moved element"});return e.spacingTokenChanges?.length&&t.push({kind:"changes",elementKey:"spacing-tokens",elementLabel:"Spacing tokens",changes:e.spacingTokenChanges.map(o=>`${o.tokenName}: ${o.originalPx}px \u2192 ${o.newPx}px`)}),t}function Cy(e){let t=e.annotations.flatMap(r=>{let o=Ju(r);return o?[{instruction:o,pathname:r.pathname}]:[]});if(t.length===0)return;if(new Set(t.map(r=>r.pathname).filter(Boolean)).size<=1)return t.map(r=>r.instruction).join(`
|
|
6
|
+
`}catch{d.add("An inaccessible stylesheet was omitted")}return d.add("Static snapshot: no scripts, external assets, event handlers or application runtime"),{revision:n,html:e.tagName==="BODY"?a.innerHTML:a.outerHTML,...e.tagName==="BODY"?{bodyAttributes:Object.fromEntries([...a.attributes].map(p=>[p.name,p.value]))}:{},css:f,width:r,height:o,warnings:[...d]}}function zu(e,t){let n=[...e.querySelectorAll(`[${ml}]`)].filter(r=>r.getAttribute(ml)===t);return n.length===1?n[0]:null}var Gg=class{constructor(e){this.generation=0,this.cancelPending=null,this.current=null,this.disposed=!1,this.frame=e.ownerDocument.createElement("iframe"),this.frame.setAttribute("sandbox","allow-same-origin"),this.frame.title="Peer plane preview",this.frame.style.cssText="border:0;display:block;pointer-events:none;",this.frame.tabIndex=-1,e.append(this.frame)}async render(e,t,n){if(this.disposed)throw new Error("Preview surface was disposed");this.cancelPending?.();let r=++this.generation;this.current=null,this.frame.width=String(e.width),this.frame.height=String(e.height);let o=this.frame.ownerDocument.implementation.createHTMLDocument("Peer preview"),i=o.createElement("meta");i.httpEquiv="Content-Security-Policy",i.content="default-src 'none'; style-src 'unsafe-inline'; form-action 'none'; base-uri 'none'; script-src 'none'",o.head.prepend(i);let a=o.createElement("style");a.textContent=e.css.replace(/<\/style/gi,"<\\/style"),o.head.append(a),o.body.innerHTML=e.html;for(let[s,d]of Object.entries(e.bodyAttributes??{}))o.body.setAttribute(s,d);let l=o.createElement("style");return l.textContent="*,*::before,*::after{animation:none!important;transition:none!important;caret-color:transparent!important}",o.head.append(l),o.documentElement.dataset.previewGeneration=String(r),new Promise(s=>{let d=h=>{clearTimeout(p),this.frame.removeEventListener("load",f),this.cancelPending===c&&(this.cancelPending=null),s(h)},c=()=>d(!1),f=()=>{if(r!==this.generation||this.frame.contentDocument?.documentElement.dataset.previewGeneration!==String(r))return;let h=this.frame.contentDocument;n?.(h);for(let g of t.artifacts)g.kind==="style"&&zu(h,g.targetKey)?.style.setProperty(g.property,g.value,"important");this.current={baseline:e,plane:{...t}},d(!0)},p=setTimeout(c,5e3);this.cancelPending=c,this.frame.addEventListener("load",f),queueMicrotask(()=>{!this.disposed&&r===this.generation&&(this.frame.srcdoc="<!doctype html>"+o.documentElement.outerHTML)})})}inspect(e,t){let n=this.current,r=this.frame.contentDocument;if(!n||!r)return null;let o=zu(r,e);if(!o)return null;let i=this.frame.contentWindow.getComputedStyle(o),a=o.getBoundingClientRect();return{planeId:n.plane.id,planeRevision:n.plane.revision,sourceRevision:n.baseline.revision,targetKey:e,styles:Object.fromEntries(t.map(l=>[l,i.getPropertyValue(l)])),rect:{x:a.x,y:a.y,width:a.width,height:a.height}}}dispose(){this.disposed=!0,++this.generation,this.cancelPending?.(),this.current=null,this.frame.remove()}};function Zg(e,t){return{id:e,ownerId:t,revision:0,artifacts:[],undo:[],redo:[],attention:null}}function Js(e){return tl(e).flatMap(t=>t==="color"?[...jc]:[t])}function ey(e,t){if(e===void 0)return{families:Di.map(n=>({family:n,label:ws(n)}))};if(!Di.includes(e))throw new Error("Unknown omnidial family");if(!t)return{family:e,subproperties:Js(e)};if(!Js(e).includes(t))throw new Error("Unknown omnidial subproperty");return{family:e,subproperty:t,...e==="transform"&&t==="translate"?{composedToken:"translate-x-<xStep>-y-<yStep>",axisSteps:pi(e,t)}:{},tokens:pi(e,t).map(n=>({token:el(e,n,t),value:zi(e,n,t)}))}}function ty(e,t){if(t!==void 0&&!Di.includes(t))throw new Error("Unknown omnidial family");let n=/^translate-x-(-?\d+)-y-(-?\d+)$/.exec(e);if(n&&(!t||t==="transform")){let o=pi("transform","translate"),i=o.find(l=>String(l)===n[1]),a=o.find(l=>String(l)===n[2]);if(i!==void 0&&a!==void 0)return{family:"transform",subproperty:"translate",step:i,axisSteps:{x:i,y:a}}}let r=[];for(let o of t?[t]:Di)for(let i of Js(o))for(let a of pi(o,i))el(o,a,i)===e&&r.push({family:o,subproperty:i,step:a});if(r.length>1)throw new Error("Ambiguous omnidial token; include its family (for example stack or grid)");if(!r.length)throw new Error("Unknown omnidial token; discover available tokens or use an explicit custom property/value");return r[0]}function Du(e,t,n,r){let o=e.ownerDocument.defaultView.getComputedStyle(e),i=vc(t,r),a=zi(t,n,r),l=xc(t),s=wc(t,r,n),d=t==="border"&&!ui(t,r)&&typeof n=="number"&&n>0?Sc(r):null,c={family:t,subproperty:$c(t,r),step:n},f=[{property:i,original:o.getPropertyValue(i).trim()||"0px",modified:a,token:el(t,n,r),sticker:c}];l&&f.unshift({property:"display",original:o.getPropertyValue("display").trim()||"block",modified:l,token:l,sticker:c});for(let p of s)f.push({property:p.property,original:o.getPropertyValue(p.property).trim(),modified:p.value,token:p.token,sticker:c});if(d){let p=o.getPropertyValue(d).trim();(!p||p==="none")&&f.push({property:d,original:p||"none",modified:"solid",token:el(t,n,r),sticker:c})}return{alreadyApplied:bc(t,n,r,p=>o.getPropertyValue(p)),changes:f}}function Ou(e,t,n){let r=e.ownerDocument.defaultView.getComputedStyle(e),o="translate",i=`${Number(t)*4}px ${Number(n)*4}px`,a={family:"transform",subproperty:"translate",step:t,axisSteps:{x:t,y:n}};return{alreadyApplied:r.getPropertyValue(o).trim()===i,changes:[{property:o,original:r.getPropertyValue(o).trim()||"none",modified:i,token:`translate-x-${t}-y-${n}`,sticker:a}]}}function ny(e,t){for(let n of t.changes)ot(e,n.property,n.modified)}var ry=new Set(["text","transform","opacity"]),oy=new Set(["padding","margin","border","radius","color"]);function iy(e){return e instanceof SVGSVGElement&&!(e.parentElement instanceof SVGElement)}function ay(e){return e!=="text-align"}function gl(e,t,n){return jr(e)?e instanceof HTMLElement?!0:t==="text"&&!ay(n)?!1:ry.has(t)||iy(e)&&oy.has(t):!1}function ba(e){return[...new Set([...e?.annotations.flatMap(t=>t.linkedSelector?[t.linkedSelector]:[])??[],...e?.styleModifications.map(t=>t.selector)??[],...e?.textModifications.map(t=>t.selector)??[]])]}function ly(e,t){return Object.keys(t).filter(n=>e[n]!==void 0&&e[n]!==t[n])}function Hu(e,t){return Object.keys(e).length===Object.keys(t).length&&Object.keys(t).every(n=>e[n]===t[n])}function qs(e,t,n,r){let o={...e};for(let i of r){if(n[i]===void 0){delete o[i];continue}o[i]=t[i]??e[i]??n[i]}return o}function sy(e){let t=e.ownerDocument.defaultView.getComputedStyle(e),n=Array.from(t).filter(i=>!i.startsWith("--")).map(i=>`${i}:${t.getPropertyValue(i)}`).join(";"),r=e.outerHTML+n,o=2166136261;for(let i=0;i<r.length;i++)o=Math.imul(o^r.charCodeAt(i),16777619);return`target-v2:${(o>>>0).toString(16)}`}var sr=()=>location.origin+location.pathname;function yl(e){let t=document.querySelectorAll(e),n=t[0];if(t.length!==1||!(n instanceof HTMLElement||n instanceof SVGElement)||n.closest("[data-devtools], [data-popmelt-peer-surface], [data-popmelt-canvas-block]"))throw new Error("Target must resolve to exactly one app element");if(n.matches("input,textarea,select,[contenteditable],script,style")||n.closest("[data-private], [data-sensitive]"))throw new Error("Private/editable controls are outside the peer preview");return n}var Nu=class{constructor(){this.sources={},this.changed=[],this.container=document.createElement("div"),this.container.dataset.popmeltPeerSurface="",this.container.setAttribute("aria-hidden","true"),this.container.style.cssText="position:fixed;left:-100000px;top:0;pointer-events:none;",document.body.append(this.container),this.surface=new Gg(this.container)}async render(e,t,n,r=!1){if(t.domModifications.length||t.spacingTokenChanges.length)throw new Error("Independent previews do not yet support staged structure or spacing-token edits; your draft is preserved");let o=e.state??al,i=new Set([...n?[n]:[],...ba(o)]),a=new Map;for(let c of i)a.set(c,yl(c));let l=new Map;for(let c of t.textModifications){let f=document.querySelector(c.selector);f&&l.set(f,[...l.get(f)??[],c])}let s=Qg({root:document.body,targets:a,revision:sr(),width:innerWidth,height:innerHeight,cleanClone:(c,f)=>{if(!r){dg(c,f);for(let p of l.get(c)??[]){let h=f;for(let g of p.textNodePath)h=h?.childNodes[g];h?.nodeType===Node.TEXT_NODE&&(h.nodeValue=p.original)}}}}),d=Zg(e.identity.id,e.identity.id);if(d.revision=e.revision,r||(d.artifacts=o.styleModifications.flatMap(c=>c.changes.map(f=>({kind:"style",id:c.selector+f.property,targetKey:c.selector,property:f.property,value:f.modified})))),!await this.surface.render(s,d,c=>{this.sources=Object.fromEntries([...i].map(f=>[f,sy(c.querySelector(`[data-popmelt-preview-target="${CSS.escape(f)}"]`))])),this.changed=ly(e.basis??{},this.sources)}))throw new Error("Preview superseded or unavailable");return this.surface.frame.contentWindow?.scrollTo(scrollX,scrollY),s.warnings}async execute(e,t){let{action:n}=e,r=structuredClone(e.peer);if(n.type==="prepare-send"){if(!ba(r.state).length)throw new Error("There are no peer changes to send");if(await this.render(r,t),!e.observedSources||Object.keys(this.sources).some(s=>e.observedSources[s]!==this.sources[s]))throw new Error("Source changed since the last preview. Take another look, then send again.");return this.changed.length&&r.revision++,r.basis={...this.sources},delete r.pendingRevision,{peer:r,sources:this.sources}}if(n.type==="check-source"){let s={...r,state:{...structuredClone(al),annotations:Object.keys(n.sources).map((d,c)=>({id:`source-${c}`,type:"text",text:"",points:[],strokeWidth:1,color:r.color,timestamp:0,linkedSelector:d}))}};if(await this.render(s,t),!Hu(n.sources,this.sources))throw new Error("Source changed since Send. Preview the current source and send again.");return{peer:r,evidence:{status:"source-current"}}}if(n.type==="tokens")return{peer:r,evidence:ey(n.family,n.subproperty)};let o=r.state??{...structuredClone(al),isAnnotating:!0,activeColor:r.color},i=o,a,l=s=>{i=Vm(i,s)};if(n.type==="send")throw new Error("Send requires the implementation bridge");if(n.type==="rebase")await this.render(r,t),r.basis={...this.sources},r.revision++,delete r.pendingRevision,a={status:"rebased",note:"Draft preserved against current source; Send requires a new approval if in Suggest."};else if(n.type==="undo"||n.type==="redo"){l({type:n.type==="undo"?"UNDO":"REDO"}),await this.render({...r,state:i},t);let s=[...new Set([...ba(o),...ba(i)])].filter(d=>{let c=f=>JSON.stringify([f.annotations.filter(p=>p.linkedSelector===d),f.styleModifications.filter(p=>p.selector===d)]);return c(o)!==c(i)});r.basis=qs(r.basis??{},e.observedSources??{},this.sources,s)}else if(n.type==="attention"&&!n.selector)r.attention=null;else if(n.type==="clear"){let s=n.kind!=="style"&&o.annotations.some(c=>c.linkedSelector===n.selector),d=n.kind!=="comment"&&o.styleModifications.some(c=>c.selector===n.selector);if(!s&&!d)return{peer:r,evidence:{status:"nothing-to-clear"}};i={...o,annotations:n.kind==="style"?o.annotations:o.annotations.filter(c=>c.linkedSelector!==n.selector),styleModifications:n.kind==="comment"?o.styleModifications:o.styleModifications.filter(c=>c.selector!==n.selector),undoStack:[...o.undoStack,{annotations:o.annotations,styleModifications:o.styleModifications,textModifications:o.textModifications,domModifications:o.domModifications,spacingTokenChanges:o.spacingTokenChanges,spacingTokenMods:o.spacingTokenMods}],redoStack:[]},await this.render({...r,state:i},t),r.basis=qs(r.basis??{},e.observedSources??{},this.sources,[n.selector])}else if("selector"in n&&n.selector){let s=yl(n.selector),d=yn(s),c=n.selector;if(n.type==="inspect"){let f=await this.render(r,t,c,n.plane==="host");a={...this.surface.inspect(c,n.properties??[]),element:d,warnings:f,view:n.plane??"own",url:sr(),changedSourceTargets:n.plane==="host"?void 0:this.changed}}else if(n.type==="style")if("token"in n){let f=ty(n.token,n.family);if(!gl(s,f.family,f.subproperty))throw new Error("This omnidial token does not support the target");await this.render(r,t,c);let p=this.surface.frame.contentDocument?.querySelector(c);if(!p)throw new Error("Could not inspect original style");let h=f.axisSteps?Ou(p,f.axisSteps.x,f.axisSteps.y):Du(p,f.family,f.step,f.subproperty);h.alreadyApplied||l({type:"MODIFY_STYLES_BATCH",payload:{selector:c,element:{...d,selector:c},changes:h.changes}}),a={token:n.token,selection:f,alreadyApplied:h.alreadyApplied}}else{if(!CSS.supports(n.property,n.value))throw new Error("Unsupported CSS property/value");await this.render(r,t,c);let f=this.surface.inspect(c,[n.property])?.styles[n.property];if(f===void 0)throw new Error("Could not inspect original style");l({type:"MODIFY_STYLES_BATCH",payload:{selector:c,element:{...d,selector:c},changes:[{property:n.property,original:f,modified:n.value}]}})}else if(n.type==="comment"){await this.render(r,t,c);let f=s.getBoundingClientRect();l({type:"ADD_TEXT",payload:{id:`peer-note-${e.id}`,point:{x:f.x+scrollX,y:f.y+scrollY-26},text:n.text,linkedSelector:c,elements:[{...d,selector:c}]}})}r.attention=null,(n.type==="comment"||n.type==="style")&&(r.basis=qs(r.basis??{},e.observedSources??{},this.sources,[c]))}if(i!==o){if(i.annotations.length+i.styleModifications.length>100)throw new Error("Peer draft is full; submit or undo before adding more");i={...i,undoStack:i.undoStack.slice(-50),redoStack:i.redoStack.slice(-50)},r.state=i,r.revision++,r.url=sr(),delete r.pendingRevision}return{peer:r,evidence:a,...["inspect","style","comment","clear","undo","redo","rebase"].includes(n.type)&&!(n.type==="inspect"&&n.plane==="host")?{sources:this.sources}:{}}}dispose(){this.surface.dispose(),this.container.remove()}};async function dy(e,t,n){let r=!0,o,i=new Set,a=async c=>{let f=new AbortController;i.add(f);let p=setTimeout(()=>f.abort(),1500);try{return await e(c,f.signal)}catch{return!1}finally{clearTimeout(p),i.delete(f)}},l=()=>{r=!1,clearTimeout(o);for(let c of i)c.abort()},s=()=>{l(),a("finish")},d=async()=>{if(!r)return;let c=await a("renew");r&&c&&(o=setTimeout(()=>{d()},1e3))};n.addEventListener("abort",s,{once:!0});try{if(n.aborted)throw new Error("Canvas disconnected before action");let c=await a("start");if(n.aborted)throw new Error("Canvas disconnected before action");return r&&c&&(o=setTimeout(()=>{d()},1e3)),await t()}finally{l(),n.removeEventListener("abort",s),await a("finish")}}function cy(e){let t=`popmelt-peer-seen:${e}`,[n,r]=$({key:"",revisions:{}});return _(()=>{let o={};try{let i=JSON.parse(localStorage.getItem(t)??"{}");i&&typeof i=="object"&&!Array.isArray(i)&&(o=Object.fromEntries(Object.entries(i).filter(([,a])=>Number.isSafeInteger(a)&&a>=0)))}catch{}r({key:t,revisions:o})},[t]),{markSeen:B((o,i)=>{r(a=>{if(a.key!==t||(a.revisions[o]??0)>=i)return a;let l={key:t,revisions:{...a.revisions,[o]:i}};try{localStorage.setItem(t,JSON.stringify(l.revisions))}catch{}return l})},[t]),isUnseen:(o,i)=>n.key===t&&i>(n.revisions[o]??0)}}function uy(e,t){let n,r=l=>(l instanceof Element?l:l.parentElement)?.closest("[data-devtools], [data-popmelt-peer-surface], [data-popmelt-root], popmelt-root"),o=()=>{n===void 0&&(n=setTimeout(()=>{n=void 0,t()},400))},i=new MutationObserver(l=>{document.hidden||!e.length||l.some(s=>{if(r(s.target)||s.type==="childList"&&[...s.addedNodes,...s.removedNodes].every(c=>r(c)))return!1;let d=s.target instanceof Element?s.target:s.target.parentElement;return d?.closest("style,head")?!0:e.some(c=>{let f=document.querySelector(c);return!f||f.contains(s.target)||d?.contains(f)})})&&o()});i.observe(document.documentElement,{subtree:!0,attributes:!0,childList:!0,characterData:!0}),window.addEventListener("resize",o);let a=()=>{document.hidden||o()};return document.addEventListener("visibilitychange",a),()=>{i.disconnect(),clearTimeout(n),window.removeEventListener("resize",o),document.removeEventListener("visibilitychange",a)}}function _u(e){if(!e)return 0;let t=Uh(e.annotations);return lc({annotations:e.annotations.filter(n=>!n.captured&&!t.has(n)),styleModifications:e.styleModifications.filter(n=>!n.captured),textModifications:e.textModifications.filter(n=>!n.captured)}).count}function py(e,t,n,r,o){let[i,a]=$([]),[l,s]=$([]),d=kh(l,e&&r.isAnnotating),c=Eh(e&&r.isAnnotating),{viewedId:f,isPeeking:p}=c,[h,g]=$(),[m,x]=$(),[w,z]=$([]),A=q(null),{markSeen:S,isUnseen:H}=cy(n),R=Se(()=>new Map(i.map(U=>[U.identity.id,_u(U.state)])),[i]),{annotations:K,styleModifications:G,textModifications:N}=r,V=Se(()=>_u({annotations:K,styleModifications:G,textModifications:N}),[K,G,N]),[Y,I]=$(null),X=q(null),te=q({human:r,settings:o});te.current={human:r,settings:o};let D=q({clientId:crypto.randomUUID()}),O=q(async()=>{throw new Error("Canvas is disconnected")}),j=e?i.find(U=>U.identity.id===f):void 0,P=i.find(U=>U.identity.id===c.selectedId)?.state,L=Se(()=>Th(P),[P]);_(()=>{if(!e||!n)return;D.current.token||(D.current={clientId:crypto.randomUUID()});let U=!1,me,le=-1,oe=-1,Me=new AbortController,Te="",Ce=!1,J=new Nu,ve=new Map,$e=ge=>{U||typeof ge.presenceVersion!="number"||ge.presenceVersion<=oe||!Array.isArray(ge.presence)||(oe=ge.presenceVersion,s(ge.presence))},De=async(ge,pe={},Fe=AbortSignal.any([Me.signal,AbortSignal.timeout(5e4)]))=>{let Be=D.current.token,st=await Kt(`${t}/peers/${ge}`,{method:"POST",headers:{"Content-Type":"application/json","X-Popmelt-Project-Id":n},body:JSON.stringify({...D.current,...pe}),signal:Fe}),Ve=await st.json();if(ge!=="host"&&Be!==D.current.token)throw new Error("Canvas session changed during request");if(!st.ok||Ve.error)throw new Error(Ve.error??`Peer request failed (${st.status})`);return Ve};O.current=De;async function et(ge){if(ge.url&&ge.url!==sr())throw new Error("Canvas navigated before the operation could run");if(ge.action.type!=="send"){let Je=im(ge.action);return Je?(yl(Je.selector),dy(async(pt,kn)=>{let Xt=await De("activity",{id:ge.id,phase:pt},kn);return $e(Xt),Xt.accepted===!0},()=>J.execute(ge,te.current.human),Me.signal)):J.execute(ge,te.current.human)}if(!ge.grant)throw new Error("No host-approved Send grant");let pe=structuredClone(ge.peer);if(pe.url!==sr())throw new Error("Return to the proposal\u2019s page before sending");let Fe=pe.state;if(!Fe||!Fe.annotations.length&&!Fe.styleModifications.length)throw new Error("There are no peer changes to send");await J.render(pe,te.current.human);let Be={...J.sources};if(!ge.observedSources||Object.keys(Be).some(Je=>ge.observedSources[Je]!==Be[Je]))throw new Error("Source changed since the last preview. Take another look, then send again.");let st=J.surface.frame.contentDocument;if(!st)throw new Error("Peer preview is unavailable");let[Ve]=await Oi(st.body,null,[],{viewportOnly:!0});if(!Ve)throw new Error("Could not capture the peer preview");if(await J.render(pe,te.current.human),!Hu(Be,J.sources))throw new Error("Source changed while preparing Send. Take another look, then send again.");await De("source",{grant:ge.grant,sources:Be});let ke=Nc(Fe.annotations,Fe.styleModifications,void 0,void 0,Fe.textModifications),{provider:Ue,model:mt,agentSettings:_t}=te.current.settings,yt=await Yc(Ve,JSON.stringify(ke),t,pe.color,Ue,mt,void 0,void 0,_t,void 0,void 0,void 0,ge.grant);return pe.state={...structuredClone(al),isAnnotating:!0,activeColor:pe.color},pe.revision++,pe.basis={},delete pe.pendingRevision,pe.lastJob={jobId:yt.jobId,threadId:yt.threadId},{peer:pe,evidence:{status:"submitted",...yt}}}async function rt(){try{if(!D.current.token||Te!==sr()){let pe=await De("host",{url:sr()});if(U)return;D.current.token=String(pe.token),Te=sr()}let ge=await De("poll",{version:le,presenceVersion:oe});if(U)return;$e(ge),ge.peers&&(a(ge.peers),Ce=ge.peers.length>0,le=Number(ge.version));for(let pe of ge.requests){let Fe=ve.get(pe.id);if(!Fe){try{Fe=await et(pe)}catch(Be){Fe={error:Be instanceof Error?Be.message:String(Be)}}ve.set(pe.id,Fe),ve.size>100&&ve.delete(ve.keys().next().value)}await De("response",{id:pe.id,result:Fe})}}catch(ge){!U&&ge instanceof Error&&ge.message.includes("Host capability")&&(D.current.token=void 0,le=-1,oe=-1,U||s([]))}finally{U||(me=setTimeout(()=>{rt()},document.hidden||!Ce?2e3:600))}}return rt(),()=>{U=!0,Me.abort(),clearTimeout(me),J.dispose(),a([]),s([]),O.current=async()=>{throw new Error("Canvas is disconnected")}}},[e,t,n]),_(()=>{if(x(void 0),z([]),A.current=null,!j||!r.isAnnotating||!X.current){I(null);return}let U=new Nu;X.current.append(U.container),I(null),U.container.removeAttribute("aria-hidden"),U.container.style.cssText="position:absolute;inset:0;pointer-events:none;";let me=!1;j.url&&j.url!==sr()&&x("This draft belongs to another page. Return to it to preview.");let le=!1,oe=!1,Me=()=>{if(!me){if(le){oe=!0;return}le=!0,U.render(j,te.current.human).then(()=>{me||(x(void 0),z(U.changed),A.current={id:j.identity.id,revision:j.revision,values:{...U.sources}},I(U.surface.frame),S(j.identity.id,j.revision))}).catch(ve=>{me||(A.current=null,I(null),x(ve.message))}).finally(()=>{le=!1,oe&&(oe=!1,Me())})}},Te=!j.url||j.url===sr();Te&&Me();let Ce=Te?uy(ba(j.state),Me):()=>{},J=()=>U.surface.frame.contentWindow?.scrollTo(scrollX,scrollY);return window.addEventListener("scroll",J,{passive:!0}),()=>{me=!0,Ce(),window.removeEventListener("scroll",J),U.dispose()}},[j,r.isAnnotating,S]);let E=async U=>{try{return await U(),g(void 0),!0}catch(me){return g(me instanceof Error?me.message:String(me)),!1}},Z=e&&i.length?{peers:[{identity:{id:"host",name:"You",kind:"human",relationship:"host"},permission:"direct",color:r.activeColor,stagedCount:V},...i.map(U=>({...U,stagedCount:R.get(U.identity.id)??0,unseenActivity:H(U.identity.id,U.revision)}))],viewedPeerId:f,selectedPeerId:c.selectedId,onPeek:c.peek,onPeekEnd:c.leave,onPreview:U=>{c.select(U),g(void 0)},onPermissionChange:(U,me)=>E(()=>O.current("permission",{peerId:U,permission:me}))}:null,re=j?.pendingRevision!==void 0?()=>E(()=>{let U=A.current;if(!U||U.id!==f||U.revision!==j.revision)throw new Error("Wait for this draft\u2019s preview before sending.");return O.current("approve",{peerId:f,revision:j.pendingRevision,sources:U.values})}):void 0,ee=!!(j&&r.isAnnotating),ie=e&&(h??(ee?m:void 0));return _(()=>{if(!ee)return;let U=me=>{me.composedPath().some(le=>le instanceof Element&&le.hasAttribute("data-devtools"))||(me.metaKey||me.ctrlKey)&&me.key==="Enter"||(me.key.length===1||["Backspace","Delete","Enter"].includes(me.key))&&(me.preventDefault(),me.stopPropagation())};return window.addEventListener("keydown",U,!0),()=>window.removeEventListener("keydown",U,!0)},[ee]),{toolbar:Z,selectedId:c.selectedId,threadAnnotationNumbers:L,activePreview:ee,isPeeking:p,viewed:j,approve:re,overlay:C(it,{children:[ee&&u("div",{ref:X,"data-devtools":"peer-preview","data-peer-revision":j?.revision,"data-pending-revision":j?.pendingRevision,"data-popmelt-peer-surface":!0,style:{position:"fixed",inset:0,zIndex:1e4,background:"#111",pointerEvents:"auto"}}),d.map(({presence:U,engaged:me})=>{if(p)return null;let le=i.find(Me=>Me.identity.id===U.peerId);if(!le||U.clientId!==D.current.clientId||U.url!==sr()||ee&&le.identity.id!==f)return null;let oe=null;try{oe=ee?Y?.contentDocument?.querySelector(U.selector)??null:yl(U.selector)}catch{}return u(Uc,{element:oe,engaged:me,label:`${le.identity.name} is looking at this element`},`${le.identity.id}:${U.operationId}`)}),!p&&ee&&j&&Y?.contentDocument&&u(Ch,{peer:j,targetDocument:Y.contentDocument,onApprove:re?()=>{re()}:void 0}),ee&&j&&f===c.selectedId&&u("div",{"data-devtools":"peer-plane-border","data-plane-owner":j.identity.id,"aria-hidden":"true",style:{position:"fixed",inset:0,border:`2px solid ${j.color}`,boxSizing:"border-box",pointerEvents:"none",zIndex:10002}}),ee&&j&&f===c.selectedId&&u(Ah,{name:j.identity.name,isOwnPlane:j.identity.id==="host",color:j.color,changed:w.length>0}),ie&&u("div",{"data-devtools":"peer-error",role:"status",style:{position:"fixed",bottom:100,right:24,maxWidth:360,padding:12,background:"#222",color:"#ddd",borderRadius:12,fontFamily:Ts,fontSize:12,lineHeight:1.4,zIndex:10002},children:ie})]})}}function fy(e,t,n,r,o,i,a){let[l,s]=$(),d=q({navigation:e,selectedId:t});_(()=>{if(!e||!n||l?.navigation===e)return;let c=e.read(),f=o.current,p=!1;if(!c.threadId||c.selectedId!==t){s({navigation:e});return}return i(c.threadId).then(h=>{if(!p){if(f===o.current&&e.read()===c)if(h>=200&&h<300)a(c.threadId);else if(h===403||h===404||h===410)e.rememberThread(t,null);else{s({navigation:e,unresolvedRevision:f});return}s({navigation:e})}}).catch(()=>{p||s({navigation:e,unresolvedRevision:f})}),()=>{p=!0}},[e,t,n,l,o,i,a]),_(()=>{let c=d.current.navigation!==e||d.current.selectedId!==t;d.current={navigation:e,selectedId:t},!(!e||l?.navigation!==e||c)&&(l.unresolvedRevision===o.current&&!r||e.rememberThread(t,r))},[e,t,r,l,o])}var hy=yu(()=>import("./ParticipantRuntime-SYIF75DS.mjs")),my=yu(()=>import("./PreviewRuntime-JAZLAGQE.mjs"));function gy({children:e,projectId:t,adapters:n,multiplayer:r=!1}){let[o,i]=$(!1);if(_(()=>{i(!0)},[]),!o)return null;let a=window.__POPMELT_PARTICIPANTS__;if(!r)return Oc()?null:a?u("p",{role:"status","data-devtools":"participant-disabled",children:"Multiplayer is disabled. Enable the multiplayer option in your Popmelt integration to use this participant page."}):e;if(a)try{fm(a,t)}catch(l){return u("p",{role:"alert","data-devtools":"participant-error",children:l.message})}return Oc()?a?u(vu,{fallback:null,children:u(my,{config:a,adapters:n})}):null:a?u(vu,{fallback:null,children:u(hy,{config:a,children:xg(e,{bridgeUrl:a.url,projectId:a.projectId})},a.projectId)}):e}function yy(e,t,n,r){let o=q(e);o.current=e;let[i,a]=$([]),l=q(null),[s,d]=$(null),[c,f]=$(null),p=i.filter(x=>x.scope===e),h=x=>a(w=>w.filter(z=>z.id!==x)),g=(x,w)=>{let z=Symbol(x);f(null);let A=t(x).then(()=>!0,()=>(o.current===e&&(w(),f({scope:e,message:"Could not dismiss thread. Please try again."})),h(z),!1));a(S=>[...S.filter(H=>H.scope===e),{id:z,threadId:x,rollback:w,saved:A,scope:e,undoHead:r}])},m=async()=>{let x=p.at(-1);if(!(!x||l.current===e)){l.current=e,d(e),f(null);try{if(!await x.saved||o.current!==e||(await n(x.threadId),o.current!==e))return;x.rollback(),h(x.id)}catch{o.current===e&&f({scope:e,message:"Could not restore thread. Try Undo again."})}finally{l.current===e&&(l.current=null,d(null))}}};return{dismiss:g,undo:m,tryUndo:()=>{let x=p.at(-1);return!x||x.undoHead!==r?!1:(m(),!0)},busy:s===e,count:p.length,error:c?.scope===e?c.message:null}}function vy({enabled:e,active:t,configuration:n=!0,adapters:r}){let[o,i]=$(!1),[a,l]=$(null),s=Se(()=>hm(),[]),{recognition:d,selector:c,root:f,observe:p,store:h,imageHasher:g,onError:m}=typeof n=="object"?n:{},x=r.some(S=>S.surfaceKind==="image"||S.id==="see:image"),w=e&&n!==!1&&!x,z=t||o,A=z?d:void 0;return _(()=>{e?t&&i(!0):i(!1)},[e,t]),_(()=>{if(!w)return;let S=mm({recognition:A?{cacheKey:A.cacheKey,configurationKey:A.configurationKey,detect:H=>A.detect(H),reconcile:(...H)=>A.reconcile(...H)}:void 0,hydrateOnly:!z,selector:c,root:f,observe:p,store:h??s,imageHasher:g,onError:m});return l(S),()=>{l(null),S.destroy()}},[w,A,z,c,f,p,h,s,g,m]),Se(()=>w&&a?[a,...r]:r,[w,a,r])}function by({enabled:e,configuration:t=!0,adapters:n}){let[r,o]=$(null),i=Se(()=>gm(),[]),{segmentation:a,tracking:l,selector:s,root:d,observe:c,store:f,onError:p}=typeof t=="object"?t:{},h=n.some(m=>m.surfaceKind==="video"||m.id==="see:video"),g=e&&t!==!1&&!h;return _(()=>{if(!g)return;let m=ym({tracking:l,segmentation:a,selector:s,root:d,observe:c,store:f??i,onError:p});return o(m),()=>{o(null),m.destroy()}},[g,l,a,s,d,c,f,i,p]),Se(()=>g&&r?[r,...n]:n,[g,r,n])}function Fu(e,t){return JSON.stringify([e,t.adapter,t.key])}async function Wu(e,t,n,r){for(let o of t){if(!o.target)continue;let i=Fu(n,o.target);if(!r.has(i))try{r.set(i,await e.captureFeedback(o.target))}catch{r.set(i,null)}}}function xy(e,t,n){let r=new Map;for(let o of e.annotations){let i=t.find(l=>l.id===o.id),a=(i?.groupId?t.filter(l=>l.groupId===i.groupId):t.filter(l=>l.id===o.id)).flatMap(l=>n.get(l.id)??[]);a.length&&r.set(o.id,a)}return r}function wy(e,t,n,r){for(let o of e.annotations){if(!o.target)continue;let i=n.get(Fu(o.pathname||r,o.target));if(!i){o.subjectFeedback={warning:"Live object unavailable; the following object context is the draft-time snapshot, not a refreshed detection. No object crop is attached."};continue}if(o.elements=[i.elementInfo],o.subjectFeedback=i.warning?{warning:i.warning}:void 0,i.crop){let a=t.get(o.id)??[];o.subjectFeedback={...o.subjectFeedback,cropImageIndex:a.length},t.set(o.id,[...a,i.crop])}}}function Sy(e){let t=e?.requestItems?.flatMap(r=>r.kind==="annotation"&&r.text.trim()?[r.text.trim()]:[]);if(t?.length)return t.join("; ");let n=e?.requestItems?.flatMap(r=>r.kind==="changes"?[`${r.elementLabel} [${r.changes.join(", ")}]`]:[]);return n?.length?n.join("; "):e?.requestText?.trim()||void 0}function Iy(e,t){if(!e?.frames?.length)return[];let n=new Map;for(let r of e.steps){let o=r.visuals?.afterFrameId;o&&!n.has(o)&&n.set(o,r.action?.label?`After ${r.action.label}`:"Resulting state")}return e.frames.flatMap((r,o)=>{let i=t[r.imageIndex];return i?[{id:r.id,imageIndex:r.imageIndex,label:o===0?"Initial state":n.get(r.id)??"State",url:i}]:[]})}function Ju(e){let t=e.instruction?.trim();return t?e.attachments?.some(n=>n.name?.trim()===t)?null:t:null}function ky(e,t){let n=e?.tagName?.toLowerCase(),r=e?.id?`#${e.id}`:"",o=e?.className?`.${e.className.trim().split(/\s+/).slice(0,2).join(".")}`:"",i=n?`${n}${r}${o}`:t;return e?.reactComponent?`<${e.reactComponent}> ${i}`:i}function Ey(e){let t=e.elements?.[0]?.reactComponent||e.elements?.[0]?.tagName||e.linkedSelector,n=e.type&&e.type!=="annotation"?`${e.type} annotation`:"Annotation";return t?`${n} on ${t}`:n}function Ty(e){let t=e.annotations.map(o=>{let i=o.interactionEpisode?.steps.length??0;return{kind:"annotation",annotationId:o.id,pathname:o.pathname,text:Ju(o)??Ey(o),...i>0?{interactionEpisodeStepCount:i}:{}}}),n=new Map,r=o=>{let i=`${o.pathname??""}:${o.durableSelector??o.selector}`,a=n.get(i);if(a){a.changes.push(o.text),o.annotationNumber!==void 0&&(a.annotationNumber===void 0||o.annotationNumber<a.annotationNumber)&&(a.annotationNumber=o.annotationNumber);return}let l={kind:"changes",elementKey:i,elementLabel:ky(o.element,o.selector),...o.annotationNumber!==void 0?{annotationNumber:o.annotationNumber}:{},pathname:o.pathname,changes:[o.text]};n.set(i,l),t.push(l)};for(let o of e.styleModifications??[])for(let i of o.changes)r({...o,text:`${i.property}: ${i.original||"unset"} \u2192 ${i.modified||"unset"}${i.token?` (${i.token})`:""}`});for(let o of e.textModifications??[])r({...o,text:`Text: ${o.original||"empty"} \u2192 ${o.modified||"empty"}`});for(let o of e.domModifications??[])r({...o,text:o.operation==="copy"?"Copied element":"Moved element"});return e.spacingTokenChanges?.length&&t.push({kind:"changes",elementKey:"spacing-tokens",elementLabel:"Spacing tokens",changes:e.spacingTokenChanges.map(o=>`${o.tokenName}: ${o.originalPx}px \u2192 ${o.newPx}px`)}),t}function Cy(e){let t=e.annotations.flatMap(r=>{let o=Ju(r);return o?[{instruction:o,pathname:r.pathname}]:[]});if(t.length===0)return;if(new Set(t.map(r=>r.pathname).filter(Boolean)).size<=1)return t.map(r=>r.instruction).join(`
|
|
7
7
|
|
|
8
8
|
`);let n=new Map;for(let r of t){let o=r.pathname||"(unknown)",i=n.get(o)??[];i.push(r.instruction),n.set(o,i)}return[...n.entries()].map(([r,o])=>`\`${r}\`
|
|
9
9
|
${o.map(i=>`- ${i}`).join(`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as o,b as d,c as l,d as s}from"./chunk-
|
|
1
|
+
import{a as o,b as d,c as l,d as s}from"./chunk-VKFM7ZBT.mjs";function g(r){let p=r?.basePath??"/popmelt",e={port:null,projectId:null},n="virtual:popmelt/bridge",i=`\0${n}`;return{name:"popmelt",resolveId(t){if(t===n)return i},load(t){if(t===i)return`export const bridgeUrl = ${JSON.stringify(e.port===null?null:`http://localhost:${e.port}`)}; export const projectId = ${JSON.stringify(e.projectId)};`},async configureServer(t){e=await o(r,t,5173),await d(e,t),t.middlewares.use(l(p,()=>e))},transformIndexHtml(){if(e.port!==null)return[{tag:"script",attrs:{type:"text/javascript"},children:s(e),injectTo:"head-prepend"}]}}}export{g as a};
|