@popmelt.com/core 0.31.2 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +43 -0
  2. package/claude-plugin/.claude-plugin/plugin.json +1 -1
  3. package/codex-plugin/.codex-plugin/plugin.json +1 -1
  4. package/dist/{ParticipantRuntime-BGVZAWZH.mjs → ParticipantRuntime-5K4XILTY.mjs} +1 -1
  5. package/dist/SuppliedContext-NURVPZ4L.mjs +2 -0
  6. package/dist/ThreadErrorCard-WZ2UBVWE.mjs +2 -0
  7. package/dist/bridge-entry.mjs +1 -1
  8. package/dist/{browser-runtime-VSD5R2HG.mjs → browser-runtime-UVEA7O7K.mjs} +1 -1
  9. package/dist/browser.d.mts +2 -2
  10. package/dist/browser.mjs +1 -1
  11. package/dist/canvas-chat-note-NHYL3T6J.mjs +2 -0
  12. package/dist/{chunk-SQA3PHME.mjs → chunk-67CZ5WTY.mjs} +89 -87
  13. package/dist/chunk-AEOT7B5I.mjs +2 -0
  14. package/dist/{chunk-JU7D4I76.mjs → chunk-C3VWS5R6.mjs} +2 -2
  15. package/dist/{chunk-Q5QRV4KJ.mjs → chunk-EUWNUQGJ.mjs} +1 -1
  16. package/dist/chunk-GTQSZVCQ.mjs +334 -0
  17. package/dist/chunk-IKCHOC3U.mjs +3 -0
  18. package/dist/{chunk-QLN5IYRL.mjs → chunk-KHQZYGU3.mjs} +94 -92
  19. package/dist/{chunk-2TFOULRG.mjs → chunk-UGGB6HDI.mjs} +1 -1
  20. package/dist/chunk-VMQD7UGC.mjs +2 -0
  21. package/dist/cli.mjs +8 -8
  22. package/dist/codex-note-context-VSQVT5ZL.mjs +2 -0
  23. package/dist/codex-project-MKH6TO5W.mjs +2 -0
  24. package/dist/codex-session-registry-SPRWY2WW.mjs +2 -0
  25. package/dist/{focus-inspection-WPHGCN6Y.mjs → focus-inspection-G72JLJYG.mjs} +1 -1
  26. package/dist/index.d.mts +2 -2
  27. package/dist/index.mjs +1 -1
  28. package/dist/{participantBootstrap-B0lvfCwM.d.mts → participantBootstrap-ClKpD2qC.d.mts} +14 -1
  29. package/dist/peer-client-FJGBXESA.mjs +2 -0
  30. package/dist/plugin-astro.mjs +1 -1
  31. package/dist/plugin-nuxt.mjs +1 -1
  32. package/dist/plugin-vite.mjs +1 -1
  33. package/dist/server.mjs +1 -1
  34. package/package.json +23 -32
  35. package/dist/ThreadErrorCard-5ADUBZKJ.mjs +0 -2
  36. package/dist/canvas-chat-note-7HSL7MH6.mjs +0 -2
  37. package/dist/chunk-4V7SK3M6.mjs +0 -3
  38. package/dist/chunk-7VW2KD6D.mjs +0 -2
  39. package/dist/chunk-QENHLODE.mjs +0 -327
  40. package/dist/chunk-UZUYF4D5.mjs +0 -2
  41. package/dist/codex-note-context-SGNCDBK4.mjs +0 -2
  42. package/dist/codex-project-PA5DEEPH.mjs +0 -2
  43. package/dist/codex-session-registry-25DAA2KO.mjs +0 -2
  44. package/dist/peer-client-BEU2VKYY.mjs +0 -2
  45. /package/dist/{chunk-J5HW2SCX.mjs → chunk-4JG6IVUU.mjs} +0 -0
package/README.md CHANGED
@@ -332,6 +332,49 @@ metadata is limited to 64 KiB per human turn. Keep large binaries and long
332
332
  event logs in external storage or attachments and place their stable IDs,
333
333
  hashes, and timestamps in `meta`.
334
334
 
335
+ #### Show context as a note card
336
+
337
+ Each top-level entry can use the exported `CommentMetaNote` shape. Pick a key that makes sense for your integration. Give a local note a `title` and `content`. A public web page can start with just a `sourceURI`.
338
+
339
+ ```ts
340
+ import type { CommentMetaNote, GetCommentMeta } from '@popmelt.com/core';
341
+
342
+ const exportPolicy = {
343
+ source: 'Obsidian',
344
+ title: 'Export policy',
345
+ content: 'Verify the workspace before enabling export.',
346
+ sourceIcon: '/icons/obsidian.svg',
347
+ sourceURI: 'notes/Exports.md',
348
+ } satisfies CommentMetaNote;
349
+
350
+ const getCommentMeta: GetCommentMeta = () => ({
351
+ 'my-app/export-policy/v1': exportPolicy,
352
+ });
353
+ ```
354
+
355
+ The optional `source` prefixes the title, as in **Obsidian: Export policy**. The optional `sourceIcon` replaces the plug with a same-origin PNG or SVG asset or an image data URL. If the icon fails to display, the card shows the plug.
356
+
357
+ A `sourceURI` makes the title clickable. Project-relative paths like `notes/Exports.md` open in VS Code using the viewer’s local Popmelt project root. If the root is unknown or the relative path escapes it, the title stays plain text. Absolute file paths refer to that machine. To open a note in Obsidian, use a link such as `obsidian://open?vault=Design&file=Product%2FExports`.
358
+
359
+ #### Preview a remote source
360
+
361
+ ```ts
362
+ import type { GetCommentMeta } from '@popmelt.com/core';
363
+
364
+ const getCommentMeta: GetCommentMeta = () => ({
365
+ 'my-app/reference/v1': {
366
+ sourceURI: 'https://rbkh.design/llms',
367
+ content: 'Use the accessibility section for this review.', // optional
368
+ },
369
+ });
370
+ ```
371
+
372
+ A public HTTP(S) URL opts that entry into a preview. At send time, the local bridge fills missing fields from the page title, description, and favicon. **Each developer-supplied field wins independently.** In the example, the card uses the site’s title and favicon alongside the supplied sentence. Omit `content` to use the site’s description.
373
+
374
+ Popmelt saves the preview with the human message. The model receives the text and URL and can follow the link when it needs more detail. Reopening a thread shows the saved snapshot. If a lookup fails, the message still sends and the title links to the URL, with the hostname and plug as fallbacks.
375
+
376
+ Multiple entries share one disclosure. Extra fields remain available under **Original data**, and the thread can display arbitrary JSON directly.
377
+
335
378
  ### Next.js
336
379
 
337
380
  Next.js needs both the command wrapper and the config wrapper.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "popmelt-core",
3
- "version": "0.31.2",
3
+ "version": "0.32.0",
4
4
  "description": "Local Popmelt context, canvas tools, and ambient turn capture for Claude Code.",
