@popmelt.com/core 0.30.0 → 0.30.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -27,7 +27,9 @@ Claude thread runs use Claude Code's authentication configuration, including API
27
27
 
28
28
  From inside your project, give your coding agent this prompt:
29
29
 
30
- > Let's install `@popmelt.com/core` in this project
30
+ ```text
31
+ Let's install @popmelt.com/core in this project
32
+ ```
31
33
 
32
34
  Your agent can detect the framework, add the matching integration, and preserve your existing development command. Restart the development server when it is finished.
33
35
 
@@ -37,7 +39,9 @@ For manual instructions, see [Manual setup](#manual-setup). Experimental non-Rea
37
39
 
38
40
  To add local object recognition to an existing Popmelt project, use:
39
41
 
40
- > Add `@popmelt.com/see` to this Popmelt Core project
42
+ ```text
43
+ Add @popmelt.com/see to this Popmelt Core project
44
+ ```
41
45
 
42
46
  The integration installs See and adds it to the existing Core provider's
43
47
  `extensions` array without replacing Core.
@@ -53,6 +57,24 @@ Pick one thing in your own app that you already want to improve:
53
57
 
54
58
  Questions, ideas, or issues? [Email](mailto:reb@popmelt.com) or [DM on X](https://x.com/bekhovsgun).
55
59
 
60
+ ## Useful shortcuts
61
+
62
+ | Shortcut | Action |
63
+ | -------------------------------- | ------------------------------------------------------------------- |
64
+ | Double-tap Command or Control | Open or collapse Popmelt |
65
+ | `C` | Enter Chat mode |
66
+ | `S` | Enter Steer mode |
67
+ | `I` | Enter Imprint mode |
68
+ | Command/Control+Enter | Send all pending work |
69
+ | Command/Control+C | Capture a screenshot for pending work when no text is selected |
70
+ | Command/Control+Z | Undo a pending change or thread dismissal |
71
+ | Command/Control+Shift+Z | Redo a pending change |
72
+ | Backspace/Delete | Archive the open or selected historical thread |
73
+ | Command/Control+Backspace/Delete | Clear all annotations and pending changes |
74
+ | Escape | Go back, cancel, close, discard, or deselect in the current context |
75
+
76
+ Steer additionally owns the unmodified letter, arrow, Enter, Escape, and Space keys described in [Steer](#steer) while it is active. Popmelt leaves these shortcuts alone while you are typing in an input, textarea, or editable text surface.
77
+
56
78
  ## Use Popmelt
57
79
 
58
80
  1. Run your project locally and open it in a browser
@@ -120,7 +142,7 @@ Archiving hides a thread from the active canvas without deleting its stored conv
120
142
 
121
143
  ### Message Codex or Claude from a canvas thread
122
144
 
123
- With [multiplayer enabled](#experimental-multiplayer-opt-in), open a local chat in the same project using the [Codex plugin](#ambient-popmelt-in-codex) or the [Claude plugin](#ambient-popmelt-in-claude-code-local-preview). For Claude Desktop, use the **Code** tab.
145
+ With [multiplayer enabled](#experimental-multiplayer-opt-in), open a local chat in the same project using the [Codex plugin](#ambient-popmelt-in-codex) or the [Claude plugin](#ambient-popmelt-in-claude-code). For Claude Desktop, use the **Code** tab.
124
146
 
125
147
  1. In the desktop chat, ask “Post ‘Which logo should we use?’ in the Popmelt thread about the install button.” Use the title or subject of a thread on your canvas. The note appears there with the app’s icon.
126
148
  2. As the canvas host, start a text reply with `@Codex` or `@Claude`, for example `@Claude Can you find the official asset?`. The mention goes to the **last chat from that app that participated in this canvas thread**. To send from the canvas first, ask the intended desktop chat to link itself to that thread.
@@ -169,7 +191,7 @@ This installer is Codex-specific. Claude Code toolbar threads do not need it. Fo
169
191
 
170
192
  Ambient capture stays out of toolbar-owned runs, so opening a thread from the in-page toolbar still produces exactly one toolbar job. Popmelt tools remain available for intentional context expansion, decision review, and Imprint grounding.
171
193
 
172
- ### Ambient Popmelt in Claude Code (local preview)
194
+ ### Ambient Popmelt in Claude Code
173
195
 
174
196
  The package also includes an experimental native Claude plugin with the Popmelt skill, local MCP tools, and prompt/tool/completion hooks. For local Claude Code, inspect first:
175
197
 
@@ -542,6 +564,12 @@ The wrapper can start Popmelt alongside another development command:
542
564
  }
543
565
  ```
544
566
 
567
+ ### Local event transport
568
+
569
+ Core uses WebSocket for local bridge events by default. Commands and approvals remain authenticated HTTP requests. Older bridges without WebSocket discovery continue using SSE; authentication failures never trigger a silent downgrade.
570
+
571
+ To explicitly roll back, set `POPMELT_EXPERIMENTAL_EVENT_TRANSPORT=sse` before launching your dev server, or use `popmelt({ experimentalEventTransport: 'sse' })` for a plugin-owned bridge. Explicit plugin options take precedence over the environment. Restart only the affected app/bridge and reload its page after changing the setting. The existing option name is retained for compatibility.
572
+
545
573
  ### Connect your Popmelt account
546
574
 
547
575
  Cloud account access does not require multiplayer. With your local dev server
@@ -594,7 +622,9 @@ npm run dev
594
622
 
595
623
  Only describe a check as verified when you observed it. Keep the completion message brief: give the exact local app URL, distinguish configured from verified, and name each remaining gap with its next step. For example, when the relevant checks pass:
596
624
 
597
- > Popmelt is ready at [the app's actual local URL]. Double-tap Command/Control, click something you want changed, and leave a comment.
625
+ ```text
626
+ Popmelt is ready at [the app's actual local URL]. Double-tap Command/Control, click something you want changed, and leave a comment.
627
+ ```
598
628
 
599
629
  If ambient setup still needs a restart, say so separately. Let the user choose the first change; do not create a test annotation or launch an agent run merely to validate installation.
600
630
 
@@ -743,24 +773,6 @@ When you send a thread, the context needed to complete that work is passed to yo
743
773
 
744
774
  Popmelt is designed for local development. As with any AI-assisted coding, your agent may edit files or run commands, so review its work, use version control, and run your project tests before you ship.
745
775
 
746
- ## Useful shortcuts
747
-
748
- | Shortcut | Action |
749
- | -------------------------------- | ------------------------------------------------------------------- |
750
- | Double-tap Command or Control | Open or collapse Popmelt |
751
- | `C` | Enter Chat mode |
752
- | `S` | Enter Steer mode |
753
- | `I` | Enter Imprint mode |
754
- | Command/Control+Enter | Send all pending work |
755
- | Command/Control+C | Capture a screenshot for pending work when no text is selected |
756
- | Command/Control+Z | Undo a pending change or thread dismissal |
757
- | Command/Control+Shift+Z | Redo a pending change |
758
- | Backspace/Delete | Archive the open or selected historical thread |
759
- | Command/Control+Backspace/Delete | Clear all annotations and pending changes |
760
- | Escape | Go back, cancel, close, discard, or deselect in the current context |
761
-
762
- Steer additionally owns the unmodified letter, arrow, Enter, Escape, and Space keys described above while it is active. Popmelt leaves these shortcuts alone while you are typing in an input, textarea, or editable text surface.
763
-
764
776
  ## Bridge commands
765
777
 
766
778
  Run a bridge without wrapping another command:
@@ -782,11 +794,3 @@ npx @popmelt.com/core stop
782
794
  You may use and extend Popmelt for yourself and your team. You may not sell it, offer it as a managed service, or use the code to create a competing product or service. The software is provided as-is.
783
795
 
784
796
  For custom licensing, contact **reb@popmelt.com**.
785
-
786
- ### Local event transport
787
-
788
- Core 0.29 uses WebSocket for local bridge events by default. Commands and approvals remain authenticated HTTP requests. Older bridges without WebSocket discovery continue using SSE; authentication failures never trigger a silent downgrade.
789
-
790
- To explicitly roll back, set `POPMELT_EXPERIMENTAL_EVENT_TRANSPORT=sse` before launching your dev server, or use `popmelt({ experimentalEventTransport: 'sse' })` for a plugin-owned bridge. Explicit plugin options take precedence over the environment. Restart only the affected app/bridge and reload its page after changing the setting. The existing option name is retained for compatibility.
791
-
792
- This does not create a Cloudflare Tunnel or expose your machine publicly.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "popmelt-core",
3
- "version": "0.30.0",
3
+ "version": "0.30.1",
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.30.0",
3
+ "version": "0.30.1",
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-SWTSMLHA.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 Bt,Za as Yt,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-2BVRVVHJ.mjs";import{e as ar,N as or,xa as sr,Ba as lr,g as wt}from"./chunk-ENGMQINZ.mjs";import"./chunk-JQHZFDY5.mjs";import{a as je}from"./chunk-MP7S5ALD.mjs";import"./chunk-XOGBFVWI.mjs";import{i as dr,a as cr,h as ur}from"./chunk-MZNY6VXR.mjs";import{g as pr,e as rt,a as ze,d as fr}from"./chunk-2RRYBN2J.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-HGW2U6PD.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 Ar}from"lucide-react";import{jsxs as Y,jsx as S,Fragment as We}from"react/jsx-runtime";var Cr=class extends Error{constructor(){super("The saved draft changed in another runtime. Your local changes are preserved.")}},it=(e,t)=>e.revision===t.revision&&JSON.stringify(e.source)===JSON.stringify(t.source)&&JSON.stringify(e.state)===JSON.stringify(t.state);function Tr(e){let t=structuredClone(e.draft.state??je),r=structuredClone(e.source),i=e.draft.revision,n=0,a=0,s=null,d=!1,o=structuredClone(e.draft),f=null,l=null,u=!1,w=new Set,I=new Set,y=()=>{for(let c of[...I])c()},b={getSnapshot:()=>t,subscribe:c=>(w.add(c),()=>{w.delete(c)}),dispatch:c=>{if(u)throw new Error("Participant runtime is disposed");let p=wt(t,c);if(p!==t){t=p,n++;for(let x of[...w])x();y()}}},g=()=>u?Promise.reject(new Error("Participant runtime is disposed")):l||(s||d?Promise.reject(s??new Error("Draft sync paused")):n===a?Promise.resolve():(l=Promise.resolve().then(async()=>{for(;!u&&!d&&n!==a;){let c=n,p=structuredClone(r),x=structuredClone(t);f={generation:c,draft:{revision:i+1,source:p,state:x}};let A=await e.save(i,p,x);if(!it(A,f.draft))throw new Error("Unexpected saved draft revision; reconnect before writing");i=A.revision,a=c,o=structuredClone(A),f=null}}).catch(c=>{throw s=c instanceof Error?c:new Error(String(c)),s}).finally(()=>{l=null,y()}),l));return{binding:b,flush:g,getStatus:()=>({revision:i,unsaved:n!==a,error:s,disposed:u}),subscribeStatus(c){return I.add(c),()=>{I.delete(c)}},pause(c){d=!0,s=c,y()},async whenSettled(){await l?.catch(()=>{})},reconcile(c){if(u)throw new Error("Participant runtime is disposed");if(l)throw new Error("Wait for the pending save before reconciling");if(!it(c,o)){if(!f||!it(c,f.draft))throw new Cr;i=c.revision,a=f.generation,o=structuredClone(c)}f=null,s=null,d=!1,y()},retry(){return s=null,d=!1,g()},setSource(c){if(u)throw new Error("Participant runtime is disposed");if(c.sourceId!==r.sourceId)throw new Error("Changing source worlds requires a new participant runtime");c.revision!==r.revision&&(r=structuredClone(c),n++,y())},async revoke(){u=!0,d=!0,await l?.catch(()=>{}),t=structuredClone(je),f=null,o={revision:i,source:null,state:null};for(let c of[...w])c();y()},dispose(){u=!0,w.clear(),I.clear()}}}var kt=8192,at=8*1024*1024,jr=256,Fe=100,Ae=(...e)=>JSON.stringify(e),Ve=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Re=e=>structuredClone(e),Or=class extends Error{constructor(){super("This edit predates retained synchronization history"),this.name="PlaneHistoryExpiredError"}},Et=(e,t)=>Pt(e.stamp,t.stamp)||(e.id<t.id?-1:e.id>t.id?1:0);function He(e,t){let r=new Map([...e.checkpoint?.receipts??[],...e.events].map(a=>[a.id,a])),i=[],n=[];for(let a of t){let s=r.get(a.id);if(s){if(!Ve(s,a))throw new Error("Plane event identity was reused");continue}e.checkpoint&&Et(a,e.checkpoint.through)<=0?n.push(a):i.push(a)}return{pending:i,superseded:n}}function Mr(e,t){let r=He(e,t);if(r.superseded.length)throw new Or;return r.pending}function Pt(e,t){return e.time-t.time||e.counter-t.counter||(e.actor<t.actor?-1:e.actor>t.actor?1:0)}function Nr(e,t,r,i){let n=r.reduce((s,d)=>!s||Pt(d.stamp,s)>0?d.stamp:s,t),a=Math.max(Math.floor(i),n?.time??0);return{actor:e,time:a,counter:a===n?.time?n.counter+1:0}}function ot(e){let t=new Map;for(let r of e.annotations){t.set(Ae("annotation",r.id),!0);for(let[i,n]of Object.entries(r))i!=="id"&&n!==void 0&&t.set(Ae("annotation",r.id,i),n)}for(let r of e.styleModifications){let i=Ae(r.pathname??"/",r.selector),{changes:n,...a}=r;t.set(Ae("styleMeta",i),a);for(let s of n)t.set(Ae("style",i,s.property),s)}for(let r of e.textModifications)t.set(Ae("text",Ae(r.pathname??"/",r.selector,JSON.stringify(r.textNodePath))),r);for(let r of e.domModifications)t.set(Ae("dom",r.id),r);for(let r of e.spacingTokenChanges)t.set(Ae("spacing",r.tokenPath),r);for(let r of e.spacingTokenMods)t.set(Ae("spacingMod",r.tokenPath),r);return t}function st(e,t){let r=ot(e),i=ot(t);return[...new Set([...r.keys(),...i.keys()])].filter(n=>!(JSON.parse(n)[0]==="styleMeta"&&!i.has(n))).filter(n=>!Ve(r.get(n),i.get(n))).map(n=>({key:n,...i.has(n)?{value:Re(i.get(n))}:{}}))}function xt(e,t){let r={...t,annotations:[],styleModifications:[],textModifications:[],domModifications:[],spacingTokenChanges:[],spacingTokenMods:[]},i=new Map;for(let[a,s]of e){let[d,o,f]=JSON.parse(a);d==="annotation"&&!f&&s===!0&&i.set(o,{id:o})}let n=new Map;for(let[a,s]of e){let[d,o,f]=JSON.parse(a);if(d==="annotation"&&f&&i.has(o)&&Object.defineProperty(i.get(o),f,{value:s,enumerable:!0,configurable:!0,writable:!0}),d==="style"){let l=n.get(o),u=e.get(Ae("styleMeta",o));if(!u)continue;l||(l={...u,changes:[]},n.set(o,l)),l.changes.push(s)}d==="text"&&r.textModifications.push(s),d==="dom"&&r.domModifications.push(s),d==="spacing"&&r.spacingTokenChanges.push(s),d==="spacingMod"&&r.spacingTokenMods.push(s)}return r.annotations=[...i.values()],r.styleModifications=[...n.values()],r.selectedAnnotationIds=t.selectedAnnotationIds.filter(a=>i.has(a)),r.lastSelectedId=r.selectedAnnotationIds.includes(t.lastSelectedId??"")?t.lastSelectedId:null,r}var At=e=>({annotations:e.annotations,styleModifications:e.styleModifications,textModifications:e.textModifications,domModifications:e.domModifications,spacingTokenChanges:e.spacingTokenChanges,spacingTokenMods:e.spacingTokenMods});function lt(e=je){let t=[...e.undoStack.slice(-Fe),At(e)],r={...Re(e),...Re(t[0]),undoStack:[],redoStack:[]},i=[];for(let s=1;s<t.length;s++){let d=`migration:${s}`;i.push({id:d,stamp:{time:0,counter:s,actor:"migration"},kind:"edit",group:d,changes:st({...r,...t[s-1]},{...r,...t[s]})})}let n=e,a=[];for(let s of[...e.redoStack].reverse().slice(0,Fe)){let d=`migration:${i.length+1}`,o={...r,...s};i.push({id:d,stamp:{time:0,counter:i.length+1,actor:"migration"},kind:"edit",group:d,changes:st(n,o)}),a.push(d),n=o}for(let s of a.reverse()){let d=`migration:${i.length+1}`;i.push({id:d,stamp:{time:0,counter:i.length+1,actor:"migration"},kind:"undo",target:s})}return{version:1,base:r,events:i}}function dt(e){if(!Array.isArray(e)||e.length>kt||JSON.stringify(e).length>at)throw new Error("Plane history exceeds the local session limit");for(let t of e){let r=n=>typeof n=="string"&&n.length>0&&n.length<=256;if(!t||!r(t.id)||!t.stamp||!r(t.stamp.actor)||!Number.isSafeInteger(t.stamp.time)||t.stamp.time<0||!Number.isSafeInteger(t.stamp.counter)||t.stamp.counter<0||!["edit","undo","redo"].includes(t.kind))throw new Error("Invalid plane event");if(t.kind!=="edit"){if(!r(t.target))throw new Error("Invalid history target");continue}if(t.group!==void 0&&!r(t.group)||t.reset!==void 0&&typeof t.reset!="boolean"||!Array.isArray(t.changes)||t.changes.length>1e4)throw new Error("Invalid plane edit");let i=new Set;for(let n of t.changes){if(!n||typeof n.key!="string"||n.key.length>8192)throw new Error("Invalid property key");let a=JSON.parse(n.key);if(!Array.isArray(a)||a.length<2||a.length>3||a.some(s=>typeof s!="string"||!s.length)||!["annotation","style","styleMeta","text","dom","spacing","spacingMod"].includes(a[0])||a[0]==="style"&&a.length!==3||!["style","annotation"].includes(a[0])&&a.length!==2||a[0]==="annotation"&&a.length===2&&n.value!==void 0&&n.value!==!0||i.has(n.key))throw new Error("Invalid property key");i.add(n.key)}}return Re(e)}function ct(e,t){let r=new Map(e.events.map(i=>[i.id,i]));for(let i of Mr(e,t)){let n=r.get(i.id);if(n&&!Ve(n,i))throw new Error("Plane event identity was reused");r.set(i.id,i)}if(r.size>kt)throw new Error("Plane history exceeds the local session limit");return{...e,events:[...r.values()].sort(Et)}}function Rr(e){if(e.version!==1&&e.version!==2)throw new Error("Unsupported plane history version");if(e.version===2&&!e.checkpoint)throw new Error("Missing plane history checkpoint");let t=e.checkpoint,r=t?new Map(Re(t.cells)):ot(e.base),i=new Map(t?.writers??[]),n=Re(t?.undo??[]),a=Re(t?.redo??[]),s=(d,o)=>{let f=[],l=[...d].sort((u,w)=>JSON.parse(u.key).length-JSON.parse(w.key).length);for(let u of l){let[w,I,y]=JSON.parse(u.key);if(w==="styleMeta"&&u.value===void 0)continue;let b=i.get(u.key)??"base";if(u.guard!==void 0&&b!==u.guard||w==="annotation"&&y&&!r.has(Ae(w,I)))continue;let g=r.get(u.key);u.value===void 0?r.delete(u.key):r.set(u.key,u.value);let c=u.restoreWriter??o;if(i.set(u.key,c),f.push({key:u.key,before:g,after:u.value,beforeWriter:b,afterWriter:c}),w==="annotation"&&!y&&u.value===void 0)for(let p of[...r.keys()]){let[x,A]=JSON.parse(p);x===w&&A===I&&(f.push({key:p,before:r.get(p),after:void 0,beforeWriter:i.get(p)??"base",afterWriter:c}),r.delete(p),i.set(p,c))}}return f};for(let d of e.events)if(d.kind==="edit"){let o=s(d.changes,d.group??d.id);if(d.reset&&(n.length=0,a.length=0),!d.group||!o.length)continue;let f=n.find(l=>l.id===d.group);if(f)for(let l of o){let u=f.changes.find(w=>w.key===l.key);u?(u.after=l.after,u.afterWriter=l.afterWriter):f.changes.push(l)}else n.push({id:d.group,writer:d.group,changes:o});a.length=0,n.length>Fe&&n.shift()}else{let o=d.kind==="undo"?n:a,f=d.kind==="undo"?a:n,l=o.findIndex(I=>I.id===d.target);if(l<0)continue;let u=o.splice(l,1)[0],w=s(u.changes.map(I=>({key:I.key,value:I.before,guard:I.afterWriter,restoreWriter:I.beforeWriter})),d.id);w.length&&f.push({id:d.id,writer:d.id,changes:w}),f.length>Fe&&f.shift()}return{cells:r,writers:i,undo:n,redo:a}}function ut(e,t=e.base,r=!0){let{cells:i,writers:n,undo:a,redo:s}=Rr(e),d=xt(i,t);d.styleModifications=d.styleModifications.filter(I=>!e.hostStyleDeletions?.some(y=>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 At(xt(y,t))},l=I=>I.filter(y=>y.changes.some(b=>JSON.parse(b.key)[0]!=="styleMeta"&&(n.get(b.key)??"base")===b.afterWriter&&!Ve(b.before,i.get(b.key)))),u=l(a),w=l(s);return d.undoStack=r?u.map(f):[],d.redoStack=r?w.map(f):[],{state:Re(d),undo:u.map(I=>I.id),redo:w.map(I=>I.id)}}function Lr(e){let t=structuredClone(e.draft.history??lt(e.draft.state??je)),r=He(t,e.pendingEvents??[]);t=ct(t,r.pending);let i=ut(t,{...structuredClone(e.draft.state??je),...e.view}),n=i.state,a=structuredClone(e.source),s=e.draft.revision,d=r.pending,o=structuredClone(e.draft),f=null,l=!!e.persist,u=0,w=0,I=Promise.resolve(),y=!1,b,g,c=null,p=null,x=!1,A=!1,P=new Set,C=new Set,O=()=>{for(let v of[...P])v()},M=()=>{for(let v of[...C])v()},j=()=>{i=ut(t,n),n=i.state},$=()=>{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&&j(),$()},H={getSnapshot:()=>n,getUndoHead:()=>i.undo.at(-1),subscribe(v){return P.add(v),()=>{P.delete(v)}},dispatch(v){if(A)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_TEXT_SIZE","UPDATE_ANNOTATION_COLOR"].includes(v.type);if(D.length){let be=R(),pe=oe||me?!oe&&g&&g===i.undo.at(-1)?g:be:void 0;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),j(),$()}O(),M(),e.saveView?.(n)}},ae=()=>A?Promise.reject(new Error("Participant runtime is disposed")):c||(p||x?Promise.reject(p??new Error("Draft sync paused")):!d.length&&!y&&!w&&!f?Promise.resolve():(c=Promise.resolve().then(async()=>{for(f&&await $(),await q();!A&&!x&&(d.length||y);){await q();let v=structuredClone(d.slice(0,jr)),te=structuredClone(a),z=await e.save(s,te,n,v);if(A)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:A}),subscribeStatus(v){return C.add(v),()=>{C.delete(v)}},pause(v){x=!0,p=v,M()},async whenSettled(){await c?.catch(()=>{}),await q().catch(()=>{})},whenDurable:q,async retryLocalSave(){if(A)throw new Error("Participant runtime is disposed");await $(),await q()},async clearLocalSpace(){if(x=!0,await c?.catch(()=>{}),await q().catch(()=>{}),A)throw new Error("Participant runtime is disposed");l=!1,d=[],y=!1,g=void 0,t=structuredClone(o.history??lt(o.state??je)),i=ut(t,{...structuredClone(je),activeColor:n.activeColor,isAnnotating:n.isAnnotating}),n=i.state,s=o.revision,f=null,p=null,O(),M()},async resumeLocalSaving(){if(!e.persist||A)return!1;l=!0;let v;try{return await Promise.race([$().then(q),new Promise((te,z)=>{v=setTimeout(()=>z(new Error("Local saving timed out")),2e3)})]),!A}catch{return u++,l=!1,w=0,I=Promise.resolve(),f=null,M(),!1}finally{clearTimeout(v)}},reconcile(v){if(A)throw new Error("Participant runtime is disposed");if(c)throw new Error("Wait for the pending save before reconciling");ie(v),p=null,x=!1,O(),M()},receive(v){A||x||c||v.revision<=s||(ie(v),O(),M())},retry(){return x=!1,p=null,ae()},setSource(v){if(v.sourceId!==a.sourceId)throw new Error("Changing source worlds requires a new participant runtime");v.revision===a.revision&&o.source?.revision===v.revision||(a=structuredClone(v),y=!0,M())},async revoke(){A=!0,x=!0,await c?.catch(()=>{}),await q().catch(()=>{}),d=[],t=lt(je),n=structuredClone(je),o={revision:s,source:null,state:null},O(),M()},dispose(){A=!0,P.clear(),C.clear()}}}function Dr(e,t){if(!t.reference.draft.history||t.reference.draft.source&&t.basis.sourceId!==t.reference.draft.source.sourceId)throw new Error("Offline recovery requires a matching shared-history source");if(e&&(e.version!==1||e.reference.author.id!==t.reference.author.id||e.reference.planeId!==t.reference.planeId||e.basis.sourceId!==t.basis.sourceId))throw new Error("Offline recovery belongs to a different plane");let r=e&&e.reference.draft.revision>t.reference.draft.revision?e.reference:t.reference,i=new Map;for(let o of[...dt(e?.pending??[]),...dt(t.pending)]){let f=i.get(o.id);if(f&&JSON.stringify(f)!==JSON.stringify(o))throw new Error("Offline operation identity was reused");i.set(o.id,o)}let n=He(r.draft.history,[...i.values()]),a=new Set(n.pending.map(o=>o.id)),s=e?.pending.some(o=>a.has(o.id)),d={version:1,reference:r,basis:s?e.basis:t.basis,pending:n.pending,...e?.superseded?{superseded:e.superseded}:{}};if(n.superseded.length){let o=n.superseded.slice(-128);for(;o.length&&new TextEncoder().encode(JSON.stringify(o)).length>256*1024;)o.shift();d.superseded={revision:r.draft.revision,events:o,omitted:n.superseded.length-o.length}}if(dt(d.pending),d.superseded&&new TextEncoder().encode(JSON.stringify(d)).length>at&&delete d.superseded,new TextEncoder().encode(JSON.stringify(d)).length>at)throw new Error("Offline recovery storage limit reached; pending work is preserved");return structuredClone(d)}function $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}},Ct=class{constructor(e,t,r,i=(...n)=>fetch(...n)){this.projectId=t,this.transport=i;let n=new URL(e);if(n.protocol!=="http:"||!["localhost","127.0.0.1","[::1]"].includes(n.hostname)||n.username||n.password||n.search||n.hash||n.pathname!=="/")throw new Error("Participant transport requires a local bridge origin");if(!t)throw new Error("Project identity required");this.base=n.origin,this.credential=r?{...r}:void 0}moderateStyles(e,t,r=!1){return this.rpc("moderate-styles",{participantId:e,styleModifications:t,restore:r})}moderateAnnotations(e,t,r=!1,i){return this.rpc("moderate-annotations",{participantId:e,annotationIds:t,restore:r,threadId:i})}async request(e,t,r={},i){let n=t instanceof FormData,a=await this.transport(this.base+e,{method:"POST",redirect:"error",credentials:"omit",signal:i??AbortSignal.timeout(3e4),headers:{...n?{}:{"Content-Type":"application/json"},"X-Popmelt-Project-Id":this.projectId,...this.credential?{"X-Popmelt-Participant-Id":this.credential.participantId,"X-Popmelt-Participant-Token":this.credential.token}:{},...r},body:n?t:JSON.stringify(t)}),s=await a.json().catch(()=>null);if(!a.ok)throw new ke(a.status,typeof s?.error=="string"?s.error:"Participant request failed",typeof s?.code=="string"?s.code:void 0);if(s===null)throw new Error("Invalid participant response");return{data:s,status:a.status}}async rpc(e,t={},r){return(await this.request("/participants/"+e,t,{},r)).data}mountRequestScope(e){if(!this.credential)throw new Error("Join before mounting a canvas");return 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 Ct(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 A;try{A=x.draft.history?Lr({draft:x.draft,source:n,actor:p.runtimeId,view:l,pendingEvents:g?.pending,persist:b?async(h,J,T)=>{await b.update({reference:{...x,draft:h},basis:J,pending:T})}:void 0,saveView:h=>{try{r.setItem(d,JSON.stringify({isAnnotating:h.isAnnotating,activeColor:h.activeColor}))}catch{}},save:(h,J,T,Q)=>a.merge(p,h,J,Q)}):null}catch(h){throw b?.close(),w(),h}let P=A??Tr({draft:x.draft,source:n,save:(h,J,T)=>a.publish(p,h,J,T)}),C=!1,O=!1,M=null,j="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=()=>{C||H||$||j!=="reconnecting"||(H=setTimeout(()=>{H=void 0,oe()},ae),ae=Math.min(ae*2,3e4))},D=h=>{if(!C){if(M=h instanceof Error?h:new Error(String(h)),P.pause(M),M instanceof ke&&M.status===401){j="paused",z=!0,ie++,clearTimeout(H),H=void 0,R();return}j=Xe(M)?"reconnecting":"paused",j==="paused"&&(ie++,clearTimeout(H),H=void 0),L(),R()}},oe=(h=!1)=>{if(C)return Promise.reject(new Error("Participant runtime is closed"));if(q&&!h)return q;if($)return $;let J=++ie,T=()=>!C&&J===ie;return clearTimeout(H),H=void 0,j="reconnecting",P.pause(M??new Error("Reconnecting to the participant session")),R(),$=(async()=>{if(await P.whenSettled(),!T())return;let Q=await a.connect(p.runtimeId,p.token);if(C)return;p=Q;try{r.setItem(s,JSON.stringify(p))}catch(Oe){if(!A?.getStatus().memoryOnly)throw Oe}if(!T())return;let Te=await a.read();T()&&(P.reconcile(Te.draft),await P.flush(),T()&&(M=null,j="connected",ae=1e3,R()))})().catch(Q=>{T()&&D(Q)}).finally(()=>{$=null,L()}),$},me=P.binding.subscribe(()=>{j==="connected"&&P.flush().catch(D)}),be=A?.subscribeStatus(()=>{let h=A.getStatus().localError;h&&h!==M?D(h):R()}),pe,he=setInterval(()=>{if(C||O||j!=="connected")return;O=!0;let h=p,J=P.binding.getSnapshot().activeColor;a.renew(p,J!==pe?J:void 0).then(T=>{!C&&p===h&&(p=T,pe=J,r.setItem(s,JSON.stringify(T)))}).catch(T=>{pe=void 0,!(p!==h||j!=="connected")&&(D(T),T instanceof ke&&T.status===409&&T.code==="runtime_expired"&&oe())}).finally(()=>{O=!1})},4e3),de=!1,se=0,Ee=async h=>{if(C||j!=="connected"||!A||!h)return;let J=ie;if(h.draftRevision>P.getStatus().revision){let T=await a.read();!C&&j==="connected"&&J===ie&&A.receive(T.draft)}},ce=setInterval(()=>{C||de||j!=="connected"||!A||se||(de=!0,a.snapshot().then(async h=>{let J=h.find(T=>T.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,Ce=null,B=!1,Le=setInterval(()=>{if(C||!le||B||j!=="connected")return;let h=le,J=p;B=!0,a.previewWanted(p).then(async({wanted:T})=>{if(!T||le!==h||C||j!=="connected")return;await P.flush();let Q=P.binding.getSnapshot(),Te=P.getStatus().revision,Oe=await h.frame(Jr(Q));Oe&&le===h&&!C&&j==="connected"&&J.token===p.token&&Q===P.binding.getSnapshot()&&await a.publishPreview(p,Oe.image,{draftRevision:Te,targets:Oe.targets})}).catch(T=>{if(!(C||j!=="connected")){if(T instanceof Error&&Xe(T)){D(T);return}le===h&&(Ce=T instanceof Error?T.message:"Preview unavailable",h.stop(),le=null,R())}}).finally(()=>{B=!1})},1e3);c?D(c):g?.pending.length&&P.flush().catch(D);let re;return{client:a,credential:i,navigation:o,state:P,readViewedSuggestions:f.read,markSuggestionViewed:f.mark,markSuggestionsViewed:f.markMany,captureVersion:_,reportAttention(h,J,T,Q){return C||j!=="connected"?Promise.resolve(!1):a.reportAttention(p,h,J,T,Q)},bindSubjects(h){return re=h,()=>{re===h&&(re=void 0)}},getSubjects:()=>re,getStatus:()=>({error:M,phase:j,pendingCount:ge,sending:G,sharing:!!le,previewError:Ce,accessRemoved:z}),reconnect:()=>oe(),retainExternalMembershipPolling(){se++;let h=!1;return()=>{h||(h=!0,se--)}},async retryLocalSave(){if(q)return q;await A?.retryLocalSave(),await oe()},clearLocalSpace(){return q||(C||!A?Promise.reject(new Error("Local space is unavailable")):(q=Promise.resolve().then(async()=>{let h=$;if(ie++,clearTimeout(H),H=void 0,j="paused",P.pause(new Error("Clearing local space")),R(),await h,C)throw new Error("Participant runtime is closed");try{r.setItem(I,"1")}catch{}await A.clearLocalSpace();let J;try{if(await Promise.race([b?.clear?b.clear():Promise.reject(new Error("Local storage cannot be cleared")),new Promise((T,Q)=>{J=setTimeout(()=>Q(new Error("Local clear timed out")),2e3)})]),C)throw new Error("Participant runtime is closed");if(await A.resumeLocalSaving())try{r.removeItem(I)}catch{}}catch{}finally{clearTimeout(J)}if(C)throw new Error("Participant runtime is closed");if(await oe(!0),j!=="connected")throw M??new Error("Session remains unavailable")}).finally(()=>{q=null}),q))},observeMembership(h){if(!(C||h.identity.id!==i.participantId)){if(h.revokedAt!==void 0&&!te){te=!0,D(new ke(403,"Your access was removed by the host")),le?.stop(),le=null,r.removeItem(s),r.removeItem(d),o.clear(),P.revoke().then(()=>b?.clear?.()).then(()=>{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(j==="paused"&&M instanceof ke&&M.status===403&&h.permissionEpoch>v){v=h.permissionEpoch;let J=()=>{!C&&j==="paused"&&v===h.permissionEpoch&&M instanceof ke&&M.status===403&&oe()};$?$.then(J):J()}}}},sharePreview(h){if(C){h?.stop();return}le?.stop(),le=h,Ce=null,h||a.publishPreview(p,null).catch(()=>{}),R()},subscribe:h=>(F.add(h),()=>{F.delete(h)}),async send(h,J){if(C||j!=="connected")throw M??new Error("Participant runtime is closed");if(G)throw new Error("A submission is already in progress");G=!0,R();try{if(P.setSource(n),await P.flush(),j!=="connected")throw M??new Error("Draft sync paused");if(_()!==J)throw new Error("Draft changed during capture; send again to include your latest changes");let T=await a.send(hr(h),P.getStatus().revision,n);return T.status==="pending-approval"?(ge++,R(),{pendingApproval:!0,submissionId:T.submissionId,threadId:T.threadId}):T}finally{G=!1,R()}},dispose(){C||(C=!0,re=void 0,j="closed",clearTimeout(H),clearInterval(he),clearInterval(ce),clearInterval(Le),le?.stop(),le=null,a.publishPreview(p,null).catch(()=>{}),me(),be?.(),w(),P.dispose(),P.whenSettled().finally(()=>b?.close()),F.clear())}}}function _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",Tt=/^[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)||!Tt.test(t))throw new Error("A local page and valid invitation are required");let i=jt(r.href).cleanUrl,n=new URL(i);return n.hash=`${n.hash.slice(1)}${n.hash?"&":""}${ft}=${t}`,n.href}function jt(e){let t=new URL(e),r=null,i=t.hash.slice(1).split("&").filter(n=>{if(!n.startsWith(`${ft}=`))return!0;let a=n.slice(ft.length+1);return Tt.test(a)&&(r=a),!1});return t.hash=i.join("&"),{token:r,cleanUrl:t.href}}function Fr(e){let t={phase:"starting"},r=0,i=!1,n=!1,a=0,s,d=new Set,o=`popmelt-participant:${e.projectId}`,f=new Ct(e.url,e.projectId),l=g=>{if(!n){t=g;for(let c of d)c()}},u=async(g={})=>{let c=await fetch("/__popmelt/host",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify(g),redirect:"error"});if(c.status===403)return null;if(!c.ok)throw new Error(`Host entry unavailable (${c.status}).`);let p=`popmelt-before-participants:${e.projectId}`;return localStorage.getItem(p)===null&&localStorage.setItem(p,JSON.stringify(Object.fromEntries(Object.values(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=jt(location.href),c=new URL(g.cleanUrl),p=new URLSearchParams(c.hash.slice(1)),x=p.get("popmelt-host");p.delete("popmelt-host"),x&&(c.hash=p.toString()),c.href!==location.href&&history.replaceState(history.state,"",c);let A=null;if(x){if(A=await u({token:x}),!A)throw new Error("Host entry expired. Use the current private host link.")}else if(!g.token){try{A=JSON.parse(localStorage.getItem(o)??"null")}catch{}A??(A=await u())}if(!n){if(!A){l({phase:"entry",invitation:g.token??null});return}try{await I(A)}catch(P){if(n)return;if(P.code==="access_removed"){y();return}if(P.status!==401)throw P;let C=await u();C?await I(C):y()}}};return{client:f,getSnapshot:()=>t,subscribe(g){return d.add(g),()=>{d.delete(g)}},retain(){if(n)throw new Error("Participant lifecycle is disposed");r++,i||(i=!0,b().catch(c=>l({phase:"error",message:c.message})));let g=!1;return()=>{g||(g=!0,r--,queueMicrotask(()=>{r||n||(n=!0,a++,s?.dispose(),s=void 0,d.clear())}))}},removed:y,async join(g,c){if(t.phase!=="entry"||!t.invitation||n)throw new Error("No active invitation");if(!c)throw new Error("Peer identity is not ready");let p=a,x=await f.joinOrRequestAdmission(t.invitation,g,c);if(!(n||p!==a)){if("admission"in x){localStorage.setItem(`popmelt-admission:${e.projectId}`,JSON.stringify({name:x.admission.name,receipt:c,colorIdentity:c})),l({phase:"entry",invitation:null});return}await I(x.joined.credential,p)}},admit:g=>I(g)}}function Ke(){let e=crypto.getRandomValues(new Uint8Array(32));return{id:crypto.randomUUID(),token:Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}}var Ue=360,qe=120,Be=180,Ot=260;function Vr({client:e,storage:t,storageKey:r,onAdmitted:i,theme:n="light",themePreference:a=n,onThemePreferenceChange:s,onJoin:d}){let o=K(null),f=K(!1);if(!f.current){f.current=!0;try{o.current=JSON.parse(t.getItem(r)??"null")}catch{}}let[l,u]=U(o.current?.name??""),[w,I]=U(d?void 0:o.current?.receipt),[y,b]=U(null),[g,c]=U(),[p,x]=U(),A=K(null),[P,C]=U(!!d),[O,M]=U(!1),[j,$]=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),Ce=K(()=>{});le.current||(le.current=new Promise(k=>{Ce.current=k}));let B=rt[n],Le=P&&!g;ee(()=>{let k=!1,Z,X,V=()=>{k||(k=!0,_.current=!0,Ce.current())};typeof requestAnimationFrame=="function"&&(Z=requestAnimationFrame(()=>{X=requestAnimationFrame(V)}));let Ie=window.setTimeout(V,64);return()=>{Z!==void 0&&cancelAnimationFrame(Z),X!==void 0&&cancelAnimationFrame(X),window.clearTimeout(Ie),V()}},[]),ee(()=>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(!j)return;let k=setTimeout(()=>$(0),Ue);return()=>clearTimeout(k)},[j]),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"),Be);return()=>clearTimeout(k)},[H]),ee(()=>{o.current&&delete o.current.color;try{let k=JSON.parse(t.getItem(r)??"null");k&&typeof k=="object"&&"color"in k&&(delete k.color,t.setItem(r,JSON.stringify(k)))}catch{}},[t,r]);let re=!!(w&&(!y||y.status==="pending"||y.status==="granted")),h=(k,Z)=>{o.current={...o.current,name:k,receipt:Z},t.setItem(r,JSON.stringify(o.current))};ee(()=>{if(y?.status==="cancelled"){o.current={...o.current,name:l,receipt:void 0};try{t.setItem(r,JSON.stringify(o.current))}catch{}I(void 0),b(null)}},[y,l,t,r]);let J=()=>{if(A.current)return A.current;let k=async()=>{let Z=JSON.parse(t.getItem(r)??"null"),X=Z?.colorIdentity??Z?.receipt??Ke();o.current={name:l,receipt:Z?.receipt,colorIdentity:X},t.setItem(r,JSON.stringify(o.current));let V;try{V=await e.reserveAdmissionColor(X)}catch(Ie){let Pe=Ie.status;if(Pe!==400&&Pe!==401)throw Ie;X=Ke(),o.current={...o.current,colorIdentity:X},t.setItem(r,JSON.stringify(o.current)),V=await e.reserveAdmissionColor(X)}return c(V.color),x(tr(V)),X};return A.current=k().finally(()=>{A.current=null}),A.current},T=()=>{C(!P),P||D("")},Q=K(J);Q.current=J;let Te=!!d;ee(()=>{if(!P||g)return;let k=!1,Z,X=0,V=async()=>{try{await Q.current()}catch{if(k)return;Z=setTimeout(()=>{V()},pt(++X))}};return V(),()=>{k=!0,clearTimeout(Z)}},[P,g,t,r]),ee(()=>{if(!P)return;me.current?.focus();let k=Z=>{Z.composedPath().includes(oe.current)||C(!1)};return document.addEventListener("pointerdown",k),()=>document.removeEventListener("pointerdown",k)},[P]),ee(()=>{if(!w)return;let k=!0,Z=!1,X=!1,V,Ie,Pe=()=>{ge.current+=1,o.current={...o.current,name:l,receipt:void 0};try{t.setItem(r,JSON.stringify(o.current))}catch{}I(void 0),b(null),C(!1),D("")},ye=()=>{X=!0;let ve=Ke(),we=0,De=async()=>{if(k)try{let $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),C(!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),C(!1)}catch{o.current={...o.current,name:l,receipt:Z},ie({target:k,pulse:++de.current})}finally{R.current=!1,M(!1)}};return Y("div",{ref:oe,"data-devtools":"participant-admission","data-popmelt-font":"sans","data-popmelt-theme":n,style:{display:"contents"},onKeyDown:k=>{k.key==="Escape"&&(C(!1),k.stopPropagation())},children:[S("style",{children:`
2
+ import{a as Jt}from"./chunk-SWTSMLHA.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 Bt,Za as Yt,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-5IEPFMP7.mjs";import{e as ar,N as or,xa as sr,Ba as lr,g as wt}from"./chunk-ENGMQINZ.mjs";import"./chunk-JQHZFDY5.mjs";import{a as je}from"./chunk-MP7S5ALD.mjs";import"./chunk-XOGBFVWI.mjs";import{i as dr,a as cr,h as ur}from"./chunk-MZNY6VXR.mjs";import{g as pr,e as rt,a as ze,d as fr}from"./chunk-2RRYBN2J.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-HGW2U6PD.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 Ar}from"lucide-react";import{jsxs as Y,jsx as S,Fragment as We}from"react/jsx-runtime";var Cr=class extends Error{constructor(){super("The saved draft changed in another runtime. Your local changes are preserved.")}},it=(e,t)=>e.revision===t.revision&&JSON.stringify(e.source)===JSON.stringify(t.source)&&JSON.stringify(e.state)===JSON.stringify(t.state);function Tr(e){let t=structuredClone(e.draft.state??je),r=structuredClone(e.source),i=e.draft.revision,n=0,a=0,s=null,d=!1,o=structuredClone(e.draft),f=null,l=null,u=!1,w=new Set,I=new Set,y=()=>{for(let c of[...I])c()},b={getSnapshot:()=>t,subscribe:c=>(w.add(c),()=>{w.delete(c)}),dispatch:c=>{if(u)throw new Error("Participant runtime is disposed");let p=wt(t,c);if(p!==t){t=p,n++;for(let x of[...w])x();y()}}},g=()=>u?Promise.reject(new Error("Participant runtime is disposed")):l||(s||d?Promise.reject(s??new Error("Draft sync paused")):n===a?Promise.resolve():(l=Promise.resolve().then(async()=>{for(;!u&&!d&&n!==a;){let c=n,p=structuredClone(r),x=structuredClone(t);f={generation:c,draft:{revision:i+1,source:p,state:x}};let A=await e.save(i,p,x);if(!it(A,f.draft))throw new Error("Unexpected saved draft revision; reconnect before writing");i=A.revision,a=c,o=structuredClone(A),f=null}}).catch(c=>{throw s=c instanceof Error?c:new Error(String(c)),s}).finally(()=>{l=null,y()}),l));return{binding:b,flush:g,getStatus:()=>({revision:i,unsaved:n!==a,error:s,disposed:u}),subscribeStatus(c){return I.add(c),()=>{I.delete(c)}},pause(c){d=!0,s=c,y()},async whenSettled(){await l?.catch(()=>{})},reconcile(c){if(u)throw new Error("Participant runtime is disposed");if(l)throw new Error("Wait for the pending save before reconciling");if(!it(c,o)){if(!f||!it(c,f.draft))throw new Cr;i=c.revision,a=f.generation,o=structuredClone(c)}f=null,s=null,d=!1,y()},retry(){return s=null,d=!1,g()},setSource(c){if(u)throw new Error("Participant runtime is disposed");if(c.sourceId!==r.sourceId)throw new Error("Changing source worlds requires a new participant runtime");c.revision!==r.revision&&(r=structuredClone(c),n++,y())},async revoke(){u=!0,d=!0,await l?.catch(()=>{}),t=structuredClone(je),f=null,o={revision:i,source:null,state:null};for(let c of[...w])c();y()},dispose(){u=!0,w.clear(),I.clear()}}}var kt=8192,at=8*1024*1024,jr=256,Fe=100,Ae=(...e)=>JSON.stringify(e),Ve=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Re=e=>structuredClone(e),Or=class extends Error{constructor(){super("This edit predates retained synchronization history"),this.name="PlaneHistoryExpiredError"}},Et=(e,t)=>Pt(e.stamp,t.stamp)||(e.id<t.id?-1:e.id>t.id?1:0);function He(e,t){let r=new Map([...e.checkpoint?.receipts??[],...e.events].map(a=>[a.id,a])),i=[],n=[];for(let a of t){let s=r.get(a.id);if(s){if(!Ve(s,a))throw new Error("Plane event identity was reused");continue}e.checkpoint&&Et(a,e.checkpoint.through)<=0?n.push(a):i.push(a)}return{pending:i,superseded:n}}function Mr(e,t){let r=He(e,t);if(r.superseded.length)throw new Or;return r.pending}function Pt(e,t){return e.time-t.time||e.counter-t.counter||(e.actor<t.actor?-1:e.actor>t.actor?1:0)}function Nr(e,t,r,i){let n=r.reduce((s,d)=>!s||Pt(d.stamp,s)>0?d.stamp:s,t),a=Math.max(Math.floor(i),n?.time??0);return{actor:e,time:a,counter:a===n?.time?n.counter+1:0}}function ot(e){let t=new Map;for(let r of e.annotations){t.set(Ae("annotation",r.id),!0);for(let[i,n]of Object.entries(r))i!=="id"&&n!==void 0&&t.set(Ae("annotation",r.id,i),n)}for(let r of e.styleModifications){let i=Ae(r.pathname??"/",r.selector),{changes:n,...a}=r;t.set(Ae("styleMeta",i),a);for(let s of n)t.set(Ae("style",i,s.property),s)}for(let r of e.textModifications)t.set(Ae("text",Ae(r.pathname??"/",r.selector,JSON.stringify(r.textNodePath))),r);for(let r of e.domModifications)t.set(Ae("dom",r.id),r);for(let r of e.spacingTokenChanges)t.set(Ae("spacing",r.tokenPath),r);for(let r of e.spacingTokenMods)t.set(Ae("spacingMod",r.tokenPath),r);return t}function st(e,t){let r=ot(e),i=ot(t);return[...new Set([...r.keys(),...i.keys()])].filter(n=>!(JSON.parse(n)[0]==="styleMeta"&&!i.has(n))).filter(n=>!Ve(r.get(n),i.get(n))).map(n=>({key:n,...i.has(n)?{value:Re(i.get(n))}:{}}))}function xt(e,t){let r={...t,annotations:[],styleModifications:[],textModifications:[],domModifications:[],spacingTokenChanges:[],spacingTokenMods:[]},i=new Map;for(let[a,s]of e){let[d,o,f]=JSON.parse(a);d==="annotation"&&!f&&s===!0&&i.set(o,{id:o})}let n=new Map;for(let[a,s]of e){let[d,o,f]=JSON.parse(a);if(d==="annotation"&&f&&i.has(o)&&Object.defineProperty(i.get(o),f,{value:s,enumerable:!0,configurable:!0,writable:!0}),d==="style"){let l=n.get(o),u=e.get(Ae("styleMeta",o));if(!u)continue;l||(l={...u,changes:[]},n.set(o,l)),l.changes.push(s)}d==="text"&&r.textModifications.push(s),d==="dom"&&r.domModifications.push(s),d==="spacing"&&r.spacingTokenChanges.push(s),d==="spacingMod"&&r.spacingTokenMods.push(s)}return r.annotations=[...i.values()],r.styleModifications=[...n.values()],r.selectedAnnotationIds=t.selectedAnnotationIds.filter(a=>i.has(a)),r.lastSelectedId=r.selectedAnnotationIds.includes(t.lastSelectedId??"")?t.lastSelectedId:null,r}var At=e=>({annotations:e.annotations,styleModifications:e.styleModifications,textModifications:e.textModifications,domModifications:e.domModifications,spacingTokenChanges:e.spacingTokenChanges,spacingTokenMods:e.spacingTokenMods});function lt(e=je){let t=[...e.undoStack.slice(-Fe),At(e)],r={...Re(e),...Re(t[0]),undoStack:[],redoStack:[]},i=[];for(let s=1;s<t.length;s++){let d=`migration:${s}`;i.push({id:d,stamp:{time:0,counter:s,actor:"migration"},kind:"edit",group:d,changes:st({...r,...t[s-1]},{...r,...t[s]})})}let n=e,a=[];for(let s of[...e.redoStack].reverse().slice(0,Fe)){let d=`migration:${i.length+1}`,o={...r,...s};i.push({id:d,stamp:{time:0,counter:i.length+1,actor:"migration"},kind:"edit",group:d,changes:st(n,o)}),a.push(d),n=o}for(let s of a.reverse()){let d=`migration:${i.length+1}`;i.push({id:d,stamp:{time:0,counter:i.length+1,actor:"migration"},kind:"undo",target:s})}return{version:1,base:r,events:i}}function dt(e){if(!Array.isArray(e)||e.length>kt||JSON.stringify(e).length>at)throw new Error("Plane history exceeds the local session limit");for(let t of e){let r=n=>typeof n=="string"&&n.length>0&&n.length<=256;if(!t||!r(t.id)||!t.stamp||!r(t.stamp.actor)||!Number.isSafeInteger(t.stamp.time)||t.stamp.time<0||!Number.isSafeInteger(t.stamp.counter)||t.stamp.counter<0||!["edit","undo","redo"].includes(t.kind))throw new Error("Invalid plane event");if(t.kind!=="edit"){if(!r(t.target))throw new Error("Invalid history target");continue}if(t.group!==void 0&&!r(t.group)||t.reset!==void 0&&typeof t.reset!="boolean"||!Array.isArray(t.changes)||t.changes.length>1e4)throw new Error("Invalid plane edit");let i=new Set;for(let n of t.changes){if(!n||typeof n.key!="string"||n.key.length>8192)throw new Error("Invalid property key");let a=JSON.parse(n.key);if(!Array.isArray(a)||a.length<2||a.length>3||a.some(s=>typeof s!="string"||!s.length)||!["annotation","style","styleMeta","text","dom","spacing","spacingMod"].includes(a[0])||a[0]==="style"&&a.length!==3||!["style","annotation"].includes(a[0])&&a.length!==2||a[0]==="annotation"&&a.length===2&&n.value!==void 0&&n.value!==!0||i.has(n.key))throw new Error("Invalid property key");i.add(n.key)}}return Re(e)}function ct(e,t){let r=new Map(e.events.map(i=>[i.id,i]));for(let i of Mr(e,t)){let n=r.get(i.id);if(n&&!Ve(n,i))throw new Error("Plane event identity was reused");r.set(i.id,i)}if(r.size>kt)throw new Error("Plane history exceeds the local session limit");return{...e,events:[...r.values()].sort(Et)}}function Rr(e){if(e.version!==1&&e.version!==2)throw new Error("Unsupported plane history version");if(e.version===2&&!e.checkpoint)throw new Error("Missing plane history checkpoint");let t=e.checkpoint,r=t?new Map(Re(t.cells)):ot(e.base),i=new Map(t?.writers??[]),n=Re(t?.undo??[]),a=Re(t?.redo??[]),s=(d,o)=>{let f=[],l=[...d].sort((u,w)=>JSON.parse(u.key).length-JSON.parse(w.key).length);for(let u of l){let[w,I,y]=JSON.parse(u.key);if(w==="styleMeta"&&u.value===void 0)continue;let b=i.get(u.key)??"base";if(u.guard!==void 0&&b!==u.guard||w==="annotation"&&y&&!r.has(Ae(w,I)))continue;let g=r.get(u.key);u.value===void 0?r.delete(u.key):r.set(u.key,u.value);let c=u.restoreWriter??o;if(i.set(u.key,c),f.push({key:u.key,before:g,after:u.value,beforeWriter:b,afterWriter:c}),w==="annotation"&&!y&&u.value===void 0)for(let p of[...r.keys()]){let[x,A]=JSON.parse(p);x===w&&A===I&&(f.push({key:p,before:r.get(p),after:void 0,beforeWriter:i.get(p)??"base",afterWriter:c}),r.delete(p),i.set(p,c))}}return f};for(let d of e.events)if(d.kind==="edit"){let o=s(d.changes,d.group??d.id);if(d.reset&&(n.length=0,a.length=0),!d.group||!o.length)continue;let f=n.find(l=>l.id===d.group);if(f)for(let l of o){let u=f.changes.find(w=>w.key===l.key);u?(u.after=l.after,u.afterWriter=l.afterWriter):f.changes.push(l)}else n.push({id:d.group,writer:d.group,changes:o});a.length=0,n.length>Fe&&n.shift()}else{let o=d.kind==="undo"?n:a,f=d.kind==="undo"?a:n,l=o.findIndex(I=>I.id===d.target);if(l<0)continue;let u=o.splice(l,1)[0],w=s(u.changes.map(I=>({key:I.key,value:I.before,guard:I.afterWriter,restoreWriter:I.beforeWriter})),d.id);w.length&&f.push({id:d.id,writer:d.id,changes:w}),f.length>Fe&&f.shift()}return{cells:r,writers:i,undo:n,redo:a}}function ut(e,t=e.base,r=!0){let{cells:i,writers:n,undo:a,redo:s}=Rr(e),d=xt(i,t);d.styleModifications=d.styleModifications.filter(I=>!e.hostStyleDeletions?.some(y=>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 At(xt(y,t))},l=I=>I.filter(y=>y.changes.some(b=>JSON.parse(b.key)[0]!=="styleMeta"&&(n.get(b.key)??"base")===b.afterWriter&&!Ve(b.before,i.get(b.key)))),u=l(a),w=l(s);return d.undoStack=r?u.map(f):[],d.redoStack=r?w.map(f):[],{state:Re(d),undo:u.map(I=>I.id),redo:w.map(I=>I.id)}}function Lr(e){let t=structuredClone(e.draft.history??lt(e.draft.state??je)),r=He(t,e.pendingEvents??[]);t=ct(t,r.pending);let i=ut(t,{...structuredClone(e.draft.state??je),...e.view}),n=i.state,a=structuredClone(e.source),s=e.draft.revision,d=r.pending,o=structuredClone(e.draft),f=null,l=!!e.persist,u=0,w=0,I=Promise.resolve(),y=!1,b,g,c=null,p=null,x=!1,A=!1,P=new Set,C=new Set,O=()=>{for(let v of[...P])v()},M=()=>{for(let v of[...C])v()},j=()=>{i=ut(t,n),n=i.state},$=()=>{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&&j(),$()},H={getSnapshot:()=>n,getUndoHead:()=>i.undo.at(-1),subscribe(v){return P.add(v),()=>{P.delete(v)}},dispatch(v){if(A)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_TEXT_SIZE","UPDATE_ANNOTATION_COLOR"].includes(v.type);if(D.length){let be=R(),pe=oe||me?!oe&&g&&g===i.undo.at(-1)?g:be:void 0;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),j(),$()}O(),M(),e.saveView?.(n)}},ae=()=>A?Promise.reject(new Error("Participant runtime is disposed")):c||(p||x?Promise.reject(p??new Error("Draft sync paused")):!d.length&&!y&&!w&&!f?Promise.resolve():(c=Promise.resolve().then(async()=>{for(f&&await $(),await q();!A&&!x&&(d.length||y);){await q();let v=structuredClone(d.slice(0,jr)),te=structuredClone(a),z=await e.save(s,te,n,v);if(A)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:A}),subscribeStatus(v){return C.add(v),()=>{C.delete(v)}},pause(v){x=!0,p=v,M()},async whenSettled(){await c?.catch(()=>{}),await q().catch(()=>{})},whenDurable:q,async retryLocalSave(){if(A)throw new Error("Participant runtime is disposed");await $(),await q()},async clearLocalSpace(){if(x=!0,await c?.catch(()=>{}),await q().catch(()=>{}),A)throw new Error("Participant runtime is disposed");l=!1,d=[],y=!1,g=void 0,t=structuredClone(o.history??lt(o.state??je)),i=ut(t,{...structuredClone(je),activeColor:n.activeColor,isAnnotating:n.isAnnotating}),n=i.state,s=o.revision,f=null,p=null,O(),M()},async resumeLocalSaving(){if(!e.persist||A)return!1;l=!0;let v;try{return await Promise.race([$().then(q),new Promise((te,z)=>{v=setTimeout(()=>z(new Error("Local saving timed out")),2e3)})]),!A}catch{return u++,l=!1,w=0,I=Promise.resolve(),f=null,M(),!1}finally{clearTimeout(v)}},reconcile(v){if(A)throw new Error("Participant runtime is disposed");if(c)throw new Error("Wait for the pending save before reconciling");ie(v),p=null,x=!1,O(),M()},receive(v){A||x||c||v.revision<=s||(ie(v),O(),M())},retry(){return x=!1,p=null,ae()},setSource(v){if(v.sourceId!==a.sourceId)throw new Error("Changing source worlds requires a new participant runtime");v.revision===a.revision&&o.source?.revision===v.revision||(a=structuredClone(v),y=!0,M())},async revoke(){A=!0,x=!0,await c?.catch(()=>{}),await q().catch(()=>{}),d=[],t=lt(je),n=structuredClone(je),o={revision:s,source:null,state:null},O(),M()},dispose(){A=!0,P.clear(),C.clear()}}}function Dr(e,t){if(!t.reference.draft.history||t.reference.draft.source&&t.basis.sourceId!==t.reference.draft.source.sourceId)throw new Error("Offline recovery requires a matching shared-history source");if(e&&(e.version!==1||e.reference.author.id!==t.reference.author.id||e.reference.planeId!==t.reference.planeId||e.basis.sourceId!==t.basis.sourceId))throw new Error("Offline recovery belongs to a different plane");let r=e&&e.reference.draft.revision>t.reference.draft.revision?e.reference:t.reference,i=new Map;for(let o of[...dt(e?.pending??[]),...dt(t.pending)]){let f=i.get(o.id);if(f&&JSON.stringify(f)!==JSON.stringify(o))throw new Error("Offline operation identity was reused");i.set(o.id,o)}let n=He(r.draft.history,[...i.values()]),a=new Set(n.pending.map(o=>o.id)),s=e?.pending.some(o=>a.has(o.id)),d={version:1,reference:r,basis:s?e.basis:t.basis,pending:n.pending,...e?.superseded?{superseded:e.superseded}:{}};if(n.superseded.length){let o=n.superseded.slice(-128);for(;o.length&&new TextEncoder().encode(JSON.stringify(o)).length>256*1024;)o.shift();d.superseded={revision:r.draft.revision,events:o,omitted:n.superseded.length-o.length}}if(dt(d.pending),d.superseded&&new TextEncoder().encode(JSON.stringify(d)).length>at&&delete d.superseded,new TextEncoder().encode(JSON.stringify(d)).length>at)throw new Error("Offline recovery storage limit reached; pending work is preserved");return structuredClone(d)}function $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}},Ct=class{constructor(e,t,r,i=(...n)=>fetch(...n)){this.projectId=t,this.transport=i;let n=new URL(e);if(n.protocol!=="http:"||!["localhost","127.0.0.1","[::1]"].includes(n.hostname)||n.username||n.password||n.search||n.hash||n.pathname!=="/")throw new Error("Participant transport requires a local bridge origin");if(!t)throw new Error("Project identity required");this.base=n.origin,this.credential=r?{...r}:void 0}moderateStyles(e,t,r=!1){return this.rpc("moderate-styles",{participantId:e,styleModifications:t,restore:r})}moderateAnnotations(e,t,r=!1,i){return this.rpc("moderate-annotations",{participantId:e,annotationIds:t,restore:r,threadId:i})}async request(e,t,r={},i){let n=t instanceof FormData,a=await this.transport(this.base+e,{method:"POST",redirect:"error",credentials:"omit",signal:i??AbortSignal.timeout(3e4),headers:{...n?{}:{"Content-Type":"application/json"},"X-Popmelt-Project-Id":this.projectId,...this.credential?{"X-Popmelt-Participant-Id":this.credential.participantId,"X-Popmelt-Participant-Token":this.credential.token}:{},...r},body:n?t:JSON.stringify(t)}),s=await a.json().catch(()=>null);if(!a.ok)throw new ke(a.status,typeof s?.error=="string"?s.error:"Participant request failed",typeof s?.code=="string"?s.code:void 0);if(s===null)throw new Error("Invalid participant response");return{data:s,status:a.status}}async rpc(e,t={},r){return(await this.request("/participants/"+e,t,{},r)).data}mountRequestScope(e){if(!this.credential)throw new Error("Join before mounting a canvas");return 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 Ct(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 A;try{A=x.draft.history?Lr({draft:x.draft,source:n,actor:p.runtimeId,view:l,pendingEvents:g?.pending,persist:b?async(h,J,T)=>{await b.update({reference:{...x,draft:h},basis:J,pending:T})}:void 0,saveView:h=>{try{r.setItem(d,JSON.stringify({isAnnotating:h.isAnnotating,activeColor:h.activeColor}))}catch{}},save:(h,J,T,Q)=>a.merge(p,h,J,Q)}):null}catch(h){throw b?.close(),w(),h}let P=A??Tr({draft:x.draft,source:n,save:(h,J,T)=>a.publish(p,h,J,T)}),C=!1,O=!1,M=null,j="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=()=>{C||H||$||j!=="reconnecting"||(H=setTimeout(()=>{H=void 0,oe()},ae),ae=Math.min(ae*2,3e4))},D=h=>{if(!C){if(M=h instanceof Error?h:new Error(String(h)),P.pause(M),M instanceof ke&&M.status===401){j="paused",z=!0,ie++,clearTimeout(H),H=void 0,R();return}j=Xe(M)?"reconnecting":"paused",j==="paused"&&(ie++,clearTimeout(H),H=void 0),L(),R()}},oe=(h=!1)=>{if(C)return Promise.reject(new Error("Participant runtime is closed"));if(q&&!h)return q;if($)return $;let J=++ie,T=()=>!C&&J===ie;return clearTimeout(H),H=void 0,j="reconnecting",P.pause(M??new Error("Reconnecting to the participant session")),R(),$=(async()=>{if(await P.whenSettled(),!T())return;let Q=await a.connect(p.runtimeId,p.token);if(C)return;p=Q;try{r.setItem(s,JSON.stringify(p))}catch(Oe){if(!A?.getStatus().memoryOnly)throw Oe}if(!T())return;let Te=await a.read();T()&&(P.reconcile(Te.draft),await P.flush(),T()&&(M=null,j="connected",ae=1e3,R()))})().catch(Q=>{T()&&D(Q)}).finally(()=>{$=null,L()}),$},me=P.binding.subscribe(()=>{j==="connected"&&P.flush().catch(D)}),be=A?.subscribeStatus(()=>{let h=A.getStatus().localError;h&&h!==M?D(h):R()}),pe,he=setInterval(()=>{if(C||O||j!=="connected")return;O=!0;let h=p,J=P.binding.getSnapshot().activeColor;a.renew(p,J!==pe?J:void 0).then(T=>{!C&&p===h&&(p=T,pe=J,r.setItem(s,JSON.stringify(T)))}).catch(T=>{pe=void 0,!(p!==h||j!=="connected")&&(D(T),T instanceof ke&&T.status===409&&T.code==="runtime_expired"&&oe())}).finally(()=>{O=!1})},4e3),de=!1,se=0,Ee=async h=>{if(C||j!=="connected"||!A||!h)return;let J=ie;if(h.draftRevision>P.getStatus().revision){let T=await a.read();!C&&j==="connected"&&J===ie&&A.receive(T.draft)}},ce=setInterval(()=>{C||de||j!=="connected"||!A||se||(de=!0,a.snapshot().then(async h=>{let J=h.find(T=>T.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,Ce=null,B=!1,Le=setInterval(()=>{if(C||!le||B||j!=="connected")return;let h=le,J=p;B=!0,a.previewWanted(p).then(async({wanted:T})=>{if(!T||le!==h||C||j!=="connected")return;await P.flush();let Q=P.binding.getSnapshot(),Te=P.getStatus().revision,Oe=await h.frame(Jr(Q));Oe&&le===h&&!C&&j==="connected"&&J.token===p.token&&Q===P.binding.getSnapshot()&&await a.publishPreview(p,Oe.image,{draftRevision:Te,targets:Oe.targets})}).catch(T=>{if(!(C||j!=="connected")){if(T instanceof Error&&Xe(T)){D(T);return}le===h&&(Ce=T instanceof Error?T.message:"Preview unavailable",h.stop(),le=null,R())}}).finally(()=>{B=!1})},1e3);c?D(c):g?.pending.length&&P.flush().catch(D);let re;return{client:a,credential:i,navigation:o,state:P,readViewedSuggestions:f.read,markSuggestionViewed:f.mark,markSuggestionsViewed:f.markMany,captureVersion:_,reportAttention(h,J,T,Q){return C||j!=="connected"?Promise.resolve(!1):a.reportAttention(p,h,J,T,Q)},bindSubjects(h){return re=h,()=>{re===h&&(re=void 0)}},getSubjects:()=>re,getStatus:()=>({error:M,phase:j,pendingCount:ge,sending:G,sharing:!!le,previewError:Ce,accessRemoved:z}),reconnect:()=>oe(),retainExternalMembershipPolling(){se++;let h=!1;return()=>{h||(h=!0,se--)}},async retryLocalSave(){if(q)return q;await A?.retryLocalSave(),await oe()},clearLocalSpace(){return q||(C||!A?Promise.reject(new Error("Local space is unavailable")):(q=Promise.resolve().then(async()=>{let h=$;if(ie++,clearTimeout(H),H=void 0,j="paused",P.pause(new Error("Clearing local space")),R(),await h,C)throw new Error("Participant runtime is closed");try{r.setItem(I,"1")}catch{}await A.clearLocalSpace();let J;try{if(await Promise.race([b?.clear?b.clear():Promise.reject(new Error("Local storage cannot be cleared")),new Promise((T,Q)=>{J=setTimeout(()=>Q(new Error("Local clear timed out")),2e3)})]),C)throw new Error("Participant runtime is closed");if(await A.resumeLocalSaving())try{r.removeItem(I)}catch{}}catch{}finally{clearTimeout(J)}if(C)throw new Error("Participant runtime is closed");if(await oe(!0),j!=="connected")throw M??new Error("Session remains unavailable")}).finally(()=>{q=null}),q))},observeMembership(h){if(!(C||h.identity.id!==i.participantId)){if(h.revokedAt!==void 0&&!te){te=!0,D(new ke(403,"Your access was removed by the host")),le?.stop(),le=null,r.removeItem(s),r.removeItem(d),o.clear(),P.revoke().then(()=>b?.clear?.()).then(()=>{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(j==="paused"&&M instanceof ke&&M.status===403&&h.permissionEpoch>v){v=h.permissionEpoch;let J=()=>{!C&&j==="paused"&&v===h.permissionEpoch&&M instanceof ke&&M.status===403&&oe()};$?$.then(J):J()}}}},sharePreview(h){if(C){h?.stop();return}le?.stop(),le=h,Ce=null,h||a.publishPreview(p,null).catch(()=>{}),R()},subscribe:h=>(F.add(h),()=>{F.delete(h)}),async send(h,J){if(C||j!=="connected")throw M??new Error("Participant runtime is closed");if(G)throw new Error("A submission is already in progress");G=!0,R();try{if(P.setSource(n),await P.flush(),j!=="connected")throw M??new Error("Draft sync paused");if(_()!==J)throw new Error("Draft changed during capture; send again to include your latest changes");let T=await a.send(hr(h),P.getStatus().revision,n);return T.status==="pending-approval"?(ge++,R(),{pendingApproval:!0,submissionId:T.submissionId,threadId:T.threadId}):T}finally{G=!1,R()}},dispose(){C||(C=!0,re=void 0,j="closed",clearTimeout(H),clearInterval(he),clearInterval(ce),clearInterval(Le),le?.stop(),le=null,a.publishPreview(p,null).catch(()=>{}),me(),be?.(),w(),P.dispose(),P.whenSettled().finally(()=>b?.close()),F.clear())}}}function _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",Tt=/^[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)||!Tt.test(t))throw new Error("A local page and valid invitation are required");let i=jt(r.href).cleanUrl,n=new URL(i);return n.hash=`${n.hash.slice(1)}${n.hash?"&":""}${ft}=${t}`,n.href}function jt(e){let t=new URL(e),r=null,i=t.hash.slice(1).split("&").filter(n=>{if(!n.startsWith(`${ft}=`))return!0;let a=n.slice(ft.length+1);return Tt.test(a)&&(r=a),!1});return t.hash=i.join("&"),{token:r,cleanUrl:t.href}}function Fr(e){let t={phase:"starting"},r=0,i=!1,n=!1,a=0,s,d=new Set,o=`popmelt-participant:${e.projectId}`,f=new Ct(e.url,e.projectId),l=g=>{if(!n){t=g;for(let c of d)c()}},u=async(g={})=>{let c=await fetch("/__popmelt/host",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify(g),redirect:"error"});if(c.status===403)return null;if(!c.ok)throw new Error(`Host entry unavailable (${c.status}).`);let p=`popmelt-before-participants:${e.projectId}`;return localStorage.getItem(p)===null&&localStorage.setItem(p,JSON.stringify(Object.fromEntries(Object.values(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=jt(location.href),c=new URL(g.cleanUrl),p=new URLSearchParams(c.hash.slice(1)),x=p.get("popmelt-host");p.delete("popmelt-host"),x&&(c.hash=p.toString()),c.href!==location.href&&history.replaceState(history.state,"",c);let A=null;if(x){if(A=await u({token:x}),!A)throw new Error("Host entry expired. Use the current private host link.")}else if(!g.token){try{A=JSON.parse(localStorage.getItem(o)??"null")}catch{}A??(A=await u())}if(!n){if(!A){l({phase:"entry",invitation:g.token??null});return}try{await I(A)}catch(P){if(n)return;if(P.code==="access_removed"){y();return}if(P.status!==401)throw P;let C=await u();C?await I(C):y()}}};return{client:f,getSnapshot:()=>t,subscribe(g){return d.add(g),()=>{d.delete(g)}},retain(){if(n)throw new Error("Participant lifecycle is disposed");r++,i||(i=!0,b().catch(c=>l({phase:"error",message:c.message})));let g=!1;return()=>{g||(g=!0,r--,queueMicrotask(()=>{r||n||(n=!0,a++,s?.dispose(),s=void 0,d.clear())}))}},removed:y,async join(g,c){if(t.phase!=="entry"||!t.invitation||n)throw new Error("No active invitation");if(!c)throw new Error("Peer identity is not ready");let p=a,x=await f.joinOrRequestAdmission(t.invitation,g,c);if(!(n||p!==a)){if("admission"in x){localStorage.setItem(`popmelt-admission:${e.projectId}`,JSON.stringify({name:x.admission.name,receipt:c,colorIdentity:c})),l({phase:"entry",invitation:null});return}await I(x.joined.credential,p)}},admit:g=>I(g)}}function Ke(){let e=crypto.getRandomValues(new Uint8Array(32));return{id:crypto.randomUUID(),token:Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}}var Ue=360,qe=120,Be=180,Ot=260;function Vr({client:e,storage:t,storageKey:r,onAdmitted:i,theme:n="light",themePreference:a=n,onThemePreferenceChange:s,onJoin:d}){let o=K(null),f=K(!1);if(!f.current){f.current=!0;try{o.current=JSON.parse(t.getItem(r)??"null")}catch{}}let[l,u]=U(o.current?.name??""),[w,I]=U(d?void 0:o.current?.receipt),[y,b]=U(null),[g,c]=U(),[p,x]=U(),A=K(null),[P,C]=U(!!d),[O,M]=U(!1),[j,$]=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),Ce=K(()=>{});le.current||(le.current=new Promise(k=>{Ce.current=k}));let B=rt[n],Le=P&&!g;ee(()=>{let k=!1,Z,X,V=()=>{k||(k=!0,_.current=!0,Ce.current())};typeof requestAnimationFrame=="function"&&(Z=requestAnimationFrame(()=>{X=requestAnimationFrame(V)}));let Ie=window.setTimeout(V,64);return()=>{Z!==void 0&&cancelAnimationFrame(Z),X!==void 0&&cancelAnimationFrame(X),window.clearTimeout(Ie),V()}},[]),ee(()=>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(!j)return;let k=setTimeout(()=>$(0),Ue);return()=>clearTimeout(k)},[j]),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"),Be);return()=>clearTimeout(k)},[H]),ee(()=>{o.current&&delete o.current.color;try{let k=JSON.parse(t.getItem(r)??"null");k&&typeof k=="object"&&"color"in k&&(delete k.color,t.setItem(r,JSON.stringify(k)))}catch{}},[t,r]);let re=!!(w&&(!y||y.status==="pending"||y.status==="granted")),h=(k,Z)=>{o.current={...o.current,name:k,receipt:Z},t.setItem(r,JSON.stringify(o.current))};ee(()=>{if(y?.status==="cancelled"){o.current={...o.current,name:l,receipt:void 0};try{t.setItem(r,JSON.stringify(o.current))}catch{}I(void 0),b(null)}},[y,l,t,r]);let J=()=>{if(A.current)return A.current;let k=async()=>{let Z=JSON.parse(t.getItem(r)??"null"),X=Z?.colorIdentity??Z?.receipt??Ke();o.current={name:l,receipt:Z?.receipt,colorIdentity:X},t.setItem(r,JSON.stringify(o.current));let V;try{V=await e.reserveAdmissionColor(X)}catch(Ie){let Pe=Ie.status;if(Pe!==400&&Pe!==401)throw Ie;X=Ke(),o.current={...o.current,colorIdentity:X},t.setItem(r,JSON.stringify(o.current)),V=await e.reserveAdmissionColor(X)}return c(V.color),x(tr(V)),X};return A.current=k().finally(()=>{A.current=null}),A.current},T=()=>{C(!P),P||D("")},Q=K(J);Q.current=J;let Te=!!d;ee(()=>{if(!P||g)return;let k=!1,Z,X=0,V=async()=>{try{await Q.current()}catch{if(k)return;Z=setTimeout(()=>{V()},pt(++X))}};return V(),()=>{k=!0,clearTimeout(Z)}},[P,g,t,r]),ee(()=>{if(!P)return;me.current?.focus();let k=Z=>{Z.composedPath().includes(oe.current)||C(!1)};return document.addEventListener("pointerdown",k),()=>document.removeEventListener("pointerdown",k)},[P]),ee(()=>{if(!w)return;let k=!0,Z=!1,X=!1,V,Ie,Pe=()=>{ge.current+=1,o.current={...o.current,name:l,receipt:void 0};try{t.setItem(r,JSON.stringify(o.current))}catch{}I(void 0),b(null),C(!1),D("")},ye=()=>{X=!0;let ve=Ke(),we=0,De=async()=>{if(k)try{let $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),C(!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),C(!1)}catch{o.current={...o.current,name:l,receipt:Z},ie({target:k,pulse:++de.current})}finally{R.current=!1,M(!1)}};return Y("div",{ref:oe,"data-devtools":"participant-admission","data-popmelt-font":"sans","data-popmelt-theme":n,style:{display:"contents"},onKeyDown:k=>{k.key==="Escape"&&(C(!1),k.stopPropagation())},children:[S("style",{children:`
3
3
  ${Bt}
4
4
  [data-popmelt-admission-ask] {
5
5
  transition: box-shadow 120ms ease, width ${Be}ms ease;
@@ -1,2 +1,2 @@
1
- import{k as n}from"./chunk-O6HC437G.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-3JJP637I.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-AR4MHLWP.mjs";import"./chunk-3LBOX7HQ.mjs";import"./chunk-HTHUSDZT.mjs";import"./chunk-2BVRVVHJ.mjs";import"./chunk-ENGMQINZ.mjs";import"./chunk-JQHZFDY5.mjs";import"./chunk-MP7S5ALD.mjs";import"./chunk-XOGBFVWI.mjs";import"./chunk-2P2NUZW7.mjs";import"./chunk-MZNY6VXR.mjs";import"./chunk-2RRYBN2J.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-HGW2U6PD.mjs";import{createElement as p}from"react";import{createRoot as e}from"react-dom/client";function n(o,t){let r=e(o);return r.render(p(m,t)),()=>{r.unmount(),i()}}export{n as mountBrowserRuntime};
2
+ import{b as m,a as i}from"./chunk-CXTR5UHL.mjs";import"./chunk-3LBOX7HQ.mjs";import"./chunk-HTHUSDZT.mjs";import"./chunk-5IEPFMP7.mjs";import"./chunk-ENGMQINZ.mjs";import"./chunk-JQHZFDY5.mjs";import"./chunk-MP7S5ALD.mjs";import"./chunk-XOGBFVWI.mjs";import"./chunk-2P2NUZW7.mjs";import"./chunk-MZNY6VXR.mjs";import"./chunk-2RRYBN2J.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-HGW2U6PD.mjs";import{createElement as p}from"react";import{createRoot as e}from"react-dom/client";function n(o,t){let r=e(o);return r.render(p(m,t)),()=>{r.unmount(),i()}}export{n as mountBrowserRuntime};
package/dist/browser.mjs CHANGED
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- export{a as isPopmeltPreview}from"./chunk-EX63NVDN.mjs";var m={unmount(){}},u="[data-popmelt-browser-host]";async function p(o={}){if(!o.enabled||typeof document>"u")return m;if(document.querySelector(`${u}, [data-popmelt-top-layer-host]`))throw new Error("Popmelt is already mounted. Unmount it before mounting again.");let e=document.createElement("div");e.setAttribute("data-popmelt-browser-host",""),e.setAttribute("data-devtools",""),document.documentElement.appendChild(e);let d=[["__POPMELT_PROJECT_ID__",o.projectId],["__POPMELT_BRIDGE_URL__",o.bridgeUrl]].flatMap(([t,r])=>{if(r===void 0)return[];let n=Object.prototype.hasOwnProperty.call(window,t),l=window[t],i=r??void 0;return window[t]=i,[()=>{window[t]===i&&(n?window[t]=l:delete window[t])}]}),a=()=>{e.remove();for(let t of d)t()};try{let{mountBrowserRuntime:t}=await import("./browser-runtime-PPQ2GUER.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-7324UU2Y.mjs");if(!e.isConnected)throw new Error("Popmelt mount was removed before startup.");let r=t(e,o),n=!0;return{unmount(){if(n){n=!1;try{r()}finally{a()}}}}}catch(t){throw a(),t}}export{p as mountPopmelt};
@@ -1,4 +1,4 @@
1
- import{c as rr,d as La,e as No,h as ii,i as jo,j as Do}from"./chunk-GL4I4MI6.mjs";function qa(n,e=process.env.POPMELT_EXPERIMENTAL_EVENT_TRANSPORT){let t=n??e??"websocket";if(t==="sse"||t==="websocket")return t;throw new Error("POPMELT_EXPERIMENTAL_EVENT_TRANSPORT must be sse or websocket")}function oi(n){return sp(n).slice(0,12)}var op=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function sp(n){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(n)):ap(n),t=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let m=7;m>=0;m--)e.push(t/Math.pow(2,m*8)&255);let r=1779033703,i=3144134277,o=1013904242,s=2773480762,a=1359893119,c=2600822924,d=528734635,p=1541459225,u=new Array(64);for(let m=0;m<e.length;m+=64){for(let I=0;I<16;I++){let k=m+I*4;u[I]=(e[k]<<24|e[k+1]<<16|e[k+2]<<8|e[k+3])>>>0}for(let I=16;I<64;I++){let k=kt(u[I-15],7)^kt(u[I-15],18)^u[I-15]>>>3,A=kt(u[I-2],17)^kt(u[I-2],19)^u[I-2]>>>10;u[I]=u[I-16]+k+u[I-7]+A>>>0}let h=r,y=i,w=o,b=s,x=a,v=c,T=d,E=p;for(let I=0;I<64;I++){let k=kt(x,6)^kt(x,11)^kt(x,25),A=x&v^~x&T,D=E+k+A+op[I]+u[I]>>>0,U=kt(h,2)^kt(h,13)^kt(h,22),H=h&y^h&w^y&w,V=U+H>>>0;E=T,T=v,v=x,x=b+D>>>0,b=w,w=y,y=h,h=D+V>>>0}r=r+h>>>0,i=i+y>>>0,o=o+w>>>0,s=s+b>>>0,a=a+x>>>0,c=c+v>>>0,d=d+T>>>0,p=p+E>>>0}return[r,i,o,s,a,c,d,p].map(m=>m.toString(16).padStart(8,"0")).join("")}function kt(n,e){return n>>>e|n<<32-e}function ap(n){let e=[];for(let t=0;t<n.length;t++){let r=n.charCodeAt(t);r<128?e.push(r):r<2048?e.push(192|r>>6,128|r&63):e.push(224|r>>12,128|r>>6&63,128|r&63)}return e}var Ja={name:"@popmelt.com/core",version:"0.30.0",description:"A tiny, powerful design layer for humans and AI",license:"PolyForm-Shield-1.0.0",author:"Popmelt <reb@popmelt.com> (https://popmelt.com)",homepage:"https://github.com/popmelt/core",bugs:{url:"https://github.com/popmelt/core/issues"},repository:{type:"git",url:"git+https://github.com/popmelt/core.git"},keywords:["ai","annotations","collaboration","devtools","react","visual-feedback"],bin:{popmelt:"dist/cli.mjs"},sideEffects:!1,packageManager:"pnpm@9.12.0",engines:{node:">=18.0.0"},scripts:{build:"tsup",clean:"git clean -xdf .turbo node_modules dist",format:'prettier --check "**/*.{ts,tsx}"',lint:"eslint . && node scripts/check-eslint-suppressions.mjs","pack:smoke":"node scripts/pack-smoke.mjs","peer:smoke":"node scripts/peer-compat-smoke.mjs","vue:smoke":"pnpm run build && node scripts/vue-install-smoke.mjs","nuxt:smoke":"pnpm run build && node scripts/nuxt-install-smoke.mjs","astro:smoke":"pnpm run build && node scripts/framework-install-smoke.mjs astro","svelte:smoke":"pnpm run build && node scripts/framework-install-smoke.mjs svelte && node scripts/framework-install-smoke.mjs sveltekit",prepublishOnly:"pnpm run verify",test:"vitest run","test:coverage":"vitest run --coverage.enabled","test:browser":"pnpm run build && tsc --noEmit -p tsconfig.browser.json && vitest run --config vitest.browser.config.ts","test:browser:mutation":"node e2e/check-lifecycle-mutation.mjs","test:watch":"vitest",typecheck:"tsc --noEmit --incremental false",verify:"pnpm run typecheck && pnpm run format && pnpm run lint && pnpm run test:coverage && pnpm run build && pnpm run pack:smoke"},exports:{".":{types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./provider":{types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./browser":{types:"./dist/browser.d.mts",import:"./dist/browser.mjs"},"./server":{types:"./dist/server.d.mts",import:"./dist/server.mjs"},"./memory":{types:"./dist/memory.d.mts",import:"./dist/memory.mjs"},"./memory/legacy":{types:"./dist/memory-legacy.d.mts",import:"./dist/memory-legacy.mjs"},"./memory/store":{types:"./dist/memory-store.d.mts",import:"./dist/memory-store.mjs"},"./next":{types:"./dist/plugin-next.d.mts",import:"./dist/plugin-next.mjs",default:"./dist/plugin-next.mjs"},"./vite":{types:"./dist/plugin-vite.d.mts",import:"./dist/plugin-vite.mjs",default:"./dist/plugin-vite.mjs"},"./vite/client":{types:"./dist/vite-client.d.ts"},"./astro":{types:"./dist/plugin-astro.d.mts",import:"./dist/plugin-astro.mjs",default:"./dist/plugin-astro.mjs"},"./nuxt":{types:"./dist/plugin-nuxt.d.mts",import:"./dist/plugin-nuxt.mjs",default:"./dist/plugin-nuxt.mjs"},"./media":{types:"./dist/media.d.mts",import:"./dist/media.mjs"},"./three":{types:"./dist/adapter-three.d.mts",import:"./dist/adapter-three.mjs"},"./react-three-fiber":{types:"./dist/adapter-react-three-fiber.d.mts",import:"./dist/adapter-react-three-fiber.mjs"}},files:["dist","codex-plugin","claude-plugin","LICENSE","README.md","THIRD_PARTY_NOTICES.md"],dependencies:{"modern-screenshot":"4.7.0",ws:"8.21.3"},optionalDependencies:{"@napi-rs/keyring":"2.1.0"},peerDependencies:{nuxt:">=4.5.2 <5","lucide-react":">=1.23.0",next:">=14.0.0",react:">=18.0.0","react-dom":">=18.0.0","@react-three/fiber":">=8.0.0",three:">=0.150.0"},peerDependenciesMeta:{nuxt:{optional:!0},next:{optional:!0},"@react-three/fiber":{optional:!0},three:{optional:!0}},devDependencies:{nuxt:"4.6.3","@kit/eslint-config":"workspace:^","@react-three/fiber":"9.7.0","@tanstack/react-router":"1.120.5","@types/react":"19.1.0","@types/react-dom":"19.1.2","@types/three":"^0.185.4","@types/ws":"8.18.1","@vitejs/plugin-react":"^5.1.1","@vitejs/plugin-vue":"6.0.8","@vitest/coverage-v8":"4.1.12",eslint:"^9.24.0",geist:"1.7.2",jsdom:"26.1.0","lucide-react":"^1.23.0",next:"15.5.28",prettier:"3.5.3",react:"19.1.0","react-dom":"19.1.0",three:"^0.185.1",tsup:"^8.5.1",typescript:"^5.8.3",vite:"7.3.7",vitest:"4.1.12",vue:"3.5.44","vue-router":"5.3.1"},pnpm:{overrides:{"postcss@<8.5.23":"8.5.23","source-map-js@<1.2.2":"1.2.2","esbuild@<0.28.1":"0.28.1","sharp@<0.35.5":"0.35.5"}}};var yn=Ja.version;import{createHash as dp}from"crypto";import{mkdir as lp,open as up,readFile as Ua,readdir as pp,rename as mp,unlink as fp}from"fs/promises";import{dirname as hp,join as wn}from"path";function st(n){return structuredClone(n)}function Ba(n){return dp("sha256").update(JSON.stringify(n)).digest("hex")}async function rn(n,e){await lp(hp(n),{recursive:!0});let t=`${n}.${process.pid}.${Date.now()}.tmp`,r=await up(t,"w");try{await r.writeFile(`${JSON.stringify(e,null,2)}
1
+ import{c as rr,d as La,e as No,h as ii,i as jo,j as Do}from"./chunk-GL4I4MI6.mjs";function qa(n,e=process.env.POPMELT_EXPERIMENTAL_EVENT_TRANSPORT){let t=n??e??"websocket";if(t==="sse"||t==="websocket")return t;throw new Error("POPMELT_EXPERIMENTAL_EVENT_TRANSPORT must be sse or websocket")}function oi(n){return sp(n).slice(0,12)}var op=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function sp(n){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(n)):ap(n),t=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let m=7;m>=0;m--)e.push(t/Math.pow(2,m*8)&255);let r=1779033703,i=3144134277,o=1013904242,s=2773480762,a=1359893119,c=2600822924,d=528734635,p=1541459225,u=new Array(64);for(let m=0;m<e.length;m+=64){for(let I=0;I<16;I++){let k=m+I*4;u[I]=(e[k]<<24|e[k+1]<<16|e[k+2]<<8|e[k+3])>>>0}for(let I=16;I<64;I++){let k=kt(u[I-15],7)^kt(u[I-15],18)^u[I-15]>>>3,A=kt(u[I-2],17)^kt(u[I-2],19)^u[I-2]>>>10;u[I]=u[I-16]+k+u[I-7]+A>>>0}let h=r,y=i,w=o,b=s,x=a,v=c,T=d,E=p;for(let I=0;I<64;I++){let k=kt(x,6)^kt(x,11)^kt(x,25),A=x&v^~x&T,D=E+k+A+op[I]+u[I]>>>0,U=kt(h,2)^kt(h,13)^kt(h,22),H=h&y^h&w^y&w,V=U+H>>>0;E=T,T=v,v=x,x=b+D>>>0,b=w,w=y,y=h,h=D+V>>>0}r=r+h>>>0,i=i+y>>>0,o=o+w>>>0,s=s+b>>>0,a=a+x>>>0,c=c+v>>>0,d=d+T>>>0,p=p+E>>>0}return[r,i,o,s,a,c,d,p].map(m=>m.toString(16).padStart(8,"0")).join("")}function kt(n,e){return n>>>e|n<<32-e}function ap(n){let e=[];for(let t=0;t<n.length;t++){let r=n.charCodeAt(t);r<128?e.push(r):r<2048?e.push(192|r>>6,128|r&63):e.push(224|r>>12,128|r>>6&63,128|r&63)}return e}var Ja={name:"@popmelt.com/core",version:"0.30.1",description:"A tiny, powerful design layer for humans and AI",license:"PolyForm-Shield-1.0.0",author:"Popmelt <reb@popmelt.com> (https://popmelt.com)",homepage:"https://github.com/popmelt/core",bugs:{url:"https://github.com/popmelt/core/issues"},repository:{type:"git",url:"git+https://github.com/popmelt/core.git"},keywords:["ai","annotations","collaboration","devtools","react","visual-feedback"],bin:{popmelt:"dist/cli.mjs"},sideEffects:!1,packageManager:"pnpm@9.12.0",engines:{node:">=18.0.0"},scripts:{build:"tsup",clean:"git clean -xdf .turbo node_modules dist",format:'prettier --check "**/*.{ts,tsx}"',lint:"eslint . && node scripts/check-eslint-suppressions.mjs","pack:smoke":"node scripts/pack-smoke.mjs","peer:smoke":"node scripts/peer-compat-smoke.mjs","vue:smoke":"pnpm run build && node scripts/vue-install-smoke.mjs","nuxt:smoke":"pnpm run build && node scripts/nuxt-install-smoke.mjs","astro:smoke":"pnpm run build && node scripts/framework-install-smoke.mjs astro","svelte:smoke":"pnpm run build && node scripts/framework-install-smoke.mjs svelte && node scripts/framework-install-smoke.mjs sveltekit",prepublishOnly:"pnpm run verify",test:"vitest run","test:coverage":"vitest run --coverage.enabled","test:browser":"pnpm run build && tsc --noEmit -p tsconfig.browser.json && vitest run --config vitest.browser.config.ts","test:browser:mutation":"node e2e/check-lifecycle-mutation.mjs","test:watch":"vitest",typecheck:"tsc --noEmit --incremental false",verify:"pnpm run typecheck && pnpm run format && pnpm run lint && pnpm run test:coverage && pnpm run build && pnpm run pack:smoke"},exports:{".":{types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./provider":{types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./browser":{types:"./dist/browser.d.mts",import:"./dist/browser.mjs"},"./server":{types:"./dist/server.d.mts",import:"./dist/server.mjs"},"./memory":{types:"./dist/memory.d.mts",import:"./dist/memory.mjs"},"./memory/legacy":{types:"./dist/memory-legacy.d.mts",import:"./dist/memory-legacy.mjs"},"./memory/store":{types:"./dist/memory-store.d.mts",import:"./dist/memory-store.mjs"},"./next":{types:"./dist/plugin-next.d.mts",import:"./dist/plugin-next.mjs",default:"./dist/plugin-next.mjs"},"./vite":{types:"./dist/plugin-vite.d.mts",import:"./dist/plugin-vite.mjs",default:"./dist/plugin-vite.mjs"},"./vite/client":{types:"./dist/vite-client.d.ts"},"./astro":{types:"./dist/plugin-astro.d.mts",import:"./dist/plugin-astro.mjs",default:"./dist/plugin-astro.mjs"},"./nuxt":{types:"./dist/plugin-nuxt.d.mts",import:"./dist/plugin-nuxt.mjs",default:"./dist/plugin-nuxt.mjs"},"./media":{types:"./dist/media.d.mts",import:"./dist/media.mjs"},"./three":{types:"./dist/adapter-three.d.mts",import:"./dist/adapter-three.mjs"},"./react-three-fiber":{types:"./dist/adapter-react-three-fiber.d.mts",import:"./dist/adapter-react-three-fiber.mjs"}},files:["dist","codex-plugin","claude-plugin","LICENSE","README.md","THIRD_PARTY_NOTICES.md"],dependencies:{"modern-screenshot":"4.7.0",ws:"8.21.3"},optionalDependencies:{"@napi-rs/keyring":"2.1.0"},peerDependencies:{nuxt:">=4.5.2 <5","lucide-react":">=1.23.0",next:">=14.0.0",react:">=18.0.0","react-dom":">=18.0.0","@react-three/fiber":">=8.0.0",three:">=0.150.0"},peerDependenciesMeta:{nuxt:{optional:!0},next:{optional:!0},"@react-three/fiber":{optional:!0},three:{optional:!0}},devDependencies:{nuxt:"4.6.3","@kit/eslint-config":"workspace:^","@react-three/fiber":"9.7.0","@tanstack/react-router":"1.120.5","@types/react":"19.1.0","@types/react-dom":"19.1.2","@types/three":"^0.185.4","@types/ws":"8.18.1","@vitejs/plugin-react":"^5.1.1","@vitejs/plugin-vue":"6.0.8","@vitest/coverage-v8":"4.1.12",eslint:"^9.24.0",geist:"1.7.2",jsdom:"26.1.0","lucide-react":"^1.23.0",next:"15.5.28",prettier:"3.5.3",react:"19.1.0","react-dom":"19.1.0",three:"^0.185.1",tsup:"^8.5.1",typescript:"^5.8.3",vite:"7.3.7",vitest:"4.1.12",vue:"3.5.44","vue-router":"5.3.1"},pnpm:{overrides:{"postcss@<8.5.23":"8.5.23","source-map-js@<1.2.2":"1.2.2","esbuild@<0.28.1":"0.28.1","sharp@<0.35.5":"0.35.5"}}};var yn=Ja.version;import{createHash as dp}from"crypto";import{mkdir as lp,open as up,readFile as Ua,readdir as pp,rename as mp,unlink as fp}from"fs/promises";import{dirname as hp,join as wn}from"path";function st(n){return structuredClone(n)}function Ba(n){return dp("sha256").update(JSON.stringify(n)).digest("hex")}async function rn(n,e){await lp(hp(n),{recursive:!0});let t=`${n}.${process.pid}.${Date.now()}.tmp`,r=await up(t,"w");try{await r.writeFile(`${JSON.stringify(e,null,2)}
2
2
  `,"utf8"),await r.sync()}finally{await r.close()}try{await mp(t,n)}catch(i){throw await fp(t).catch(()=>{}),i}}function gp(n,e){return{version:1,projectId:n,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function yp(n,e){let t=n.explanations.findIndex(r=>r.id===e.id);t>=0?n.explanations[t]=st(e):n.explanations.push(st(e))}function si(n,e){let t=st(n);for(let r of e)if(r.op==="add_explanation"){if(t.explanations.some(i=>i.id===r.explanation.id))throw new Error(`Imprint explanation already exists: ${r.explanation.id}`);t.explanations.push(st(r.explanation))}else if(r.op==="replace_explanation")yp(t,r.explanation);else if(r.op==="remove_explanation")t.explanations=t.explanations.filter(i=>i.id!==r.explanationId),t.relations=t.relations.filter(i=>i.fromId!==r.explanationId&&(i.toStoreId!==void 0||i.toId!==r.explanationId));else if(r.op==="add_concrete")t.concrete.some(i=>i.id===r.concrete.id)||t.concrete.push(st(r.concrete));else if(r.op==="remove_concrete")t.concrete=t.concrete.filter(i=>i.id!==r.concreteId),t.relations=t.relations.filter(i=>i.fromId!==r.concreteId&&(i.toStoreId!==void 0||i.toId!==r.concreteId));else if(r.op==="add_evidence"){let i=t.explanations.find(o=>o.id===r.explanationId);if(!i)throw new Error(`Unknown imprint explanation: ${r.explanationId}`);i.evidence.some(o=>o.id===r.evidence.id)||(i.evidence.push(st(r.evidence)),i.updatedAt=r.evidence.createdAt)}else if(r.op==="revise_explanation"){let i=t.explanations.find(o=>o.id===r.explanationId);if(!i)throw new Error(`Unknown imprint explanation: ${r.explanationId}`);Object.assign(i,st(r.patch),{updatedAt:r.updatedAt})}else if(r.op==="add_relation"){let i=r.relation,o=t.explanations.find(p=>p.id===i.fromId),s=!!i.toStoreId,a=s?void 0:t.explanations.find(p=>p.id===i.toId),c=t.concrete.some(p=>p.id===i.fromId),d=!s&&t.concrete.some(p=>p.id===i.toId);if(La(i.type)){if(!(i.type==="expresses"?s?!!o:!!((o||c)&&a):!!(o&&(a||s))))throw new Error(`Imprint ${i.type} relation has invalid endpoints: ${i.id}`);if(t.relations.some(u=>u.type===i.type&&u.fromId===i.fromId&&u.toStoreId===i.toStoreId&&u.toId===i.toId))throw new Error(`Duplicate imprint relation: ${i.type}:${i.fromId}:${i.toStoreId??""}:${i.toId}`);if(i.type==="expresses"&&o&&a){if(rr(o,a)<0)throw new Error(`Imprint expresses relation must point from specific to abstract: ${i.id}`);let u=new Map;for(let y of t.relations)y.type!=="expresses"||y.toStoreId||u.set(y.fromId,[...u.get(y.fromId)??[],y.toId]);let m=[i.toId],h=new Set;for(;m.length;){let y=m.pop();if(y===i.fromId)throw new Error(`Imprint expresses relation would create a cycle: ${i.id}`);h.has(y)||(h.add(y),m.push(...u.get(y)??[]))}}}else if(!o||!a&&!d)throw new Error(`Imprint relation references an unknown explanation: ${i.id}`);t.relations.some(p=>p.id===i.id)||t.relations.push(st(i))}else r.op==="remove_relation"&&(t.relations=t.relations.filter(i=>i.id!==r.relationId));return t}function wp(n,e){let t=[],r=st(n);for(let i of e){if(i.op==="add_explanation")t.unshift({op:"remove_explanation",explanationId:i.explanation.id});else if(i.op==="remove_explanation"){let o=r.explanations.find(s=>s.id===i.explanationId);o&&t.unshift({op:"add_explanation",explanation:st(o)})}else if(i.op==="add_concrete")t.unshift({op:"remove_concrete",concreteId:i.concrete.id});else if(i.op==="remove_concrete"){let o=r.concrete.find(s=>s.id===i.concreteId);o&&t.unshift({op:"add_concrete",concrete:st(o)})}else if(i.op==="replace_explanation"||i.op==="revise_explanation"||i.op==="add_evidence"){let o=i.op==="replace_explanation"?i.explanation.id:i.explanationId,s=r.explanations.find(a=>a.id===o);s&&t.unshift({op:"replace_explanation",explanation:st(s)})}else if(i.op==="add_relation")t.unshift({op:"remove_relation",relationId:i.relation.id});else if(i.op==="remove_relation"){let o=r.relations.find(s=>s.id===i.relationId);o&&t.unshift({op:"add_relation",relation:st(o)})}r=si(r,[i])}return t}function za(n){return n.op==="add_explanation"||n.op==="replace_explanation"?[n.explanation.id]:n.op==="remove_explanation"||n.op==="add_evidence"||n.op==="revise_explanation"?[n.explanationId]:n.op==="add_relation"?[n.relation.fromId,...n.relation.toStoreId?[]:[n.relation.toId]]:[]}var ir=class{constructor(e,t){this.projectRoot=e;this.projectId=t;this.writeChain=Promise.resolve();this.imprintDir=wn(e,".popmelt","imprint"),this.manifestPath=wn(this.imprintDir,"manifest.json"),this.graphPath=wn(this.imprintDir,"graph.json"),this.journalDir=wn(this.imprintDir,"journal")}async readHead(){return(await this.readManifest()).head}async readManifest(){try{let e=JSON.parse(await Ua(this.manifestPath,"utf8"));if(e.version!==1||e.projectId!==this.projectId)throw new Error("Imprint manifest does not match this project.");return e}catch(e){if(e.code!=="ENOENT")throw e;let t=new Date().toISOString();return{version:1,projectId:this.projectId,createdAt:t,updatedAt:t,head:{sequence:0,hash:null}}}}async loadRaw(){let e=await this.readManifest(),r=(await pp(this.journalDir).catch(a=>{if(a.code==="ENOENT")return[];throw a})).filter(a=>/^\d{12}-.+\.json$/.test(a)).sort(),i=gp(this.projectId,e.createdAt),o=[],s=null;for(let a=0;a<r.length;a++){let c=JSON.parse(await Ua(wn(this.journalDir,r[a]),"utf8")),{hash:d,...p}=c;if(c.sequence!==a+1||c.previousHash!==s||d!==Ba(p))throw new Error(`Imprint journal hash mismatch at sequence ${c.sequence}.`);i=si(i,c.mutations),i.updatedAt=c.committedAt,i.head={sequence:c.sequence,hash:c.hash},o.push(c),s=c.hash}return{graph:i,transactions:o,recoveredTransactions:Math.max(0,o.length-e.head.sequence)}}async load(){let e=await this.loadRaw();return{...e,graph:No(e.graph)}}async migrateTopology(){let e=await this.readManifest();if(e.topologyVersion===2)return{migrated:!1,relationMutations:0};let t=await this.loadRaw(),r=No(t.graph),i=new Map(r.relations.map(s=>[s.id,s])),o=[];for(let s of t.graph.relations){let a=i.get(s.id);a&&a.type===s.type&&a.fromId===s.fromId&&a.toStoreId===s.toStoreId&&a.toId===s.toId||(o.push({op:"remove_relation",relationId:s.id}),a&&o.push({op:"add_relation",relation:a}))}if(o.length){let s=new Date().toISOString();return await this.commit({transactionId:`topology-v2-${t.graph.head.sequence+1}`,committedAt:s,source:{kind:"migration",threadId:"imprint-topology",jobId:"imprint-topology-v2"},summary:"Simplify Imprint topology to expresses and excepts",mutations:o}),{migrated:!0,relationMutations:o.length}}return await rn(this.graphPath,r),await rn(this.manifestPath,{...e,topologyVersion:2}),{migrated:!0,relationMutations:0}}async commit(e){let t;return this.writeChain=this.writeChain.then(async()=>{let r=await this.load();if(r.transactions.some(u=>u.transactionId===e.transactionId))throw new Error(`Imprint transaction already exists: ${e.transactionId}`);let i=r.graph.head.sequence+1,o=wp(r.graph,e.mutations),s={version:1,sequence:i,transactionId:e.transactionId,projectId:this.projectId,committedAt:e.committedAt,previousHash:r.graph.head.hash,source:e.source,summary:e.summary,mutations:st(e.mutations),inverseMutations:o,...e.undoesTransactionId?{undoesTransactionId:e.undoesTransactionId}:{}},a={...s,hash:Ba(s)},c=si(r.graph,a.mutations);c.updatedAt=e.committedAt,c.head={sequence:i,hash:a.hash};let d=`${String(i).padStart(12,"0")}-${e.transactionId}.json`;await rn(wn(this.journalDir,d),a);let p={version:1,topologyVersion:2,projectId:this.projectId,createdAt:c.createdAt,updatedAt:e.committedAt,head:c.head};await rn(this.graphPath,c),await rn(this.manifestPath,p),t={graph:c,transaction:a}}),await this.writeChain,t}async undo(e,t,r,i){let o=await this.load(),s=o.transactions.find(d=>d.transactionId===e);if(!s)throw new Error("The imprint update is no longer available to undo.");if(o.transactions.some(d=>d.undoesTransactionId===e))throw new Error("This imprint update has already been undone.");let a=new Set(s.mutations.flatMap(za));if(o.transactions.filter(d=>d.sequence>s.sequence).some(d=>d.mutations.some(p=>za(p).some(u=>a.has(u)))))throw new Error("This imprint update has newer dependent changes and cannot be undone cleanly. Edit or challenge the current explanation instead.");return this.commit({transactionId:i,committedAt:r,source:t,summary:`Undo: ${s.summary}`,mutations:s.inverseMutations,undoesTransactionId:e})}async recover(){let e=await this.load();return await rn(this.graphPath,e.graph),await rn(this.manifestPath,{version:1,topologyVersion:2,projectId:this.projectId,createdAt:e.graph.createdAt,updatedAt:e.graph.updatedAt,head:e.graph.head}),{...e,recoveredTransactions:0}}};import{randomUUID as Mt}from"crypto";function ai(n){return[...n.matchAll(/<resolution>\s*([\s\S]*?)(?:<\/resolution>|$)/g)].at(-1)?.[1]?.trim()}function ci(n){return n.replace(/<resolution>[\s\S]*?(?:<\/resolution>|$)/g,"")}var vp=new Set(["application_only","transient_state","concrete_without_model_path","duplicate","insufficient_evidence","task_specific_detail","no_shared_understanding_change"]),bp=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only","consistent","match","matched","matching","mirror","mirrored","mirroring","align","aligned","aligning"]),Ip=[/\bconsistent\s+with\b/i,/\bmatch(?:es|ed|ing)?\b/i,/\bmirror(?:s|ed|ing)?\b/i,/\bthe\s+same\s+as\b/i,/\bborrow(?:s|ed|ing)?\s+from\b/i,/\balign(?:s|ed|ing)?\s+with\b/i,/\b(?:more|look|looks|feel|feels|behave|behaves)\s+like\b/i],xp=/\b(all|any|every|everywhere|across|throughout|globally|project[- ]wide)\b/i;function Lo(n){return!!(n&&xp.test(n))}function Sp(n){return n.scope.kind==="project"||Lo(`${n.statement} ${n.rationale}`)}function kp(n){let e=n?.scope.values.filter(t=>t!=="*").join(", ");return e?`Does applying this understanding here match your intent for ${e}?`:"Does applying this understanding here match your intent?"}function Tp(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Pp(n){return n.length>4&&n.endsWith("ies")?[n,`${n.slice(0,-3)}y`]:n.length>3&&n.endsWith("s")&&!n.endsWith("ss")?[n,n.slice(0,-1)]:[n]}function Rt(n){return new Set(Tp(n).split(" ").filter(e=>e.length>2&&!bp.has(e)).flatMap(Pp))}function Ga(n){return n.replace(/^\s*(?:please\s+)?(?:let(?:'|’)s\s+)?(?:make|apply|use|keep|change|update)\s+/i,"").replace(/[\s,.:;!?]+$/g,"").trim().slice(0,240)}function Ap(n){if(n)for(let e of Ip){let t=e.exec(n);if(!t||t.index<=0)continue;let r=Ga(n.slice(0,t.index)),i=Ga(n.slice(t.index+t[0].length));if(r&&i)return{target:r,reference:i}}}function Jt(n,e){if(!n.size||!e.size)return 0;let t=0;for(let r of n)e.has(r)&&(t+=1);return t/Math.min(n.size,e.size)}function Fo(n){return!n||!Array.isArray(n.values)||n.values.length===0?{kind:"project",values:["*"]}:{kind:n.kind,values:[...new Set(n.values.map(e=>e.trim()).filter(Boolean))]}}function Ut(n,e,t){return{id:Mt(),kind:e==="excepts"?"exception":e==="challenges"?"correction":"observation",stance:e,summary:t,threadId:n.threadId,jobId:n.jobId,createdAt:n.occurredAt??new Date().toISOString()}}function Te(n,e=800){return typeof n=="string"?n.trim().slice(0,e):""}function Ha(n){if(!n||typeof n!="object"||Array.isArray(n))return;let e=n;if(!["project","route","component","selector","file"].includes(String(e.kind))||!Array.isArray(e.values))return;let t=e.values.filter(r=>typeof r=="string"&&!!r.trim());return t.length?{kind:e.kind,values:t}:void 0}function Wa(n,e,t){if(n&&typeof n=="object"&&!Array.isArray(n)){let o=n,s=Te(o.explanationId,100),a=Te(o.clientId,100),c=Te(o.storeId,100);if(s&&a)throw new Error("relation endpoint must use either explanationId or clientId, not both");let d=s||a;return d?{explanationId:d,...c?{storeId:c}:{}}:void 0}let r=Te(e,100),i=Te(t,100);return r?{explanationId:r,...i?{storeId:i}:{}}:void 0}function Va(n,e){if(!n||!e.trim())return{found:!1};let t=n;for(let r of e.split(".").filter(Boolean))if(Array.isArray(t)){let i=Number(r);if(!Number.isInteger(i)||i<0||i>=t.length)return{found:!1};t=t[i]}else if(t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,r))t=t[r];else return{found:!1};return{found:!0,value:t}}function or(n,e={}){let t=[...n.matchAll(/<imprint>([\s\S]*?)<\/imprint>/g)],r=ci(n).replace(/<imprint>[\s\S]*?<\/imprint>/g,"").replace(/<imprint>[\s\S]*$/g,"").trim(),i=t.at(-1)?.[1],o,s=[];if(i)o=i;else{let a=ai(n);if(a===void 0)return{visibleText:r,error:"imprint assessment is missing"};try{let c=JSON.parse(a);if(!c||typeof c!="object"||Array.isArray(c)||!Object.prototype.hasOwnProperty.call(c,"imprint"))return{visibleText:r,error:"imprint assessment is missing"};let d=c;o=d.imprint,s=Array.isArray(d.annotations)?d.annotations:[]}catch{return{visibleText:r,error:"resolution envelope is invalid"}}}try{let a=typeof o=="string"?JSON.parse(o):o;if(!a||typeof a!="object"||Array.isArray(a))throw new Error("imprint assessment is invalid");if(a.decision==="none"){let w=String(a.reason);if(!vp.has(w))throw new Error("imprint no-op reason is invalid");if(w==="task_specific_detail"&&s.some(A=>{if(!A||typeof A!="object"||Array.isArray(A))return!1;let D=A;return(D.finalScope??D.inferredScope)?.breadth==="pattern"}))throw new Error("pattern-scoped resolution cannot be classified as task_specific_detail");let b=Array.isArray(a.usedExplanationIds)?a.usedExplanationIds.filter(A=>typeof A=="string"&&!!A.trim()):[],x=Array.isArray(a.appliedExplanationIds)?a.appliedExplanationIds.filter(A=>typeof A=="string"&&!!A.trim()):[],v=new Set(e.context?.explanations.map(A=>A.id)??[]);if([...new Set([...b,...x])].some(A=>!v.has(A)))throw new Error("imprint use must cite only surfaced explanations");let E=[...new Set([...b,...e.applicationOccurred?[]:x])],I=e.applicationOccurred?x:[],k;if(I.length){k=I;let A=new Set(e.context?.pendingGroundingExplanationIds??[]),D=I.filter(U=>{let H=e.context?.explanations.find(V=>V.id===U);return v.has(U)&&H&&(H.state==="emerging"||H.state==="testing")&&!A.has(U)});if(D.length){let U=a.grounding,H=typeof U?.explanationId=="string"&&D.includes(U.explanationId)?U.explanationId:D[0],V=Te(U?.question,300);return{draft:{decision:"apply",summary:{title:Te(a.summary?.title,120)||"Applied shared understanding",detail:Te(a.summary?.detail,500)||Te(e.requestText||r,500)||"Applied an ungrounded explanation in a new context."},appliedExplanationIds:I,grounding:{explanationId:H,question:V||"Does applying this understanding here match your intent?"}},visibleText:r}}}if(w==="duplicate"){let A=Te(a.duplicateOfExplanationId,100),D=a.scopeComparison;if(!A)throw new Error("duplicate assessment requires duplicateOfExplanationId");if(D!=="equivalent"&&D!=="existing_broader")throw new Error("duplicate assessment requires an equivalent or existing_broader scopeComparison");let U=e.context?.explanations.find(H=>H.id===A);if(!U)throw new Error("duplicate assessment must cite a surfaced explanation");if(Lo(e.requestText)&&!Sp(U))throw new Error("duplicate explanation does not cover the requested broader scope");return{draft:{decision:"none",reason:w,duplicateOfExplanationId:A,scopeComparison:D,...E.length?{usedExplanationIds:E}:{},...k?{appliedExplanationIds:k}:{}},visibleText:r}}return{draft:{decision:"none",reason:w,...E.length?{usedExplanationIds:E}:{},...k?{appliedExplanationIds:k}:{}},visibleText:r}}if(a.decision==="recognize"){let w=Te(a.explanationId,100);if(!w)throw new Error("recognition requires explanationId");let b=e.context?.explanations.find(T=>T.id===w);if(!b)throw new Error("recognition must cite a surfaced explanation");if(b.state!=="grounded")throw new Error("recognition must cite a grounded explanation");let x=a.summary,v={title:Te(x?.title,120),detail:Te(x?.detail,500)};if(!v.title||!v.detail)throw new Error("recognition summary title and detail are required");return{draft:{decision:"recognize",explanationId:w,summary:v},visibleText:r}}if(a.decision==="apply"){let w=a.summary,b={title:Te(w?.title,120),detail:Te(w?.detail,500)};if(!b.title||!b.detail)throw new Error("application summary title and detail are required");let x=Array.isArray(a.appliedExplanationIds)?a.appliedExplanationIds.filter(A=>typeof A=="string"&&!!A.trim()):[];if(!x.length)throw new Error("application requires appliedExplanationIds");let v=new Map(e.context?.explanations.map(A=>[A.id,A])??[]);if(x.some(A=>!v.has(A)))throw new Error("application must cite only surfaced explanations");if(!e.applicationOccurred)return{draft:{decision:"none",reason:"application_only",usedExplanationIds:[...new Set(x)]},visibleText:r};let T=new Set(e.context?.pendingGroundingExplanationIds??[]),E=x.filter(A=>{let D=v.get(A);return D&&(D.state==="emerging"||D.state==="testing")&&!T.has(A)});if(!E.length){if(x.every(D=>v.get(D)?.state==="grounded"||T.has(D)))return{draft:{decision:"none",reason:"application_only",appliedExplanationIds:x},visibleText:r};throw new Error("application must cite a surfaced ungrounded explanation")}let I=a.grounding,k=typeof I?.explanationId=="string"&&E.includes(I.explanationId)?I.explanationId:E[0];return{draft:{decision:"apply",summary:b,appliedExplanationIds:x,grounding:{explanationId:k,question:Te(I?.question,300)||"Does applying this understanding here match your intent?"}},visibleText:r}}if(a.decision!==void 0&&a.decision!=="mutate")throw new Error("imprint decision is invalid");let c=a.summary,d=c?.kind;if(!["added","strengthened","refined","challenged","exception","consolidated"].includes(String(d)))throw new Error("summary.kind is invalid");let p={kind:d,title:Te(c?.title,120),detail:Te(c?.detail,500)};if(!p.title||!p.detail)throw new Error("summary title and detail are required");let u=Array.isArray(a.appliedExplanationIds)?a.appliedExplanationIds.filter(w=>typeof w=="string"&&!!w.trim()):[],m=[];for(let w of Array.isArray(a.mutations)?a.mutations:[]){if(!w||typeof w!="object")continue;let b=w;if(b.op==="add"&&["intention","principle","pattern"].includes(String(b.kind))){let x=Te(b.statement),v=Te(b.rationale);if(!x||!v)continue;m.push({op:"add",clientId:Te(b.clientId,100)||void 0,kind:b.kind,statement:x,rationale:v,scope:Ha(b.scope),rootReason:Te(b.rootReason,300)||void 0})}else if(b.op==="revise"&&typeof b.explanationId=="string"){let x={op:"revise",explanationId:b.explanationId,statement:Te(b.statement)||void 0,rationale:Te(b.rationale)||void 0,scope:Ha(b.scope),reopenGrounding:b.reopenGrounding===!0};(x.statement||x.rationale||x.scope||x.reopenGrounding)&&m.push(x)}else if(b.op==="evidence"&&typeof b.explanationId=="string"&&["supports","challenges","excepts"].includes(String(b.stance))){let x=Te(b.summary);x&&m.push({op:"evidence",explanationId:b.explanationId,stance:b.stance,summary:x})}else if(b.op==="relation"){if(!["expresses","excepts"].includes(String(b.type)))throw new Error("relation type is invalid");let x=Te(b.rationale),v=Wa(b.from,b.fromId,b.fromStoreId),T=Wa(b.to,b.toId,b.toStoreId);if(!x)throw new Error("relation rationale is required");if(!v||!T)throw new Error("relation endpoints require an explanationId or clientId");m.push({op:"relation",type:b.type,from:v,to:T,rationale:x})}else if(b.op==="supersede"&&typeof b.explanationId=="string"&&typeof b.replacementId=="string"){let x=Te(b.reason);x&&m.push({op:"supersede",explanationId:b.explanationId,replacementId:b.replacementId,reason:x})}else if(b.op==="bind_concrete"&&typeof b.explanationId=="string"){let x=Te(b.modelPath,300);x&&m.push({op:"bind_concrete",explanationId:b.explanationId,modelPath:x,rationale:Te(b.rationale)})}else b.op==="retire"&&typeof b.explanationId=="string"&&m.push({op:"retire",explanationId:b.explanationId,reason:Te(b.reason)})}let h=a.grounding,y=h&&typeof h.explanationId=="string"&&Te(h.question)?{explanationId:h.explanationId,question:Te(h.question,300)}:void 0;return{draft:{decision:"mutate",summary:p,appliedExplanationIds:u,mutations:m,grounding:y},visibleText:r}}catch(a){return{visibleText:r,error:a instanceof Error?a.message:String(a)}}}function sr(n,e={}){let t=n?.explanations??[],r=new Set(n?.pendingGroundingExplanationIds??[]),i=new Set(n?.correctionExplanationIds??[]),o=Lo(e.requestText),s=n?.retrievalIntent,a=n?.historicalCaveats??[],c=t.find(m=>m.storeId&&!m.readOnly)?.storeId,d=(m,h)=>{let y=m[h];return y?`[${y.storeId}] ${y.explanationId}`:h==="from"?m.fromId:m.toId},p=!!n?.relations?.some(m=>m.from&&m.to&&m.from.storeId!==m.to.storeId),u=t.some(m=>m.readOnly);return["","## Continuous imprinting","","An imprint is provisional shared understanding learned through human-AI collaboration. It is advisory, not authoritative product truth. Accepted product decisions above always win when they conflict.",...t.length?["","Relevant explanations from the project imprint:",...t.map((m,h)=>[`${h+1}. [${m.state}; ${m.kind}] ${m.statement}`,` - Why: ${m.rationale}`,` - Scope: ${m.scope.kind} ${m.scope.values.join(", ")}`,` - Explanation: ${m.id}`,...m.storeId?[` - Store: ${m.storeId}${m.readOnly?" (read-only)":" (writable primary)"}`]:[],...r.has(m.id)?[" - Grounding: already pending; do not ask again"]:[],...i.has(m.id)?[" - Correction: the developer selected No for this explanation and the current reply supplies the missing correction context"]:[],...m.concrete.map(y=>` - Concrete terminal: ${y.modelPath} = ${JSON.stringify(y.value)}`)].join(`
3
3
  `)),...n?.truncated?["Additional imprint context exists outside this bounded packet."]:[]]:[],...n?.relations?.length?["","Known explanation topology:",...n.relations.map(m=>`- ${m.storeId?`[owned by ${m.storeId}${m.readOnly?"; read-only":""}] `:""}${d(m,"from")} --${m.type}--> ${d(m,"to")}: ${m.rationale}`)]:[],...u||p?["","Store-qualified topology remains locally owned: the relation must originate at an explanation in the writable primary store, while its target may be in a mounted read-only store. Never proxy a relation whose source belongs to a mounted store.",`For a cross-store relation, use qualified endpoints: {"op":"relation","type":"expresses|excepts","from":{"storeId":"${c??"<writable-primary-store>"}","clientId":"<new-specific-client-id>"},"to":{"storeId":"<mounted-target-store>","explanationId":"<existing-abstract-target-id>"},"rationale":"<why>"}. Use clientId for a new explanation created in this transaction and explanationId for an existing durable explanation.`]:[],...s?["","Explicit pattern transfer detected:",`- Target: ${s.target}`,`- Reference: ${s.reference}`,"Before editing, state which dimensions you intend to transfer from the reference and which target-specific behavior you will preserve. Compare the relevant surface, spacing, typography, radius, and interaction behavior; transfer only the dimensions supported by the request and evidence. If the intended transfer remains materially ambiguous after inspecting both anchors, ask one focused question."]:[],...a.length?["","Directly relevant challenged history (historical caveats, not current Imprint truth):",...a.map((m,h)=>[`${h+1}. [challenged; ${m.kind}] ${m.statement}`,` - Why it was previously proposed: ${m.rationale}`,` - Scope: ${m.scope.kind} ${m.scope.values.join(", ")}`,` - Historical explanation: ${m.id}`,...m.storeId?[` - Store: ${m.storeId}${m.readOnly?" (read-only)":" (writable primary)"}`]:[]].join(`
4
4
  `)),"Use these caveats only to avoid repeating a rejected or over-broad transfer. Do not cite them as usedExplanationIds or treat them as active guidance."]:[],...t.some(m=>m.readOnly)?["","Mounted-store explanations are read-only context. They may inform the work and be cited as used understanding, but do not mutate, ground, revise, or add evidence to them without an explicit writable orientation for that store."]:[],...n?.unavailableStoreIds?.length?["",`Some mounted Imprint knowledge was unavailable during this bounded read: ${n.unavailableStoreIds.join(", ")}. Do not infer its contents.`]:[],...n?.unavailableTopologyStoreIds?.length?["",`Some mounted Imprint topology was unavailable during this bounded read: ${n.unavailableTopologyStoreIds.join(", ")}. Available explanations remain usable, but do not infer missing relationships.`]:[],"","Work normally; Imprint is advisory. Testing explanations may guide action as hypotheses. Emerging explanations are observation-only: do not choose behavior from them. Independent human recurrence in a meaningfully different occurrence may promote emerging understanding to testing. Silence, acceptance of finished work, and the model's implementation choices are not confirmation.","Assess learning on every completion: would the human-supported reasoning change a future agent's behavior in a meaningfully different task? The original instruction, scope language, and corrections count as evidence; a separate learning prompt is unnecessary. Default to none, not a mutation for merely finishing work.","Compare behavior and effective scope with applicable surfaced explanations before dismissing a small edit as task-specific. A narrower departure from the same rule can establish an exception even when the developer did not say exception: add one narrow testing explanation linked by excepts. Distinct concepts may be siblings; differing implementations alone do not imply an exception.","Mutation admission requires all six: reusable beyond this edit; novel relative to explanations/evidence; durable intention, rationale, relationship or recurring pattern; atomic at one abstraction level; explicitly scoped; supported by human evidence rather than mere acceptance or AI choices. If any fails, report none. Copy, pixel tweaks, ordering and implementation mechanics alone usually fail; human-directed reusable rationale or applicability boundaries may pass.","Consolidate overlaps: same claim/new observation -> evidence; concrete application -> bind_concrete; emerging/testing scope refinement -> revise; direct rejection -> add replacement + supersede; different abstraction -> related explanation. Duplicate requires the same claim at equivalent or broader conceptual scope, not shared code or a narrower existing claim.","Explicit all/every/across/globally/project-wide language signals broadening. Preserve a grounded narrower claim; add a broader testing claim and link narrower -> broader with expresses. Pattern-scoped resolved annotations cannot use task_specific_detail; capture the change, application, valid duplicate, or another accurate no-op.","Correction context means the developer selected No but the graph has not yet been changed. Distinguish implementation-only, scope, and reasoning corrections. For emerging/testing refinement, revise with reopenGrounding:true; never also challenge the same identity. For rejection, preserve rejected wording and add a replacement + supersede. Do not challenge a whole claim for a narrow correction or recognize an overlapping clause.","Grounded explanations are append-only: compatible evidence is allowed, revision or demotion is not. Changed meaning/rationale/abstraction/applicability needs a new testing explanation. Do not append unrelated implementation facts. Emerging claims cannot alone support durable theory; one-off values are not universal principles.","Every add needs topology or rootReason explaining why no meaningful relative exists. Only expresses (specific -> abstract) and excepts (narrow exception -> rule) are relations. Multiple parents/children are allowed; no expresses cycles. Support/challenge use evidence; correction uses supersede.","Application/recognition require compatibility with the whole statement, scope and exceptions, not one clause. If narrower durable behavior passes admission, add an atomic related explanation; otherwise none.",...e.delivery==="ambient"?[]:['When a surfaced explanation materially informs an answer or action, immediately emit <imprint-use>{"explanationIds":["<used ids>"]}</imprint-use>; emit again only for newly useful IDs.'],"Cite every materially used surfaced ID in usedExplanationIds. Retrieval/reading/consideration alone is not use. Receipts do not strengthen understanding.","appliedExplanationIds is only for completed observable actions that test the explanation, never answer-only, research, advice or read-only work. All applied IDs are also used. For completed ungrounded application report decision apply even without changed wording; a no-op reason cannot suppress it. Grounded use usually means none; decision recognize is only consequential visible reuse/closing a correction loop, with one exact surfaced grounded ID. Never invent IDs.","Ask at most one grounding question, only for an applied ungrounded explanation with genuinely new evidence and no grounding already pending. The bridge can supply a fallback. Never claim a new explanation is grounded.",e.delivery==="ambient"?"Do not print a machine-readable resolution envelope in the visible response. When this collaboration changes reusable shared understanding, call `popmelt_assess_turn` before the final response.":'After normal prose emit exactly one hidden <resolution>{"annotations":[...],"imprint":{...}}</resolution>. imprint is required even for none; never emit a separate <imprint> block.',"Fields below are schemas: choose one decision and only the necessary operations, not every alternative.",...o?["CURRENT SCOPE SIGNAL: The developer used explicit broadening language in this instruction. Do not classify it as duplicate unless the cited existing explanation already expresses universal or project-wide applicability."]:[],"For no learning, include:",'"imprint":{"decision":"none","reason":"application_only|transient_state|concrete_without_model_path|duplicate|insufficient_evidence|task_specific_detail|no_shared_understanding_change","usedExplanationIds":["<every surfaced explanation that was actively useful, or omit when none>"]}',"A no-op reason cannot suppress genuine application evidence. When a completed action was governed by an ungrounded explanation, report decision apply directly so the summary and grounding question are intentional. Answering a question with that explanation is usage, not application.","When and only when reason is duplicate, also include `duplicateOfExplanationId` naming one surfaced explanation and `scopeComparison` set to `equivalent` or `existing_broader`. The bridge rejects uncited duplicates and duplicates whose cited explanation cannot cover explicit broadening language.","For application evidence without a conceptual change, include:",'"imprint":{"decision":"apply","summary":{"title":"<short expandable-summary title>","detail":"<how the explanation influenced this completed action>"},"appliedExplanationIds":["<surfaced emerging or testing explanation id>"],"grounding":{"explanationId":"<one applied id>","question":"<brief post-application confirmation question>"}}',"For a consequential, non-mutating reuse of grounded understanding that should be visible, include:",'"imprint":{"decision":"recognize","explanationId":"<one exact surfaced grounded explanation id>","summary":{"title":"<short name for the recognized understanding>","detail":"<how it guided this outcome>"}}',"Or, only after every admission test passes for a conceptual change:",'"imprint":{"decision":"mutate","summary":{"kind":"added|strengthened|refined|challenged|exception|consolidated","title":"<short expandable-summary title>","detail":"<what changed in shared understanding>"},"appliedExplanationIds":["<only an ungrounded explanation materially tested here>"],"mutations":[{"op":"add","clientId":"new-1","kind":"intention|principle|pattern","statement":"<one durable atomic explanation>","rationale":"<why the evidence supports it>","scope":{"kind":"project|route|component|selector|file","values":["<scope>"]},"rootReason":"<only when this is genuinely unrelated to every surfaced or new explanation>"},{"op":"revise","explanationId":"<only an emerging or testing id>","statement":"<optional>","rationale":"<optional>","scope":{"kind":"component","values":["CardTile"]},"reopenGrounding":false},{"op":"evidence","explanationId":"<id>","stance":"supports|challenges|excepts","summary":"<thread evidence>"},{"op":"relation","type":"expresses|excepts","from":{"clientId":"<new-specific-client-id>"},"to":{"explanationId":"<existing-abstract-id>"},"rationale":"<why; use clientId for new transaction-local explanations and explanationId for existing durable explanations>"},{"op":"supersede","explanationId":"<contradicted old id>","replacementId":"<new clientId or existing id>","reason":"<direct conflict>"},{"op":"bind_concrete","explanationId":"<id or clientId>","modelPath":"<exact existing model path>","rationale":"<how this fact expresses the explanation>"},{"op":"retire","explanationId":"<id>","reason":"<why>"}],"grounding":{"explanationId":"<one applied ungrounded id or clientId>","question":"<brief post-application confirmation question>"}}',e.delivery==="ambient"?'Pass the complete `<resolution>{"annotations":[...],"imprint":{...}}</resolution>` shape as `assessmentText` to `popmelt_assess_turn`; do not include it in conversational prose.':'The final shape is `<resolution>{"annotations":[...],"imprint":{...}}</resolution>`. The `imprint` field is required even when the decision is none; omission leaves the completed run explicitly unassessed.',"Include only necessary mutations. For a new explanation established through completed action, include its clientId in appliedExplanationIds. Grounded use requires usedExplanationIds; include appliedExplanationIds only for completed observable application, never answer-only use. Never claim new understanding is grounded."].join(`