5
5
  "author": {
6
6
  "name": "Popmelt",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "popmelt-core",
3
- "version": "0.31.2",
3
+ "version": "0.32.0",
4
4
  "description": "Point out what you mean, talk through changes, and keep your AI on the same page.",
5
5
  "author": {
6
6
  "name": "Popmelt",
@@ -1,5 +1,5 @@
1
1
  "use client";
2
- import{a as Jt}from"./chunk-QTGE5KAA.mjs";import{tb as Wt,db as Ut,Cb as gt,Qa as qt,Xa as _t,cb as tt,Ta as zt,Wa as Ft,Ua as Vt,M as Ht,Sa as Xt,Va as Kt,sb as Yt,Za as Bt,pb as Zt,rb as Gt,qb as yt,Pa as vt,Ra as Qt,Ka as er,bb as tr,Ya as rr,Lb as nr,d as ir}from"./chunk-Q5QRV4KJ.mjs";import"./chunk-J4WDYITA.mjs";import{e as ar,N as or,xa as sr,Ca as lr,g as wt}from"./chunk-GNZ73T3H.mjs";import"./chunk-4LHTPRFY.mjs";import"./chunk-MTQ5IWIK.mjs";import{a as Te}from"./chunk-F6AMPRUB.mjs";import"./chunk-EXDOFFFJ.mjs";import{i as dr,a as cr,h as ur}from"./chunk-D32YV5O6.mjs";import{g as pr,e as rt,a as ze,d as fr}from"./chunk-V44RIEET.mjs";import{n as hr}from"./chunk-CPOYMGYY.mjs";import{a as mr}from"./chunk-6VXFTT5U.mjs";import"./chunk-XTOCFTVW.mjs";import"./chunk-LVEMYZOA.mjs";import{v as gr,o as bt}from"./chunk-RCVAPQ7X.mjs";import{useState as U,useSyncExternalStore as It,useEffect as ee,useRef as K,useCallback as Je,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 Cr}from"lucide-react";import{jsxs as B,jsx as S,Fragment as We}from"react/jsx-runtime";var Ar=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 jr(e){let t=structuredClone(e.draft.state??Te),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 C=await e.save(i,p,x);if(!it(C,f.draft))throw new Error("Unexpected saved draft revision; reconnect before writing");i=C.revision,a=c,o=structuredClone(C),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 Ar;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(Te),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,Tr=256,Fe=100,Ce=(...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(Ce("annotation",r.id),!0);for(let[i,n]of Object.entries(r))i!=="id"&&n!==void 0&&t.set(Ce("annotation",r.id,i),n)}for(let r of e.styleModifications){let i=Ce(r.pathname??"/",r.selector),{changes:n,...a}=r;t.set(Ce("styleMeta",i),a);for(let s of n)t.set(Ce("style",i,s.property),s)}for(let r of e.textModifications)t.set(Ce("text",Ce(r.pathname??"/",r.selector,JSON.stringify(r.textNodePath))),r);for(let r of e.domModifications)t.set(Ce("dom",r.id),r);for(let r of e.spacingTokenChanges)t.set(Ce("spacing",r.tokenPath),r);for(let r of e.spacingTokenMods)t.set(Ce("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(Ce("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 Ct=e=>({annotations:e.annotations,styleModifications:e.styleModifications,textModifications:e.textModifications,domModifications:e.domModifications,spacingTokenChanges:e.spacingTokenChanges,spacingTokenMods:e.spacingTokenMods});function lt(e=Te){let t=[...e.undoStack.slice(-Fe),Ct(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(Ce(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,C]=JSON.parse(p);x===w&&C===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=>ir(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 Ct(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??Te)),r=He(t,e.pendingEvents??[]);t=ct(t,r.pending);let i=ut(t,{...structuredClone(e.draft.state??Te),...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,C=!1,P=new Set,A=new Set,O=()=>{for(let v of[...P])v()},M=()=>{for(let v of[...A])v()},T=()=>{i=ut(t,n),n=i.state},$=()=>{if(!e.persist||!l)return Promise.resolve();let v=structuredClone(o),te=structuredClone(a),z=structuredClone(d),F=u;return w++,I=I.then(()=>e.persist(v,te,z)).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),z=ct(structuredClone(v.history),te.pending),F=JSON.stringify(z.hostStyleDeletions)!==JSON.stringify(t.hostStyleDeletions)||JSON.stringify(z.hostDeletions)!==JSON.stringify(t.hostDeletions)||z.checkpoint?.through.id!==t.checkpoint?.through.id||z.events.length!==t.events.length||z.events.some((R,L)=>R.id!==t.events[L]?.id);d=te.pending,te.superseded.length&&(g=void 0),t=z,s=v.revision,o=structuredClone(v),F&&T(),$()},H={getSnapshot:()=>n,getUndoHead:()=>i.undo.at(-1),subscribe(v){return P.add(v),()=>{P.delete(v)}},dispatch(v){if(C)throw new Error("Participant runtime is disposed");let te=n,z,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;z={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_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;z={id:be,stamp:F(),kind:"edit",changes:D,...pe?{group:pe}:{},...v.type==="CLEAR"?{reset:!0}:{}},g=pe}n=L}if(z){try{t=ct(t,[z])}catch(L){n=te,p=L instanceof Error?L:new Error(String(L)),x=!0,g=void 0,O(),M();return}d.push(z),T(),$()}O(),M(),e.saveView?.(n)}},ae=()=>C?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 $(),await q();!C&&!x&&(d.length||y);){await q();let v=structuredClone(d.slice(0,Tr)),te=structuredClone(a),z=await e.save(s,te,n,v);if(C)return;ie(z),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:C}),subscribeStatus(v){return A.add(v),()=>{A.delete(v)}},pause(v){x=!0,p=v,M()},async whenSettled(){await c?.catch(()=>{}),await q().catch(()=>{})},whenDurable:q,async retryLocalSave(){if(C)throw new Error("Participant runtime is disposed");await $(),await q()},async clearLocalSpace(){if(x=!0,await c?.catch(()=>{}),await q().catch(()=>{}),C)throw new Error("Participant runtime is disposed");l=!1,d=[],y=!1,g=void 0,t=structuredClone(o.history??lt(o.state??Te)),i=ut(t,{...structuredClone(Te),activeColor:n.activeColor,isAnnotating:n.isAnnotating}),n=i.state,s=o.revision,f=null,p=null,O(),M()},async resumeLocalSaving(){if(!e.persist||C)return!1;l=!0;let v;try{return await Promise.race([$().then(q),new Promise((te,z)=>{v=setTimeout(()=>z(new Error("Local saving timed out")),2e3)})]),!C}catch{return u++,l=!1,w=0,I=Promise.resolve(),f=null,M(),!1}finally{clearTimeout(v)}},reconcile(v){if(C)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){C||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(){C=!0,x=!0,await c?.catch(()=>{}),await q().catch(()=>{}),d=[],t=lt(Te),n=structuredClone(Te),o={revision:s,source:null,state:null},O(),M()},dispose(){C=!0,P.clear(),A.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 $r(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}},At=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 mr(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 Jr(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 Wr(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 Ur(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 At(e.bridgeUrl,t,i),s=`popmelt-runtime:${t}:${i.participantId}`,d=`popmelt-view:${t}:${i.participantId}`,o=Ur(r,`popmelt-navigation:${t}:${i.participantId}`,i.participantId),f=rr(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"?$r(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(J=>J.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 C;try{C=x.draft.history?Lr({draft:x.draft,source:n,actor:p.runtimeId,view:l,pendingEvents:g?.pending,persist:b?async(h,J,j)=>{await b.update({reference:{...x,draft:h},basis:J,pending:j})}:void 0,saveView:h=>{try{r.setItem(d,JSON.stringify({isAnnotating:h.isAnnotating,activeColor:h.activeColor}))}catch{}},save:(h,J,j,Q)=>a.merge(p,h,J,Q)}):null}catch(h){throw b?.close(),w(),h}let P=C??jr({draft:x.draft,source:n,save:(h,J,j)=>a.publish(p,h,J,j)}),A=!1,O=!1,M=null,T="connected",$=null,q=null,ie=0,H,ae=1e3,v=-1,te=!1,z=!1,F=new Set,R=()=>{for(let h of F)h()},L=()=>{A||H||$||T!=="reconnecting"||(H=setTimeout(()=>{H=void 0,oe()},ae),ae=Math.min(ae*2,3e4))},D=h=>{if(!A){if(M=h instanceof Error?h:new Error(String(h)),P.pause(M),M instanceof ke&&M.status===401){T="paused",z=!0,ie++,clearTimeout(H),H=void 0,R();return}T=Xe(M)?"reconnecting":"paused",T==="paused"&&(ie++,clearTimeout(H),H=void 0),L(),R()}},oe=(h=!1)=>{if(A)return Promise.reject(new Error("Participant runtime is closed"));if(q&&!h)return q;if($)return $;let J=++ie,j=()=>!A&&J===ie;return clearTimeout(H),H=void 0,T="reconnecting",P.pause(M??new Error("Reconnecting to the participant session")),R(),$=(async()=>{if(await P.whenSettled(),!j())return;let Q=await a.connect(p.runtimeId,p.token);if(A)return;p=Q;try{r.setItem(s,JSON.stringify(p))}catch(Oe){if(!C?.getStatus().memoryOnly)throw Oe}if(!j())return;let je=await a.read();j()&&(P.reconcile(je.draft),await P.flush(),j()&&(M=null,T="connected",ae=1e3,R()))})().catch(Q=>{j()&&D(Q)}).finally(()=>{$=null,L()}),$},me=P.binding.subscribe(()=>{T==="connected"&&P.flush().catch(D)}),be=C?.subscribeStatus(()=>{let h=C.getStatus().localError;h&&h!==M?D(h):R()}),pe,he=setInterval(()=>{if(A||O||T!=="connected")return;O=!0;let h=p,J=P.binding.getSnapshot().activeColor;a.renew(p,J!==pe?J:void 0).then(j=>{!A&&p===h&&(p=j,pe=J,r.setItem(s,JSON.stringify(j)))}).catch(j=>{pe=void 0,!(p!==h||T!=="connected")&&(D(j),j instanceof ke&&j.status===409&&j.code==="runtime_expired"&&oe())}).finally(()=>{O=!1})},4e3),de=!1,se=0,Ee=async h=>{if(A||T!=="connected"||!C||!h)return;let J=ie;if(h.draftRevision>P.getStatus().revision){let j=await a.read();!A&&T==="connected"&&J===ie&&C.receive(j.draft)}},ce=setInterval(()=>{A||de||T!=="connected"||!C||se||(de=!0,a.snapshot().then(async h=>{let J=h.find(j=>j.identity.id===i.participantId);await Ee(J)}).catch(D).finally(()=>{de=!1}))},1e3),ge=0,G=!1,_=()=>{let h=P.binding.getSnapshot();return JSON.stringify({annotations:h.annotations.map(J=>({...J,status:void 0})),styles:h.styleModifications,text:h.textModifications,dom:h.domModifications,spacing:h.spacingTokenChanges})},le=null,Ae=null,Y=!1,Le=setInterval(()=>{if(A||!le||Y||T!=="connected")return;let h=le,J=p;Y=!0,a.previewWanted(p).then(async({wanted:j})=>{if(!j||le!==h||A||T!=="connected")return;await P.flush();let Q=P.binding.getSnapshot(),je=P.getStatus().revision,Oe=await h.frame(Jr(Q));Oe&&le===h&&!A&&T==="connected"&&J.token===p.token&&Q===P.binding.getSnapshot()&&await a.publishPreview(p,Oe.image,{draftRevision:je,targets:Oe.targets})}).catch(j=>{if(!(A||T!=="connected")){if(j instanceof Error&&Xe(j)){D(j);return}le===h&&(Ae=j instanceof Error?j.message:"Preview unavailable",h.stop(),le=null,R())}}).finally(()=>{Y=!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:_,reportAttention(h,J,j,Q){return A||T!=="connected"?Promise.resolve(!1):a.reportAttention(p,h,J,j,Q)},bindSubjects(h){return re=h,()=>{re===h&&(re=void 0)}},getSubjects:()=>re,getStatus:()=>({error:M,phase:T,pendingCount:ge,sending:G,sharing:!!le,previewError:Ae,accessRemoved:z}),reconnect:()=>oe(),retainExternalMembershipPolling(){se++;let h=!1;return()=>{h||(h=!0,se--)}},async retryLocalSave(){if(q)return q;await C?.retryLocalSave(),await oe()},clearLocalSpace(){return q||(A||!C?Promise.reject(new Error("Local space is unavailable")):(q=Promise.resolve().then(async()=>{let h=$;if(ie++,clearTimeout(H),H=void 0,T="paused",P.pause(new Error("Clearing local space")),R(),await h,A)throw new Error("Participant runtime is closed");try{r.setItem(I,"1")}catch{}await C.clearLocalSpace();let J;try{if(await Promise.race([b?.clear?b.clear():Promise.reject(new Error("Local storage cannot be cleared")),new Promise((j,Q)=>{J=setTimeout(()=>Q(new Error("Local clear timed out")),2e3)})]),A)throw new Error("Participant runtime is closed");if(await C.resumeLocalSaving())try{r.removeItem(I)}catch{}}catch{}finally{clearTimeout(J)}if(A)throw new Error("Participant runtime is closed");if(await oe(!0),T!=="connected")throw M??new Error("Session remains unavailable")}).finally(()=>{q=null}),q))},observeMembership(h){if(!(A||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(()=>{z=!0,R()}).catch(J=>{M=J instanceof Error?J: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(T==="paused"&&M instanceof ke&&M.status===403&&h.permissionEpoch>v){v=h.permissionEpoch;let J=()=>{!A&&T==="paused"&&v===h.permissionEpoch&&M instanceof ke&&M.status===403&&oe()};$?$.then(J):J()}}}},sharePreview(h){if(A){h?.stop();return}le?.stop(),le=h,Ae=null,h||a.publishPreview(p,null).catch(()=>{}),R()},subscribe:h=>(F.add(h),()=>{F.delete(h)}),async send(h,J){if(A||T!=="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(),T!=="connected")throw M??new Error("Draft sync paused");if(_()!==J)throw new Error("Draft changed during capture; send again to include your latest changes");let j=await a.send(hr(h),P.getStatus().revision,n);return j.status==="pending-approval"?(ge++,R(),{pendingApproval:!0,submissionId:j.submissionId,threadId:j.threadId}):j}finally{G=!1,R()}},dispose(){A||(A=!0,re=void 0,T="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 _r(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",jt=/^[A-Za-z0-9_-]{43}$/;function zr(e,t){let r=new URL(e);if(!["http:","https:"].includes(r.protocol)||!["localhost","127.0.0.1","[::1]"].includes(r.hostname)||!jt.test(t))throw new Error("A local page and valid invitation are required");let i=Tt(r.href).cleanUrl,n=new URL(i);return n.hash=`${n.hash.slice(1)}${n.hash?"&":""}${ft}=${t}`,n.href}function Tt(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 jt.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 At(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(er(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,_r(localStorage,e.projectId),l({phase:"entry",invitation:null})},b=async()=>{let g=Tt(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 C=null;if(x){if(C=await u({token:x}),!C)throw new Error("Host entry expired. Use the current private host link.")}else if(!g.token){try{C=JSON.parse(localStorage.getItem(o)??"null")}catch{}C??(C=await u())}if(!n){if(!C){l({phase:"entry",invitation:g.token??null});return}try{await I(C)}catch(P){if(n)return;if(P.code==="access_removed"){y();return}if(P.status!==401)throw P;let A=await u();A?await I(A):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 Ue=360,qe=120,Ye=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]=U(o.current?.name??""),[w,I]=U(d?void 0:o.current?.receipt),[y,b]=U(null),[g,c]=U(),[p,x]=U(),C=K(null),[P,A]=U(!!d),[O,M]=U(!1),[T,$]=U(0),[q,ie]=U(),[H,ae]=U("idle"),[v,te]=U(),[z,F]=U(),R=K(!1),[L,D]=U(""),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 _=K(!1),le=K(null),Ae=K(()=>{});le.current||(le.current=new Promise(k=>{Ae.current=k}));let Y=rt[n],Le=P&&!g;ee(()=>{let k=!1,Z,X,V=()=>{k||(k=!0,_.current=!0,Ae.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(()=>fr(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(!T)return;let k=setTimeout(()=>$(0),Ue);return()=>clearTimeout(k)},[T]),ee(()=>{if(!q)return;let k=setTimeout(()=>ie(void 0),Ue);return()=>clearTimeout(k)},[q]),ee(()=>{if(H!=="in")return;let k=setTimeout(()=>ae("idle"),Ye);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 J=()=>{if(C.current)return C.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(tr(V)),X};return C.current=k().finally(()=>{C.current=null}),C.current},j=()=>{A(!P),P||D("")},Q=K(J);Q.current=J;let je=!!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)||A(!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),A(!1),D("")},ye=()=>{X=!0;let ve=Ke(),we=0,De=async()=>{if(k)try{let $e=await Q.current();o.current={...o.current,name:l,receipt:ve,colorIdentity:$e},t.setItem(r,JSON.stringify(o.current));let _e=await e.requestAdmission(ve,l,$e);if(!k)return;ge.current+=1,I(ve),b(_e),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(_.current||await le.current,!k||ve!==ge.current)return;X=!0;let De=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches,$e=()=>{k&&(ae("rejected"),$(_e=>_e+1),V=setTimeout(()=>{if(k){if(De){Pe(),ae("idle");return}ae("rejected-out"),V=setTimeout(()=>{k&&(Pe(),ae("in"))},qe)}},Ue))};De?$e():(ae("pending-out"),V=setTimeout($e,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),A(!1)}catch{$(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 J();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 J();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),A(!1)}catch{o.current={...o.current,name:l,receipt:Z},ie({target:k,pulse:++de.current})}finally{R.current=!1,M(!1)}};return B("div",{ref:oe,"data-devtools":"participant-admission","data-popmelt-font":"sans","data-popmelt-theme":n,style:{display:"contents"},onKeyDown:k=>{k.key==="Escape"&&(A(!1),k.stopPropagation())},children:[S("style",{children:`
2
+ import{a as Jt}from"./chunk-QTGE5KAA.mjs";import{tb as Wt,db as Ut,Cb as gt,Qa as qt,Xa as _t,cb as tt,Ta as zt,Wa as Ft,Ua as Vt,M as Ht,Sa as Xt,Va as Kt,sb as Yt,Za as Bt,pb as Zt,rb as Gt,qb as yt,Pa as vt,Ra as Qt,Ka as er,bb as tr,Ya as rr,Lb as nr,d as ir}from"./chunk-EUWNUQGJ.mjs";import"./chunk-J4WDYITA.mjs";import{e as ar,N as or,xa as sr,Ca as lr,g as wt}from"./chunk-GNZ73T3H.mjs";import"./chunk-4LHTPRFY.mjs";import"./chunk-MTQ5IWIK.mjs";import{a as Te}from"./chunk-F6AMPRUB.mjs";import"./chunk-EXDOFFFJ.mjs";import{i as dr,a as cr,h as ur}from"./chunk-D32YV5O6.mjs";import{g as pr,e as rt,a as ze,d as fr}from"./chunk-V44RIEET.mjs";import{n as hr}from"./chunk-CPOYMGYY.mjs";import{a as mr}from"./chunk-6VXFTT5U.mjs";import"./chunk-XTOCFTVW.mjs";import"./chunk-LVEMYZOA.mjs";import{v as gr,o as bt}from"./chunk-RCVAPQ7X.mjs";import{useState as U,useSyncExternalStore as It,useEffect as ee,useRef as K,useCallback as Je,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 Cr}from"lucide-react";import{jsxs as B,jsx as S,Fragment as We}from"react/jsx-runtime";var Ar=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 jr(e){let t=structuredClone(e.draft.state??Te),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 C=await e.save(i,p,x);if(!it(C,f.draft))throw new Error("Unexpected saved draft revision; reconnect before writing");i=C.revision,a=c,o=structuredClone(C),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 Ar;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(Te),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,Tr=256,Fe=100,Ce=(...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(Ce("annotation",r.id),!0);for(let[i,n]of Object.entries(r))i!=="id"&&n!==void 0&&t.set(Ce("annotation",r.id,i),n)}for(let r of e.styleModifications){let i=Ce(r.pathname??"/",r.selector),{changes:n,...a}=r;t.set(Ce("styleMeta",i),a);for(let s of n)t.set(Ce("style",i,s.property),s)}for(let r of e.textModifications)t.set(Ce("text",Ce(r.pathname??"/",r.selector,JSON.stringify(r.textNodePath))),r);for(let r of e.domModifications)t.set(Ce("dom",r.id),r);for(let r of e.spacingTokenChanges)t.set(Ce("spacing",r.tokenPath),r);for(let r of e.spacingTokenMods)t.set(Ce("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(Ce("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 Ct=e=>({annotations:e.annotations,styleModifications:e.styleModifications,textModifications:e.textModifications,domModifications:e.domModifications,spacingTokenChanges:e.spacingTokenChanges,spacingTokenMods:e.spacingTokenMods});function lt(e=Te){let t=[...e.undoStack.slice(-Fe),Ct(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(Ce(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,C]=JSON.parse(p);x===w&&C===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=>ir(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 Ct(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??Te)),r=He(t,e.pendingEvents??[]);t=ct(t,r.pending);let i=ut(t,{...structuredClone(e.draft.state??Te),...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,C=!1,P=new Set,A=new Set,O=()=>{for(let v of[...P])v()},M=()=>{for(let v of[...A])v()},T=()=>{i=ut(t,n),n=i.state},$=()=>{if(!e.persist||!l)return Promise.resolve();let v=structuredClone(o),te=structuredClone(a),z=structuredClone(d),F=u;return w++,I=I.then(()=>e.persist(v,te,z)).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),z=ct(structuredClone(v.history),te.pending),F=JSON.stringify(z.hostStyleDeletions)!==JSON.stringify(t.hostStyleDeletions)||JSON.stringify(z.hostDeletions)!==JSON.stringify(t.hostDeletions)||z.checkpoint?.through.id!==t.checkpoint?.through.id||z.events.length!==t.events.length||z.events.some((R,L)=>R.id!==t.events[L]?.id);d=te.pending,te.superseded.length&&(g=void 0),t=z,s=v.revision,o=structuredClone(v),F&&T(),$()},H={getSnapshot:()=>n,getUndoHead:()=>i.undo.at(-1),subscribe(v){return P.add(v),()=>{P.delete(v)}},dispatch(v){if(C)throw new Error("Participant runtime is disposed");let te=n,z,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;z={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_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;z={id:be,stamp:F(),kind:"edit",changes:D,...pe?{group:pe}:{},...v.type==="CLEAR"?{reset:!0}:{}},g=pe}n=L}if(z){try{t=ct(t,[z])}catch(L){n=te,p=L instanceof Error?L:new Error(String(L)),x=!0,g=void 0,O(),M();return}d.push(z),T(),$()}O(),M(),e.saveView?.(n)}},ae=()=>C?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 $(),await q();!C&&!x&&(d.length||y);){await q();let v=structuredClone(d.slice(0,Tr)),te=structuredClone(a),z=await e.save(s,te,n,v);if(C)return;ie(z),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:C}),subscribeStatus(v){return A.add(v),()=>{A.delete(v)}},pause(v){x=!0,p=v,M()},async whenSettled(){await c?.catch(()=>{}),await q().catch(()=>{})},whenDurable:q,async retryLocalSave(){if(C)throw new Error("Participant runtime is disposed");await $(),await q()},async clearLocalSpace(){if(x=!0,await c?.catch(()=>{}),await q().catch(()=>{}),C)throw new Error("Participant runtime is disposed");l=!1,d=[],y=!1,g=void 0,t=structuredClone(o.history??lt(o.state??Te)),i=ut(t,{...structuredClone(Te),activeColor:n.activeColor,isAnnotating:n.isAnnotating}),n=i.state,s=o.revision,f=null,p=null,O(),M()},async resumeLocalSaving(){if(!e.persist||C)return!1;l=!0;let v;try{return await Promise.race([$().then(q),new Promise((te,z)=>{v=setTimeout(()=>z(new Error("Local saving timed out")),2e3)})]),!C}catch{return u++,l=!1,w=0,I=Promise.resolve(),f=null,M(),!1}finally{clearTimeout(v)}},reconcile(v){if(C)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){C||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(){C=!0,x=!0,await c?.catch(()=>{}),await q().catch(()=>{}),d=[],t=lt(Te),n=structuredClone(Te),o={revision:s,source:null,state:null},O(),M()},dispose(){C=!0,P.clear(),A.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 $r(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}},At=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 mr(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 Jr(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 Wr(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 Ur(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 At(e.bridgeUrl,t,i),s=`popmelt-runtime:${t}:${i.participantId}`,d=`popmelt-view:${t}:${i.participantId}`,o=Ur(r,`popmelt-navigation:${t}:${i.participantId}`,i.participantId),f=rr(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"?$r(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(J=>J.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 C;try{C=x.draft.history?Lr({draft:x.draft,source:n,actor:p.runtimeId,view:l,pendingEvents:g?.pending,persist:b?async(h,J,j)=>{await b.update({reference:{...x,draft:h},basis:J,pending:j})}:void 0,saveView:h=>{try{r.setItem(d,JSON.stringify({isAnnotating:h.isAnnotating,activeColor:h.activeColor}))}catch{}},save:(h,J,j,Q)=>a.merge(p,h,J,Q)}):null}catch(h){throw b?.close(),w(),h}let P=C??jr({draft:x.draft,source:n,save:(h,J,j)=>a.publish(p,h,J,j)}),A=!1,O=!1,M=null,T="connected",$=null,q=null,ie=0,H,ae=1e3,v=-1,te=!1,z=!1,F=new Set,R=()=>{for(let h of F)h()},L=()=>{A||H||$||T!=="reconnecting"||(H=setTimeout(()=>{H=void 0,oe()},ae),ae=Math.min(ae*2,3e4))},D=h=>{if(!A){if(M=h instanceof Error?h:new Error(String(h)),P.pause(M),M instanceof ke&&M.status===401){T="paused",z=!0,ie++,clearTimeout(H),H=void 0,R();return}T=Xe(M)?"reconnecting":"paused",T==="paused"&&(ie++,clearTimeout(H),H=void 0),L(),R()}},oe=(h=!1)=>{if(A)return Promise.reject(new Error("Participant runtime is closed"));if(q&&!h)return q;if($)return $;let J=++ie,j=()=>!A&&J===ie;return clearTimeout(H),H=void 0,T="reconnecting",P.pause(M??new Error("Reconnecting to the participant session")),R(),$=(async()=>{if(await P.whenSettled(),!j())return;let Q=await a.connect(p.runtimeId,p.token);if(A)return;p=Q;try{r.setItem(s,JSON.stringify(p))}catch(Oe){if(!C?.getStatus().memoryOnly)throw Oe}if(!j())return;let je=await a.read();j()&&(P.reconcile(je.draft),await P.flush(),j()&&(M=null,T="connected",ae=1e3,R()))})().catch(Q=>{j()&&D(Q)}).finally(()=>{$=null,L()}),$},me=P.binding.subscribe(()=>{T==="connected"&&P.flush().catch(D)}),be=C?.subscribeStatus(()=>{let h=C.getStatus().localError;h&&h!==M?D(h):R()}),pe,he=setInterval(()=>{if(A||O||T!=="connected")return;O=!0;let h=p,J=P.binding.getSnapshot().activeColor;a.renew(p,J!==pe?J:void 0).then(j=>{!A&&p===h&&(p=j,pe=J,r.setItem(s,JSON.stringify(j)))}).catch(j=>{pe=void 0,!(p!==h||T!=="connected")&&(D(j),j instanceof ke&&j.status===409&&j.code==="runtime_expired"&&oe())}).finally(()=>{O=!1})},4e3),de=!1,se=0,Ee=async h=>{if(A||T!=="connected"||!C||!h)return;let J=ie;if(h.draftRevision>P.getStatus().revision){let j=await a.read();!A&&T==="connected"&&J===ie&&C.receive(j.draft)}},ce=setInterval(()=>{A||de||T!=="connected"||!C||se||(de=!0,a.snapshot().then(async h=>{let J=h.find(j=>j.identity.id===i.participantId);await Ee(J)}).catch(D).finally(()=>{de=!1}))},1e3),ge=0,G=!1,_=()=>{let h=P.binding.getSnapshot();return JSON.stringify({annotations:h.annotations.map(J=>({...J,status:void 0})),styles:h.styleModifications,text:h.textModifications,dom:h.domModifications,spacing:h.spacingTokenChanges})},le=null,Ae=null,Y=!1,Le=setInterval(()=>{if(A||!le||Y||T!=="connected")return;let h=le,J=p;Y=!0,a.previewWanted(p).then(async({wanted:j})=>{if(!j||le!==h||A||T!=="connected")return;await P.flush();let Q=P.binding.getSnapshot(),je=P.getStatus().revision,Oe=await h.frame(Jr(Q));Oe&&le===h&&!A&&T==="connected"&&J.token===p.token&&Q===P.binding.getSnapshot()&&await a.publishPreview(p,Oe.image,{draftRevision:je,targets:Oe.targets})}).catch(j=>{if(!(A||T!=="connected")){if(j instanceof Error&&Xe(j)){D(j);return}le===h&&(Ae=j instanceof Error?j.message:"Preview unavailable",h.stop(),le=null,R())}}).finally(()=>{Y=!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:_,reportAttention(h,J,j,Q){return A||T!=="connected"?Promise.resolve(!1):a.reportAttention(p,h,J,j,Q)},bindSubjects(h){return re=h,()=>{re===h&&(re=void 0)}},getSubjects:()=>re,getStatus:()=>({error:M,phase:T,pendingCount:ge,sending:G,sharing:!!le,previewError:Ae,accessRemoved:z}),reconnect:()=>oe(),retainExternalMembershipPolling(){se++;let h=!1;return()=>{h||(h=!0,se--)}},async retryLocalSave(){if(q)return q;await C?.retryLocalSave(),await oe()},clearLocalSpace(){return q||(A||!C?Promise.reject(new Error("Local space is unavailable")):(q=Promise.resolve().then(async()=>{let h=$;if(ie++,clearTimeout(H),H=void 0,T="paused",P.pause(new Error("Clearing local space")),R(),await h,A)throw new Error("Participant runtime is closed");try{r.setItem(I,"1")}catch{}await C.clearLocalSpace();let J;try{if(await Promise.race([b?.clear?b.clear():Promise.reject(new Error("Local storage cannot be cleared")),new Promise((j,Q)=>{J=setTimeout(()=>Q(new Error("Local clear timed out")),2e3)})]),A)throw new Error("Participant runtime is closed");if(await C.resumeLocalSaving())try{r.removeItem(I)}catch{}}catch{}finally{clearTimeout(J)}if(A)throw new Error("Participant runtime is closed");if(await oe(!0),T!=="connected")throw M??new Error("Session remains unavailable")}).finally(()=>{q=null}),q))},observeMembership(h){if(!(A||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(()=>{z=!0,R()}).catch(J=>{M=J instanceof Error?J: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(T==="paused"&&M instanceof ke&&M.status===403&&h.permissionEpoch>v){v=h.permissionEpoch;let J=()=>{!A&&T==="paused"&&v===h.permissionEpoch&&M instanceof ke&&M.status===403&&oe()};$?$.then(J):J()}}}},sharePreview(h){if(A){h?.stop();return}le?.stop(),le=h,Ae=null,h||a.publishPreview(p,null).catch(()=>{}),R()},subscribe:h=>(F.add(h),()=>{F.delete(h)}),async send(h,J){if(A||T!=="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(),T!=="connected")throw M??new Error("Draft sync paused");if(_()!==J)throw new Error("Draft changed during capture; send again to include your latest changes");let j=await a.send(hr(h),P.getStatus().revision,n);return j.status==="pending-approval"?(ge++,R(),{pendingApproval:!0,submissionId:j.submissionId,threadId:j.threadId}):j}finally{G=!1,R()}},dispose(){A||(A=!0,re=void 0,T="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 _r(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",jt=/^[A-Za-z0-9_-]{43}$/;function zr(e,t){let r=new URL(e);if(!["http:","https:"].includes(r.protocol)||!["localhost","127.0.0.1","[::1]"].includes(r.hostname)||!jt.test(t))throw new Error("A local page and valid invitation are required");let i=Tt(r.href).cleanUrl,n=new URL(i);return n.hash=`${n.hash.slice(1)}${n.hash?"&":""}${ft}=${t}`,n.href}function Tt(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 jt.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 At(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(er(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,_r(localStorage,e.projectId),l({phase:"entry",invitation:null})},b=async()=>{let g=Tt(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 C=null;if(x){if(C=await u({token:x}),!C)throw new Error("Host entry expired. Use the current private host link.")}else if(!g.token){try{C=JSON.parse(localStorage.getItem(o)??"null")}catch{}C??(C=await u())}if(!n){if(!C){l({phase:"entry",invitation:g.token??null});return}try{await I(C)}catch(P){if(n)return;if(P.code==="access_removed"){y();return}if(P.status!==401)throw P;let A=await u();A?await I(A):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 Ue=360,qe=120,Ye=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]=U(o.current?.name??""),[w,I]=U(d?void 0:o.current?.receipt),[y,b]=U(null),[g,c]=U(),[p,x]=U(),C=K(null),[P,A]=U(!!d),[O,M]=U(!1),[T,$]=U(0),[q,ie]=U(),[H,ae]=U("idle"),[v,te]=U(),[z,F]=U(),R=K(!1),[L,D]=U(""),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 _=K(!1),le=K(null),Ae=K(()=>{});le.current||(le.current=new Promise(k=>{Ae.current=k}));let Y=rt[n],Le=P&&!g;ee(()=>{let k=!1,Z,X,V=()=>{k||(k=!0,_.current=!0,Ae.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(()=>fr(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(!T)return;let k=setTimeout(()=>$(0),Ue);return()=>clearTimeout(k)},[T]),ee(()=>{if(!q)return;let k=setTimeout(()=>ie(void 0),Ue);return()=>clearTimeout(k)},[q]),ee(()=>{if(H!=="in")return;let k=setTimeout(()=>ae("idle"),Ye);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 J=()=>{if(C.current)return C.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(tr(V)),X};return C.current=k().finally(()=>{C.current=null}),C.current},j=()=>{A(!P),P||D("")},Q=K(J);Q.current=J;let je=!!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)||A(!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),A(!1),D("")},ye=()=>{X=!0;let ve=Ke(),we=0,De=async()=>{if(k)try{let $e=await Q.current();o.current={...o.current,name:l,receipt:ve,colorIdentity:$e},t.setItem(r,JSON.stringify(o.current));let _e=await e.requestAdmission(ve,l,$e);if(!k)return;ge.current+=1,I(ve),b(_e),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(_.current||await le.current,!k||ve!==ge.current)return;X=!0;let De=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches,$e=()=>{k&&(ae("rejected"),$(_e=>_e+1),V=setTimeout(()=>{if(k){if(De){Pe(),ae("idle");return}ae("rejected-out"),V=setTimeout(()=>{k&&(Pe(),ae("in"))},qe)}},Ue))};De?$e():(ae("pending-out"),V=setTimeout($e,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),A(!1)}catch{$(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 J();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 J();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),A(!1)}catch{o.current={...o.current,name:l,receipt:Z},ie({target:k,pulse:++de.current})}finally{R.current=!1,M(!1)}};return B("div",{ref:oe,"data-devtools":"participant-admission","data-popmelt-font":"sans","data-popmelt-theme":n,style:{display:"contents"},onKeyDown:k=>{k.key==="Escape"&&(A(!1),k.stopPropagation())},children:[S("style",{children:`
3
3
  ${Yt}
4
4
  [data-popmelt-admission-ask] {
5
5
  transition: box-shadow 120ms ease, width ${Ye}ms ease;
@@ -0,0 +1,2 @@
1
+ "use client";
2
+ import{useState as I}from"react";import{ChevronDown as z,Plug as O}from"lucide-react";import{jsx as o,jsxs as c,Fragment as U}from"react/jsx-runtime";function f(e){return typeof e=="string"&&e.trim()?e:void 0}function k(e){if(!e||typeof e!="object"||Array.isArray(e))return;let n=f(e.sourceURI),i=n&&/^https?:\/\//i.test(n)&&y(n),t=f(e.title)??(i?new URL(i).hostname:void 0),l=f(e.content)??"";if(!t||!l&&!i||e.content!=null&&typeof e.content!="string"||e.title!=null&&typeof e.title!="string")return;let a=f(e.source),p=f(e.sourceIcon),s=f(e.sourceURI);return{title:t,content:l,...a&&{source:a},...p&&{sourceIcon:p},...s&&{sourceURI:s}}}function y(e,n){let i=e?.trim();if(!i||Array.from(i).some(l=>l.charCodeAt(0)<32))return;let t=/^[a-z]:[\\/]/i;try{if(!t.test(i)&&/^[a-z][a-z0-9+.-]*:/i.test(i)){let r=new URL(i);return r.username||r.password?void 0:/^https?:$/.test(r.protocol)||r.protocol==="obsidian:"&&r.host==="open"&&!r.pathname&&!r.hash&&[...r.searchParams.keys()].every(d=>["vault","file","path","paneType"].includes(d))?r.href:void 0}let l=i.replaceAll("\\","/");if(l.startsWith("//")||l.startsWith("~"))return;let a=[];for(let r of l.split("/"))if(r===".."){if(!a.length||a.length===1&&t.test(l))return;a.pop()}else r&&r!=="."&&a.push(r);let p=n?.replaceAll("\\","/").replace(/\/$/,""),s=l.startsWith("/")?"/"+a.join("/"):t.test(l)?a.join("/"):n&&p+"/"+a.join("/");return!a.length||!s||!s.startsWith("/")&&!t.test(s)||s.startsWith("//")?void 0:"vscode://file/"+s.split("/").filter(Boolean).map((r,d)=>d===0&&t.test(s)?r:encodeURIComponent(r)).join("/")}catch{return}}function C(e){if(e){if(/^data:image\/(?:png|svg\+xml|x-icon)(?:;[^,]*)?,/i.test(e))return e;try{let n=new URL(e,document.baseURI);if(n.origin===location.origin&&/^https?:$/.test(n.protocol)&&/\.(?:png|svg)$/i.test(n.pathname)&&!n.username&&!n.password)return n.href}catch{}}}function m({value:e}){let n=C(e),[i,t]=I();return n&&n!==i?o("img",{src:n,alt:"",width:12,height:12,referrerPolicy:"no-referrer",style:{flexShrink:0,objectFit:"contain"},onError:()=>t(n)}):o(O,{size:12,"aria-hidden":"true",style:{flexShrink:0}})}function j(e,n){return c(U,{children:[e.source&&e.source+": ",n?o("a",{href:n,target:"_blank",rel:"noopener noreferrer",style:{color:"inherit",textDecoration:"underline"},children:e.title}):e.title]})}var A="var(--popmelt-thread-secondary)",L={display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},$={display:"-webkit-box",marginTop:4,contain:"inline-size",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden",color:"var(--popmelt-thread-primary)"};function W(e){let n=JSON.stringify(e);return n.length<2048?JSON.stringify(e,null,2):n}function P({meta:e,projectRoot:n}){let i=Object.entries(e),t=i.length===1?k(i[0][1]):void 0,l=t&&t.content.length>160?t.content.slice(0,159)+"\u2026":void 0,a=!t||!!t.content||Object.keys(i[0][1]).some(h=>!(h in t)),[p,s]=I(!!(t&&!l)),r=a&&p;if(!i.length)return null;let d=t?(t.source?t.source+": ":"")+t.title:i.length>1?`Context (${i.length} entries)`:"Context",x=t&&y(t.sourceURI,n),v={...L,whiteSpace:r?"normal":"nowrap",fontWeight:550},b=o(z,{size:12,"aria-hidden":"true",style:{marginLeft:"auto",flexShrink:0,transform:r?"rotate(180deg)":void 0}}),w={type:"button","aria-expanded":r,onClick:()=>s(!r)},S={font:"inherit",color:"inherit",cursor:"pointer",background:"transparent",border:0,padding:0,textAlign:"left"};return c("div",{"data-supplied-context":"",style:{alignSelf:"flex-end",boxSizing:"border-box",minWidth:0,maxWidth:"100%",marginTop:-10,borderRadius:"16px 16px 8px 16px",color:A,background:"var(--popmelt-thread-control)",fontSize:12,lineHeight:1.4,overflowWrap:"anywhere"},children:[c("div",{style:{padding:r?"12px 12px 4px":12},children:[x&&t?c("div",{style:{display:"flex",alignItems:"center",gap:4},children:[o(m,{value:t.sourceIcon}),o("span",{style:v,children:j(t,x)}),a&&o("button",{...w,"aria-label":`${r?"Collapse":"Expand"} context: ${d}`,style:{...S,marginLeft:"auto",alignSelf:"stretch",display:"grid",placeItems:"center",minWidth:20},children:b})]}):c("button",{...w,style:{...S,display:"flex",width:"100%",alignItems:"center",gap:4},children:[o(m,{value:t?.sourceIcon}),o("span",{style:v,children:d}),b]}),!r&&l&&o("span",{style:$,children:l})]}),o("div",{"aria-hidden":!r,style:{padding:r?"0 12px 12px":"0 12px",maxHeight:r?240:0,overflowY:r?"auto":"hidden",visibility:r?"visible":"hidden",color:"var(--popmelt-thread-primary)",whiteSpace:"pre-wrap"},children:i.map(([h,g])=>{let u=k(g);return u?c("div",{style:{marginTop:t?0:4},children:[!t&&c("div",{style:{display:"flex",alignItems:"center",gap:4,fontWeight:550},children:[o(m,{value:u.sourceIcon}),o("span",{children:j(u,y(u.sourceURI,n))})]}),u.content,Object.keys(g).some(R=>!Object.prototype.hasOwnProperty.call(u,R))&&c("details",{children:[o("summary",{children:"Original data"}),o("pre",{style:{whiteSpace:"pre-wrap",fontSize:11},children:W({[h]:g})})]})]},h):o("pre",{style:{fontSize:11,whiteSpace:"pre-wrap",margin:"4px 0"},children:W({[h]:g})},h)})})]})}export{P as default};
@@ -0,0 +1,2 @@
1
+ "use client";
2
+ import{a as k}from"./chunk-2P2NUZW7.mjs";import{i as j}from"./chunk-D32YV5O6.mjs";import"./chunk-V44RIEET.mjs";import{b as $}from"./chunk-CPOYMGYY.mjs";import"./chunk-6VXFTT5U.mjs";import{useState as S,useRef as w,useEffect as C,useCallback as O}from"react";import{ArrowUpRight as R,Copy as P}from"lucide-react";import{jsx as i,jsxs as d,Fragment as x}from"react/jsx-runtime";var U={unavailable:"Open Codex or Claude in this project with the Popmelt integration enabled, then try again.",ambiguous:"More than one chat is available for this project. Send a note to this canvas thread from the intended chat first.",changed:"The destination chat has changed or its access is unavailable. Refresh the thread before trying again.",uncertain:"Delivery is unconfirmed. Check the destination chat before sending another copy."};function z(n,a){let e=k(n,a);return a==="send_rejected"&&typeof n=="string"&&Object.values(U).some(t=>t===n)&&(e.message=n),e}function A({provider:n,bridgeUrl:a}){let[e,t]=S("idle"),[p,o]=S(!1),s=w(!0),h=w(!1),c=n==="codex"?"Codex":"Claude",m=n==="codex"?"codex login":"claude auth login",b=`${a}/provider-login/${n}`;C(()=>(s.current=!0,()=>{s.current=!1}),[]);let g=O(async r=>{let l=await $(b,{method:r,cache:"no-store",signal:AbortSignal.timeout(1e4),...r==="POST"?{headers:{"Content-Type":"application/json"},body:"{}"}:{}});if(!l.ok)throw new Error("Sign-in unavailable");let u=await l.json();return["pending","complete","failed","manual"].includes(u.state)?u.state:"failed"},[b]);C(()=>{if(e!=="pending")return;let r=!1,l,u=Date.now()+10*6e4;async function v(){try{let f=await g("GET");if(r)return;f!=="pending"||Date.now()>=u?t(f==="pending"?"failed":f):l=setTimeout(()=>{v()},1500)}catch{r||t("failed")}}return l=setTimeout(()=>{v()},1500),()=>{r=!0,clearTimeout(l)}},[e,g]);async function T(){if(!h.current){h.current=!0,t("opening");try{let r=await g("POST");s.current&&t(r)}catch{s.current&&t("failed")}finally{h.current=!1}}}let y={...j("dark"),display:"inline-flex",alignItems:"center",gap:8,font:"inherit",fontWeight:400,color:"var(--popmelt-thread-primary)",background:"var(--popmelt-thread-control)",cursor:"pointer"};return i("span",{"data-provider-sign-in":n,children:e==="complete"?d("span",{role:"status",children:["Signed in to ",c,". Send your reply to continue."]}):d(x,{children:[d("button",{type:"button",style:y,disabled:e==="opening"||e==="pending",onClick:()=>{T()},children:[e==="opening"?"Opening\u2026":e==="pending"?`Signing in to ${c}\u2026`:`Sign in to ${c}`,i(R,{size:14,"aria-hidden":"true"})]}),i("span",{role:"status",children:e==="pending"?" Complete sign-in in the terminal window, then return here.":e==="manual"?" Open your terminal and paste the login command.":e==="failed"?" Sign-in did not finish. Try again, or use your terminal.":" to continue."}),(e==="manual"||e==="failed")&&d("button",{type:"button",style:{...y,marginLeft:6},onClick:()=>{navigator.clipboard.writeText(m).then(()=>o(!0)).catch(()=>o(!1))},"aria-label":`Copy ${c} login command`,children:[p?"Copied":m,i(P,{size:14,"aria-hidden":"true"})]})]})})}function D({message:{error:n,errorKind:a,provider:e},bridgeUrl:t,canSignIn:p}){let o=z(n,a);return i("div",{style:{backgroundColor:"var(--popmelt-thread-soft)",border:"1px solid var(--popmelt-thread-border)",borderRadius:24,color:"var(--popmelt-thread-muted-strong)",fontSize:14,letterSpacing:"0.14px",lineHeight:1.35,padding:16},children:p&&o.kind==="authentication"&&(e==="codex"||e==="claude")?i(A,{provider:e,bridgeUrl:t}):d(x,{children:[i("span",{style:{color:"#f59e0b"},children:o.label})," \u2014 "+o.message]})})}export{D as default};
@@ -1,2 +1,2 @@
1
- import{k as n}from"./chunk-SQA3PHME.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()})+`
1
+ import{k as n}from"./chunk-67CZ5WTY.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-QENHLODE.mjs";import"./chunk-JU7D4I76.mjs";import"./chunk-IPR652AZ.mjs";import"./chunk-Q5QRV4KJ.mjs";import"./chunk-J4WDYITA.mjs";import"./chunk-GNZ73T3H.mjs";import"./chunk-4LHTPRFY.mjs";import"./chunk-MTQ5IWIK.mjs";import"./chunk-F6AMPRUB.mjs";import"./chunk-EXDOFFFJ.mjs";import"./chunk-2P2NUZW7.mjs";import"./chunk-D32YV5O6.mjs";import"./chunk-V44RIEET.mjs";import"./chunk-CPOYMGYY.mjs";import"./chunk-EX63NVDN.mjs";import"./chunk-N2ZEZCHO.mjs";import"./chunk-J3UIBBU2.mjs";import"./chunk-6VXFTT5U.mjs";import"./chunk-XTOCFTVW.mjs";import"./chunk-LVEMYZOA.mjs";import"./chunk-RCVAPQ7X.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};
2
+ import{b as m,a as i}from"./chunk-GTQSZVCQ.mjs";import"./chunk-C3VWS5R6.mjs";import"./chunk-IPR652AZ.mjs";import"./chunk-EUWNUQGJ.mjs";import"./chunk-J4WDYITA.mjs";import"./chunk-GNZ73T3H.mjs";import"./chunk-4LHTPRFY.mjs";import"./chunk-MTQ5IWIK.mjs";import"./chunk-F6AMPRUB.mjs";import"./chunk-EXDOFFFJ.mjs";import"./chunk-2P2NUZW7.mjs";import"./chunk-D32YV5O6.mjs";import"./chunk-V44RIEET.mjs";import"./chunk-CPOYMGYY.mjs";import"./chunk-EX63NVDN.mjs";import"./chunk-N2ZEZCHO.mjs";import"./chunk-J3UIBBU2.mjs";import"./chunk-6VXFTT5U.mjs";import"./chunk-XTOCFTVW.mjs";import"./chunk-LVEMYZOA.mjs";import"./chunk-RCVAPQ7X.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};
@@ -1,5 +1,5 @@
1
- import { P as PopmeltOptions } from './participantBootstrap-B0lvfCwM.mjs';
2
- export { i as isPopmeltPreview } from './participantBootstrap-B0lvfCwM.mjs';
1
+ import { P as PopmeltOptions } from './participantBootstrap-ClKpD2qC.mjs';
2
+ export { i as isPopmeltPreview } from './participantBootstrap-ClKpD2qC.mjs';
3
3
  import './subjects-EWAR5-0S.mjs';
4
4
  import './video-adapter-BUMpNTCP.mjs';
5
5
 
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-VSD5R2HG.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};
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-UVEA7O7K.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};
@@ -0,0 +1,2 @@
1
+ "use client";
2
+ import{b as w}from"./chunk-CPOYMGYY.mjs";import"./chunk-6VXFTT5U.mjs";async function y(s,d,p,a,I,S){let t=a[1].toLowerCase()==="claude"?"Claude":"Codex";if(!I)throw new Error("Only the host can send a chat note.");if(S)throw new Error("Send a text-only note.");let g=p.find(e=>e.provider===t&&e.linked),h=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(a[2])),c=Array.from(new Uint8Array(h),e=>e.toString(16).padStart(2,"0")).join(""),m=e=>JSON.stringify(["popmelt-note",s,d,e,c]),o=m(t),i=m(g?.id??t),r=sessionStorage.getItem(o)??sessionStorage.getItem(i)??crypto.randomUUID();sessionStorage.setItem(o,r);let l=await w(`${s}/participants/send-to-${t.toLowerCase()}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({threadId:d,text:a[2],requestId:r,linkId:g?.id})}),n=await l.json();if(!l.ok||!(n.queuedInChat||n.availableInChat))throw new Error(n.error??"The bridge did not confirm delivery.");return sessionStorage.getItem(o)===r&&sessionStorage.removeItem(o),sessionStorage.getItem(i)===r&&sessionStorage.removeItem(i),{jobId:n.jobId}}export{y as sendCanvasChatNote};