@fork-api/chat-sdk 0.1.184 → 0.1.185
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/dist/index.cjs +7 -7
- package/dist/index.d.cts +3 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +7 -7
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
'use strict';var ar=require('react'),Vs=require('react-dom'),Xs=require('react/jsx-runtime'),qs=require('react/jsx-dev-runtime'),lucideReact=require('lucide-react');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var ar__namespace=/*#__PURE__*/_interopNamespace(ar);var Vs__namespace=/*#__PURE__*/_interopNamespace(Vs);var Xs__namespace=/*#__PURE__*/_interopNamespace(Xs);var qs__namespace=/*#__PURE__*/_interopNamespace(qs);var wt="__FORK_SHARED__";function Zn(){var t,n,r,o;let e=globalThis;return e[wt]||(e[wt]={}),(t=e[wt]).react||(t.react=ar__namespace),(n=e[wt])["react-dom"]||(n["react-dom"]=Vs__namespace),(r=e[wt])["react/jsx-runtime"]||(r["react/jsx-runtime"]=Xs__namespace),(o=e[wt])["react/jsx-dev-runtime"]||(o["react/jsx-dev-runtime"]=qs__namespace),e[wt]}function Qn(e){return Object.assign(Zn(),e)}var go=false,er=null,tr=null;function mo(e,t,n){go=e,er=t,tr=n;}function ue(){if(!go)return {};let e={};return er&&(e["X-Fork-App-Id"]=er),tr&&(e["X-Fork-Container-Id"]=tr),e}async function nr(e){let t=new URLSearchParams({app:e.appId,user:e.userId});e.containerId&&t.set("containerId",e.containerId);let n=`${e.baseUrl}/api/v1/manifest?${t.toString()}`,r={Authorization:`Bearer ${e.apiKey}`,"X-Fork-App-Id":e.appId,"X-Fork-User-Id":e.userId,...e.extraHeaders??{}};e.userHash&&(r["X-Fork-User-Hash"]=e.userHash),e.userJwt&&(r["X-Fork-User-Jwt"]=e.userJwt),e.previous?.etag&&(r["If-None-Match"]=e.previous.etag);let o=await fetch(n,{headers:r,signal:e.signal});if(o.status===304)return null;if(!o.ok)throw new Error(`manifest ${o.status} ${o.statusText}`);let i=await o.json(),a={};for(let[l,u]of Object.entries(i.modules)){let w=u.moduleUrl??u.bundleUrl??null,A=u.legacyModuleUrl??u.legacyBundleUrl??null;a[l]={forkId:u.forkId,moduleUrl:w,legacyModuleUrl:A,bundleUrl:u.bundleUrl??w,legacyBundleUrl:u.legacyBundleUrl??A,cssUrls:u.cssUrls??[],integrity:u.integrity,metadata:u.metadata,highlightHint:u.highlightHint,buildId:u.buildId,updatedAt:u.updatedAt};}return {containerId:i.containerId,forksPaused:!!i.forksPaused,slots:i.slots,modules:a,generatedAt:i.generatedAt,etag:o.headers.get("ETag")??void 0}}var Gs="fork:manifest:v1";function rr(e,t,n){return `${Gs}:${e}:${t}:${n}`}function Ys(e,t,n){if(typeof window>"u")return null;try{let r=window.localStorage.getItem(rr(e,t,n));return r?JSON.parse(r):null}catch{return null}}function Zs(e,t,n,r){if(!(typeof window>"u"))try{window.localStorage.setItem(rr(e,t,n),JSON.stringify(r));}catch{}}function Qs(e,t,n){if(!(typeof window>"u"))try{window.localStorage.removeItem(rr(e,t,n));}catch{}}function ei(e,t){if(!e||!t)return e!==t;if(e.containerId!==t.containerId||!!e.forksPaused!=!!t.forksPaused)return true;let n=Object.entries(e.slots),r=Object.entries(t.slots);if(n.length!==r.length)return true;for(let[a,l]of n){let u=t.slots[a];if(!u||u.forkId!==l.forkId||u.buildId!==l.buildId)return true}let o=Object.entries(e.modules),i=Object.entries(t.modules);if(o.length!==i.length)return true;for(let[a,l]of o){let u=t.modules[a];if(!u||u.forkId!==l.forkId||u.buildId!==l.buildId)return true}return false}var En={isAdmin:false,actingUserId:null,containerId:null,containerName:null,containers:[]},ko=ar.createContext(null),ri=12e3,oi=45e3,ho="fork:activity:v1",si=new Set(["pending","running","building"]),ii="Setting up environment";function je(e){return si.has(e)}function ai(e,t){return t?.targetId?t:e.boundaryId?{targetKind:"module",targetId:e.boundaryId}:e.slotId?{targetKind:"slot",targetId:e.slotId}:null}function li(e,t){let n=ai(e,t);if(!n)return null;let r=new Date().toISOString();return {id:e.id,status:e.status,targetKind:n.targetKind,targetId:n.targetId,summary:e.summary??null,estimateMinutes:e.estimateMinutes??null,createdAt:e.createdAt||r,updatedAt:e.completedAt||r,completedAt:e.completedAt??null}}function yo(e){return {id:e.id,status:e.status,targetKind:e.targetKind,targetId:e.targetId,summary:e.summary??null,estimateMinutes:e.estimateMinutes??null,promptCount:e.promptCount,messageCount:e.messageCount,isActive:e.isActive,createdAt:e.createdAt,updatedAt:e.updatedAt,completedAt:e.completedAt??null}}function In(e,t){let n=typeof t.summary=="string"&&t.summary.trim()?t.summary.trim():void 0,r=typeof e?.summary=="string"&&e.summary.trim()?e.summary.trim():void 0,o=typeof t.estimateMinutes=="number"&&Number.isFinite(t.estimateMinutes)?t.estimateMinutes:void 0,i=typeof e?.estimateMinutes=="number"&&Number.isFinite(e.estimateMinutes)?e.estimateMinutes:void 0;return {...e,...t,summary:n??r??null,estimateMinutes:o??i??null,latestMessage:t.latestMessage??e?.latestMessage??null,unread:t.unread??e?.unread??false}}function Zt(e){return `${e.id}:${e.completedAt||e.updatedAt}`}function St(e){if(typeof window>"u")return new Set;try{let t=window.localStorage.getItem(e);if(!t)return new Set;let n=JSON.parse(t);return Array.isArray(n)?new Set(n.filter(r=>typeof r=="string")):new Set}catch{return new Set}}function xt(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify([...t].slice(-200)));}catch{}}function ci(e){if(e.estimateMinutes)return `~${e.estimateMinutes}m`}function di(e){let t=e.data&&typeof e.data=="object"?e.data:{};if(e.type==="status"){let n=typeof t.status=="string"?t.status:"running",r=typeof t.summary=="string"?t.summary:void 0;return {status:n,latestMessage:je(n)?"Building":void 0,summary:r,estimateMinutes:typeof t.estimateMinutes=="number"?t.estimateMinutes:void 0,updatedAt:e.timestamp}}return e.type==="tool_use"?{status:"running",latestMessage:"Building",updatedAt:e.timestamp}:e.type==="build_start"?{status:"building",latestMessage:"Building",updatedAt:e.timestamp}:e.type==="build_complete"?{status:"building",latestMessage:"Building",updatedAt:e.timestamp}:e.type==="complete"?{status:"complete",summary:typeof t.summary=="string"?t.summary:void 0,estimateMinutes:typeof t.estimateMinutes=="number"?t.estimateMinutes:void 0,latestMessage:"Fork ready",completedAt:e.timestamp,updatedAt:e.timestamp}:e.type==="error"||e.type==="build_error"?{status:"error",latestMessage:typeof t.error=="string"?t.error:typeof t.message=="string"?t.message:"Fork failed",updatedAt:e.timestamp}:{updatedAt:e.timestamp}}function ui(e){let t=e.filter(o=>je(o.status)),n=e.filter(o=>o.status==="complete"&&o.unread),r=[...e].sort((o,i)=>Date.parse(i.updatedAt)-Date.parse(o.updatedAt))[0]??null;if(t.length>1)return {state:"running",label:`${t.length} forks running`,count:t.length,runningCount:t.length,unreadCompletedCount:n.length,latest:t[0]};if(t.length===1){let o=t[0],i=!!(typeof o.summary=="string"&&o.summary.trim());return {state:"running",label:i?o.summary.trim():ii,detail:i?ci(o):void 0,count:1,runningCount:1,unreadCompletedCount:n.length,latest:o}}if(n.length>1)return {state:"complete",label:`${n.length} forks ready`,count:n.length,runningCount:0,unreadCompletedCount:n.length,latest:n[0]};if(n.length===1){let o=n[0];return {state:"complete",label:o.summary||"Fork ready",count:1,runningCount:0,unreadCompletedCount:1,latest:o}}return {state:r?.status==="error"?"error":"idle",label:"Fork",count:0,runningCount:0,unreadCompletedCount:0,latest:r}}function or(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function fi(e,t,n,r){let o={};for(let[i,a]of Object.entries(t.slots)){let l=a.bundleUrl??a.legacyBundleUrl;l&&(o[i]={id:a.forkId,userId:n,prompt:"",status:"complete",slotId:i,appId:r,bundleUrl:or(e,l),revealPending:a.revealPending===true,createdAt:a.updatedAt,completedAt:a.updatedAt});}return o}function pi(e,t){let n={};for(let[r,o]of Object.entries(t.modules)){let i=o.moduleUrl??o.legacyModuleUrl??o.bundleUrl??"";i&&(n[r]={id:o.forkId,boundaryId:r,moduleUrl:or(e,i),cssUrls:(o.cssUrls??[]).map(a=>or(e,a)),integrity:o.integrity,metadata:o.metadata,highlightHint:o.highlightHint,createdAt:o.updatedAt});}return n}function gi(e){let{apiKey:t,baseUrl:n,children:r,appId:o,shared:i}=e,a="userId"in e?e.userId:void 0,l="userHash"in e?e.userHash:void 0,u="userJwt"in e?e.userJwt:void 0,w="authUrl"in e?e.authUrl:void 0,[A,b]=ar.useState({}),[E,U]=ar.useState(a?{userId:a,userHash:l,userJwt:u}:null),[R,p]=ar.useState(!!a),[f,T]=ar.useState(En),[x,k]=ar.useState(false),[L,N]=ar.useState(false),[K,_]=ar.useState({}),[H,j]=ar.useState(!o),[W,M]=ar.useState(0),[S,O]=ar.useState(null),[V,q]=ar.useState(false),[Q,Z]=ar.useState([]),[ee,fe]=ar.useState(()=>typeof document>"u"?true:document.visibilityState!=="hidden"),de=ar.useRef(new Map),oe=ar.useRef(new Map),[me,te]=ar.useState(0),pe=ar.useRef(new Set),d=ar.useRef(new Map),I=ar.useRef(void 0),h=ar.useRef(new Map),c=ar.useRef([]),g=ar.useRef(new Set),$=ar.useRef(false);Zn(),ar.useEffect(()=>{if(!o||!E?.userId||!(E.userHash||E.userJwt)){T(En),k(true);return}let m=false;k(false);let F=new URLSearchParams({app:o});return fetch(`${n}/api/v1/admin/containers?${F.toString()}`,{headers:{Authorization:`Bearer ${t}`,"X-Fork-App-Id":o,"X-Fork-User-Id":E.userId,...E.userHash?{"X-Fork-User-Hash":E.userHash}:{},...E.userJwt?{"X-Fork-User-Jwt":E.userJwt}:{}}}).then(async P=>P.status===403||!P.ok?null:P.json()).then(P=>{if(m)return;if(!P){T(En),k(true);return}let G=Array.isArray(P.containers)?P.containers:[],ie=P.currentContainerId??null,ae=G.find(ce=>ce.id===ie)?.name??null;T({isAdmin:true,actingUserId:typeof P.actingUserId=="string"?P.actingUserId:null,containerId:ie,containerName:ae,containers:G}),k(true);}).catch(()=>{m||(T(En),k(true));}),()=>{m=true;}},[t,o,E?.userHash,E?.userJwt,E?.userId,n]),ar.useEffect(()=>{mo(f.isAdmin,o??null,f.containerId);},[f.isAdmin,f.containerId,o]);let B=ar.useCallback((m,F)=>{T(P=>{if(!P.isAdmin)return P;let G=P.containers.find(ce=>ce.id===m),ie=F??G?.name??null,ae=G?P.containers.map(ce=>({...ce,isPrimary:ce.id===m})):[{id:m,name:ie??"New container",isPrimary:true,forkCount:0},...P.containers.map(ce=>({...ce,isPrimary:false}))];return {...P,containerId:m,containerName:ie,containers:ae}}),N(false);},[]);i&&I.current!==i&&(Qn(i),I.current=i),ar.useEffect(()=>{w&&(p(false),fetch(w,{credentials:"include"}).then(m=>{if(!m.ok)throw new Error(`Auth endpoint returned ${m.status}`);return m.json()}).then(m=>{if(!m.userId||typeof m.userId!="string")throw new Error("authUrl response must include userId");U({userId:m.userId,userHash:typeof m.userHash=="string"?m.userHash:void 0,userJwt:typeof m.userJwt=="string"?m.userJwt:void 0});}).catch(m=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",m.message);}).finally(()=>{p(true);}));},[w]),ar.useEffect(()=>{!w&&a&&(U({userId:a,userHash:l,userJwt:u}),p(true));},[a,l,u,w]);let D=E?.userId??"",Y=E?.userHash,ft=E?.userJwt,ve=!!o,Pe=ar.useCallback(async()=>{if(!ve){O(null),q(false),_({}),j(true),M(F=>F+1);return}if(!R){j(false);return}if(!D||!o){O(null),q(false),b({}),_({}),j(true),M(F=>F+1);return}j(false);let m=f.isAdmin?f.containerId:null;if(f.isAdmin&&L){q(true),b({}),_({}),M(F=>F+1),j(true);return}try{let F=await nr({baseUrl:n,apiKey:t,appId:o,userId:D,userHash:Y,userJwt:ft,containerId:m??void 0});F&&(O(F.containerId),q(f.isAdmin?!1:!!F.forksPaused),b(fi(n,F,D,o)),_(pi(n,F)));}catch(F){console.error("[ForkProvider] Failed to fetch fork manifest:",F.message),O(null),q(false),b({}),_({});}finally{M(F=>F+1),j(true);}},[t,o,n,R,ve,Y,ft,D,f.isAdmin,f.containerId,L]);ar.useEffect(()=>{if(!D||o)return;let m=new URLSearchParams({userId:D});Y&&m.set("userHash",Y),fetch(`${n}/api/v1/forks/active?${m.toString()}`,{headers:{Authorization:`Bearer ${t}`,...ue()}}).then(F=>{if(!F.ok)throw new Error(`${F.status}`);return F.json()}).then(F=>{F&&typeof F=="object"&&b(F);}).catch(()=>{});},[t,o,D,Y,n]),ar.useEffect(()=>{Pe();},[Pe]);let gn=ar.useCallback(async m=>{if(o){if(f.isAdmin){N(m),q(m),m?(b({}),_({}),M(F=>F+1)):await Pe();return}if(D){q(m),m&&(b({}),_({}),M(F=>F+1));try{let F=await fetch(`${n}/api/v1/containers/primary/paused`,{method:"PUT",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json","X-Fork-App-Id":o},body:JSON.stringify({appId:o,paused:m,userId:D,userHash:Y})});if(!F.ok)throw new Error(`${F.status}`);m||await Pe();}catch(F){console.error("[ForkProvider] Failed to persist fork pause state:",F?.message??F),Pe().catch(()=>{});}}}},[t,o,n,Pe,f.isAdmin,Y,D]),Ie=ar.useCallback((m,F)=>{b(P=>({...P,[m]:F}));},[]),mn=ar.useCallback(m=>{b(F=>{let P={...F};return delete P[m],P});},[]),rt=ar.useCallback(m=>{pe.current.add(m);},[]),pt=ar.useCallback(m=>pe.current.has(m)?(pe.current.delete(m),true):false,[]),gt=ar.useCallback(m=>{if(m.slotId&&b(P=>{let G=P[m.slotId];return !G||G.id!==m.id||!G.revealPending?P:{...P,[m.slotId]:{...G,revealPending:false}}}),f.isAdmin||!D)return;let F={Authorization:`Bearer ${t}`,"Content-Type":"application/json","X-Fork-User-Id":D};Y&&(F["X-Fork-User-Hash"]=Y),fetch(`${n}/api/v1/forks/reveals`,{method:"POST",headers:F,body:JSON.stringify({forkId:m.id,userId:D,userHash:Y})}).catch(()=>{});},[t,n,f.isAdmin,Y,D]),ot=ar.useCallback((m,F)=>{d.current.set(m,F);},[]),mt=ar.useCallback((m,F)=>d.current.get(m)!==F?false:(d.current.delete(m),true),[]),$e=ar.useCallback(m=>{if(!o)return;let F=JSON.stringify(m);de.current.get(m.id)===F||oe.current.get(m.id)?.signature===F||(oe.current.set(m.id,{boundary:m,signature:F}),te(G=>G+1));},[o]);ar.useEffect(()=>{if(!o||oe.current.size===0)return;let m=setTimeout(()=>{let F=Array.from(oe.current.values());F.length!==0&&fetch(`${n}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:o,boundaries:F.map(P=>P.boundary)})}).then(P=>{if(!P.ok)throw new Error(`${P.status}`)}).then(()=>{for(let P of F)oe.current.get(P.boundary.id)?.signature===P.signature&&(oe.current.delete(P.boundary.id),de.current.set(P.boundary.id,P.signature));}).catch(P=>{console.error("[ForkProvider] Failed to register module boundaries:",P.message);});},50);return ()=>{clearTimeout(m);}},[t,o,n,me]);let Kt=ar.useCallback(m=>K[m],[K]),Ge=f.isAdmin?`admin:${f.actingUserId??"op"}`:D,Wt=`${t}:${o||"no-app"}:${S||"no-container"}:${Ge||"anonymous"}`,It=f.isAdmin?`op:${f.actingUserId??"op"}`:D,Ct=`${t}:${o||"no-app"}:${It||"anonymous"}`,Ne=`${ho}:seen:${Wt}`,we=`${ho}:tracked:${Wt}`;ar.useEffect(()=>{c.current=Q;},[Q]);let Je=ar.useCallback(()=>{let m={Authorization:`Bearer ${t}`,...ue()};return o&&(m["X-Fork-App-Id"]=o),D&&(m["X-Fork-User-Id"]=D),Y&&(m["X-Fork-User-Hash"]=Y),m},[t,o,Y,D]);ar.useEffect(()=>{if(typeof window>"u")return;let m=window.__FORK_RUNTIME__,F={dataFetch:async(P,G,ie="POST")=>{if(!o||!S)throw new Error("Fork data is unavailable until appId and containerId are resolved");let ae=typeof P=="string"&&P.startsWith("/")?P:`/${String(P||"")}`,ce=ae.startsWith("/api/v1/data")?ae:`/api/v1/data${ae}`,Se=ie.toUpperCase(),Te=new URL(`${n}${ce}`),le={Authorization:`Bearer ${t}`,"Content-Type":"application/json","X-Fork-App-Id":o,...ue()};D&&(le["X-Fork-User-Id"]=D),Y&&(le["X-Fork-User-Hash"]=Y);let he={method:Se,headers:le};Se==="GET"?(Te.searchParams.set("appId",o),Te.searchParams.set("containerId",S)):he.body=JSON.stringify({appId:o,containerId:S,...G&&typeof G=="object"?G:{}});let ye=await fetch(Te.toString(),he),ke=await ye.json().catch(()=>({}));if(!ye.ok)throw new Error(typeof ke?.error=="string"?ke.error:`Fork data API ${ye.status}`);return ke}};return window.__FORK_RUNTIME__=F,()=>{window.__FORK_RUNTIME__===F&&(window.__FORK_RUNTIME__=m);}},[t,o,n,S,Y,D]);let Ve=ar.useCallback(async()=>{if(!S||!x)return;let m=new URLSearchParams({container_id:S}),F=await fetch(`${n}/api/v1/forks?${m.toString()}`,{headers:Je()}).catch(()=>null);if(!F||!F.ok)return;let P=await F.json().catch(()=>({})),G=Array.isArray(P.forks)?P.forks:[],ie=St(Ne),ae=St(we),ce=false,Se=new Map(c.current.map(le=>[le.id,le])),Te=[];for(let le of G){let he=yo(le);je(he.status)&&!ae.has(he.id)&&(ae.add(he.id),ce=true);let ye=Se.get(he.id),ke=ye?je(ye.status):false,_e=Zt(he);he.status==="complete"&&(ae.has(he.id)||ke)&&!ie.has(_e)&&!g.current.has(_e)&&!ye?.unread&&($.current||ae.has(he.id)||ke)&&(g.current.add(_e),Te.push(he));}if(Z(le=>{let he=new Map(le.map(xe=>[xe.id,xe])),ye=new Set,ke=new Map;for(let xe of G){let Fe=yo(xe);ye.add(Fe.id);let Be=he.get(Fe.id),De=Be?je(Be.status):false,$t=Zt(Fe),st=Fe.status==="complete"&&(ae.has(Fe.id)||De)&&!ie.has($t),Kn=In(Be,{...Fe,unread:st});ke.set(Fe.id,Kn);}for(let xe of le)ye.has(xe.id)||(je(xe.status)||xe.unread)&&ke.set(xe.id,xe);let _e=[...ke.values()].sort((xe,Fe)=>Date.parse(Fe.updatedAt)-Date.parse(xe.updatedAt));return c.current=_e,_e}),ce&&xt(we,ae),Te.length>0){for(let le of Te)le.targetKind==="module"&&ot(le.targetId,le.id);Pe().catch(()=>{});}$.current=true;},[Ne,we,x,n,Je,S,Pe,ot]),zn=ar.useCallback((m,F)=>{let P=li(m,F);if(!P)return;let G=m.containerId??m._containerId;if(G&&!S&&O(G),je(P.status)){let ce=St(we);ce.has(P.id)||(ce.add(P.id),xt(we,ce)),q(false),f.isAdmin&&N(false);}let ie=new Map(c.current.map(ce=>[ce.id,ce]));ie.set(P.id,In(ie.get(P.id),P));let ae=[...ie.values()].sort((ce,Se)=>Date.parse(Se.updatedAt)-Date.parse(ce.updatedAt));c.current=ae,Z(ae);},[we,t,o,S,f.isAdmin]),Tt=ar.useCallback((m,F)=>{let P=di(F),G=St(Ne),ie=St(we),ae=c.current.find(ye=>ye.id===m),ce=ae?je(ae.status):false;P.status&&je(P.status)&&!ie.has(m)&&(ie.add(m),xt(we,ie));let Se=ae?In(ae,{...ae,...P}):null,Te=Se?Zt(Se):null,le=!!(Se&&Se.status==="complete"&&(ie.has(m)||ce)&&Te&&!G.has(Te)&&!g.current.has(Te)&&!ae?.unread),he=F.type==="complete"&&ae?.targetKind==="module"?ae.targetId:null;if(Z(ye=>{let ke=ye.find(De=>De.id===m);if(!ke)return ye;let _e=In(ke,{...ke,...P}),xe=_e.status==="complete"&&(ie.has(m)||je(ke.status))&&!G.has(Zt(_e)),Fe={..._e,unread:xe},Be=ye.map(De=>De.id===m?Fe:De).sort((De,$t)=>Date.parse($t.updatedAt)-Date.parse(De.updatedAt));return c.current=Be,Be}),le&&Se&&Te&&g.current.add(Te),F.type==="complete"){let ye=F.data&&typeof F.data=="object"?F.data:{},ke=typeof ye.boundaryId=="string"?ye.boundaryId:he;ke&&ot(ke,m),Pe().catch(()=>{});}},[Ne,we,Pe,ot]),Jt=ar.useCallback(m=>{let F=St(Ne),P=St(we),G=false,ie=false;for(let ae of c.current){if(ae.status!=="complete"||m&&ae.id!==m)continue;let ce=Zt(ae);F.has(ce)||(F.add(ce),G=true),P.delete(ae.id)&&(ie=true);}Z(ae=>{let ce=ae.map(Se=>Se.status!=="complete"||m&&Se.id!==m?Se:{...Se,unread:false});return c.current=ce,ce}),G&&xt(Ne,F),ie&&xt(we,P);},[Ne,we]);ar.useEffect(()=>{$.current=false,g.current.clear(),Z([]);for(let m of h.current.values())m.close();h.current.clear(),S&&Ve();},[S,Ve]),ar.useEffect(()=>{if(typeof document>"u")return;let m=()=>{let F=document.visibilityState!=="hidden";fe(F),F&&S&&Ve();};return document.addEventListener("visibilitychange",m),window.addEventListener("focus",m),window.addEventListener("online",m),()=>{document.removeEventListener("visibilitychange",m),window.removeEventListener("focus",m),window.removeEventListener("online",m);}},[S,Ve]),ar.useEffect(()=>{let m=Q.filter(G=>je(G.status));if(!S||m.length===0)return;let F=ee?ri:oi,P=window.setInterval(()=>{Ve();},F);return ()=>window.clearInterval(P)},[S,ee,Q,Ve]),ar.useEffect(()=>{for(let m of h.current.values())m.close();h.current.clear();},[t,n,f.containerId,Y,D]),ar.useEffect(()=>{let m=new Set(Q.filter(F=>je(F.status)).map(F=>F.id));for(let[F,P]of h.current.entries())m.has(F)||(P.close(),h.current.delete(F));for(let F of m){if(h.current.has(F))continue;let P=new URLSearchParams({key:t});D&&P.set("userId",D),Y&&P.set("userHash",Y),f.isAdmin&&f.containerId&&P.set("containerId",f.containerId);let G=new EventSource(`${n}/api/v1/forks/${F}/events?${P.toString()}`);G.onmessage=ie=>{try{Tt(F,JSON.parse(ie.data));}catch{}},G.onerror=()=>{G.close(),h.current.delete(F);},h.current.set(F,G);}},[t,n,Q,f.isAdmin,f.containerId,Tt,Y,D]),ar.useEffect(()=>()=>{for(let m of h.current.values())m.close();h.current.clear();},[]);let ht=ui(Q),Ce=ar.useCallback(async()=>{if(!D)throw new Error("Reset requires a resolved user identity.");let m=new URLSearchParams({userId:D});Y&&m.set("userHash",Y);let F={Authorization:`Bearer ${t}`,...ue()};o&&(F["X-Fork-App-Id"]=o);let P=await fetch(`${n}/api/v1/forks/all?${m.toString()}`,{method:"DELETE",headers:F});if(!P.ok){let ie=await P.json().catch(()=>({}));throw new Error(ie.error||`API error: ${P.status}`)}let G=await P.json().catch(()=>({}));return b({}),_({}),j(true),M(ie=>ie+1),Z([]),g.current.clear(),xt(Ne,new Set),xt(we,new Set),pe.current.clear(),d.current.clear(),G},[Ne,we,t,o,n,Y,D]);return Xs.jsx(ko.Provider,{value:{apiKey:t,userId:D,userHash:Y,baseUrl:n,appId:o,forks:A,moduleOverridesEnabled:ve,moduleManifestReady:H,moduleManifestVersion:W,currentContainerId:S,forksPaused:V,setForksPaused:gn,forkActivities:Q,activitySummary:ht,adminContext:f,setAdminContainer:B,trackForkActivity:zn,recordForkActivityEvent:Tt,markForkActivitySeen:Jt,refreshForkActivities:Ve,setSlotFork:Ie,clearSlotFork:mn,skipAnimationForSlot:rt,shouldSkipAnimation:pt,markRevealSeen:gt,queueBoundaryAnimation:ot,consumeBoundaryAnimation:mt,registerBoundary:$e,getBoundaryOverride:Kt,refreshModuleManifest:Pe,resetAllForks:Ce,highlightScope:Ct},children:r})}function Ee(){let e=ar.useContext(ko);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function Cn(e){return Ee().forks[e]}var Qt=class{constructor(t){this.values=new Map;this.snapshots=new Map;this.listeners=new Map;this.eventHandlers=new Map;this.slotId=t,window.__FORK_BRIDGE__||(window.__FORK_BRIDGE__={}),window.__FORK_BRIDGE__[t]=this;}set(t,n){let r=this.values.get(t);if(Object.is(r,n))return;if(r!==void 0&&n!==null&&r!==null&&typeof r=="object"&&typeof n=="object")try{if(JSON.stringify(r)===JSON.stringify(n))return}catch{}this.values.set(t,n),this.snapshots.set(t,n);let o=this.listeners.get(t);o&&o.forEach(i=>i());}get(t){return this.values.get(t)}getSnapshot(t){return this.snapshots.get(t)}subscribe(t,n){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(n),()=>{this.listeners.get(t)?.delete(n);}}useValue(t){let n=window.__FORK_REACT__;return n?.useSyncExternalStore?n.useSyncExternalStore(r=>this.subscribe(t,r),()=>this.getSnapshot(t)):(console.warn("[ForkBridge] React.useSyncExternalStore not available, returning static value"),this.values.get(t))}emit(t,...n){let r=this.eventHandlers.get(t);r&&r.forEach(o=>o(...n));}on(t,n){return this.eventHandlers.has(t)||this.eventHandlers.set(t,new Set),this.eventHandlers.get(t).add(n),()=>{this.eventHandlers.get(t)?.delete(n);}}destroy(){this.listeners.clear(),this.eventHandlers.clear(),this.values.clear(),this.snapshots.clear();let t=window.__FORK_BRIDGE__;t&&delete t[this.slotId];}};var sr=new Set;function lr(e,t){let n;try{n=ar.Children.only(e);}catch{let o=ar.Children.count(e);throw new Error(`<ForkSlot slotId="${t}"> must wrap exactly one React component, got ${o} children. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`)}let r=n.type;if(typeof r=="string")throw new Error(`<ForkSlot slotId="${t}"> child must be a React component (function or class), not an HTML element <${r}>. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`);if(typeof r=="symbol")throw new Error(`<ForkSlot slotId="${t}"> child must be a single React component, not a fragment or special React element. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`);return n}var vo=new Set;function wo(e){let t=[],n=e.querySelectorAll("*");for(let r of n){if(!(r instanceof HTMLElement))continue;let o=r.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(r.tagName))continue;let i=getComputedStyle(r),a=parseFloat(i.borderTopLeftRadius)||0;t.push({tag:r.tagName,className:r.className||"",text:(r.textContent||"").slice(0,50).trim(),rect:o,borderRadius:a});}return t}function bi(e,t){let n=[];for(let r of t)if(!e.find(i=>i.tag===r.tag&&i.className===r.className&&Math.abs(i.rect.top-r.rect.top)<20&&Math.abs(i.rect.left-r.rect.left)<20)&&!n.some(a=>r.rect.top>=a.rect.top&&r.rect.left>=a.rect.left&&r.rect.right<=a.rect.right&&r.rect.bottom<=a.rect.bottom)){for(let a=n.length-1;a>=0;a--){let l=n[a];l.rect.top>=r.rect.top&&l.rect.left>=r.rect.left&&l.rect.right<=r.rect.right&&l.rect.bottom<=r.rect.bottom&&n.splice(a,1);}n.push({rect:r.rect,borderRadius:r.borderRadius});}return n}function vi(e,t){let n=[];for(let r of e)if(!t.find(i=>i.tag===r.tag&&i.className===r.className&&Math.abs(i.rect.top-r.rect.top)<20&&Math.abs(i.rect.left-r.rect.left)<20)&&!n.some(a=>r.rect.top>=a.rect.top&&r.rect.left>=a.rect.left&&r.rect.right<=a.rect.right&&r.rect.bottom<=a.rect.bottom)){for(let a=n.length-1;a>=0;a--){let l=n[a];l.rect.top>=r.rect.top&&l.rect.left>=r.rect.left&&l.rect.right<=r.rect.right&&l.rect.bottom<=r.rect.bottom&&n.splice(a,1);}n.push({rect:r.rect,borderRadius:r.borderRadius});}return n}function xo(e,t,n,r,o){return o=Math.max(0,Math.min(o,n/2,r/2)),o===0?`M ${e} ${t} L ${e+n} ${t} L ${e+n} ${t+r} L ${e} ${t+r} Z`:[`M ${e+o} ${t}`,`L ${e+n-o} ${t}`,`A ${o} ${o} 0 0 1 ${e+n} ${t+o}`,`L ${e+n} ${t+r-o}`,`A ${o} ${o} 0 0 1 ${e+n-o} ${t+r}`,`L ${e+o} ${t+r}`,`A ${o} ${o} 0 0 1 ${e} ${t+r-o}`,`L ${e} ${t+o}`,`A ${o} ${o} 0 0 1 ${e+o} ${t}`,"Z"].join(" ")}function So(e){let t="http://www.w3.org/2000/svg",n=document.createElement("div");n.setAttribute("data-fork-highlights","true"),n.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let r=document.createElementNS(t,"svg");r.setAttribute("width","100%"),r.setAttribute("height","100%"),r.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");r.appendChild(o);let i=[];for(let A=0;A<e.length;A++){let{rect:b,borderRadius:E}=e[A],U=b.left-.5,R=b.top-.5,p=b.width+1,f=b.height+1,T=Math.min(E+.5,p/2,f/2),x=xo(U,R,p,f,T),k=`__fork-glow-${A}`,L=document.createElementNS(t,"filter");L.setAttribute("id",k),L.setAttribute("x","-100%"),L.setAttribute("y","-100%"),L.setAttribute("width","300%"),L.setAttribute("height","300%");let N=document.createElementNS(t,"feGaussianBlur");N.setAttribute("in","SourceGraphic"),N.setAttribute("stdDeviation","8"),L.appendChild(N),o.appendChild(L);let K=`__fork-mask-${A}`,_=document.createElementNS(t,"mask");_.setAttribute("id",K),_.setAttribute("maskUnits","userSpaceOnUse"),_.setAttribute("x",String(U-200)),_.setAttribute("y",String(R-200)),_.setAttribute("width",String(p+400)),_.setAttribute("height",String(f+400));let H=document.createElementNS(t,"rect");H.setAttribute("x",String(U-200)),H.setAttribute("y",String(R-200)),H.setAttribute("width",String(p+400)),H.setAttribute("height",String(f+400)),H.setAttribute("fill","white"),_.appendChild(H);let j=document.createElementNS(t,"path");j.setAttribute("d",x),j.setAttribute("fill","black"),_.appendChild(j),o.appendChild(_);let W=document.createElementNS(t,"g");W.setAttribute("mask",`url(#${K})`),W.setAttribute("opacity","0");let M=document.createElementNS(t,"g");M.setAttribute("filter",`url(#${k})`);let S=document.createElementNS(t,"path");S.setAttribute("d",x),S.setAttribute("fill","none"),S.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),S.setAttribute("stroke-width","6"),S.setAttribute("stroke-linecap","round"),M.appendChild(S),W.appendChild(M),r.appendChild(W);let O=document.createElementNS(t,"path");O.setAttribute("d",x),O.setAttribute("fill","none"),O.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),O.setAttribute("stroke-width","2"),O.setAttribute("stroke-linecap","round"),O.setAttribute("opacity","0"),r.appendChild(O),i.push(S,O),S.__group=W;}n.appendChild(r),document.body.appendChild(n);let a=[];for(let A=0;A<i.length;A+=2){let b=i[A],E=i[A+1],U=b.__group,R=E.getTotalLength(),p=b.getTotalLength();if(R<=0)continue;let f=R*.35;E.setAttribute("stroke-dasharray",`${f} ${R-f}`),E.setAttribute("stroke-dashoffset","0"),a.push(E.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*R,opacity:.92,offset:.06},{strokeDashoffset:-2*R,opacity:.92,offset:.92},{strokeDashoffset:-2.25*R,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let T=p*.35;b.setAttribute("stroke-dasharray",`${T} ${p-T}`),b.setAttribute("stroke-dashoffset","0"),a.push(b.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*p,offset:.06},{strokeDashoffset:-2*p,offset:.92},{strokeDashoffset:-2.25*p,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),a.push(U.animate([{opacity:0,offset:0},{opacity:.92,offset:.06},{opacity:.92,offset:.92},{opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));}let l=false,u=()=>{if(l)return;l=true,clearTimeout(w);for(let b of a)try{b.cancel();}catch{}let A=n.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});A.onfinish=()=>n.remove(),window.removeEventListener("click",u);},w=setTimeout(u,14500);return setTimeout(()=>{l||window.addEventListener("click",u);},500),u}function wi(e){let t="http://www.w3.org/2000/svg",n=document.createElement("div");n.setAttribute("data-fork-removed","true"),n.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let r=document.createElementNS(t,"svg");r.setAttribute("width","100%"),r.setAttribute("height","100%"),r.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs"),i=document.createElementNS(t,"filter");i.setAttribute("id","__fork-removed-shadow"),i.setAttribute("x","-10%"),i.setAttribute("y","-10%"),i.setAttribute("width","120%"),i.setAttribute("height","120%");let a=document.createElementNS(t,"feDropShadow");a.setAttribute("dx","0"),a.setAttribute("dy","1"),a.setAttribute("stdDeviation","2"),a.setAttribute("flood-color","rgba(0,0,0,0.15)"),i.appendChild(a),o.appendChild(i),r.appendChild(o);for(let{rect:l,borderRadius:u}of e){let w=l.left,A=l.top,b=l.width,E=l.height,U=Math.min(u,b/2,E/2),R=xo(w,A,b,E,U),p=document.createElementNS(t,"path");p.setAttribute("d",R),p.setAttribute("fill","none"),p.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),p.setAttribute("stroke-width","1.5"),p.setAttribute("stroke-dasharray","8 4"),p.setAttribute("stroke-linecap","round"),p.setAttribute("filter","url(#__fork-removed-shadow)"),p.setAttribute("opacity","0"),r.appendChild(p),p.animate([{opacity:0,offset:0},{opacity:.6,offset:.08},{opacity:.05,offset:.45},{opacity:.6,offset:.85},{opacity:.05,offset:1}],{duration:5e3,easing:"ease-in-out",fill:"forwards"});}return n.appendChild(r),document.body.appendChild(n),n}function Si(e,t){if(e===t)return true;let n=Object.keys(e);if(n.length!==Object.keys(t).length)return false;for(let r of n)if(!Object.is(e[r],t[r]))return false;return true}var xi=ar__namespace.default.memo(function({component:t,containerRef:n,wrapperStyle:r,hostProps:o}){return Xs.jsx("div",{ref:n,style:r,children:Xs.jsx(t,{...o})})},(e,t)=>e.component===t.component&&Si(e.hostProps,t.hostProps)),ir=class extends ar__namespace.default.Component{constructor(t){super(t),this.state={hasError:false};}static getDerivedStateFromError(){return {hasError:true}}componentDidCatch(t){console.error(`[Fork:${this.props.slotId}] fork render failed`,t);}componentDidUpdate(t){t.resetKey!==this.props.resetKey&&this.state.hasError&&this.setState({hasError:false});}render(){return this.state.hasError?this.props.fallback:this.props.children}};function Fo({slotId:e,children:t,githubRepo:n,shared:r,events:o,entityBindings:i}){lr(t,e);let a=Cn(e),{baseUrl:l,apiKey:u,appId:w,shouldSkipAnimation:A,markRevealSeen:b}=Ee(),[E,U]=ar.useState(null),R=ar.useRef(null),p=ar.useRef(null),f=ar.useRef(null),T=ar.useRef(false),x=ar.useRef(null),k=ar.useRef(null),L=!!(r||o),N=ar.useRef(null);L&&!N.current&&(N.current=new Qt(e));let K=ar.useRef(o);if(K.current=o,ar.useEffect(()=>{if(L)return ()=>{N.current?.destroy(),N.current=null;}},[L,e]),L&&N.current&&r)for(let[M,S]of Object.entries(r))N.current.set(M,S);ar.useEffect(()=>{if(!L)return;N.current||(N.current=new Qt(e));let M=N.current,S=Object.keys(K.current||{}).map(O=>M.on(O,(...V)=>K.current?.[O]?.(...V)));return ()=>S.forEach(O=>O())},[L,e]),ar.useEffect(()=>{if(vo.has(e))return;vo.add(e);let M={id:e,appId:w,label:e,eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:n,mode:"direct",sharedKeys:r?Object.keys(r):[],eventNames:o?Object.keys(o):[],propsShape:"",callbackNames:[],entityBindings:i||{}};fetch(`${l}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${u}`,"Content-Type":"application/json"},body:JSON.stringify(M)}).catch(()=>{});},[e,l,u,n,w,i]);let _=a?.id||null;ar.useEffect(()=>{if(a?.bundleUrl,R.current,p.current,!a?.bundleUrl||!_){return}let M=`${l}${a.bundleUrl.replace("bundle.js","component.js")}`,S=a.revealPending===true&&!sr.has(_),O=A(e),V=!O&&S;if(a.revealPending,O&&S&&(sr.add(_),b(a)),V&&p.current){let fe=wo(p.current);f.current=fe,T.current=true,`${e}${fe.length}`;}window.__FORK_REACT__=ar__namespace.default,window.__FORK_REACT_DOM__=Vs__namespace,window.__FORK_REACT_JSX__=Xs__namespace;let q=Date.now(),Q=`${l}${a.bundleUrl.replace("bundle.js","component.css")}?t=${q}`,Z=document.createElement("link");Z.rel="stylesheet",Z.href=Q,Z.dataset.forkSlot=e,document.head.appendChild(Z);let ee=document.createElement("script");return ee.src=M+"?t="+q,ee.onload=()=>{let fe=window.__FORK_EXPORT__;if(fe?.default){if(p.current&&f.current&&T.current){let de=p.current.getBoundingClientRect(),oe=p.current.cloneNode(true);oe.setAttribute("data-fork-clone-overlay","true"),oe.style.position="fixed",oe.style.top=`${de.top}px`,oe.style.left=`${de.left}px`,oe.style.width=`${de.width}px`,oe.style.height=`${de.height}px`,oe.style.flex="none",oe.style.minHeight="auto",oe.style.zIndex="9998",oe.style.pointerEvents="none",oe.style.overflow="hidden";let me=getComputedStyle(p.current).backgroundColor;oe.style.backgroundColor=me&&me!=="rgba(0, 0, 0, 0)"&&me!=="transparent"?me:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(oe);let te=p.current.querySelectorAll("*"),pe=oe.querySelectorAll("*");for(let d=0;d<te.length;d++)te[d].scrollTop!==0&&(pe[d].scrollTop=te[d].scrollTop),te[d].scrollLeft!==0&&(pe[d].scrollLeft=te[d].scrollLeft);x.current=oe;}U(()=>fe.default),R.current=_;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},ee.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(ee),()=>{ee.remove(),Z.remove(),k.current&&(clearTimeout(k.current),k.current=null),x.current&&(x.current.remove(),x.current=null);}},[_,l,e]),ar.useEffect(()=>{if(!T.current||!E||!p.current){`${e}${T.current}`,p.current;return}let M=f.current;if(!M){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!p.current)return;let S=wo(p.current),O=bi(M,S),V=vi(M,S),q=x.current;if(`${e}${O.length}${V.length}`,V.length>0&&q){let Q=wi(V);k.current=setTimeout(()=>{k.current=null;let Z=400;q.animate([{opacity:1},{opacity:0}],{duration:Z,fill:"forwards"}),Q.animate([{opacity:1},{opacity:0}],{duration:Z,fill:"forwards"}),setTimeout(()=>{q.remove(),Q.remove(),x.current=null,O.length>0&&(So(O));},Z);},3500);}else q&&(q.remove(),x.current=null),O.length>0&&(So(O));f.current=null,T.current=false,a&&_&&(sr.add(_),b(a),`${e}`);});});},[E]);let H={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!a||a.status!=="complete"||!a.bundleUrl)return Xs.jsx("div",{ref:p,style:H,children:t});if(!E)return Xs.jsx("div",{ref:p,style:H,children:t});let W=t?.props??{};return Xs.jsx(ir,{slotId:e,resetKey:_,fallback:Xs.jsx("div",{ref:p,style:H,children:t}),children:Xs.jsx(xi,{component:E,containerRef:p,wrapperStyle:H,hostProps:W})})}var Ro=new Set;function Ri(e){return `{ ${Object.entries(e).map(([n,r])=>r==null?`${n}: unknown`:Array.isArray(r)?`${n}: ${r.length>0?typeof r[0]:"unknown"}[]`:`${n}: ${typeof r}`).join("; ")} }`}function Eo(e,t=new Set){return ar.Children.forEach(e,n=>{if(!ar.isValidElement(n))return;let r=n.props;for(let[o,i]of Object.entries(r))typeof i=="function"&&/^on[A-Z]/.test(o)&&t.add(o);r.children&&Eo(r.children,t);}),t}function Ei({slotId:e,props:t,children:n,allowedFetches:r,entityBindings:o,githubRepo:i,callbacks:a,mode:l="iframe",shared:u,events:w}){if(lr(n,e),l==="direct")return Xs.jsx(Fo,{slotId:e,githubRepo:i,shared:u,events:w,entityBindings:o,children:n});let A=Cn(e),{baseUrl:b,apiKey:E,appId:U,userId:R,userHash:p,currentContainerId:f}=Ee(),T=ar.useRef(null),x=ar.useRef(false),k=ar.useRef(null),L=ar.useRef(a);L.current=a;let N=ar.useRef(t);N.current=t;let K=ar.useRef(r);K.current=r,ar.useEffect(()=>{if(typeof process<"u")return;let W=Eo(n),M=new Set(a?Object.keys(a):[]),S=[...W].filter(O=>!M.has(O));S.length>0&&console.error(`[ForkSlot:${e}] Missing bridged callbacks! The following callback props are used by children but not passed to ForkSlot's \`callbacks\` prop:
|
|
2
|
-
`+S.map(
|
|
3
|
-
`)+"\n\nThe forked component will not be able to call these. Add them to the `callbacks` prop of <ForkSlot>.");},[e,n,a]),ar.useEffect(()=>{Ro.has(e)||(Ro.add(e),fetch(`${b}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${E}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:U,label:e,propsShape:t?Ri(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:i,callbackNames:a?Object.keys(a):[],mode:l||"iframe",entityBindings:o||{}})}).catch(()=>{}));},[e,b,E,i,U,o]);let _=ar.useCallback(W=>{let M=T.current;if(M?.contentWindow&&x.current){let S=L.current?Object.keys(L.current):[];M.contentWindow.postMessage({type:"slot:props",props:W,callbackNames:S},"*"),k.current=null;}else k.current=W;},[]),H=ar.useCallback((W,M)=>{let S=K.current;return !S||S.length===0?false:S.some(O=>{let[V,q]=O.split(" "),Q=M.split("?")[0];return W.toUpperCase()===V.toUpperCase()&&Q.startsWith(q)})},[]);if(ar.useEffect(()=>{if(!A?.bundleUrl)return;let W=async M=>{if(M.source===T.current?.contentWindow){if(M.data?.type==="slot:ready")x.current=true,T.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:K.current||[]},"*"),K.current,k.current?_(k.current):_(N.current||{});else if(M.data?.type==="slot:event"){let S=M.data.event;S?.navigate&&(window.location.hash=S.navigate);}else if(M.data?.type==="slot:clipboard-write")navigator.clipboard.writeText(M.data.text).catch(S=>{console.warn(`[ForkSlot:${e}] clipboard write failed:`,S.message);});else if(M.data?.type==="slot:callback"){let{name:S,args:O}=M.data,V=L.current?.[S];V?(V(...O||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${S}`);}else if(M.data?.type==="slot:fetch"){let{id:S,method:O,url:V,body:q}=M.data,Q=T.current?.contentWindow;if(!Q)return;let Z=O||"GET";if(!H(Z,V)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${S}: ${Z} ${V} \u2014 not in allowedFetches`),Q.postMessage({type:"slot:fetch-response",id:S,error:`Fetch not allowed: ${Z} ${V}`},"*");return}try{let ee={method:Z};q&&Z!=="GET"&&(ee.headers={"Content-Type":"application/json"},ee.body=JSON.stringify(q));let fe=await fetch(V,ee),de=await fe.json();`${e}${S}${fe.status}`,Q.postMessage({type:"slot:fetch-response",id:S,data:de,status:fe.status},"*");}catch(ee){console.error(`[ForkSlot:${e}] fetch #${S} failed:`,ee.message),Q.postMessage({type:"slot:fetch-response",id:S,error:ee.message},"*");}}else if(M.data?.type==="slot:fork-data"){let{id:S,path:O,method:V,body:q}=M.data,Q=T.current?.contentWindow;if(!Q)return;if(!f||!U){Q.postMessage({type:"slot:fork-data-response",id:S,error:"Fork data is unavailable until appId and containerId are resolved"},"*");return}let Z=typeof O=="string"&&O.startsWith("/")?O:`/${String(O||"")}`,ee=Z.startsWith("/api/v1/data")?Z:`/api/v1/data${Z}`;try{let fe={Authorization:`Bearer ${E}`,"Content-Type":"application/json","X-Fork-App-Id":U,...ue()};R&&(fe["X-Fork-User-Id"]=R),p&&(fe["X-Fork-User-Hash"]=p);let de=typeof V=="string"?V.toUpperCase():"POST",oe=new URL(`${b}${ee}`),me={method:de,headers:fe};de==="GET"?(oe.searchParams.set("appId",U),oe.searchParams.set("containerId",f)):me.body=JSON.stringify({appId:U,containerId:f,...q&&typeof q=="object"?q:{}});let te=await fetch(oe.toString(),me),pe=await te.json().catch(()=>({}));if(!te.ok){let d=typeof pe?.error=="string"?pe.error:`Fork data API ${te.status}`;Q.postMessage({type:"slot:fork-data-response",id:S,error:d,status:te.status},"*");return}Q.postMessage({type:"slot:fork-data-response",id:S,data:pe,status:te.status},"*");}catch(fe){Q.postMessage({type:"slot:fork-data-response",id:S,error:fe.message},"*");}}}};return window.addEventListener("message",W),()=>{window.removeEventListener("message",W),x.current=false;}},[A?.bundleUrl,e,_,H,f,U,E,b,p,R]),ar.useEffect(()=>{A?.bundleUrl&&x.current&&_(t||{});},[t,A?.bundleUrl,_]),!A||A.status!=="complete"||!A.bundleUrl)return `${e}${A?.status||"none"}${A?.bundleUrl||"none"}`,Xs.jsx(Xs.Fragment,{children:n});`${e}${A.bundleUrl}`;let j=`${b}${A.bundleUrl.replace("/bundle.js","/host")}`;return Xs.jsx("iframe",{ref:T,src:j,sandbox:"allow-scripts allow-same-origin allow-forms allow-clipboard-write",title:`Forked ${e}`,style:{width:"100%",border:"none",flex:1,minHeight:0}})}function $n({style:e={width:20,height:20},...t}){return Xs.jsxs("svg",{viewBox:"320 95 270 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:e,...t,children:[Xs.jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M357.789 145.428c0-16.186 13.121-29.307 29.307-29.307 7.773 0 15.227 3.088 20.723 8.584 5.496 5.496 8.584 12.95 8.584 20.723 0 16.186-13.121 29.307-29.307 29.307s-29.307-13.121-29.307-29.307z"}),Xs.jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M387.096 174.735v188"}),Xs.jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M357.789 394.572c0-16.186 13.121-29.307 29.307-29.307 7.773 0 15.227 3.088 20.723 8.584 5.496 5.496 8.584 12.95 8.584 20.723 0 16.186-13.121 29.307-29.307 29.307s-29.307-13.121-29.307-29.307z"}),Xs.jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M388.739 319c10.168-6.317 43.997-26.932 61.009-37.9 17.012-10.968 31.758-19.978 41.064-27.91 9.305-7.931 11.782-14.213 14.767-19.679 2.985-5.465 3.014-8.99 3.141-13.114.128-4.124-.999-8.178-2.377-11.632-1.378-3.454-3.563-6.55-5.889-9.094-2.326-2.543-4.98-4.679-8.066-6.167-3.085-1.488-6.624-2.601-10.448-2.76-3.823-.159-8.624.2-12.495 1.806-3.871 1.607-8.047 4.68-10.732 7.835-2.685 3.156-4.446 7.448-5.378 11.099-.932 3.651-.742 7.485-.213 10.807.528 3.322 1.864 6.46 3.386 9.123 1.523 2.663 3.543 4.843 5.75 6.854 2.207 2.011 4.38 3.914 7.491 5.214 3.111 1.3 6.57 2.808 11.178 2.584 4.607-.225 9.363-.471 16.466-3.932 7.103-3.46 16.076-5.382 26.154-16.831 10.077-11.449 28.593-43.219 34.312-51.862"}),Xs.jsx("path",{fill:"currentColor",stroke:"currentColor",strokeWidth:"1",strokeLinejoin:"round",d:"M527.117 162.547L570.487 134.368Q577.196 130.009 577.624 137.997L580.39 189.69Q580.818 197.678 573.69 194.047L527.536 170.538Q520.408 166.907 527.117 162.547Z"})]})}var Io=5600,dr=2147483002;function Mi(e){return !e||e.state!=="complete"||!e.latest?null:`${e.latest.id}:${e.latest.completedAt??e.latest.updatedAt}`}function Pi(){return typeof document>"u"?false:!!document.querySelector("[data-fork-clone-overlay], [data-fork-removed], [data-fork-highlights]")}function ur(e,t){let n=Math.min(e.length,t?26:34)*7.4,r=t?Math.min(t.length,24)*6.8+10:0;return Math.round(Math.min(390,Math.max(116,56+n+r)))}function _i(e,t=false){return e?.state==="complete"&&e.unreadCompletedCount>0?e.unreadCompletedCount>1?`${e.unreadCompletedCount} forks ready`:`${e.label} ready`:t?"Fork update ready":void 0}function fr({onClick:e,hasNotification:t=false,activity:n}){let[r,o]=ar.useState(false),[i,a]=ar.useState(false),[l,u]=ar.useState(null),[w,A]=ar.useState(null),[b,E]=ar.useState(null),U=ar.useRef(0),R=r?48:40,p=Mi(n),f=!!(p&&n?.state==="complete"&&n.unreadCompletedCount>0),T=f?p:w?.key??null,x=!!(n&&n.state==="running"&&n.runningCount>0),k=!!(T&&T!==l&&(f||w)),L=x||k,N=f?n?.label:w?.label,K=k?"Built":n?.label??"Fork this app",_=k?N:n?.detail,H=ur(n?.label??"Fork this app",n?.detail),j=ur(K,_),W=k?Math.min(420,Math.max(326,j,w?.width??0,U.current+40)):j,M=k?46:40,S=L?[K,_].filter(Boolean).join(" "):_i(n,t)??"Fork this app",O=L?`${K}:${_??""}`:"idle",V=(t||n?.state==="complete"&&n.unreadCompletedCount>0)&&!L;ar.useEffect(()=>{if(typeof document>"u")return;let te=document.createElement("div");return te.setAttribute("data-fork-button-host","true"),te.style.position="relative",te.style.zIndex=String(dr),document.body.appendChild(te),E(te),()=>{te.remove(),E(null);}},[]),ar.useEffect(()=>{x&&(U.current=H);},[H,x]),ar.useEffect(()=>{!f||!p||!n?.label||A(te=>{if(te?.key===p)return te;let pe=Math.min(420,Math.max(326,ur("Built",n.label),U.current+40));return {key:p,label:n.label,width:pe,startedAt:Date.now()}});},[n?.label,p,f]),ar.useEffect(()=>{n&&n.unreadCompletedCount===0&&n.state!=="running"&&A(null);},[n,n?.state,n?.unreadCompletedCount]),ar.useEffect(()=>{if(!T||!k||T===l)return;let te,pe=w?.key===T?w.startedAt:Date.now(),d=()=>{let I=Date.now()-pe;if(I>=Io&&!Pi()||I>=Io*3){u(T);return}te=window.setTimeout(d,250);};return te=window.setTimeout(d,250),()=>{te!==void 0&&window.clearTimeout(te);}},[T,l,w?.key,w?.startedAt,k]);let q=L?{position:"fixed",bottom:24,right:24,zIndex:dr,width:`min(${W}px, calc(100vw - 32px))`,height:M,minWidth:0,maxWidth:"calc(100vw - 32px)",borderRadius:k?12:999,backgroundColor:r?"#ffffff":"rgba(255, 255, 255, 0.92)",border:"1px solid rgba(148, 163, 184, 0.42)",display:"inline-flex",alignItems:"center",justifyContent:k?"flex-start":"center",gap:k?10:8,color:"#111827",boxShadow:r?"0 12px 24px -16px rgba(15, 23, 42, 0.45), 0 4px 10px -6px rgba(15, 23, 42, 0.25)":"0 10px 20px -18px rgba(15, 23, 42, 0.35), 0 2px 7px -5px rgba(15, 23, 42, 0.18)",transform:i?"scale(0.98)":"scale(1)",transition:"width 320ms cubic-bezier(0.16, 1, 0.3, 1), height 320ms cubic-bezier(0.16, 1, 0.3, 1), border-radius 320ms cubic-bezier(0.16, 1, 0.3, 1), transform 180ms ease, box-shadow 180ms ease, background-color 180ms ease, border-color 180ms ease",cursor:"pointer",padding:k?"0 16px 0 14px":"0 13px 0 11px",margin:0,outline:"none",boxSizing:"border-box",fontFamily:'Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif'}:{position:"fixed",bottom:24,right:24,zIndex:dr,width:R,height:R,borderRadius:"50%",backgroundColor:r?"rgba(255, 255, 255, 1)":"rgba(255, 255, 255, 0.3)",border:r?"1px solid rgba(156, 163, 175, 1)":"1px solid rgba(156, 163, 175, 0.3)",display:"flex",alignItems:"center",justifyContent:"center",color:r?"#111827":"rgba(17, 24, 39, 0.5)",boxShadow:r?"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1)":"0 1px 2px 0 rgba(0, 0, 0, 0.05)",transform:i?"scale(0.95)":"scale(1)",transition:"width 320ms cubic-bezier(0.16, 1, 0.3, 1), height 320ms cubic-bezier(0.16, 1, 0.3, 1), border-radius 320ms cubic-bezier(0.16, 1, 0.3, 1), transform 180ms ease, box-shadow 180ms ease, background-color 180ms ease, border-color 180ms ease, color 180ms ease",cursor:"pointer",padding:0,margin:0,outline:"none",boxSizing:"border-box"},Q={minWidth:0,maxWidth:x?286:k?82:_?116:238,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13,fontWeight:650,lineHeight:"16px",letterSpacing:0},Z={minWidth:0,maxWidth:k?278:void 0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flexShrink:k?1:0,color:"#64748b",fontSize:x?13:12,fontWeight:650,lineHeight:"16px",letterSpacing:0},ee={minWidth:0,flex:k?1:void 0,display:"inline-flex",alignItems:"center",justifyContent:k?"flex-start":void 0,gap:8,animation:"__forkButtonTextSwap 220ms ease-out"},fe={width:8,height:8,borderRadius:"50%",backgroundColor:n?.state==="complete"?"#16a34a":"#ef4444",boxShadow:n?.state==="complete"?"0 0 0 3px rgba(22, 163, 74, 0.14)":"none",animation:k?"__forkButtonBuiltDot 420ms ease-out":void 0,flexShrink:0},me=Xs.jsxs(Xs.Fragment,{children:[Xs.jsx("style",{children:`
|
|
1
|
+
'use strict';var ar=require('react'),Vs=require('react-dom'),Xs=require('react/jsx-runtime'),qs=require('react/jsx-dev-runtime'),lucideReact=require('lucide-react');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var ar__namespace=/*#__PURE__*/_interopNamespace(ar);var Vs__namespace=/*#__PURE__*/_interopNamespace(Vs);var Xs__namespace=/*#__PURE__*/_interopNamespace(Xs);var qs__namespace=/*#__PURE__*/_interopNamespace(qs);var wt="__FORK_SHARED__";function Zn(){var t,n,r,o;let e=globalThis;return e[wt]||(e[wt]={}),(t=e[wt]).react||(t.react=ar__namespace),(n=e[wt])["react-dom"]||(n["react-dom"]=Vs__namespace),(r=e[wt])["react/jsx-runtime"]||(r["react/jsx-runtime"]=Xs__namespace),(o=e[wt])["react/jsx-dev-runtime"]||(o["react/jsx-dev-runtime"]=qs__namespace),e[wt]}function Qn(e){return Object.assign(Zn(),e)}var go=false,er=null,tr=null;function mo(e,t,n){go=e,er=t,tr=n;}function ue(){if(!go)return {};let e={};return er&&(e["X-Fork-App-Id"]=er),tr&&(e["X-Fork-Container-Id"]=tr),e}async function nr(e){let t=new URLSearchParams({app:e.appId,user:e.userId});e.containerId&&t.set("containerId",e.containerId);let n=`${e.baseUrl}/api/v1/manifest?${t.toString()}`,r={Authorization:`Bearer ${e.apiKey}`,"X-Fork-App-Id":e.appId,"X-Fork-User-Id":e.userId,...e.extraHeaders??{}};e.userHash&&(r["X-Fork-User-Hash"]=e.userHash),e.userJwt&&(r["X-Fork-User-Jwt"]=e.userJwt),e.previous?.etag&&(r["If-None-Match"]=e.previous.etag);let o=await fetch(n,{headers:r,signal:e.signal});if(o.status===304)return null;if(!o.ok)throw new Error(`manifest ${o.status} ${o.statusText}`);let i=await o.json(),a={};for(let[l,u]of Object.entries(i.modules)){let w=u.moduleUrl??u.bundleUrl??null,A=u.legacyModuleUrl??u.legacyBundleUrl??null;a[l]={forkId:u.forkId,moduleUrl:w,legacyModuleUrl:A,bundleUrl:u.bundleUrl??w,legacyBundleUrl:u.legacyBundleUrl??A,cssUrls:u.cssUrls??[],integrity:u.integrity,metadata:u.metadata,highlightHint:u.highlightHint,buildId:u.buildId,updatedAt:u.updatedAt};}return {containerId:i.containerId,forksPaused:!!i.forksPaused,slots:i.slots,modules:a,generatedAt:i.generatedAt,etag:o.headers.get("ETag")??void 0}}var Gs="fork:manifest:v1";function rr(e,t,n){return `${Gs}:${e}:${t}:${n}`}function Ys(e,t,n){if(typeof window>"u")return null;try{let r=window.localStorage.getItem(rr(e,t,n));return r?JSON.parse(r):null}catch{return null}}function Zs(e,t,n,r){if(!(typeof window>"u"))try{window.localStorage.setItem(rr(e,t,n),JSON.stringify(r));}catch{}}function Qs(e,t,n){if(!(typeof window>"u"))try{window.localStorage.removeItem(rr(e,t,n));}catch{}}function ei(e,t){if(!e||!t)return e!==t;if(e.containerId!==t.containerId||!!e.forksPaused!=!!t.forksPaused)return true;let n=Object.entries(e.slots),r=Object.entries(t.slots);if(n.length!==r.length)return true;for(let[a,l]of n){let u=t.slots[a];if(!u||u.forkId!==l.forkId||u.buildId!==l.buildId)return true}let o=Object.entries(e.modules),i=Object.entries(t.modules);if(o.length!==i.length)return true;for(let[a,l]of o){let u=t.modules[a];if(!u||u.forkId!==l.forkId||u.buildId!==l.buildId)return true}return false}var In={isAdmin:false,actingUserId:null,containerId:null,containerName:null,containers:[]},ko=ar.createContext(null),ri=12e3,oi=45e3,ho="fork:activity:v1",si=new Set(["pending","running","building"]),ii="Setting up environment";function je(e){return si.has(e)}function ai(e,t){return t?.targetId?t:e.boundaryId?{targetKind:"module",targetId:e.boundaryId}:e.slotId?{targetKind:"slot",targetId:e.slotId}:null}function li(e,t){let n=ai(e,t);if(!n)return null;let r=new Date().toISOString();return {id:e.id,status:e.status,targetKind:n.targetKind,targetId:n.targetId,summary:e.summary??null,estimateMinutes:e.estimateMinutes??null,createdAt:e.createdAt||r,updatedAt:e.completedAt||r,completedAt:e.completedAt??null}}function yo(e){return {id:e.id,status:e.status,targetKind:e.targetKind,targetId:e.targetId,summary:e.summary??null,estimateMinutes:e.estimateMinutes??null,promptCount:e.promptCount,messageCount:e.messageCount,isActive:e.isActive,createdAt:e.createdAt,updatedAt:e.updatedAt,completedAt:e.completedAt??null,lastFeatureCompletedAt:e.lastFeatureCompletedAt??null}}function En(e,t){let n=typeof t.summary=="string"&&t.summary.trim()?t.summary.trim():void 0,r=typeof e?.summary=="string"&&e.summary.trim()?e.summary.trim():void 0,o=typeof t.estimateMinutes=="number"&&Number.isFinite(t.estimateMinutes)?t.estimateMinutes:void 0,i=typeof e?.estimateMinutes=="number"&&Number.isFinite(e.estimateMinutes)?e.estimateMinutes:void 0;return {...e,...t,summary:n??r??null,estimateMinutes:o??i??null,latestMessage:t.latestMessage??e?.latestMessage??null,unread:t.unread??e?.unread??false}}function Zt(e){return `${e.id}:${e.lastFeatureCompletedAt||e.completedAt||e.updatedAt}`}function St(e){if(typeof window>"u")return new Set;try{let t=window.localStorage.getItem(e);if(!t)return new Set;let n=JSON.parse(t);return Array.isArray(n)?new Set(n.filter(r=>typeof r=="string")):new Set}catch{return new Set}}function xt(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify([...t].slice(-200)));}catch{}}function ci(e){if(e.estimateMinutes)return `~${e.estimateMinutes}m`}function di(e){let t=e.data&&typeof e.data=="object"?e.data:{};if(e.type==="status"){let n=typeof t.status=="string"?t.status:"running",r=typeof t.summary=="string"?t.summary:void 0;return {status:n,latestMessage:je(n)?"Building":void 0,summary:r,estimateMinutes:typeof t.estimateMinutes=="number"?t.estimateMinutes:void 0,updatedAt:e.timestamp}}return e.type==="tool_use"?{status:"running",latestMessage:"Building",updatedAt:e.timestamp}:e.type==="build_start"?{status:"building",latestMessage:"Building",updatedAt:e.timestamp}:e.type==="build_complete"?{status:"building",latestMessage:"Building",updatedAt:e.timestamp}:e.type==="complete"?{status:"complete",summary:typeof t.summary=="string"?t.summary:void 0,estimateMinutes:typeof t.estimateMinutes=="number"?t.estimateMinutes:void 0,latestMessage:"Fork ready",completedAt:e.timestamp,updatedAt:e.timestamp}:e.type==="error"||e.type==="build_error"?{status:"error",latestMessage:typeof t.error=="string"?t.error:typeof t.message=="string"?t.message:"Fork failed",updatedAt:e.timestamp}:{updatedAt:e.timestamp}}function ui(e){let t=e.filter(o=>je(o.status)),n=e.filter(o=>o.status==="complete"&&o.unread),r=[...e].sort((o,i)=>Date.parse(i.updatedAt)-Date.parse(o.updatedAt))[0]??null;if(t.length>1)return {state:"running",label:`${t.length} forks running`,count:t.length,runningCount:t.length,unreadCompletedCount:n.length,latest:t[0]};if(t.length===1){let o=t[0],i=!!(typeof o.summary=="string"&&o.summary.trim());return {state:"running",label:i?o.summary.trim():ii,detail:i?ci(o):void 0,count:1,runningCount:1,unreadCompletedCount:n.length,latest:o}}if(n.length>1)return {state:"complete",label:`${n.length} forks ready`,count:n.length,runningCount:0,unreadCompletedCount:n.length,latest:n[0]};if(n.length===1){let o=n[0];return {state:"complete",label:o.summary||"Fork ready",count:1,runningCount:0,unreadCompletedCount:1,latest:o}}return {state:r?.status==="error"?"error":"idle",label:"Fork",count:0,runningCount:0,unreadCompletedCount:0,latest:r}}function or(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function fi(e,t,n,r){let o={};for(let[i,a]of Object.entries(t.slots)){let l=a.bundleUrl??a.legacyBundleUrl;l&&(o[i]={id:a.forkId,userId:n,prompt:"",status:"complete",slotId:i,appId:r,bundleUrl:or(e,l),revealPending:a.revealPending===true,createdAt:a.updatedAt,completedAt:a.updatedAt});}return o}function pi(e,t){let n={};for(let[r,o]of Object.entries(t.modules)){let i=o.moduleUrl??o.legacyModuleUrl??o.bundleUrl??"";i&&(n[r]={id:o.forkId,boundaryId:r,moduleUrl:or(e,i),cssUrls:(o.cssUrls??[]).map(a=>or(e,a)),integrity:o.integrity,metadata:o.metadata,highlightHint:o.highlightHint,createdAt:o.updatedAt});}return n}function gi(e){let{apiKey:t,baseUrl:n,children:r,appId:o,shared:i}=e,a="userId"in e?e.userId:void 0,l="userHash"in e?e.userHash:void 0,u="userJwt"in e?e.userJwt:void 0,w="authUrl"in e?e.authUrl:void 0,[A,b]=ar.useState({}),[I,O]=ar.useState(a?{userId:a,userHash:l,userJwt:u}:null),[R,p]=ar.useState(!!a),[f,T]=ar.useState(In),[x,k]=ar.useState(false),[L,N]=ar.useState(false),[K,_]=ar.useState({}),[H,j]=ar.useState(!o),[W,M]=ar.useState(0),[S,U]=ar.useState(null),[X,V]=ar.useState(false),[Q,Z]=ar.useState([]),[ee,fe]=ar.useState(()=>typeof document>"u"?true:document.visibilityState!=="hidden"),de=ar.useRef(new Map),oe=ar.useRef(new Map),[me,te]=ar.useState(0),pe=ar.useRef(new Set),d=ar.useRef(new Map),E=ar.useRef(void 0),h=ar.useRef(new Map),c=ar.useRef([]),g=ar.useRef(new Set),$=ar.useRef(false);Zn(),ar.useEffect(()=>{if(!o||!I?.userId||!(I.userHash||I.userJwt)){T(In),k(true);return}let m=false;k(false);let F=new URLSearchParams({app:o});return fetch(`${n}/api/v1/admin/containers?${F.toString()}`,{headers:{Authorization:`Bearer ${t}`,"X-Fork-App-Id":o,"X-Fork-User-Id":I.userId,...I.userHash?{"X-Fork-User-Hash":I.userHash}:{},...I.userJwt?{"X-Fork-User-Jwt":I.userJwt}:{}}}).then(async P=>P.status===403||!P.ok?null:P.json()).then(P=>{if(m)return;if(!P){T(In),k(true);return}let G=Array.isArray(P.containers)?P.containers:[],ie=P.currentContainerId??null,ae=G.find(ce=>ce.id===ie)?.name??null;T({isAdmin:true,actingUserId:typeof P.actingUserId=="string"?P.actingUserId:null,containerId:ie,containerName:ae,containers:G}),k(true);}).catch(()=>{m||(T(In),k(true));}),()=>{m=true;}},[t,o,I?.userHash,I?.userJwt,I?.userId,n]),ar.useEffect(()=>{mo(f.isAdmin,o??null,f.containerId);},[f.isAdmin,f.containerId,o]);let B=ar.useCallback((m,F)=>{T(P=>{if(!P.isAdmin)return P;let G=P.containers.find(ce=>ce.id===m),ie=F??G?.name??null,ae=G?P.containers.map(ce=>({...ce,isPrimary:ce.id===m})):[{id:m,name:ie??"New container",isPrimary:true,forkCount:0},...P.containers.map(ce=>({...ce,isPrimary:false}))];return {...P,containerId:m,containerName:ie,containers:ae}}),N(false);},[]);i&&E.current!==i&&(Qn(i),E.current=i),ar.useEffect(()=>{w&&(p(false),fetch(w,{credentials:"include"}).then(m=>{if(!m.ok)throw new Error(`Auth endpoint returned ${m.status}`);return m.json()}).then(m=>{if(!m.userId||typeof m.userId!="string")throw new Error("authUrl response must include userId");O({userId:m.userId,userHash:typeof m.userHash=="string"?m.userHash:void 0,userJwt:typeof m.userJwt=="string"?m.userJwt:void 0});}).catch(m=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",m.message);}).finally(()=>{p(true);}));},[w]),ar.useEffect(()=>{!w&&a&&(O({userId:a,userHash:l,userJwt:u}),p(true));},[a,l,u,w]);let D=I?.userId??"",Y=I?.userHash,ft=I?.userJwt,ve=!!o,Pe=ar.useCallback(async()=>{if(!ve){U(null),V(false),_({}),j(true),M(F=>F+1);return}if(!R){j(false);return}if(!D||!o){U(null),V(false),b({}),_({}),j(true),M(F=>F+1);return}j(false);let m=f.isAdmin?f.containerId:null;if(f.isAdmin&&L){V(true),b({}),_({}),M(F=>F+1),j(true);return}try{let F=await nr({baseUrl:n,apiKey:t,appId:o,userId:D,userHash:Y,userJwt:ft,containerId:m??void 0});F&&(U(F.containerId),V(f.isAdmin?!1:!!F.forksPaused),b(fi(n,F,D,o)),_(pi(n,F)));}catch(F){console.error("[ForkProvider] Failed to fetch fork manifest:",F.message),U(null),V(false),b({}),_({});}finally{M(F=>F+1),j(true);}},[t,o,n,R,ve,Y,ft,D,f.isAdmin,f.containerId,L]);ar.useEffect(()=>{if(!D||o)return;let m=new URLSearchParams({userId:D});Y&&m.set("userHash",Y),fetch(`${n}/api/v1/forks/active?${m.toString()}`,{headers:{Authorization:`Bearer ${t}`,...ue()}}).then(F=>{if(!F.ok)throw new Error(`${F.status}`);return F.json()}).then(F=>{F&&typeof F=="object"&&b(F);}).catch(()=>{});},[t,o,D,Y,n]),ar.useEffect(()=>{Pe();},[Pe]);let gn=ar.useCallback(async m=>{if(o){if(f.isAdmin){N(m),V(m),m?(b({}),_({}),M(F=>F+1)):await Pe();return}if(D){V(m),m&&(b({}),_({}),M(F=>F+1));try{let F=await fetch(`${n}/api/v1/containers/primary/paused`,{method:"PUT",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json","X-Fork-App-Id":o},body:JSON.stringify({appId:o,paused:m,userId:D,userHash:Y})});if(!F.ok)throw new Error(`${F.status}`);m||await Pe();}catch(F){console.error("[ForkProvider] Failed to persist fork pause state:",F?.message??F),Pe().catch(()=>{});}}}},[t,o,n,Pe,f.isAdmin,Y,D]),Ce=ar.useCallback((m,F)=>{b(P=>({...P,[m]:F}));},[]),mn=ar.useCallback(m=>{b(F=>{let P={...F};return delete P[m],P});},[]),tt=ar.useCallback(m=>{pe.current.add(m);},[]),pt=ar.useCallback(m=>pe.current.has(m)?(pe.current.delete(m),true):false,[]),gt=ar.useCallback(m=>{if(m.slotId&&b(P=>{let G=P[m.slotId];return !G||G.id!==m.id||!G.revealPending?P:{...P,[m.slotId]:{...G,revealPending:false}}}),f.isAdmin||!D)return;let F={Authorization:`Bearer ${t}`,"Content-Type":"application/json","X-Fork-User-Id":D};Y&&(F["X-Fork-User-Hash"]=Y),fetch(`${n}/api/v1/forks/reveals`,{method:"POST",headers:F,body:JSON.stringify({forkId:m.id,userId:D,userHash:Y})}).catch(()=>{});},[t,n,f.isAdmin,Y,D]),nt=ar.useCallback((m,F)=>{d.current.set(m,F);},[]),mt=ar.useCallback((m,F)=>d.current.get(m)!==F?false:(d.current.delete(m),true),[]),Fe=ar.useCallback(m=>{if(!o)return;let F=JSON.stringify(m);de.current.get(m.id)===F||oe.current.get(m.id)?.signature===F||(oe.current.set(m.id,{boundary:m,signature:F}),te(G=>G+1));},[o]);ar.useEffect(()=>{if(!o||oe.current.size===0)return;let m=setTimeout(()=>{let F=Array.from(oe.current.values());F.length!==0&&fetch(`${n}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:o,boundaries:F.map(P=>P.boundary)})}).then(P=>{if(!P.ok)throw new Error(`${P.status}`)}).then(()=>{for(let P of F)oe.current.get(P.boundary.id)?.signature===P.signature&&(oe.current.delete(P.boundary.id),de.current.set(P.boundary.id,P.signature));}).catch(P=>{console.error("[ForkProvider] Failed to register module boundaries:",P.message);});},50);return ()=>{clearTimeout(m);}},[t,o,n,me]);let Et=ar.useCallback(m=>K[m],[K]),Ge=f.isAdmin?`admin:${f.actingUserId??"op"}`:D,Kt=`${t}:${o||"no-app"}:${S||"no-container"}:${Ge||"anonymous"}`,Ct=f.isAdmin?`op:${f.actingUserId??"op"}`:D,Tt=`${t}:${o||"no-app"}:${Ct||"anonymous"}`,Ne=`${ho}:seen:${Kt}`,we=`${ho}:tracked:${Kt}`;ar.useEffect(()=>{c.current=Q;},[Q]);let Je=ar.useCallback(()=>{let m={Authorization:`Bearer ${t}`,...ue()};return o&&(m["X-Fork-App-Id"]=o),D&&(m["X-Fork-User-Id"]=D),Y&&(m["X-Fork-User-Hash"]=Y),m},[t,o,Y,D]);ar.useEffect(()=>{if(typeof window>"u")return;let m=window.__FORK_RUNTIME__,F={dataFetch:async(P,G,ie="POST")=>{if(!o||!S)throw new Error("Fork data is unavailable until appId and containerId are resolved");let ae=typeof P=="string"&&P.startsWith("/")?P:`/${String(P||"")}`,ce=ae.startsWith("/api/v1/data")?ae:`/api/v1/data${ae}`,Se=ie.toUpperCase(),$e=new URL(`${n}${ce}`),le={Authorization:`Bearer ${t}`,"Content-Type":"application/json","X-Fork-App-Id":o,...ue()};D&&(le["X-Fork-User-Id"]=D),Y&&(le["X-Fork-User-Hash"]=Y);let he={method:Se,headers:le};Se==="GET"?($e.searchParams.set("appId",o),$e.searchParams.set("containerId",S)):he.body=JSON.stringify({appId:o,containerId:S,...G&&typeof G=="object"?G:{}});let ye=await fetch($e.toString(),he),ke=await ye.json().catch(()=>({}));if(!ye.ok)throw new Error(typeof ke?.error=="string"?ke.error:`Fork data API ${ye.status}`);return ke}};return window.__FORK_RUNTIME__=F,()=>{window.__FORK_RUNTIME__===F&&(window.__FORK_RUNTIME__=m);}},[t,o,n,S,Y,D]);let Ve=ar.useCallback(async()=>{if(!S||!x)return;let m=new URLSearchParams({container_id:S}),F=await fetch(`${n}/api/v1/forks?${m.toString()}`,{headers:Je()}).catch(()=>null);if(!F||!F.ok)return;let P=await F.json().catch(()=>({})),G=Array.isArray(P.forks)?P.forks:[],ie=St(Ne),ae=St(we),ce=false,Se=new Map(c.current.map(le=>[le.id,le])),$e=[];for(let le of G){let he=yo(le);je(he.status)&&!ae.has(he.id)&&(ae.add(he.id),ce=true);let ye=Se.get(he.id),ke=ye?je(ye.status):false,_e=Zt(he);he.status==="complete"&&(ae.has(he.id)||ke)&&!ie.has(_e)&&!g.current.has(_e)&&!ye?.unread&&($.current||ae.has(he.id)||ke)&&(g.current.add(_e),$e.push(he));}if(Z(le=>{let he=new Map(le.map(xe=>[xe.id,xe])),ye=new Set,ke=new Map;for(let xe of G){let Ae=yo(xe);ye.add(Ae.id);let Be=he.get(Ae.id),De=Be?je(Be.status):false,Mt=Zt(Ae),rt=Ae.status==="complete"&&(ae.has(Ae.id)||De)&&!ie.has(Mt),Kn=En(Be,{...Ae,unread:rt});ke.set(Ae.id,Kn);}for(let xe of le)ye.has(xe.id)||(je(xe.status)||xe.unread)&&ke.set(xe.id,xe);let _e=[...ke.values()].sort((xe,Ae)=>Date.parse(Ae.updatedAt)-Date.parse(xe.updatedAt));return c.current=_e,_e}),ce&&xt(we,ae),$e.length>0){for(let le of $e)le.targetKind==="module"&&nt(le.targetId,le.id);Pe().catch(()=>{});}$.current=true;},[Ne,we,x,n,Je,S,Pe,nt]),zn=ar.useCallback((m,F)=>{let P=li(m,F);if(!P)return;let G=m.containerId??m._containerId;if(G&&!S&&U(G),je(P.status)){let ce=St(we);ce.has(P.id)||(ce.add(P.id),xt(we,ce)),V(false),f.isAdmin&&N(false);}let ie=new Map(c.current.map(ce=>[ce.id,ce]));ie.set(P.id,En(ie.get(P.id),P));let ae=[...ie.values()].sort((ce,Se)=>Date.parse(Se.updatedAt)-Date.parse(ce.updatedAt));c.current=ae,Z(ae);},[we,t,o,S,f.isAdmin]),$t=ar.useCallback((m,F)=>{let P=di(F),G=St(Ne),ie=St(we),ae=c.current.find(ye=>ye.id===m),ce=ae?je(ae.status):false;P.status&&je(P.status)&&!ie.has(m)&&(ie.add(m),xt(we,ie));let Se=ae?En(ae,{...ae,...P}):null,$e=Se?Zt(Se):null,le=!!(Se&&Se.status==="complete"&&(ie.has(m)||ce)&&$e&&!G.has($e)&&!g.current.has($e)&&!ae?.unread),he=F.type==="complete"&&ae?.targetKind==="module"?ae.targetId:null;if(Z(ye=>{let ke=ye.find(De=>De.id===m);if(!ke)return ye;let _e=En(ke,{...ke,...P}),xe=_e.status==="complete"&&(ie.has(m)||je(ke.status))&&!G.has(Zt(_e)),Ae={..._e,unread:xe},Be=ye.map(De=>De.id===m?Ae:De).sort((De,Mt)=>Date.parse(Mt.updatedAt)-Date.parse(De.updatedAt));return c.current=Be,Be}),le&&Se&&$e&&g.current.add($e),F.type==="complete"){let ye=F.data&&typeof F.data=="object"?F.data:{},ke=typeof ye.boundaryId=="string"?ye.boundaryId:he;ke&&nt(ke,m),Pe().catch(()=>{});}},[Ne,we,Pe,nt]),Wt=ar.useCallback(m=>{let F=St(Ne),P=St(we),G=false,ie=false;for(let ae of c.current){if(ae.status!=="complete"||m&&ae.id!==m)continue;let ce=Zt(ae);F.has(ce)||(F.add(ce),G=true),P.delete(ae.id)&&(ie=true);}Z(ae=>{let ce=ae.map(Se=>Se.status!=="complete"||m&&Se.id!==m?Se:{...Se,unread:false});return c.current=ce,ce}),G&&xt(Ne,F),ie&&xt(we,P);},[Ne,we]);ar.useEffect(()=>{$.current=false,g.current.clear(),Z([]);for(let m of h.current.values())m.close();h.current.clear(),S&&Ve();},[S,Ve]),ar.useEffect(()=>{if(typeof document>"u")return;let m=()=>{let F=document.visibilityState!=="hidden";fe(F),F&&S&&Ve();};return document.addEventListener("visibilitychange",m),window.addEventListener("focus",m),window.addEventListener("online",m),()=>{document.removeEventListener("visibilitychange",m),window.removeEventListener("focus",m),window.removeEventListener("online",m);}},[S,Ve]),ar.useEffect(()=>{let m=Q.filter(G=>je(G.status));if(!S||m.length===0)return;let F=ee?ri:oi,P=window.setInterval(()=>{Ve();},F);return ()=>window.clearInterval(P)},[S,ee,Q,Ve]),ar.useEffect(()=>{for(let m of h.current.values())m.close();h.current.clear();},[t,n,f.containerId,Y,D]),ar.useEffect(()=>{let m=new Set(Q.filter(F=>je(F.status)).map(F=>F.id));for(let[F,P]of h.current.entries())m.has(F)||(P.close(),h.current.delete(F));for(let F of m){if(h.current.has(F))continue;let P=new URLSearchParams({key:t});D&&P.set("userId",D),Y&&P.set("userHash",Y),f.isAdmin&&f.containerId&&P.set("containerId",f.containerId);let G=new EventSource(`${n}/api/v1/forks/${F}/events?${P.toString()}`);G.onmessage=ie=>{try{$t(F,JSON.parse(ie.data));}catch{}},G.onerror=()=>{G.close(),h.current.delete(F);},h.current.set(F,G);}},[t,n,Q,f.isAdmin,f.containerId,$t,Y,D]),ar.useEffect(()=>()=>{for(let m of h.current.values())m.close();h.current.clear();},[]);let ht=ui(Q),Te=ar.useCallback(async()=>{if(!D)throw new Error("Reset requires a resolved user identity.");let m=new URLSearchParams({userId:D});Y&&m.set("userHash",Y);let F={Authorization:`Bearer ${t}`,...ue()};o&&(F["X-Fork-App-Id"]=o);let P=await fetch(`${n}/api/v1/forks/all?${m.toString()}`,{method:"DELETE",headers:F});if(!P.ok){let ie=await P.json().catch(()=>({}));throw new Error(ie.error||`API error: ${P.status}`)}let G=await P.json().catch(()=>({}));return b({}),_({}),j(true),M(ie=>ie+1),Z([]),g.current.clear(),xt(Ne,new Set),xt(we,new Set),pe.current.clear(),d.current.clear(),G},[Ne,we,t,o,n,Y,D]);return Xs.jsx(ko.Provider,{value:{apiKey:t,userId:D,userHash:Y,baseUrl:n,appId:o,forks:A,moduleOverridesEnabled:ve,moduleManifestReady:H,moduleManifestVersion:W,currentContainerId:S,forksPaused:X,setForksPaused:gn,forkActivities:Q,activitySummary:ht,adminContext:f,setAdminContainer:B,trackForkActivity:zn,recordForkActivityEvent:$t,markForkActivitySeen:Wt,refreshForkActivities:Ve,setSlotFork:Ce,clearSlotFork:mn,skipAnimationForSlot:tt,shouldSkipAnimation:pt,markRevealSeen:gt,queueBoundaryAnimation:nt,consumeBoundaryAnimation:mt,registerBoundary:Fe,getBoundaryOverride:Et,refreshModuleManifest:Pe,resetAllForks:Te,highlightScope:Tt},children:r})}function Ee(){let e=ar.useContext(ko);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function Cn(e){return Ee().forks[e]}var Qt=class{constructor(t){this.values=new Map;this.snapshots=new Map;this.listeners=new Map;this.eventHandlers=new Map;this.slotId=t,window.__FORK_BRIDGE__||(window.__FORK_BRIDGE__={}),window.__FORK_BRIDGE__[t]=this;}set(t,n){let r=this.values.get(t);if(Object.is(r,n))return;if(r!==void 0&&n!==null&&r!==null&&typeof r=="object"&&typeof n=="object")try{if(JSON.stringify(r)===JSON.stringify(n))return}catch{}this.values.set(t,n),this.snapshots.set(t,n);let o=this.listeners.get(t);o&&o.forEach(i=>i());}get(t){return this.values.get(t)}getSnapshot(t){return this.snapshots.get(t)}subscribe(t,n){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(n),()=>{this.listeners.get(t)?.delete(n);}}useValue(t){let n=window.__FORK_REACT__;return n?.useSyncExternalStore?n.useSyncExternalStore(r=>this.subscribe(t,r),()=>this.getSnapshot(t)):(console.warn("[ForkBridge] React.useSyncExternalStore not available, returning static value"),this.values.get(t))}emit(t,...n){let r=this.eventHandlers.get(t);r&&r.forEach(o=>o(...n));}on(t,n){return this.eventHandlers.has(t)||this.eventHandlers.set(t,new Set),this.eventHandlers.get(t).add(n),()=>{this.eventHandlers.get(t)?.delete(n);}}destroy(){this.listeners.clear(),this.eventHandlers.clear(),this.values.clear(),this.snapshots.clear();let t=window.__FORK_BRIDGE__;t&&delete t[this.slotId];}};var sr=new Set;function lr(e,t){let n;try{n=ar.Children.only(e);}catch{let o=ar.Children.count(e);throw new Error(`<ForkSlot slotId="${t}"> must wrap exactly one React component, got ${o} children. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`)}let r=n.type;if(typeof r=="string")throw new Error(`<ForkSlot slotId="${t}"> child must be a React component (function or class), not an HTML element <${r}>. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`);if(typeof r=="symbol")throw new Error(`<ForkSlot slotId="${t}"> child must be a single React component, not a fragment or special React element. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`);return n}var vo=new Set;function wo(e){let t=[],n=e.querySelectorAll("*");for(let r of n){if(!(r instanceof HTMLElement))continue;let o=r.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(r.tagName))continue;let i=getComputedStyle(r),a=parseFloat(i.borderTopLeftRadius)||0;t.push({tag:r.tagName,className:r.className||"",text:(r.textContent||"").slice(0,50).trim(),rect:o,borderRadius:a});}return t}function bi(e,t){let n=[];for(let r of t)if(!e.find(i=>i.tag===r.tag&&i.className===r.className&&Math.abs(i.rect.top-r.rect.top)<20&&Math.abs(i.rect.left-r.rect.left)<20)&&!n.some(a=>r.rect.top>=a.rect.top&&r.rect.left>=a.rect.left&&r.rect.right<=a.rect.right&&r.rect.bottom<=a.rect.bottom)){for(let a=n.length-1;a>=0;a--){let l=n[a];l.rect.top>=r.rect.top&&l.rect.left>=r.rect.left&&l.rect.right<=r.rect.right&&l.rect.bottom<=r.rect.bottom&&n.splice(a,1);}n.push({rect:r.rect,borderRadius:r.borderRadius});}return n}function vi(e,t){let n=[];for(let r of e)if(!t.find(i=>i.tag===r.tag&&i.className===r.className&&Math.abs(i.rect.top-r.rect.top)<20&&Math.abs(i.rect.left-r.rect.left)<20)&&!n.some(a=>r.rect.top>=a.rect.top&&r.rect.left>=a.rect.left&&r.rect.right<=a.rect.right&&r.rect.bottom<=a.rect.bottom)){for(let a=n.length-1;a>=0;a--){let l=n[a];l.rect.top>=r.rect.top&&l.rect.left>=r.rect.left&&l.rect.right<=r.rect.right&&l.rect.bottom<=r.rect.bottom&&n.splice(a,1);}n.push({rect:r.rect,borderRadius:r.borderRadius});}return n}function xo(e,t,n,r,o){return o=Math.max(0,Math.min(o,n/2,r/2)),o===0?`M ${e} ${t} L ${e+n} ${t} L ${e+n} ${t+r} L ${e} ${t+r} Z`:[`M ${e+o} ${t}`,`L ${e+n-o} ${t}`,`A ${o} ${o} 0 0 1 ${e+n} ${t+o}`,`L ${e+n} ${t+r-o}`,`A ${o} ${o} 0 0 1 ${e+n-o} ${t+r}`,`L ${e+o} ${t+r}`,`A ${o} ${o} 0 0 1 ${e} ${t+r-o}`,`L ${e} ${t+o}`,`A ${o} ${o} 0 0 1 ${e+o} ${t}`,"Z"].join(" ")}function So(e){let t="http://www.w3.org/2000/svg",n=document.createElement("div");n.setAttribute("data-fork-highlights","true"),n.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let r=document.createElementNS(t,"svg");r.setAttribute("width","100%"),r.setAttribute("height","100%"),r.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");r.appendChild(o);let i=[];for(let A=0;A<e.length;A++){let{rect:b,borderRadius:I}=e[A],O=b.left-.5,R=b.top-.5,p=b.width+1,f=b.height+1,T=Math.min(I+.5,p/2,f/2),x=xo(O,R,p,f,T),k=`__fork-glow-${A}`,L=document.createElementNS(t,"filter");L.setAttribute("id",k),L.setAttribute("x","-100%"),L.setAttribute("y","-100%"),L.setAttribute("width","300%"),L.setAttribute("height","300%");let N=document.createElementNS(t,"feGaussianBlur");N.setAttribute("in","SourceGraphic"),N.setAttribute("stdDeviation","8"),L.appendChild(N),o.appendChild(L);let K=`__fork-mask-${A}`,_=document.createElementNS(t,"mask");_.setAttribute("id",K),_.setAttribute("maskUnits","userSpaceOnUse"),_.setAttribute("x",String(O-200)),_.setAttribute("y",String(R-200)),_.setAttribute("width",String(p+400)),_.setAttribute("height",String(f+400));let H=document.createElementNS(t,"rect");H.setAttribute("x",String(O-200)),H.setAttribute("y",String(R-200)),H.setAttribute("width",String(p+400)),H.setAttribute("height",String(f+400)),H.setAttribute("fill","white"),_.appendChild(H);let j=document.createElementNS(t,"path");j.setAttribute("d",x),j.setAttribute("fill","black"),_.appendChild(j),o.appendChild(_);let W=document.createElementNS(t,"g");W.setAttribute("mask",`url(#${K})`),W.setAttribute("opacity","0");let M=document.createElementNS(t,"g");M.setAttribute("filter",`url(#${k})`);let S=document.createElementNS(t,"path");S.setAttribute("d",x),S.setAttribute("fill","none"),S.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),S.setAttribute("stroke-width","6"),S.setAttribute("stroke-linecap","round"),M.appendChild(S),W.appendChild(M),r.appendChild(W);let U=document.createElementNS(t,"path");U.setAttribute("d",x),U.setAttribute("fill","none"),U.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),U.setAttribute("stroke-width","2"),U.setAttribute("stroke-linecap","round"),U.setAttribute("opacity","0"),r.appendChild(U),i.push(S,U),S.__group=W;}n.appendChild(r),document.body.appendChild(n);let a=[];for(let A=0;A<i.length;A+=2){let b=i[A],I=i[A+1],O=b.__group,R=I.getTotalLength(),p=b.getTotalLength();if(R<=0)continue;let f=R*.35;I.setAttribute("stroke-dasharray",`${f} ${R-f}`),I.setAttribute("stroke-dashoffset","0"),a.push(I.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*R,opacity:.92,offset:.06},{strokeDashoffset:-2*R,opacity:.92,offset:.92},{strokeDashoffset:-2.25*R,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let T=p*.35;b.setAttribute("stroke-dasharray",`${T} ${p-T}`),b.setAttribute("stroke-dashoffset","0"),a.push(b.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*p,offset:.06},{strokeDashoffset:-2*p,offset:.92},{strokeDashoffset:-2.25*p,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),a.push(O.animate([{opacity:0,offset:0},{opacity:.92,offset:.06},{opacity:.92,offset:.92},{opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));}let l=false,u=()=>{if(l)return;l=true,clearTimeout(w);for(let b of a)try{b.cancel();}catch{}let A=n.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});A.onfinish=()=>n.remove(),window.removeEventListener("click",u);},w=setTimeout(u,14500);return setTimeout(()=>{l||window.addEventListener("click",u);},500),u}function wi(e){let t="http://www.w3.org/2000/svg",n=document.createElement("div");n.setAttribute("data-fork-removed","true"),n.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let r=document.createElementNS(t,"svg");r.setAttribute("width","100%"),r.setAttribute("height","100%"),r.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs"),i=document.createElementNS(t,"filter");i.setAttribute("id","__fork-removed-shadow"),i.setAttribute("x","-10%"),i.setAttribute("y","-10%"),i.setAttribute("width","120%"),i.setAttribute("height","120%");let a=document.createElementNS(t,"feDropShadow");a.setAttribute("dx","0"),a.setAttribute("dy","1"),a.setAttribute("stdDeviation","2"),a.setAttribute("flood-color","rgba(0,0,0,0.15)"),i.appendChild(a),o.appendChild(i),r.appendChild(o);for(let{rect:l,borderRadius:u}of e){let w=l.left,A=l.top,b=l.width,I=l.height,O=Math.min(u,b/2,I/2),R=xo(w,A,b,I,O),p=document.createElementNS(t,"path");p.setAttribute("d",R),p.setAttribute("fill","none"),p.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),p.setAttribute("stroke-width","1.5"),p.setAttribute("stroke-dasharray","8 4"),p.setAttribute("stroke-linecap","round"),p.setAttribute("filter","url(#__fork-removed-shadow)"),p.setAttribute("opacity","0"),r.appendChild(p),p.animate([{opacity:0,offset:0},{opacity:.6,offset:.08},{opacity:.05,offset:.45},{opacity:.6,offset:.85},{opacity:.05,offset:1}],{duration:5e3,easing:"ease-in-out",fill:"forwards"});}return n.appendChild(r),document.body.appendChild(n),n}function Si(e,t){if(e===t)return true;let n=Object.keys(e);if(n.length!==Object.keys(t).length)return false;for(let r of n)if(!Object.is(e[r],t[r]))return false;return true}var xi=ar__namespace.default.memo(function({component:t,containerRef:n,wrapperStyle:r,hostProps:o}){return Xs.jsx("div",{ref:n,style:r,children:Xs.jsx(t,{...o})})},(e,t)=>e.component===t.component&&Si(e.hostProps,t.hostProps)),ir=class extends ar__namespace.default.Component{constructor(t){super(t),this.state={hasError:false};}static getDerivedStateFromError(){return {hasError:true}}componentDidCatch(t){console.error(`[Fork:${this.props.slotId}] fork render failed`,t);}componentDidUpdate(t){t.resetKey!==this.props.resetKey&&this.state.hasError&&this.setState({hasError:false});}render(){return this.state.hasError?this.props.fallback:this.props.children}};function Fo({slotId:e,children:t,githubRepo:n,shared:r,events:o,entityBindings:i}){lr(t,e);let a=Cn(e),{baseUrl:l,apiKey:u,appId:w,shouldSkipAnimation:A,markRevealSeen:b}=Ee(),[I,O]=ar.useState(null),R=ar.useRef(null),p=ar.useRef(null),f=ar.useRef(null),T=ar.useRef(false),x=ar.useRef(null),k=ar.useRef(null),L=!!(r||o),N=ar.useRef(null);L&&!N.current&&(N.current=new Qt(e));let K=ar.useRef(o);if(K.current=o,ar.useEffect(()=>{if(L)return ()=>{N.current?.destroy(),N.current=null;}},[L,e]),L&&N.current&&r)for(let[M,S]of Object.entries(r))N.current.set(M,S);ar.useEffect(()=>{if(!L)return;N.current||(N.current=new Qt(e));let M=N.current,S=Object.keys(K.current||{}).map(U=>M.on(U,(...X)=>K.current?.[U]?.(...X)));return ()=>S.forEach(U=>U())},[L,e]),ar.useEffect(()=>{if(vo.has(e))return;vo.add(e);let M={id:e,appId:w,label:e,eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:n,mode:"direct",sharedKeys:r?Object.keys(r):[],eventNames:o?Object.keys(o):[],propsShape:"",callbackNames:[],entityBindings:i||{}};fetch(`${l}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${u}`,"Content-Type":"application/json"},body:JSON.stringify(M)}).catch(()=>{});},[e,l,u,n,w,i]);let _=a?.id||null;ar.useEffect(()=>{if(a?.bundleUrl,R.current,p.current,!a?.bundleUrl||!_){return}let M=`${l}${a.bundleUrl.replace("bundle.js","component.js")}`,S=a.revealPending===true&&!sr.has(_),U=A(e),X=!U&&S;if(a.revealPending,U&&S&&(sr.add(_),b(a)),X&&p.current){let fe=wo(p.current);f.current=fe,T.current=true,`${e}${fe.length}`;}window.__FORK_REACT__=ar__namespace.default,window.__FORK_REACT_DOM__=Vs__namespace,window.__FORK_REACT_JSX__=Xs__namespace;let V=Date.now(),Q=`${l}${a.bundleUrl.replace("bundle.js","component.css")}?t=${V}`,Z=document.createElement("link");Z.rel="stylesheet",Z.href=Q,Z.dataset.forkSlot=e,document.head.appendChild(Z);let ee=document.createElement("script");return ee.src=M+"?t="+V,ee.onload=()=>{let fe=window.__FORK_EXPORT__;if(fe?.default){if(p.current&&f.current&&T.current){let de=p.current.getBoundingClientRect(),oe=p.current.cloneNode(true);oe.setAttribute("data-fork-clone-overlay","true"),oe.style.position="fixed",oe.style.top=`${de.top}px`,oe.style.left=`${de.left}px`,oe.style.width=`${de.width}px`,oe.style.height=`${de.height}px`,oe.style.flex="none",oe.style.minHeight="auto",oe.style.zIndex="9998",oe.style.pointerEvents="none",oe.style.overflow="hidden";let me=getComputedStyle(p.current).backgroundColor;oe.style.backgroundColor=me&&me!=="rgba(0, 0, 0, 0)"&&me!=="transparent"?me:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(oe);let te=p.current.querySelectorAll("*"),pe=oe.querySelectorAll("*");for(let d=0;d<te.length;d++)te[d].scrollTop!==0&&(pe[d].scrollTop=te[d].scrollTop),te[d].scrollLeft!==0&&(pe[d].scrollLeft=te[d].scrollLeft);x.current=oe;}O(()=>fe.default),R.current=_;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},ee.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(ee),()=>{ee.remove(),Z.remove(),k.current&&(clearTimeout(k.current),k.current=null),x.current&&(x.current.remove(),x.current=null);}},[_,l,e]),ar.useEffect(()=>{if(!T.current||!I||!p.current){`${e}${T.current}`,p.current;return}let M=f.current;if(!M){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!p.current)return;let S=wo(p.current),U=bi(M,S),X=vi(M,S),V=x.current;if(`${e}${U.length}${X.length}`,X.length>0&&V){let Q=wi(X);k.current=setTimeout(()=>{k.current=null;let Z=400;V.animate([{opacity:1},{opacity:0}],{duration:Z,fill:"forwards"}),Q.animate([{opacity:1},{opacity:0}],{duration:Z,fill:"forwards"}),setTimeout(()=>{V.remove(),Q.remove(),x.current=null,U.length>0&&(So(U));},Z);},3500);}else V&&(V.remove(),x.current=null),U.length>0&&(So(U));f.current=null,T.current=false,a&&_&&(sr.add(_),b(a),`${e}`);});});},[I]);let H={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!a||a.status!=="complete"||!a.bundleUrl)return Xs.jsx("div",{ref:p,style:H,children:t});if(!I)return Xs.jsx("div",{ref:p,style:H,children:t});let W=t?.props??{};return Xs.jsx(ir,{slotId:e,resetKey:_,fallback:Xs.jsx("div",{ref:p,style:H,children:t}),children:Xs.jsx(xi,{component:I,containerRef:p,wrapperStyle:H,hostProps:W})})}var Ro=new Set;function Ri(e){return `{ ${Object.entries(e).map(([n,r])=>r==null?`${n}: unknown`:Array.isArray(r)?`${n}: ${r.length>0?typeof r[0]:"unknown"}[]`:`${n}: ${typeof r}`).join("; ")} }`}function Io(e,t=new Set){return ar.Children.forEach(e,n=>{if(!ar.isValidElement(n))return;let r=n.props;for(let[o,i]of Object.entries(r))typeof i=="function"&&/^on[A-Z]/.test(o)&&t.add(o);r.children&&Io(r.children,t);}),t}function Ii({slotId:e,props:t,children:n,allowedFetches:r,entityBindings:o,githubRepo:i,callbacks:a,mode:l="iframe",shared:u,events:w}){if(lr(n,e),l==="direct")return Xs.jsx(Fo,{slotId:e,githubRepo:i,shared:u,events:w,entityBindings:o,children:n});let A=Cn(e),{baseUrl:b,apiKey:I,appId:O,userId:R,userHash:p,currentContainerId:f}=Ee(),T=ar.useRef(null),x=ar.useRef(false),k=ar.useRef(null),L=ar.useRef(a);L.current=a;let N=ar.useRef(t);N.current=t;let K=ar.useRef(r);K.current=r,ar.useEffect(()=>{if(typeof process<"u")return;let W=Io(n),M=new Set(a?Object.keys(a):[]),S=[...W].filter(U=>!M.has(U));S.length>0&&console.error(`[ForkSlot:${e}] Missing bridged callbacks! The following callback props are used by children but not passed to ForkSlot's \`callbacks\` prop:
|
|
2
|
+
`+S.map(U=>` - ${U}`).join(`
|
|
3
|
+
`)+"\n\nThe forked component will not be able to call these. Add them to the `callbacks` prop of <ForkSlot>.");},[e,n,a]),ar.useEffect(()=>{Ro.has(e)||(Ro.add(e),fetch(`${b}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${I}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:O,label:e,propsShape:t?Ri(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:i,callbackNames:a?Object.keys(a):[],mode:l||"iframe",entityBindings:o||{}})}).catch(()=>{}));},[e,b,I,i,O,o]);let _=ar.useCallback(W=>{let M=T.current;if(M?.contentWindow&&x.current){let S=L.current?Object.keys(L.current):[];M.contentWindow.postMessage({type:"slot:props",props:W,callbackNames:S},"*"),k.current=null;}else k.current=W;},[]),H=ar.useCallback((W,M)=>{let S=K.current;return !S||S.length===0?false:S.some(U=>{let[X,V]=U.split(" "),Q=M.split("?")[0];return W.toUpperCase()===X.toUpperCase()&&Q.startsWith(V)})},[]);if(ar.useEffect(()=>{if(!A?.bundleUrl)return;let W=async M=>{if(M.source===T.current?.contentWindow){if(M.data?.type==="slot:ready")x.current=true,T.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:K.current||[]},"*"),K.current,k.current?_(k.current):_(N.current||{});else if(M.data?.type==="slot:event"){let S=M.data.event;S?.navigate&&(window.location.hash=S.navigate);}else if(M.data?.type==="slot:clipboard-write")navigator.clipboard.writeText(M.data.text).catch(S=>{console.warn(`[ForkSlot:${e}] clipboard write failed:`,S.message);});else if(M.data?.type==="slot:callback"){let{name:S,args:U}=M.data,X=L.current?.[S];X?(X(...U||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${S}`);}else if(M.data?.type==="slot:fetch"){let{id:S,method:U,url:X,body:V}=M.data,Q=T.current?.contentWindow;if(!Q)return;let Z=U||"GET";if(!H(Z,X)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${S}: ${Z} ${X} \u2014 not in allowedFetches`),Q.postMessage({type:"slot:fetch-response",id:S,error:`Fetch not allowed: ${Z} ${X}`},"*");return}try{let ee={method:Z};V&&Z!=="GET"&&(ee.headers={"Content-Type":"application/json"},ee.body=JSON.stringify(V));let fe=await fetch(X,ee),de=await fe.json();`${e}${S}${fe.status}`,Q.postMessage({type:"slot:fetch-response",id:S,data:de,status:fe.status},"*");}catch(ee){console.error(`[ForkSlot:${e}] fetch #${S} failed:`,ee.message),Q.postMessage({type:"slot:fetch-response",id:S,error:ee.message},"*");}}else if(M.data?.type==="slot:fork-data"){let{id:S,path:U,method:X,body:V}=M.data,Q=T.current?.contentWindow;if(!Q)return;if(!f||!O){Q.postMessage({type:"slot:fork-data-response",id:S,error:"Fork data is unavailable until appId and containerId are resolved"},"*");return}let Z=typeof U=="string"&&U.startsWith("/")?U:`/${String(U||"")}`,ee=Z.startsWith("/api/v1/data")?Z:`/api/v1/data${Z}`;try{let fe={Authorization:`Bearer ${I}`,"Content-Type":"application/json","X-Fork-App-Id":O,...ue()};R&&(fe["X-Fork-User-Id"]=R),p&&(fe["X-Fork-User-Hash"]=p);let de=typeof X=="string"?X.toUpperCase():"POST",oe=new URL(`${b}${ee}`),me={method:de,headers:fe};de==="GET"?(oe.searchParams.set("appId",O),oe.searchParams.set("containerId",f)):me.body=JSON.stringify({appId:O,containerId:f,...V&&typeof V=="object"?V:{}});let te=await fetch(oe.toString(),me),pe=await te.json().catch(()=>({}));if(!te.ok){let d=typeof pe?.error=="string"?pe.error:`Fork data API ${te.status}`;Q.postMessage({type:"slot:fork-data-response",id:S,error:d,status:te.status},"*");return}Q.postMessage({type:"slot:fork-data-response",id:S,data:pe,status:te.status},"*");}catch(fe){Q.postMessage({type:"slot:fork-data-response",id:S,error:fe.message},"*");}}}};return window.addEventListener("message",W),()=>{window.removeEventListener("message",W),x.current=false;}},[A?.bundleUrl,e,_,H,f,O,I,b,p,R]),ar.useEffect(()=>{A?.bundleUrl&&x.current&&_(t||{});},[t,A?.bundleUrl,_]),!A||A.status!=="complete"||!A.bundleUrl)return `${e}${A?.status||"none"}${A?.bundleUrl||"none"}`,Xs.jsx(Xs.Fragment,{children:n});`${e}${A.bundleUrl}`;let j=`${b}${A.bundleUrl.replace("/bundle.js","/host")}`;return Xs.jsx("iframe",{ref:T,src:j,sandbox:"allow-scripts allow-same-origin allow-forms allow-clipboard-write",title:`Forked ${e}`,style:{width:"100%",border:"none",flex:1,minHeight:0}})}function $n({style:e={width:20,height:20},...t}){return Xs.jsxs("svg",{viewBox:"320 95 270 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:e,...t,children:[Xs.jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M357.789 145.428c0-16.186 13.121-29.307 29.307-29.307 7.773 0 15.227 3.088 20.723 8.584 5.496 5.496 8.584 12.95 8.584 20.723 0 16.186-13.121 29.307-29.307 29.307s-29.307-13.121-29.307-29.307z"}),Xs.jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M387.096 174.735v188"}),Xs.jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M357.789 394.572c0-16.186 13.121-29.307 29.307-29.307 7.773 0 15.227 3.088 20.723 8.584 5.496 5.496 8.584 12.95 8.584 20.723 0 16.186-13.121 29.307-29.307 29.307s-29.307-13.121-29.307-29.307z"}),Xs.jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M388.739 319c10.168-6.317 43.997-26.932 61.009-37.9 17.012-10.968 31.758-19.978 41.064-27.91 9.305-7.931 11.782-14.213 14.767-19.679 2.985-5.465 3.014-8.99 3.141-13.114.128-4.124-.999-8.178-2.377-11.632-1.378-3.454-3.563-6.55-5.889-9.094-2.326-2.543-4.98-4.679-8.066-6.167-3.085-1.488-6.624-2.601-10.448-2.76-3.823-.159-8.624.2-12.495 1.806-3.871 1.607-8.047 4.68-10.732 7.835-2.685 3.156-4.446 7.448-5.378 11.099-.932 3.651-.742 7.485-.213 10.807.528 3.322 1.864 6.46 3.386 9.123 1.523 2.663 3.543 4.843 5.75 6.854 2.207 2.011 4.38 3.914 7.491 5.214 3.111 1.3 6.57 2.808 11.178 2.584 4.607-.225 9.363-.471 16.466-3.932 7.103-3.46 16.076-5.382 26.154-16.831 10.077-11.449 28.593-43.219 34.312-51.862"}),Xs.jsx("path",{fill:"currentColor",stroke:"currentColor",strokeWidth:"1",strokeLinejoin:"round",d:"M527.117 162.547L570.487 134.368Q577.196 130.009 577.624 137.997L580.39 189.69Q580.818 197.678 573.69 194.047L527.536 170.538Q520.408 166.907 527.117 162.547Z"})]})}var Eo=5600,dr=2147483002;function Mi(e){return !e||e.state!=="complete"||!e.latest?null:`${e.latest.id}:${e.latest.completedAt??e.latest.updatedAt}`}function Pi(){return typeof document>"u"?false:!!document.querySelector("[data-fork-clone-overlay], [data-fork-removed], [data-fork-highlights]")}function ur(e,t){let n=Math.min(e.length,t?26:34)*7.4,r=t?Math.min(t.length,24)*6.8+10:0;return Math.round(Math.min(390,Math.max(116,56+n+r)))}function _i(e,t=false){return e?.state==="complete"&&e.unreadCompletedCount>0?e.unreadCompletedCount>1?`${e.unreadCompletedCount} forks ready`:`${e.label} ready`:t?"Fork update ready":void 0}function fr({onClick:e,hasNotification:t=false,activity:n}){let[r,o]=ar.useState(false),[i,a]=ar.useState(false),[l,u]=ar.useState(null),[w,A]=ar.useState(null),[b,I]=ar.useState(null),O=ar.useRef(0),R=r?48:40,p=Mi(n),f=!!(p&&n?.state==="complete"&&n.unreadCompletedCount>0),T=f?p:w?.key??null,x=!!(n&&n.state==="running"&&n.runningCount>0),k=!!(T&&T!==l&&(f||w)),L=x||k,N=f?n?.label:w?.label,K=k?"Built":n?.label??"Fork this app",_=k?N:n?.detail,H=ur(n?.label??"Fork this app",n?.detail),j=ur(K,_),W=k?Math.min(420,Math.max(326,j,w?.width??0,O.current+40)):j,M=k?46:40,S=L?[K,_].filter(Boolean).join(" "):_i(n,t)??"Fork this app",U=L?`${K}:${_??""}`:"idle",X=(t||n?.state==="complete"&&n.unreadCompletedCount>0)&&!L;ar.useEffect(()=>{if(typeof document>"u")return;let te=document.createElement("div");return te.setAttribute("data-fork-button-host","true"),te.style.position="relative",te.style.zIndex=String(dr),document.body.appendChild(te),I(te),()=>{te.remove(),I(null);}},[]),ar.useEffect(()=>{x&&(O.current=H);},[H,x]),ar.useEffect(()=>{!f||!p||!n?.label||A(te=>{if(te?.key===p)return te;let pe=Math.min(420,Math.max(326,ur("Built",n.label),O.current+40));return {key:p,label:n.label,width:pe,startedAt:Date.now()}});},[n?.label,p,f]),ar.useEffect(()=>{n&&n.unreadCompletedCount===0&&n.state!=="running"&&A(null);},[n,n?.state,n?.unreadCompletedCount]),ar.useEffect(()=>{if(!T||!k||T===l)return;let te,pe=w?.key===T?w.startedAt:Date.now(),d=()=>{let E=Date.now()-pe;if(E>=Eo&&!Pi()||E>=Eo*3){u(T);return}te=window.setTimeout(d,250);};return te=window.setTimeout(d,250),()=>{te!==void 0&&window.clearTimeout(te);}},[T,l,w?.key,w?.startedAt,k]);let V=L?{position:"fixed",bottom:24,right:24,zIndex:dr,width:`min(${W}px, calc(100vw - 32px))`,height:M,minWidth:0,maxWidth:"calc(100vw - 32px)",borderRadius:k?12:999,backgroundColor:r?"#ffffff":"rgba(255, 255, 255, 0.92)",border:"1px solid rgba(148, 163, 184, 0.42)",display:"inline-flex",alignItems:"center",justifyContent:k?"flex-start":"center",gap:k?10:8,color:"#111827",boxShadow:r?"0 12px 24px -16px rgba(15, 23, 42, 0.45), 0 4px 10px -6px rgba(15, 23, 42, 0.25)":"0 10px 20px -18px rgba(15, 23, 42, 0.35), 0 2px 7px -5px rgba(15, 23, 42, 0.18)",transform:i?"scale(0.98)":"scale(1)",transition:"width 320ms cubic-bezier(0.16, 1, 0.3, 1), height 320ms cubic-bezier(0.16, 1, 0.3, 1), border-radius 320ms cubic-bezier(0.16, 1, 0.3, 1), transform 180ms ease, box-shadow 180ms ease, background-color 180ms ease, border-color 180ms ease",cursor:"pointer",padding:k?"0 16px 0 14px":"0 13px 0 11px",margin:0,outline:"none",boxSizing:"border-box",fontFamily:'Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif'}:{position:"fixed",bottom:24,right:24,zIndex:dr,width:R,height:R,borderRadius:"50%",backgroundColor:r?"rgba(255, 255, 255, 1)":"rgba(255, 255, 255, 0.3)",border:r?"1px solid rgba(156, 163, 175, 1)":"1px solid rgba(156, 163, 175, 0.3)",display:"flex",alignItems:"center",justifyContent:"center",color:r?"#111827":"rgba(17, 24, 39, 0.5)",boxShadow:r?"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1)":"0 1px 2px 0 rgba(0, 0, 0, 0.05)",transform:i?"scale(0.95)":"scale(1)",transition:"width 320ms cubic-bezier(0.16, 1, 0.3, 1), height 320ms cubic-bezier(0.16, 1, 0.3, 1), border-radius 320ms cubic-bezier(0.16, 1, 0.3, 1), transform 180ms ease, box-shadow 180ms ease, background-color 180ms ease, border-color 180ms ease, color 180ms ease",cursor:"pointer",padding:0,margin:0,outline:"none",boxSizing:"border-box"},Q={minWidth:0,maxWidth:x?286:k?82:_?116:238,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13,fontWeight:650,lineHeight:"16px",letterSpacing:0},Z={minWidth:0,maxWidth:k?278:void 0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flexShrink:k?1:0,color:"#64748b",fontSize:x?13:12,fontWeight:650,lineHeight:"16px",letterSpacing:0},ee={minWidth:0,flex:k?1:void 0,display:"inline-flex",alignItems:"center",justifyContent:k?"flex-start":void 0,gap:8,animation:"__forkButtonTextSwap 220ms ease-out"},fe={width:8,height:8,borderRadius:"50%",backgroundColor:n?.state==="complete"?"#16a34a":"#ef4444",boxShadow:n?.state==="complete"?"0 0 0 3px rgba(22, 163, 74, 0.14)":"none",animation:k?"__forkButtonBuiltDot 420ms ease-out":void 0,flexShrink:0},me=Xs.jsxs(Xs.Fragment,{children:[Xs.jsx("style",{children:`
|
|
4
4
|
@keyframes __forkButtonSpin { to { transform: rotate(360deg); } }
|
|
5
5
|
@keyframes __forkButtonTextSwap {
|
|
6
6
|
from { opacity: 0; transform: translateY(2px); }
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
70% { opacity: 1; transform: scale(1.18); }
|
|
16
16
|
100% { opacity: 1; transform: scale(1); }
|
|
17
17
|
}
|
|
18
|
-
`}),Xs.jsxs("button",{onClick:e,onMouseEnter:()=>o(true),onMouseLeave:()=>{o(false),a(false);},onMouseDown:()=>a(true),onMouseUp:()=>a(false),style:
|
|
18
|
+
`}),Xs.jsxs("button",{onClick:e,onMouseEnter:()=>o(true),onMouseLeave:()=>{o(false),a(false);},onMouseDown:()=>a(true),onMouseUp:()=>a(false),style:V,title:S,"aria-label":S,children:[L&&n?Xs.jsxs(Xs.Fragment,{children:[x?Xs.jsx("span",{"aria-hidden":true,style:{width:14,height:14,borderRadius:"50%",border:"2px solid rgba(17, 24, 39, 0.18)",borderTopColor:"#111827",animation:"__forkButtonSpin 780ms linear infinite",flexShrink:0,boxSizing:"border-box"}}):Xs.jsx("span",{"aria-hidden":true,style:fe}),Xs.jsxs("span",{style:ee,children:[Xs.jsx("span",{style:Q,children:K}),_&&Xs.jsx("span",{style:Z,children:_})]},U)]}):Xs.jsx($n,{style:{width:24,height:24,animation:"__forkButtonLogoIn 220ms ease-out"}}),X&&Xs.jsx("span",{"aria-hidden":true,style:{position:"absolute",top:2,right:2,width:10,height:10,borderRadius:"50%",backgroundColor:"#111827",border:"2px solid #ffffff",boxSizing:"border-box",pointerEvents:"none"}})]})]});return b?Vs.createPortal(me,b):me}var ji={status:lucideReact.Loader2,agent_message:lucideReact.MessageSquare,tool_use:lucideReact.Wrench,build_start:lucideReact.Package,build_complete:lucideReact.Check,build_error:lucideReact.AlertCircle,complete:lucideReact.Sparkles,error:lucideReact.AlertCircle},zi={status:"#60a5fa",agent_message:"#a0a0a0",tool_use:"#fbbf24",build_start:"#c084fc",build_complete:"#6b7280",build_error:"#f87171",complete:"#6b7280",error:"#f87171"},Ki={read:lucideReact.FileSearch,write:lucideReact.Pencil,search:lucideReact.FileSearch,shell:lucideReact.Terminal,build:lucideReact.Package},Wi={read:"#60a5fa",write:"#fbbf24",search:"#60a5fa",shell:"#a78bfa",build:"#c084fc"};function gr(e){let t=e.data;switch(e.type){case "status":return `${t.message||t.status||"..."}`;case "agent_message":{let n=String(t.content||"");return /failed:/i.test(n)&&(n.includes("ENOENT")||n.includes("{")||n.includes("/Users/"))?"Adapting approach...":n}case "tool_use":return String(t.label||"Working on it");case "build_start":return "Bundling your component...";case "build_complete":return "Build complete!";case "build_error":return `Build failed: ${t.error}`;case "complete":return "Your fork is ready!";case "error":return `Error: ${t.error}`;default:return JSON.stringify(t)}}function Lo({events:e}){let t=ar.useRef(null);return ar.useEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight);},[e]),Xs.jsxs(Xs.Fragment,{children:[Xs.jsx("style",{children:`
|
|
19
19
|
@keyframes __fork-spin {
|
|
20
20
|
from { transform: rotate(0deg); }
|
|
21
21
|
to { transform: rotate(360deg); }
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
background: rgba(255, 255, 255, 0.3);
|
|
35
35
|
}
|
|
36
36
|
`}),Xs.jsxs("div",{className:"__fork-stream",ref:t,style:{scrollbarWidth:"thin",scrollbarColor:"rgba(255, 255, 255, 0.15) transparent",backgroundColor:"#1a1a2e",borderRadius:"8px",padding:"12px",fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:"11px",maxHeight:"300px",overflowY:"auto",boxSizing:"border-box"},children:[e.length===0&&Xs.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"#6b7280",fontSize:"11px"},children:[Xs.jsx(lucideReact.Loader2,{style:{width:"12px",height:"12px",animation:"__fork-spin 1s linear infinite",flexShrink:0}}),"Connecting to agent..."]}),e.map((n,r)=>{let o=r===e.length-1,i=n.type==="complete"||n.type==="error"||n.type==="build_complete"||n.type==="build_error",a=o&&!i&&(n.type==="status"||n.type==="tool_use"||n.type==="build_start"),l=ji[n.type]||lucideReact.Code,u=zi[n.type]||"#9ca3af";if(n.type==="tool_use"){let w=String(n.data.category||"");l=Ki[w]||lucideReact.Wrench,u=Wi[w]||"#fbbf24";}return a?l=lucideReact.Loader2:!o&&n.type==="status"&&(l=lucideReact.Check,u="#4ade80"),Xs.jsxs("div",{style:{display:"flex",gap:"6px",marginBottom:"6px",lineHeight:1.625},children:[Xs.jsx(l,{style:{width:"12px",height:"12px",marginTop:"2px",flexShrink:0,color:u,...a?{animation:"__fork-spin 1s linear infinite"}:{}}}),Xs.jsx("span",{style:{color:o&&!i?"#d1d5db":"#6b7280",wordBreak:"break-all"},children:gr(n)})]},r)})]})]})}var Vi=0;function Xi(e){let t=/^data:([^;,]+);base64,(.+)$/.exec(e);return t?{mediaType:t[1],data:t[2]}:null}function qi(e){return new Promise((t,n)=>{let r=URL.createObjectURL(e),o=new Image;o.onload=()=>{URL.revokeObjectURL(r),t(o);},o.onerror=()=>{URL.revokeObjectURL(r),n(new Error("Failed to decode image"));},o.src=r;})}async function Ho(e){if(!e.type.startsWith("image/"))return null;let t;try{t=await qi(e);}catch{return null}let{naturalWidth:n,naturalHeight:r}=t;if(!n||!r)return null;let o=Math.min(1,1568/Math.max(n,r)),i=document.createElement("canvas");i.width=Math.max(1,Math.round(n*o)),i.height=Math.max(1,Math.round(r*o));let a=i.getContext("2d");if(!a)return null;a.fillStyle="#ffffff",a.fillRect(0,0,i.width,i.height),a.drawImage(t,0,0,i.width,i.height);let l=i.toDataURL("image/png");l.length>2e6&&(l=i.toDataURL("image/jpeg",.85));let u=Xi(l);return u?{id:`img-${++Vi}-${Date.now().toString(36)}`,dataUrl:l,mediaType:u.mediaType,data:u.data}:null}function Oo(e){let t=e.clipboardData?.items;if(!t)return [];let n=[];for(let r=0;r<t.length;r++){let o=t[r];if(o.kind==="file"&&o.type.startsWith("image/")){let i=o.getAsFile();i&&n.push(i);}}return n}var Gi="rgba(59, 130, 246, 0.16)",Yi="1px solid #3b82f6";function Zi(e){let t=e;for(;t;){if(t.hasAttribute("data-fork-panel-host")||t.hasAttribute("data-fork-button-host")||t.hasAttribute("data-fork-picker-overlay"))return true;let n=t.getRootNode();t=t.parentElement??(n instanceof ShadowRoot?n.host:null);}return false}function Uo(e){let t=Object.keys(e).find(o=>o.startsWith("__reactFiber$")||o.startsWith("__reactInternalInstance$"));if(!t)return;let n=e[t],r=0;for(;n&&r<30;){let o=n.type;if(typeof o=="function"){let i=o.displayName||o.name;if(i&&!/^(styled|ForwardRef|Anonymous)/.test(i))return i}else if(typeof o=="object"&&o!==null){let i=o.displayName||o.render?.displayName||o.render?.name;if(i)return i}n=n.return,r++;}}function Qi(e){let t=[],n=e,r=0;for(;n&&n!==document.body&&r<6;){let o=n.tagName.toLowerCase();if(n.id){t.unshift(`#${CSS.escape(n.id)}`);break}let i=Array.from(n.classList).filter(a=>!/[[\]:]/.test(a)).slice(0,2);if(i.length>0)o+="."+i.map(a=>CSS.escape(a)).join(".");else if(n.parentElement){let a=Array.from(n.parentElement.children).filter(l=>l.tagName===n.tagName);a.length>1&&(o+=`:nth-of-type(${a.indexOf(n)+1})`);}t.unshift(o),n=n.parentElement,r++;}return t.join(" > ")}function ea(e){let t=e.outerHTML;if(t.length>2e3){let n=t.indexOf(">");n>-1&&n<1900?t=t.slice(0,2e3)+`
|
|
37
|
-
<!-- \u2026truncated\u2026 -->`:t=t.slice(0,2e3);}return t}function ta(e){let t=e.getBoundingClientRect(),n=(e.textContent??"").replace(/\s+/g," ").trim(),r={tag:e.tagName.toLowerCase(),selector:Qi(e),html:ea(e),rect:{x:Math.round(t.x),y:Math.round(t.y),width:Math.round(t.width),height:Math.round(t.height)}};e.id&&(r.id=e.id);let o=Array.from(e.classList).slice(0,10);o.length>0&&(r.classes=o),n&&(r.text=n.slice(0,300));let i=Uo(e);return i&&(r.componentName=i),r}function Ln(e){let t=e.tag;if(e.id)t+=`#${e.id}`;else if(e.classes?.length)t+=`.${e.classes.slice(0,2).join(".")}`;else if(e.componentName)return `<${e.componentName}>`;return t.length>36?t.slice(0,35)+"\u2026":t}function No(e){let t=document.createElement("div");t.setAttribute("data-fork-picker-overlay",""),t.style.cssText=["position: fixed","inset: 0","pointer-events: none","z-index: 2147483001"].join(";");let n=document.createElement("div");n.style.cssText=["position: fixed","display: none",`background: ${Gi}`,`border: ${Yi}`,"border-radius: 2px","pointer-events: none","box-sizing: border-box","transition: all 40ms linear"].join(";");let r=document.createElement("div");r.style.cssText=["position: fixed","display: none","background: #1f2937","color: #ffffff","font: 500 11px/1.4 ui-sans-serif, system-ui, sans-serif","padding: 3px 8px","border-radius: 6px","pointer-events: none","white-space: nowrap","box-shadow: 0 2px 8px rgba(0,0,0,0.25)"].join(";"),t.appendChild(n),t.appendChild(r),document.body.appendChild(t);let o=document.createElement("style");o.textContent="*, * > * { cursor: crosshair !important; }",document.head.appendChild(o);let i=null,a=false,l=()=>{i=null,n.style.display="none",r.style.display="none";},u=f=>{let T=f.getBoundingClientRect();n.style.display="block",n.style.left=`${T.left}px`,n.style.top=`${T.top}px`,n.style.width=`${T.width}px`,n.style.height=`${T.height}px`;let x=Uo(f),k=f.tagName.toLowerCase();f.id?k+=`#${f.id}`:f.classList.length>0&&(k+=`.${Array.from(f.classList).slice(0,2).join(".")}`),k.length>42&&(k=k.slice(0,41)+"\u2026"),r.textContent=x?`${k} \xB7 ${x} \xB7 ${Math.round(T.width)}\xD7${Math.round(T.height)}`:`${k} \xB7 ${Math.round(T.width)}\xD7${Math.round(T.height)}`,r.style.display="block";let L=T.top>=30?T.top-26:Math.max(4,T.top+4);r.style.top=`${L}px`,r.style.left=`${Math.max(4,Math.min(T.left,window.innerWidth-320))}px`;},w=(f,T)=>{let x=document.elementFromPoint(f,T);return !x||x===document.documentElement||x===document.body||Zi(x)?null:x},A=f=>{let T=w(f.clientX,f.clientY);if(!T){l();return}T!==i&&(i=T,u(T));},b=()=>{i&&u(i);},E=f=>{let T=w(f.clientX,f.clientY);if(!T)return;f.preventDefault(),f.stopPropagation();let x=ta(T);p(),e.onPick(x);},U=f=>{w(f.clientX,f.clientY)&&(f.preventDefault(),f.stopPropagation());},R=f=>{f.key==="Escape"&&(f.preventDefault(),f.stopPropagation(),p(),e.onCancel());};function p(){a||(a=true,document.removeEventListener("mousemove",A,true),document.removeEventListener("click",E,true),document.removeEventListener("mousedown",U,true),document.removeEventListener("mouseup",U,true),document.removeEventListener("keydown",R,true),document.removeEventListener("scroll",b,true),window.removeEventListener("resize",b),t.remove(),o.remove());}return document.addEventListener("mousemove",A,true),document.addEventListener("click",E,true),document.addEventListener("mousedown",U,true),document.addEventListener("mouseup",U,true),document.addEventListener("keydown",R,true),document.addEventListener("scroll",b,true),window.addEventListener("resize",b),{stop:p}}function Bo(){if(typeof window>"u")return null;let e=window;return e.SpeechRecognition||e.webkitSpeechRecognition||null}function Do(){return Bo()!==null}function jo(e){let t=Bo();if(!t)return null;let n=true,r="",o=null,i=0,a=0,l=()=>{let u=new t;u.lang=typeof navigator<"u"&&navigator.language||"en-US",u.continuous=true,u.interimResults=true,u.onresult=w=>{let A="";for(let b=w.resultIndex;b<w.results.length;b++){let E=w.results[b],U=E[0]?.transcript??"";E.isFinal?r+=U:A+=U;}n&&e.onText(r,A);},u.onerror=w=>{let A=String(w?.error??"");if(A==="no-speech"||A==="aborted")return;n=false;let b=A==="not-allowed"||A==="service-not-allowed"?"not-allowed":A==="network"?"network":"other";e.onError(b);},u.onend=()=>{if(!n)return;let w=Date.now();if(w-i<1e3){if(a++,a>2){n=false,e.onError("other");return}}else a=0;i=w;try{u.start();}catch{try{l();}catch{n=false,e.onError("other");}}},o=u,u.start();};try{l();}catch{return null}return {stop:()=>{n=false;try{o?.stop();}catch{}}}}var Wo=35,pa="Setting up environment",ga="Built Custom Feature",hr=360,on=380;function yr(e){let t=Date.parse(e);if(Number.isNaN(t))return "";let n=Math.max(1,Math.round((Date.now()-t)/1e3));if(n<60)return `${n}s`;let r=Math.round(n/60);if(r<60)return `${r}m`;let o=Math.round(r/60);return o<24?`${o}h`:`${Math.round(o/24)}d`}function ma(e){return e.length<=Wo?e:e.slice(0,Wo-3).trimEnd()+"..."}function ha({events:e}){let[t,n]=ar.useState("Setting up environment..."),[r,o]=ar.useState(true),i=ar.useRef(t),a=ar.useRef(false);return ar.useEffect(()=>{if(!a.current){for(let u of e)if(u.type==="status"&&String(u.data.message||"").includes("Agent started")){a.current=true;break}}let l="Setting up environment...";if(a.current)for(let u=e.length-1;u>=0;u--){let w=e[u];if(w.type==="tool_use"||w.type==="build_start"||w.type==="build_complete"){l=ma(gr(w));break}}if(l!==i.current){o(false);let u=setTimeout(()=>{n(l),i.current=l,o(true);},200);return ()=>clearTimeout(u)}},[e]),Xs.jsx("span",{style:{fontSize:12.5,color:"#334155",fontWeight:600,opacity:r?1:0,transition:"opacity 0.2s ease",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},children:t})}function ya({children:e}){let[t,n]=ar.useState(null);return ar.useEffect(()=>{if(typeof document>"u")return;let r=document.createElement("div");r.setAttribute("data-fork-panel-host",""),r.style.cssText="all: initial;",document.body.appendChild(r);let o=r.attachShadow({mode:"open"});return n(o),()=>{r.remove();}},[]),t?Vs.createPortal(e,t):null}function Un({state:e,fork:t,events:n,error:r,runs:o={},slotId:i,targetId:a,targetLabel:l,historyMode:u="slot",onSubmit:w,onUndo:A,onPlanRevert:b,onRevert:E,onSetForkDisabled:U,onRenameFork:R,onClose:p,baseUrl:f,apiKey:T,userId:x,userHash:k,appId:L,embedded:N=false,completeVariant:K="bubble"}){let[_,H]=ar.useState(""),[j,W]=ar.useState([]),[M,S]=ar.useState(false),[O,V]=ar.useState(false),[q,Q]=ar.useState(false),[Z,ee]=ar.useState(false),[fe,de]=ar.useState(false),[oe,me]=ar.useState(false),[te,pe]=ar.useState(false),[d,I]=ar.useState(false),[h,c]=ar.useState(false),[g,$]=ar.useState(null),[B,D]=ar.useState(null),[Y,ft]=ar.useState(null),[ve,Pe]=ar.useState(false),[gn,Ie]=ar.useState(null),[mn,rt]=ar.useState(0),[pt,gt]=ar.useState(null),[ot,mt]=ar.useState(null),[$e,Kt]=ar.useState(null),[Ge,Wt]=ar.useState(false),[It,Ct]=ar.useState(null),[Ne,we]=ar.useState(""),[Je,Ve]=ar.useState(false),[zn,Tt]=ar.useState(false),[Jt,ht]=ar.useState([]),[Ce,m]=ar.useState(null),[F,P]=ar.useState(false),[G,ie]=ar.useState(false),[ae,ce]=ar.useState(false),[Se,Te]=ar.useState(null),[le,he]=ar.useState(null),[ye,ke]=ar.useState(false),[_e,xe]=ar.useState(false),[Fe,Be]=ar.useState(""),De=ar.useRef(null),[$t,st]=ar.useState(null),[Kn,Wn]=ar.useState(false),[Mt,Pr]=ar.useState(null),[Pt,hn]=ar.useState([]),[Ss,xs]=ar.useState(0),[re,Ye]=ar.useState(null),[Xe,Ze]=ar.useState(false),it=ar.useRef(false),_t=ar.useRef(null),yn=ar.useRef(null),[at,Jn]=ar.useState([]),[yt,Vn]=ar.useState(null),[kt,kn]=ar.useState(false),Lt=ar.useRef(null),[Ht,Xn]=ar.useState(false),Vt=ar.useRef(null),_r=ar.useRef(""),[Lr,Hr]=ar.useState(null),Ot=ar.useRef(null),Or=ar.useRef(null),[Fs,Ur]=ar.useState(false),[As,Nr]=ar.useState(false),[Rs,Br]=ar.useState(false),[Es,Dr]=ar.useState(null),{resetAllForks:Is,adminContext:ze,setAdminContainer:Cs,currentContainerId:jr,forksPaused:Ut,setForksPaused:Ts,forkActivities:zr,markForkActivitySeen:Kr}=Ee(),bn=ze.containerId??jr,vn=!!(ze.isAdmin&&Kn),$s=!!(ze.containerId??jr),[Wr,Jr]=ar.useState(false),Ke=Mt!==null,Vr=ar.useRef(p);ar.useEffect(()=>{Vr.current=p;});let qn=ar.useRef(null),wn=ar.useRef(false),Xr=typeof window<"u"&&"documentPictureInPicture"in window,Ms=async()=>{if(!(!Xr||Ke))try{let s=await window.documentPictureInPicture.requestWindow({width:hr,height:640});s.document.body.style.margin="0",s.document.body.style.padding="0",s.document.body.style.height="100vh",s.document.body.style.overflow="hidden",s.document.body.style.background="#ffffff";try{let v=document.adoptedStyleSheets??[];v.length>0&&(s.document.adoptedStyleSheets=[...v]);}catch{}s.addEventListener("pagehide",()=>{qn.current=null,Pr(null),wn.current||Vr.current(),wn.current=!1;},{once:!0}),qn.current=s,Pr(s);}catch(s){console.warn("[Fork] PiP open failed:",s);}},Ps=()=>{Mt&&(wn.current=true,Mt.close());};ar.useEffect(()=>()=>{wn.current=true,qn.current?.close();},[]);let Xt=a??i??"";(l||Xt).replace(/[-_]+/g," ").replace(/\b\w/g,s=>s.toUpperCase());let Sn=ar.useRef(""),qt=()=>{let s={Authorization:`Bearer ${T}`,...ue()};return L&&(s["X-Fork-App-Id"]=L),x&&(s["X-Fork-User-Id"]=x),k&&(s["X-Fork-User-Hash"]=k),s},Nt=N?true:O&&!q,Gt=re?o[re]??null:null,Yt=re?Pt.find(s=>s.id===re)??null:null,_s=Yt?(s=>s==="pending"||s==="running"||s==="building")(Yt.status):false,qe=re?Gt?.state??(_s?"running":null):Xe?e:null,Bt=re?Gt?.events??[]:Xe?n:[],Ls=re?Gt?.state==="error"?Gt.error:null:Xe&&e==="error"?r:null,Gn=re?Gt?.fork??null:Xe?t:null,Hs=Object.values(o).filter(s=>s.state!=="running").length,qr=re?!!zr.find(s=>s.id===re)?.unread:false;ar.useEffect(()=>{re&&qr&&Kr(re);},[re,qr,Kr]);let Os=Bt.find(s=>{let v=s.data;return s.type==="status"&&v.summary})?.data?.summary||Gn?.summary||pa,bt=Bt.find(s=>{let v=s.data;return (s.type==="status"||s.type==="complete")&&typeof v?.estimateMinutes=="number"})?.data?.estimateMinutes??Gn?.estimateMinutes;ar.useEffect(()=>{if(u==="none"){S(true);return}if(!f||!T)return;if(!re){W([]),S(true);return}let s=new AbortController;return fetch(`${f}/api/v1/forks/${encodeURIComponent(re)}/messages`,{headers:qt(),signal:s.signal}).then(v=>v.ok?v.json():[]).then(v=>{if(s.signal.aborted)return;let C=[];for(let z of v){let se=z.forkId??re,be={promptId:z.promptId??null,promptKind:z.promptKind??null,reverted:!!z.reverted};if(z.role==="user"){let Qe=(z.attachments??[]).filter(Le=>Le&&typeof Le.mediaType=="string"&&typeof Le.data=="string").map(Le=>({dataUrl:`data:${Le.mediaType};base64,${Le.data}`}));C.push({type:"user",text:z.content,forkId:se,timestamp:z.timestamp,attachments:Qe.length>0?Qe:void 0,selectedElement:z.selectedElement?{label:Ln(z.selectedElement)}:void 0,...be});}else C.push({type:"applied",text:z.content,forkId:se,timestamp:z.timestamp,...be});}W(C),S(true);}).catch(()=>{s.signal.aborted||S(true);}),()=>{s.abort();}},[T,L,f,u,re,ze.containerId,k,x,t?.id,t?.completedAt,mn]),ar.useEffect(()=>{if(u==="none"||!f||!T||!F)return;if(!Ce){hn([]);return}let s=new AbortController,v=new URLSearchParams({container_id:Ce});return fetch(`${f}/api/v1/forks?${v.toString()}`,{headers:qt(),signal:s.signal}).then(C=>C.ok?C.json():{forks:[]}).then(C=>{s.signal.aborted||hn(C.forks??[]);}).catch(()=>{}),()=>{s.abort();}},[T,L,f,u,Ce,F,t?.id,t?.completedAt,Hs,Ss,ze.containerId,k,x,mn]),ar.useEffect(()=>{e==="complete"&&I(false);},[e]);let Gr=Pt.some(s=>s.status==="pending"||s.status==="running"||s.status==="building");ar.useEffect(()=>{if(!Gr||!f||!T||!Ce)return;let s=new URLSearchParams({container_id:Ce}),v=qt(),z=setInterval(async()=>{try{let se=await fetch(`${f}/api/v1/forks?${s.toString()}`,{headers:v});if(!se.ok)return;let be=await se.json();hn(be.forks??[]);}catch{}},3e3);return ()=>clearInterval(z)},[Gr,f,T,L,Ce]),ar.useEffect(()=>{if(N&&u==="none"){ht([]),m(null),P(true),Wn(false);return}if(ze.isAdmin){st(null),ht(ze.containers.map(s=>({id:s.id,name:s.name,createdAt:"",hasAccess:true,isPrimary:s.isPrimary}))),m(ze.containerId??null),Wn(true),P(true);return}bn?(ht([{id:bn,name:"Primary container",createdAt:""}]),m(bn)):(ht([]),m(null)),P(true),Wn(false);},[T,bn,f,N,u,ze.isAdmin,ze.containerId,ze.containers]);let xn=ar.useRef(void 0);ar.useEffect(()=>{if(F){if(xn.current===void 0){xn.current=Ce;return}xn.current!==Ce&&(xn.current=Ce,W([]),S(false));}},[Ce,F]);let Fn=ar.useRef(null);ar.useEffect(()=>{if(!G)return;let s=C=>{if(!Fn.current)return;let z=typeof C.composedPath=="function"?C.composedPath():[];Fn.current.contains(C.target)||z.includes(Fn.current)||ie(false);},v=C=>{C.key==="Escape"&&ie(false);};return document.addEventListener("mousedown",s,true),document.addEventListener("keydown",v,true),()=>{document.removeEventListener("mousedown",s,true),document.removeEventListener("keydown",v,true);}},[G]),ar.useEffect(()=>{if(N||!Nt||q||Ke||kt)return;let s=v=>{(typeof v.composedPath=="function"?v.composedPath():[]).some(se=>se instanceof Element&&se.hasAttribute("data-fork-panel-host"))||(Q(true),V(false),setTimeout(()=>p(),on));};return document.addEventListener("mousedown",s,true),()=>{document.removeEventListener("mousedown",s,true);}},[N,Nt,q,Ke,kt,p]),ar.useEffect(()=>{G||(xe(false),Be(""));},[G]),ar.useEffect(()=>{_e&&(De.current?.focus(),De.current?.select());},[_e]),ar.useEffect(()=>{if(N)return;let s=requestAnimationFrame(()=>V(true));return ()=>cancelAnimationFrame(s)},[N]),ar.useEffect(()=>{let s=N||Ke;if((s||Nt)&&(e==="prompting"||e==="complete")){let v=setTimeout(()=>_t.current?.focus(),s?100:on+100);return ()=>clearTimeout(v)}},[Nt,N,Ke,e]);let Yr=ar.useRef(new Set);ar.useEffect(()=>{for(let s of Object.values(o)){if(s.state!=="complete"||s.events.length===0)continue;let v=`${s.forkId}:${s.fork.completedAt??""}`;if(Yr.current.has(v))continue;Yr.current.add(v);let z=s.events.find(se=>se.type==="complete")?.data?.summary||s.fork.summary||ga;W(se=>{let be=[...se].reverse().find(Qe=>Qe.forkId===s.forkId);return be?.type==="applied"&&be.text===z?se:[...se,{type:"applied",text:z,forkId:s.forkId,timestamp:s.fork.completedAt??new Date().toISOString()}]});}},[o]),ar.useEffect(()=>{qe==="complete"&&Sn.current&&(H(""),setTimeout(()=>_t.current?.focus(),200));},[qe]),ar.useEffect(()=>{yn.current&&(yn.current.scrollTop=yn.current.scrollHeight);},[j,e]),ar.useEffect(()=>{let s=_t.current;s&&(s.style.height="auto",s.style.height=Math.min(s.scrollHeight,160)+"px");},[_]);let lt=s=>{Hr(s),Ot.current&&clearTimeout(Ot.current),Ot.current=setTimeout(()=>{Ot.current=null,Hr(null);},3200);},Zr=async s=>{if(s.length===0)return;let v=4-at.length;if(v<=0){lt(`Up to ${4} images per prompt`);return}s.length>v&<(`Up to ${4} images per prompt`);let z=(await Promise.all(s.slice(0,v).map(Ho))).filter(se=>se!==null);z.length!==0&&(Jn(se=>[...se,...z].slice(0,4)),_t.current?.focus());},Qr=()=>{Lt.current?.stop(),Lt.current=null,kn(false);},Us=()=>{if(kt){Qr();return}kn(true),lt("Click an element on the page \xB7 Esc to cancel"),Lt.current=No({onPick:s=>{Lt.current=null,kn(false),Vn(s),_t.current?.focus();},onCancel:()=>{Lt.current=null,kn(false);}});},eo=()=>{Vt.current?.stop(),Vt.current=null,Xn(false);},Ns=()=>{if(Ht){eo();return}if(!Do()){lt("Voice input is coming soon for this browser");return}let s=_.length>0&&!_.endsWith(" ")?_+" ":_;_r.current=s;let v=jo({onText:(C,z)=>{H(_r.current+C+z);},onError:C=>{Vt.current=null,Xn(false),lt(C==="not-allowed"?"Microphone access is blocked":C==="network"?"Voice input is coming soon for this browser":"Voice input stopped");}});if(!v){lt("Voice input is coming soon for this browser");return}Vt.current=v,Xn(true);};ar.useEffect(()=>()=>{Lt.current?.stop(),Vt.current?.stop(),Ot.current&&clearTimeout(Ot.current);},[]);let Dt=!!(_.trim()||at.length>0),to=()=>{if(!Dt)return;Ht&&eo(),kt&&Qr();let s=_.trim()||"See the attached screenshot.";Sn.current=s;let v={};at.length>0&&(v.attachments=at.map(({mediaType:z,data:se})=>({mediaType:z,data:se}))),yt&&(v.selectedElement=yt);let C=Xe||!re;C?(v.forceNew=true,it.current=true,Xe||Ze(true)):v.forkId=re,C||W(z=>[...z,{type:"user",text:s,forkId:re,attachments:at.length>0?at.map(se=>({dataUrl:se.dataUrl})):void 0,selectedElement:yt?{label:Ln(yt)}:void 0}]),w(s,Xt,Ce,v),H(""),Jn([]),Vn(null);};ar.useEffect(()=>{if(it.current){if(e==="error"){it.current=false;return}t?.id&&(Ye(t.id),Ze(false),it.current=false);}},[t?.id,e]);let no=ar.useRef(new Set);ar.useEffect(()=>{t?.id&&(it.current||e!=="running"&&e!=="complete"||no.current.has(t.id)||(no.current.add(t.id),Ye(s=>s??t.id),Ze(false)));},[t?.id,e]);let ro=s=>{Cs(s.container.id,s.container.name),m(s.container.id),ht(v=>{let C=v.filter(z=>z.id!==s.container.id);return [{...s.container,isPrimary:true,hasAccess:true},...C.map(z=>({...z,isPrimary:false}))]}),Ye(null),Ze(false),it.current=false,W([]),S(false),Sn.current="";},Bs=async s=>{if(!(!vn||le)){he(s),st(null);try{let v=await fetch(`${f}/api/v1/admin/containers/${encodeURIComponent(s)}/primary`,{method:"POST",headers:qt()});if(!v.ok){let C=await v.json().catch(()=>({}));throw new Error(C.error||`API error: ${v.status}`)}ro(await v.json()),ie(!1);}catch(v){st(v instanceof Error?v.message:String(v));}finally{he(null);}}},oo=async s=>{if(!vn||le)return;let v=s.trim();if(v){he("__new__"),st(null);try{let C=await fetch(`${f}/api/v1/admin/containers`,{method:"POST",headers:{...qt(),"Content-Type":"application/json"},body:JSON.stringify({name:v})});if(!C.ok){let z=await C.json().catch(()=>({}));throw new Error(z.error||`API error: ${C.status}`)}ro(await C.json()),xe(!1),Be(""),ie(!1);}catch(C){st(C instanceof Error?C.message:String(C));}finally{he(null);}}},so=async()=>{if(!(!A||h||!Xt)){c(true);try{(await A(Xt,re))?.removed?(W([]),Ye(null),Ze(!1),it.current=!1):W(v=>{let C=[...v];return C.length>=2&&C[C.length-1]?.type==="applied"?C.splice(-2,2):C.length>=1&&C[C.length-1]?.type==="applied"&&C.splice(-1,1),C}),xs(v=>v+1);}catch{}finally{c(false);}}},Ds=async(s,v)=>{if(!b||!s.forkId||!s.promptId||ve)return;let C=s.forkId,z=s.promptId;Ie(null),ft(z),D({forkId:C,promptId:z,mode:v,scope:"step",plan:null});try{let se=await b(C,z,v);D(be=>be&&be.forkId===C&&be.promptId===z&&be.mode===v?{...be,plan:se}:be);}catch(se){Ie(se instanceof Error?se.message:String(se)),D(be=>be&&be.forkId===C&&be.promptId===z?null:be);}finally{ft(null);}},js=async s=>{if(!(!b||ve)){gt(null),Ie(null),ft(s),D({forkId:s,mode:"remove_step",scope:"fork",plan:null});try{let v=await b(s,void 0,"remove_step");D(C=>C&&C.forkId===s&&C.scope==="fork"?{...C,plan:v}:C);}catch(v){let C=v instanceof Error?v.message:String(v);mt(s),Ie(/not found/i.test(C)?`Error: ${C} for this fork`:`Error: ${C}`),D(z=>z&&z.forkId===s?null:z);}finally{ft(null);}}};ar.useEffect(()=>{if(!$e)return;let s=o[$e.tipId]?.state;s==="complete"?(Kt(null),rt(v=>v+1)):s==="error"&&(mt($e.forkId),Ie(`Error: couldn't ${$e.disabling?"disable":"re-enable"} this fork \u2014 ${o[$e.tipId]?.error??"the rewrite failed"}. Nothing was changed.`),Kt(null),rt(v=>v+1));},[o,$e]);let io=async()=>{if(!(!R||!It||Je)){Ve(true),Ie(null);try{await R(It,Ne.trim()),Ct(null),we(""),rt(s=>s+1);}catch(s){Ie(s instanceof Error?s.message:String(s));}finally{Ve(false);}}},ao=async(s,v)=>{if(!(!U||Ge)){gt(null),Ie(null),mt(null),Wt(true);try{let C=await U(s,v);C?.agentic&&C?.fork?.id?Kt({forkId:s,tipId:C.fork.id,disabling:v}):rt(z=>z+1);}catch(C){let z=C instanceof Error?C.message:String(C);mt(s),/not found/i.test(z)?(Ie("Error: this fork no longer exists \u2014 refreshing the list."),setTimeout(()=>{mt(null),Ie(null),rt(se=>se+1);},1800)):Ie(`Error: ${z}`);}finally{Wt(false);}}},lo=async s=>{if(!(!E||!B?.plan||ve)){Pe(true),Ie(null);try{let v=await E({forkId:B.forkId,promptId:B.promptId,mode:B.mode,strategy:s});D(null),v.agentic?(Ze(!1),Ye(v.fork.id)):v.removed&&(W([]),Ye(null)),rt(C=>C+1);}catch(v){Ie(v instanceof Error?v.message:String(v));}finally{Pe(false);}}},co=()=>{if(N){p();return}if(Ke){Mt?.close();return}Q(true),V(false),setTimeout(()=>p(),on);},zs=N||Ke?{position:"relative",width:"100%",height:"100%",background:"#ffffff",display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'}:{position:"fixed",top:0,right:0,bottom:0,zIndex:2147483e3,width:hr,maxWidth:"100vw",background:"#ffffff",boxShadow:Nt?"-12px 0 32px -16px rgba(0, 0, 0, 0.18), -2px 0 8px -2px rgba(0, 0, 0, 0.06)":"none",borderLeft:"1px solid rgba(0, 0, 0, 0.08)",transform:Nt?"translateX(0)":"translateX(100%)",transition:`transform ${on}ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow ${on}ms ease`,display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'},uo=Jt.find(s=>s.id===Ce)?.name??(F?"Fork":"Loading..."),Ks=[...Pt].sort((s,v)=>+!!s.disabledAt-+!!v.disabledAt),jt=Xe?[]:re?j.filter(s=>s.forkId===re||s.forkId==null):j,vt=B?.scope==="fork",We=B?.plan??null,fo=B?Xs.jsxs("div",{style:{animation:"__fork-expand-in 0.22s cubic-bezier(0.22, 1, 0.36, 1)",overflow:"hidden",background:"#f9fafb",border:"1px solid #f3f4f6",borderRadius:10,padding:"10px 12px"},children:[Xs.jsx("div",{style:{fontSize:13,fontWeight:600,color:"#111827",textAlign:"center"},children:B.mode==="revert_to"?"Go Back to This Point?":vt?"Delete This Fork?":"Remove This Change?"}),We?Xs.jsxs(Xs.Fragment,{children:[Xs.jsxs("div",{style:{fontSize:12,color:"#6b7280",marginTop:3,lineHeight:1.5,textAlign:"center"},children:[B.mode==="revert_to"?`${We.removes.length} later change${We.removes.length===1?"":"s"} will be discarded.`:We.laterSteps.length>0?`${We.laterSteps.length} later change${We.laterSteps.length===1?" was":"s were"} built on top of ${vt?"this fork":"this one"}.`:vt?"Deleting it is instant and cannot be undone.":"This is the latest change; removing it is instant.",We.busy&&" A run is in progress \u2014 try again once it finishes."]}),Xs.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flexWrap:"wrap",gap:8,marginTop:10},children:[Xs.jsx("button",{onClick:()=>{D(null),Ie(null);},disabled:ve,style:{padding:"5px 12px",fontSize:12,fontWeight:500,borderRadius:7,border:"none",background:"#f3f4f6",color:"#374151",cursor:ve?"default":"pointer",transition:"background 0.12s"},onMouseEnter:s=>s.currentTarget.style.background="#e5e7eb",onMouseLeave:s=>s.currentTarget.style.background="#f3f4f6",children:"Cancel"}),We.strategies.some(s=>s.id==="keep_later")&&Xs.jsx("button",{onClick:()=>lo("keep_later"),disabled:ve,title:"The AI rewrites the later forks' code so their features survive without this one",style:{padding:"5px 12px",fontSize:12,fontWeight:500,borderRadius:7,border:"none",background:"#eef2ff",color:"#4338ca",cursor:ve?"default":"pointer",opacity:ve?.5:1,transition:"background 0.12s"},onMouseEnter:s=>s.currentTarget.style.background="#e0e7ff",onMouseLeave:s=>s.currentTarget.style.background="#eef2ff",children:`${vt?"Delete This Fork":"Remove This Change"} (~${We.strategies.find(s=>s.id==="keep_later")?.estimateMinutes??2}m)`}),Xs.jsx("button",{onClick:()=>lo("discard_later"),disabled:ve,title:We.laterSteps.length>0?"Instant \u2014 also removes everything built on top of this":"Instant",style:{padding:"5px 12px",fontSize:12,fontWeight:500,borderRadius:7,border:"none",background:"#fef2f2",color:"#b91c1c",cursor:ve?"default":"pointer",opacity:ve?.5:1,transition:"background 0.12s"},onMouseEnter:s=>s.currentTarget.style.background="#fee2e2",onMouseLeave:s=>s.currentTarget.style.background="#fef2f2",children:B.mode==="revert_to"?"Go Back to Here":We.laterSteps.length>0?vt?"Delete All Related":"Remove All Related":vt?"Delete":"Remove"})]})]}):Xs.jsx("div",{style:{fontSize:12,color:"#9ca3af",fontStyle:"italic",marginTop:4,textAlign:"center",animation:"__fork-pulse 1.2s ease-in-out infinite"},children:B.mode==="revert_to"?"Evaluating undo...":vt?"Evaluating delete...":"Evaluating remove..."})]}):null,An=gn?Xs.jsx("div",{style:{animation:"__fork-expand-in 0.22s cubic-bezier(0.22, 1, 0.36, 1)",marginTop:8,fontSize:12,color:"#b91c1c",background:"#fef2f2",border:"1px solid #fecaca",borderRadius:8,padding:"6px 10px"},children:gn}):null,Yn=Xs.jsxs(Xs.Fragment,{children:[Xs.jsx("style",{children:`
|
|
37
|
+
<!-- \u2026truncated\u2026 -->`:t=t.slice(0,2e3);}return t}function ta(e){let t=e.getBoundingClientRect(),n=(e.textContent??"").replace(/\s+/g," ").trim(),r={tag:e.tagName.toLowerCase(),selector:Qi(e),html:ea(e),rect:{x:Math.round(t.x),y:Math.round(t.y),width:Math.round(t.width),height:Math.round(t.height)}};e.id&&(r.id=e.id);let o=Array.from(e.classList).slice(0,10);o.length>0&&(r.classes=o),n&&(r.text=n.slice(0,300));let i=Uo(e);return i&&(r.componentName=i),r}function Ln(e){let t=e.tag;if(e.id)t+=`#${e.id}`;else if(e.classes?.length)t+=`.${e.classes.slice(0,2).join(".")}`;else if(e.componentName)return `<${e.componentName}>`;return t.length>36?t.slice(0,35)+"\u2026":t}function No(e){let t=document.createElement("div");t.setAttribute("data-fork-picker-overlay",""),t.style.cssText=["position: fixed","inset: 0","pointer-events: none","z-index: 2147483001"].join(";");let n=document.createElement("div");n.style.cssText=["position: fixed","display: none",`background: ${Gi}`,`border: ${Yi}`,"border-radius: 2px","pointer-events: none","box-sizing: border-box","transition: all 40ms linear"].join(";");let r=document.createElement("div");r.style.cssText=["position: fixed","display: none","background: #1f2937","color: #ffffff","font: 500 11px/1.4 ui-sans-serif, system-ui, sans-serif","padding: 3px 8px","border-radius: 6px","pointer-events: none","white-space: nowrap","box-shadow: 0 2px 8px rgba(0,0,0,0.25)"].join(";"),t.appendChild(n),t.appendChild(r),document.body.appendChild(t);let o=document.createElement("style");o.textContent="*, * > * { cursor: crosshair !important; }",document.head.appendChild(o);let i=null,a=false,l=()=>{i=null,n.style.display="none",r.style.display="none";},u=f=>{let T=f.getBoundingClientRect();n.style.display="block",n.style.left=`${T.left}px`,n.style.top=`${T.top}px`,n.style.width=`${T.width}px`,n.style.height=`${T.height}px`;let x=Uo(f),k=f.tagName.toLowerCase();f.id?k+=`#${f.id}`:f.classList.length>0&&(k+=`.${Array.from(f.classList).slice(0,2).join(".")}`),k.length>42&&(k=k.slice(0,41)+"\u2026"),r.textContent=x?`${k} \xB7 ${x} \xB7 ${Math.round(T.width)}\xD7${Math.round(T.height)}`:`${k} \xB7 ${Math.round(T.width)}\xD7${Math.round(T.height)}`,r.style.display="block";let L=T.top>=30?T.top-26:Math.max(4,T.top+4);r.style.top=`${L}px`,r.style.left=`${Math.max(4,Math.min(T.left,window.innerWidth-320))}px`;},w=(f,T)=>{let x=document.elementFromPoint(f,T);return !x||x===document.documentElement||x===document.body||Zi(x)?null:x},A=f=>{let T=w(f.clientX,f.clientY);if(!T){l();return}T!==i&&(i=T,u(T));},b=()=>{i&&u(i);},I=f=>{let T=w(f.clientX,f.clientY);if(!T)return;f.preventDefault(),f.stopPropagation();let x=ta(T);p(),e.onPick(x);},O=f=>{w(f.clientX,f.clientY)&&(f.preventDefault(),f.stopPropagation());},R=f=>{f.key==="Escape"&&(f.preventDefault(),f.stopPropagation(),p(),e.onCancel());};function p(){a||(a=true,document.removeEventListener("mousemove",A,true),document.removeEventListener("click",I,true),document.removeEventListener("mousedown",O,true),document.removeEventListener("mouseup",O,true),document.removeEventListener("keydown",R,true),document.removeEventListener("scroll",b,true),window.removeEventListener("resize",b),t.remove(),o.remove());}return document.addEventListener("mousemove",A,true),document.addEventListener("click",I,true),document.addEventListener("mousedown",O,true),document.addEventListener("mouseup",O,true),document.addEventListener("keydown",R,true),document.addEventListener("scroll",b,true),window.addEventListener("resize",b),{stop:p}}function Bo(){if(typeof window>"u")return null;let e=window;return e.SpeechRecognition||e.webkitSpeechRecognition||null}function Do(){return Bo()!==null}function jo(e){let t=Bo();if(!t)return null;let n=true,r="",o=null,i=0,a=0,l=()=>{let u=new t;u.lang=typeof navigator<"u"&&navigator.language||"en-US",u.continuous=true,u.interimResults=true,u.onresult=w=>{let A="";for(let b=w.resultIndex;b<w.results.length;b++){let I=w.results[b],O=I[0]?.transcript??"";I.isFinal?r+=O:A+=O;}n&&e.onText(r,A);},u.onerror=w=>{let A=String(w?.error??"");if(A==="no-speech"||A==="aborted")return;n=false;let b=A==="not-allowed"||A==="service-not-allowed"?"not-allowed":A==="network"?"network":"other";e.onError(b);},u.onend=()=>{if(!n)return;let w=Date.now();if(w-i<1e3){if(a++,a>2){n=false,e.onError("other");return}}else a=0;i=w;try{u.start();}catch{try{l();}catch{n=false,e.onError("other");}}},o=u,u.start();};try{l();}catch{return null}return {stop:()=>{n=false;try{o?.stop();}catch{}}}}var Wo=35,pa="Setting up environment",ga="Built Custom Feature",hr=360,on=380;function yr(e){let t=Date.parse(e);if(Number.isNaN(t))return "";let n=Math.max(1,Math.round((Date.now()-t)/1e3));if(n<60)return `${n}s`;let r=Math.round(n/60);if(r<60)return `${r}m`;let o=Math.round(r/60);return o<24?`${o}h`:`${Math.round(o/24)}d`}function ma(e){return e.length<=Wo?e:e.slice(0,Wo-3).trimEnd()+"..."}function ha({events:e}){let[t,n]=ar.useState("Setting up environment..."),[r,o]=ar.useState(true),i=ar.useRef(t),a=ar.useRef(false);return ar.useEffect(()=>{if(!a.current){for(let u of e)if(u.type==="status"&&String(u.data.message||"").includes("Agent started")){a.current=true;break}}let l="Setting up environment...";if(a.current)for(let u=e.length-1;u>=0;u--){let w=e[u];if(w.type==="tool_use"||w.type==="build_start"||w.type==="build_complete"){l=ma(gr(w));break}}if(l!==i.current){o(false);let u=setTimeout(()=>{n(l),i.current=l,o(true);},200);return ()=>clearTimeout(u)}},[e]),Xs.jsx("span",{style:{fontSize:12.5,color:"#334155",fontWeight:600,opacity:r?1:0,transition:"opacity 0.2s ease",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},children:t})}function ya({children:e}){let[t,n]=ar.useState(null);return ar.useEffect(()=>{if(typeof document>"u")return;let r=document.createElement("div");r.setAttribute("data-fork-panel-host",""),r.style.cssText="all: initial;",document.body.appendChild(r);let o=r.attachShadow({mode:"open"});return n(o),()=>{r.remove();}},[]),t?Vs.createPortal(e,t):null}function Un({state:e,fork:t,events:n,error:r,runs:o={},slotId:i,targetId:a,targetLabel:l,historyMode:u="slot",onSubmit:w,onUndo:A,onPlanRevert:b,onRevert:I,onSetForkDisabled:O,onRenameFork:R,onClose:p,baseUrl:f,apiKey:T,userId:x,userHash:k,appId:L,embedded:N=false,completeVariant:K="bubble"}){let[_,H]=ar.useState(""),[j,W]=ar.useState([]),[M,S]=ar.useState(false),[U,X]=ar.useState(false),[V,Q]=ar.useState(false),[Z,ee]=ar.useState(false),[fe,de]=ar.useState(false),[oe,me]=ar.useState(false),[te,pe]=ar.useState(false),[d,E]=ar.useState(false),[h,c]=ar.useState(false),[g,$]=ar.useState(null),[B,D]=ar.useState(null),[Y,ft]=ar.useState(null),[ve,Pe]=ar.useState(false),[gn,Ce]=ar.useState(null),[mn,tt]=ar.useState(0),[pt,gt]=ar.useState(null),[nt,mt]=ar.useState(null),[Fe,Et]=ar.useState(null),[Ge,Kt]=ar.useState(false),[Ct,Tt]=ar.useState(null),[Ne,we]=ar.useState(""),[Je,Ve]=ar.useState(false),[zn,$t]=ar.useState(false),[Wt,ht]=ar.useState([]),[Te,m]=ar.useState(null),[F,P]=ar.useState(false),[G,ie]=ar.useState(false),[ae,ce]=ar.useState(false),[Se,$e]=ar.useState(null),[le,he]=ar.useState(null),[ye,ke]=ar.useState(false),[_e,xe]=ar.useState(false),[Ae,Be]=ar.useState(""),De=ar.useRef(null),[Mt,rt]=ar.useState(null),[Kn,Wn]=ar.useState(false),[Pt,Pr]=ar.useState(null),[Jt,hn]=ar.useState([]),[Ss,xs]=ar.useState(0),[re,ot]=ar.useState(null),[Xe,st]=ar.useState(false),it=ar.useRef(false),_t=ar.useRef(null),yn=ar.useRef(null),[at,Jn]=ar.useState([]),[yt,Vn]=ar.useState(null),[kt,kn]=ar.useState(false),Lt=ar.useRef(null),[Ht,Xn]=ar.useState(false),Vt=ar.useRef(null),_r=ar.useRef(""),[Lr,Hr]=ar.useState(null),Ot=ar.useRef(null),Or=ar.useRef(null),[Fs,Ur]=ar.useState(false),[As,Nr]=ar.useState(false),[Rs,Br]=ar.useState(false),[Is,Dr]=ar.useState(null),{resetAllForks:Es,adminContext:ze,setAdminContainer:Cs,currentContainerId:jr,forksPaused:Ut,setForksPaused:Ts,forkActivities:zr,markForkActivitySeen:Kr}=Ee(),bn=ze.containerId??jr,vn=!!(ze.isAdmin&&Kn),$s=!!(ze.containerId??jr),[Wr,Jr]=ar.useState(false),Ke=Pt!==null,Vr=ar.useRef(p);ar.useEffect(()=>{Vr.current=p;});let qn=ar.useRef(null),wn=ar.useRef(false),Xr=typeof window<"u"&&"documentPictureInPicture"in window,Ms=async()=>{if(!(!Xr||Ke))try{let s=await window.documentPictureInPicture.requestWindow({width:hr,height:640});s.document.body.style.margin="0",s.document.body.style.padding="0",s.document.body.style.height="100vh",s.document.body.style.overflow="hidden",s.document.body.style.background="#ffffff";try{let v=document.adoptedStyleSheets??[];v.length>0&&(s.document.adoptedStyleSheets=[...v]);}catch{}s.addEventListener("pagehide",()=>{qn.current=null,Pr(null),wn.current||Vr.current(),wn.current=!1;},{once:!0}),qn.current=s,Pr(s);}catch(s){console.warn("[Fork] PiP open failed:",s);}},Ps=()=>{Pt&&(wn.current=true,Pt.close());};ar.useEffect(()=>()=>{wn.current=true,qn.current?.close();},[]);let Xt=a??i??"";(l||Xt).replace(/[-_]+/g," ").replace(/\b\w/g,s=>s.toUpperCase());let Sn=ar.useRef(""),qt=()=>{let s={Authorization:`Bearer ${T}`,...ue()};return L&&(s["X-Fork-App-Id"]=L),x&&(s["X-Fork-User-Id"]=x),k&&(s["X-Fork-User-Hash"]=k),s},Nt=N?true:U&&!V,Gt=re?o[re]??null:null,Yt=re?Jt.find(s=>s.id===re)??null:null,_s=Yt?(s=>s==="pending"||s==="running"||s==="building")(Yt.status):false,qe=re?Gt?.state??(_s?"running":null):Xe?e:null,Bt=re?Gt?.events??[]:Xe?n:[],Ls=re?Gt?.state==="error"?Gt.error:null:Xe&&e==="error"?r:null,Gn=re?Gt?.fork??null:Xe?t:null,Hs=Object.values(o).filter(s=>s.state!=="running").length,qr=re?!!zr.find(s=>s.id===re)?.unread:false;ar.useEffect(()=>{re&&qr&&Kr(re);},[re,qr,Kr]);let Os=Bt.find(s=>{let v=s.data;return s.type==="status"&&v.summary})?.data?.summary||Gn?.summary||pa,bt=Bt.find(s=>{let v=s.data;return (s.type==="status"||s.type==="complete")&&typeof v?.estimateMinutes=="number"})?.data?.estimateMinutes??Gn?.estimateMinutes;ar.useEffect(()=>{if(u==="none"){S(true);return}if(!f||!T)return;if(!re){W([]),S(true);return}let s=new AbortController;return fetch(`${f}/api/v1/forks/${encodeURIComponent(re)}/messages`,{headers:qt(),signal:s.signal}).then(v=>v.ok?v.json():[]).then(v=>{if(s.signal.aborted)return;let C=[];for(let z of v){let se=z.forkId??re,be={promptId:z.promptId??null,promptKind:z.promptKind??null,reverted:!!z.reverted};if(z.role==="user"){let Ye=(z.attachments??[]).filter(Le=>Le&&typeof Le.mediaType=="string"&&typeof Le.data=="string").map(Le=>({dataUrl:`data:${Le.mediaType};base64,${Le.data}`}));C.push({type:"user",text:z.content,forkId:se,timestamp:z.timestamp,attachments:Ye.length>0?Ye:void 0,selectedElement:z.selectedElement?{label:Ln(z.selectedElement)}:void 0,...be});}else C.push({type:"applied",text:z.content,forkId:se,timestamp:z.timestamp,...be});}W(C),S(true);}).catch(()=>{s.signal.aborted||S(true);}),()=>{s.abort();}},[T,L,f,u,re,ze.containerId,k,x,t?.id,t?.completedAt,mn]),ar.useEffect(()=>{if(u==="none"||!f||!T||!F)return;if(!Te){hn([]);return}let s=new AbortController,v=new URLSearchParams({container_id:Te});return fetch(`${f}/api/v1/forks?${v.toString()}`,{headers:qt(),signal:s.signal}).then(C=>C.ok?C.json():{forks:[]}).then(C=>{s.signal.aborted||hn(C.forks??[]);}).catch(()=>{}),()=>{s.abort();}},[T,L,f,u,Te,F,t?.id,t?.completedAt,Hs,Ss,ze.containerId,k,x,mn]),ar.useEffect(()=>{e==="complete"&&E(false);},[e]);let Gr=Jt.some(s=>s.status==="pending"||s.status==="running"||s.status==="building");ar.useEffect(()=>{if(!Gr||!f||!T||!Te)return;let s=new URLSearchParams({container_id:Te}),v=qt(),z=setInterval(async()=>{try{let se=await fetch(`${f}/api/v1/forks?${s.toString()}`,{headers:v});if(!se.ok)return;let be=await se.json();hn(be.forks??[]);}catch{}},3e3);return ()=>clearInterval(z)},[Gr,f,T,L,Te]),ar.useEffect(()=>{if(N&&u==="none"){ht([]),m(null),P(true),Wn(false);return}if(ze.isAdmin){rt(null),ht(ze.containers.map(s=>({id:s.id,name:s.name,createdAt:"",hasAccess:true,isPrimary:s.isPrimary}))),m(ze.containerId??null),Wn(true),P(true);return}bn?(ht([{id:bn,name:"Primary container",createdAt:""}]),m(bn)):(ht([]),m(null)),P(true),Wn(false);},[T,bn,f,N,u,ze.isAdmin,ze.containerId,ze.containers]);let xn=ar.useRef(void 0);ar.useEffect(()=>{if(F){if(xn.current===void 0){xn.current=Te;return}xn.current!==Te&&(xn.current=Te,W([]),S(false));}},[Te,F]);let Fn=ar.useRef(null);ar.useEffect(()=>{if(!G)return;let s=C=>{if(!Fn.current)return;let z=typeof C.composedPath=="function"?C.composedPath():[];Fn.current.contains(C.target)||z.includes(Fn.current)||ie(false);},v=C=>{C.key==="Escape"&&ie(false);};return document.addEventListener("mousedown",s,true),document.addEventListener("keydown",v,true),()=>{document.removeEventListener("mousedown",s,true),document.removeEventListener("keydown",v,true);}},[G]),ar.useEffect(()=>{if(N||!Nt||V||Ke||kt)return;let s=v=>{(typeof v.composedPath=="function"?v.composedPath():[]).some(se=>se instanceof Element&&se.hasAttribute("data-fork-panel-host"))||(Q(true),X(false),setTimeout(()=>p(),on));};return document.addEventListener("mousedown",s,true),()=>{document.removeEventListener("mousedown",s,true);}},[N,Nt,V,Ke,kt,p]),ar.useEffect(()=>{G||(xe(false),Be(""));},[G]),ar.useEffect(()=>{_e&&(De.current?.focus(),De.current?.select());},[_e]),ar.useEffect(()=>{if(N)return;let s=requestAnimationFrame(()=>X(true));return ()=>cancelAnimationFrame(s)},[N]),ar.useEffect(()=>{let s=N||Ke;if((s||Nt)&&(e==="prompting"||e==="complete")){let v=setTimeout(()=>_t.current?.focus(),s?100:on+100);return ()=>clearTimeout(v)}},[Nt,N,Ke,e]);let Yr=ar.useRef(new Set);ar.useEffect(()=>{for(let s of Object.values(o)){if(s.state!=="complete"||s.events.length===0)continue;let v=`${s.forkId}:${s.fork.completedAt??""}`;if(Yr.current.has(v))continue;Yr.current.add(v);let z=s.events.find(se=>se.type==="complete")?.data?.summary||s.fork.summary||ga;W(se=>{let be=[...se].reverse().find(Ye=>Ye.forkId===s.forkId);return be?.type==="applied"&&be.text===z?se:[...se,{type:"applied",text:z,forkId:s.forkId,timestamp:s.fork.completedAt??new Date().toISOString()}]});}},[o]),ar.useEffect(()=>{qe==="complete"&&Sn.current&&(H(""),setTimeout(()=>_t.current?.focus(),200));},[qe]),ar.useEffect(()=>{yn.current&&(yn.current.scrollTop=yn.current.scrollHeight);},[j,e]),ar.useEffect(()=>{let s=_t.current;s&&(s.style.height="auto",s.style.height=Math.min(s.scrollHeight,160)+"px");},[_]);let lt=s=>{Hr(s),Ot.current&&clearTimeout(Ot.current),Ot.current=setTimeout(()=>{Ot.current=null,Hr(null);},3200);},Zr=async s=>{if(s.length===0)return;let v=4-at.length;if(v<=0){lt(`Up to ${4} images per prompt`);return}s.length>v&<(`Up to ${4} images per prompt`);let z=(await Promise.all(s.slice(0,v).map(Ho))).filter(se=>se!==null);z.length!==0&&(Jn(se=>[...se,...z].slice(0,4)),_t.current?.focus());},Qr=()=>{Lt.current?.stop(),Lt.current=null,kn(false);},Us=()=>{if(kt){Qr();return}kn(true),lt("Click an element on the page \xB7 Esc to cancel"),Lt.current=No({onPick:s=>{Lt.current=null,kn(false),Vn(s),_t.current?.focus();},onCancel:()=>{Lt.current=null,kn(false);}});},eo=()=>{Vt.current?.stop(),Vt.current=null,Xn(false);},Ns=()=>{if(Ht){eo();return}if(!Do()){lt("Voice input is coming soon for this browser");return}let s=_.length>0&&!_.endsWith(" ")?_+" ":_;_r.current=s;let v=jo({onText:(C,z)=>{H(_r.current+C+z);},onError:C=>{Vt.current=null,Xn(false),lt(C==="not-allowed"?"Microphone access is blocked":C==="network"?"Voice input is coming soon for this browser":"Voice input stopped");}});if(!v){lt("Voice input is coming soon for this browser");return}Vt.current=v,Xn(true);};ar.useEffect(()=>()=>{Lt.current?.stop(),Vt.current?.stop(),Ot.current&&clearTimeout(Ot.current);},[]);let Dt=!!(_.trim()||at.length>0),to=()=>{if(!Dt)return;Ht&&eo(),kt&&Qr();let s=_.trim()||"See the attached screenshot.";Sn.current=s;let v={};at.length>0&&(v.attachments=at.map(({mediaType:z,data:se})=>({mediaType:z,data:se}))),yt&&(v.selectedElement=yt);let C=Xe||!re;C?(v.forceNew=true,it.current=true,Xe||st(true)):v.forkId=re,C||W(z=>[...z,{type:"user",text:s,forkId:re,attachments:at.length>0?at.map(se=>({dataUrl:se.dataUrl})):void 0,selectedElement:yt?{label:Ln(yt)}:void 0}]),w(s,Xt,Te,v),H(""),Jn([]),Vn(null);};ar.useEffect(()=>{if(it.current){if(e==="error"){it.current=false;return}t?.id&&(ot(t.id),st(false),it.current=false);}},[t?.id,e]);let no=ar.useRef(new Set);ar.useEffect(()=>{t?.id&&(it.current||e!=="running"&&e!=="complete"||no.current.has(t.id)||(no.current.add(t.id),ot(s=>s??t.id),st(false)));},[t?.id,e]);let ro=s=>{Cs(s.container.id,s.container.name),m(s.container.id),ht(v=>{let C=v.filter(z=>z.id!==s.container.id);return [{...s.container,isPrimary:true,hasAccess:true},...C.map(z=>({...z,isPrimary:false}))]}),ot(null),st(false),it.current=false,W([]),S(false),Sn.current="";},Bs=async s=>{if(!(!vn||le)){he(s),rt(null);try{let v=await fetch(`${f}/api/v1/admin/containers/${encodeURIComponent(s)}/primary`,{method:"POST",headers:qt()});if(!v.ok){let C=await v.json().catch(()=>({}));throw new Error(C.error||`API error: ${v.status}`)}ro(await v.json()),ie(!1);}catch(v){rt(v instanceof Error?v.message:String(v));}finally{he(null);}}},oo=async s=>{if(!vn||le)return;let v=s.trim();if(v){he("__new__"),rt(null);try{let C=await fetch(`${f}/api/v1/admin/containers`,{method:"POST",headers:{...qt(),"Content-Type":"application/json"},body:JSON.stringify({name:v})});if(!C.ok){let z=await C.json().catch(()=>({}));throw new Error(z.error||`API error: ${C.status}`)}ro(await C.json()),xe(!1),Be(""),ie(!1);}catch(C){rt(C instanceof Error?C.message:String(C));}finally{he(null);}}},so=async()=>{if(!(!A||h||!Xt)){c(true);try{(await A(Xt,re))?.removed?(W([]),ot(null),st(!1),it.current=!1):W(v=>{let C=[...v];return C.length>=2&&C[C.length-1]?.type==="applied"?C.splice(-2,2):C.length>=1&&C[C.length-1]?.type==="applied"&&C.splice(-1,1),C}),xs(v=>v+1);}catch{}finally{c(false);}}},Ds=async(s,v)=>{if(!b||!s.forkId||!s.promptId||ve)return;let C=s.forkId,z=s.promptId;Ce(null),ft(z),D({forkId:C,promptId:z,mode:v,scope:"step",plan:null});try{let se=await b(C,z,v);D(be=>be&&be.forkId===C&&be.promptId===z&&be.mode===v?{...be,plan:se}:be);}catch(se){Ce(se instanceof Error?se.message:String(se)),D(be=>be&&be.forkId===C&&be.promptId===z?null:be);}finally{ft(null);}},js=async s=>{if(!(!b||ve)){gt(null),Ce(null),ft(s),D({forkId:s,mode:"remove_step",scope:"fork",plan:null});try{let v=await b(s,void 0,"remove_step");D(C=>C&&C.forkId===s&&C.scope==="fork"?{...C,plan:v}:C);}catch(v){let C=v instanceof Error?v.message:String(v);mt(s),Ce(/not found/i.test(C)?`Error: ${C} for this fork`:`Error: ${C}`),D(z=>z&&z.forkId===s?null:z);}finally{ft(null);}}};ar.useEffect(()=>{if(!Fe)return;let s=o[Fe.tipId]?.state;s==="complete"?(Et(null),tt(v=>v+1)):s==="error"&&(mt(Fe.forkId),Ce(`Error: couldn't ${Fe.kind==="disable"?"disable":Fe.kind==="enable"?"re-enable":"remove"} this fork \u2014 ${o[Fe.tipId]?.error??"the rewrite failed"}. Nothing was changed.`),Et(null),tt(v=>v+1));},[o,Fe]);let io=async()=>{if(!(!R||!Ct||Je)){Ve(true),Ce(null);try{await R(Ct,Ne.trim()),Tt(null),we(""),tt(s=>s+1);}catch(s){Ce(s instanceof Error?s.message:String(s));}finally{Ve(false);}}},ao=async(s,v)=>{if(!(!O||Ge)){gt(null),Ce(null),mt(null),Kt(true);try{let C=await O(s,v);C?.agentic&&C?.fork?.id?Et({forkId:s,tipId:C.fork.id,kind:v?"disable":"enable"}):tt(z=>z+1);}catch(C){let z=C instanceof Error?C.message:String(C);mt(s),/not found/i.test(z)?(Ce("Error: this fork no longer exists \u2014 refreshing the list."),setTimeout(()=>{mt(null),Ce(null),tt(se=>se+1);},1800)):Ce(`Error: ${z}`);}finally{Kt(false);}}},lo=async s=>{if(!(!I||!B?.plan||ve)){Pe(true),Ce(null);try{let v=await I({forkId:B.forkId,promptId:B.promptId,mode:B.mode,strategy:s}),C=B;D(null),v.agentic?Et({forkId:C.forkId,tipId:v.fork.id,kind:"delete"}):v.removed&&(W([]),ot(null)),tt(z=>z+1);}catch(v){Ce(v instanceof Error?v.message:String(v));}finally{Pe(false);}}},co=()=>{if(N){p();return}if(Ke){Pt?.close();return}Q(true),X(false),setTimeout(()=>p(),on);},zs=N||Ke?{position:"relative",width:"100%",height:"100%",background:"#ffffff",display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'}:{position:"fixed",top:0,right:0,bottom:0,zIndex:2147483e3,width:hr,maxWidth:"100vw",background:"#ffffff",boxShadow:Nt?"-12px 0 32px -16px rgba(0, 0, 0, 0.18), -2px 0 8px -2px rgba(0, 0, 0, 0.06)":"none",borderLeft:"1px solid rgba(0, 0, 0, 0.08)",transform:Nt?"translateX(0)":"translateX(100%)",transition:`transform ${on}ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow ${on}ms ease`,display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'},uo=Wt.find(s=>s.id===Te)?.name??(F?"Fork":"Loading..."),Ks=[...Jt].sort((s,v)=>+!!s.disabledAt-+!!v.disabledAt),jt=Xe?[]:re?j.filter(s=>s.forkId===re||s.forkId==null):j,vt=B?.scope==="fork",We=B?.plan??null,fo=B?Xs.jsxs("div",{style:{animation:"__fork-expand-in 0.22s cubic-bezier(0.22, 1, 0.36, 1)",overflow:"hidden",background:"#f9fafb",border:"1px solid #f3f4f6",borderRadius:10,padding:"10px 12px"},children:[Xs.jsx("div",{style:{fontSize:13,fontWeight:600,color:"#111827",textAlign:"center"},children:B.mode==="revert_to"?"Go Back to This Point?":vt?"Delete This Fork?":"Remove This Change?"}),We?Xs.jsxs(Xs.Fragment,{children:[Xs.jsxs("div",{style:{fontSize:12,color:"#6b7280",marginTop:3,lineHeight:1.5,textAlign:"center"},children:[B.mode==="revert_to"?`${We.removes.length} later change${We.removes.length===1?"":"s"} will be discarded.`:We.laterSteps.length>0?`${We.laterSteps.length} later change${We.laterSteps.length===1?" was":"s were"} built on top of ${vt?"this fork":"this one"}.`:vt?"Deleting it is instant and cannot be undone.":"This is the latest change; removing it is instant.",We.busy&&" A run is in progress \u2014 try again once it finishes."]}),Xs.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flexWrap:"wrap",gap:8,marginTop:10},children:[Xs.jsx("button",{onClick:()=>{D(null),Ce(null);},disabled:ve,style:{padding:"5px 12px",fontSize:12,fontWeight:500,borderRadius:7,border:"none",background:"#f3f4f6",color:"#374151",cursor:ve?"default":"pointer",transition:"background 0.12s"},onMouseEnter:s=>s.currentTarget.style.background="#e5e7eb",onMouseLeave:s=>s.currentTarget.style.background="#f3f4f6",children:"Cancel"}),We.strategies.some(s=>s.id==="keep_later")&&Xs.jsx("button",{onClick:()=>lo("keep_later"),disabled:ve,title:"The AI rewrites the later forks' code so their features survive without this one",style:{padding:"5px 12px",fontSize:12,fontWeight:500,borderRadius:7,border:"none",background:"#eef2ff",color:"#4338ca",cursor:ve?"default":"pointer",opacity:ve?.5:1,transition:"background 0.12s"},onMouseEnter:s=>s.currentTarget.style.background="#e0e7ff",onMouseLeave:s=>s.currentTarget.style.background="#eef2ff",children:`${vt?"Delete This Fork":"Remove This Change"} (~${We.strategies.find(s=>s.id==="keep_later")?.estimateMinutes??2}m)`}),Xs.jsx("button",{onClick:()=>lo("discard_later"),disabled:ve,title:We.laterSteps.length>0?"Instant \u2014 also removes everything built on top of this":"Instant",style:{padding:"5px 12px",fontSize:12,fontWeight:500,borderRadius:7,border:"none",background:"#fef2f2",color:"#b91c1c",cursor:ve?"default":"pointer",opacity:ve?.5:1,transition:"background 0.12s"},onMouseEnter:s=>s.currentTarget.style.background="#fee2e2",onMouseLeave:s=>s.currentTarget.style.background="#fef2f2",children:B.mode==="revert_to"?"Go Back to Here":We.laterSteps.length>0?vt?"Delete All Related":"Remove All Related":vt?"Delete":"Remove"})]})]}):Xs.jsx("div",{style:{fontSize:12,color:"#9ca3af",fontStyle:"italic",marginTop:4,textAlign:"center",animation:"__fork-pulse 1.2s ease-in-out infinite"},children:B.mode==="revert_to"?"Evaluating undo...":vt?"Evaluating delete...":"Evaluating remove..."})]}):null,An=gn?Xs.jsx("div",{style:{animation:"__fork-expand-in 0.22s cubic-bezier(0.22, 1, 0.36, 1)",marginTop:8,fontSize:12,color:"#b91c1c",background:"#fef2f2",border:"1px solid #fecaca",borderRadius:8,padding:"6px 10px"},children:gn}):null,Yn=Xs.jsxs(Xs.Fragment,{children:[Xs.jsx("style",{children:`
|
|
38
38
|
@keyframes __fork-pulse {
|
|
39
39
|
0%, 100% { opacity: 1; }
|
|
40
40
|
50% { opacity: 0.5; }
|
|
@@ -60,9 +60,9 @@
|
|
|
60
60
|
scrollbar-width: thin;
|
|
61
61
|
scrollbar-color: rgba(0, 0, 0, 0.12) transparent;
|
|
62
62
|
}
|
|
63
|
-
`}),Xs.jsxs("div",{className:"__fork-panel",style:zs,children:[Xs.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0 16px",height:54,boxSizing:"border-box",borderBottom:"1px solid rgba(229, 231, 235, 0.8)",flexShrink:0},children:[Xs.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:[re||Xe?Xs.jsxs(Xs.Fragment,{children:[Xs.jsx("button",{onClick:()=>{Ye(null),Ze(false),it.current=false;},style:{width:30,height:30,borderRadius:9,background:"#ffffff",border:"1px solid #e5e7eb",color:"#111827",cursor:"pointer",display:"inline-flex",alignItems:"center",justifyContent:"center",padding:0,flexShrink:0,transition:"background 0.12s, border-color 0.12s"},onMouseEnter:s=>{s.currentTarget.style.background="#f9fafb",s.currentTarget.style.borderColor="#d1d5db";},onMouseLeave:s=>{s.currentTarget.style.background="#ffffff",s.currentTarget.style.borderColor="#e5e7eb";},title:"Back to all forks",children:Xs.jsx(lucideReact.ChevronLeft,{style:{width:15,height:15}})}),(()=>{let s=re?o[re]:void 0,C=(s?s.events.find(z=>{let se=z.data;return z.type==="status"&&se.summary})?.data?.summary??s.fork.summary:void 0)||Yt?.summary||"New Feature";return Xs.jsx("span",{style:{fontSize:13.5,fontWeight:700,color:"#111827",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},title:C,children:C})})()]}):Xs.jsxs(Xs.Fragment,{children:[Xs.jsx("span",{onDoubleClick:async s=>{if(s.stopPropagation(),!zn&&confirm("Kill all forks in this container?")){Tt(true);try{let v=await Is();`${v?.deleted??0}`,hn([]),Ye(null),Ze(!1),H("");}catch(v){console.error("[Fork] Reset failed:",v);}finally{Tt(false);}}},style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:4,margin:-4,cursor:"pointer",flexShrink:0},children:Xs.jsx($n,{style:{width:16,height:16,color:"#111827",pointerEvents:"none"}})}),qe==="running"?Xs.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:Os}):Jt.length===0&&!vn?Xs.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:"Fork"}):vn?Xs.jsxs("div",{ref:Fn,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[Xs.jsxs("button",{type:"button",onClick:()=>{ie(s=>!s);},onMouseEnter:()=>ce(true),onMouseLeave:()=>ce(false),"aria-haspopup":"menu","aria-expanded":G,style:{display:"inline-flex",alignItems:"center",gap:4,padding:"3px 6px",border:"1px solid transparent",borderRadius:6,background:ae||G?"#f3f4f6":"transparent",fontSize:13,fontWeight:600,color:"#111827",fontFamily:"inherit",cursor:"pointer",maxWidth:180,minWidth:0,transition:"background-color 0.12s"},children:[Xs.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:uo}),Xs.jsx(lucideReact.ChevronDown,{style:{width:12,height:12,color:"#6b7280",flexShrink:0,transform:G?"rotate(180deg)":void 0,transition:"transform 0.15s"}})]}),G&&Xs.jsxs("div",{role:"menu",style:{position:"absolute",top:"calc(100% + 4px)",left:0,minWidth:200,maxWidth:260,background:"#ffffff",border:"1px solid #e5e7eb",borderRadius:8,boxShadow:"0 4px 12px rgba(0,0,0,0.08), 0 1px 3px rgba(0,0,0,0.06)",padding:4,zIndex:2147483001},children:[Jt.map(s=>{let v=s.id===Ce,C=Se===s.id,z=le===s.id;return Xs.jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>Te(s.id),onMouseLeave:()=>Te(null),onClick:()=>{s.id!==Ce&&Bs(s.id);},disabled:!!le,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:C?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:le?"default":"pointer",textAlign:"left",fontWeight:v?600:400,opacity:le&&!z?.55:1},children:[Xs.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:v&&Xs.jsx(lucideReact.Check,{style:{width:12,height:12}})}),Xs.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:z?"Switching...":s.name})]},s.id)}),Xs.jsx("div",{style:{height:1,background:"#e5e7eb",margin:"4px 0"}}),_e?Xs.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"4px 4px"},children:[Xs.jsx("input",{ref:De,type:"text",value:Fe,placeholder:"Container name",disabled:le==="__new__",onChange:s=>Be(s.target.value),onKeyDown:s=>{s.key==="Enter"?(s.preventDefault(),oo(Fe)):s.key==="Escape"&&(s.preventDefault(),s.stopPropagation(),xe(false),Be(""));},style:{flex:1,minWidth:0,padding:"5px 8px",border:"1px solid #d1d5db",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",background:"#ffffff",outline:"none"},onFocus:s=>{s.currentTarget.style.borderColor="#111827",s.currentTarget.style.boxShadow="0 0 0 2px rgba(17,24,39,0.15)";},onBlur:s=>{s.currentTarget.style.borderColor="#d1d5db",s.currentTarget.style.boxShadow="none";}}),Xs.jsx("button",{type:"button",onClick:()=>{oo(Fe);},disabled:!Fe.trim()||le==="__new__",title:"Create",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:26,height:26,border:"none",borderRadius:4,background:!Fe.trim()||le==="__new__"?"#e5e7eb":"#111827",color:!Fe.trim()||le==="__new__"?"#9ca3af":"#ffffff",cursor:!Fe.trim()||le==="__new__"?"default":"pointer",flexShrink:0},children:le==="__new__"?Xs.jsx("span",{style:{width:10,height:10,border:"1.5px solid currentColor",borderTopColor:"transparent",borderRadius:"50%",animation:"__fork-spin 0.7s linear infinite"}}):Xs.jsx(lucideReact.Check,{style:{width:12,height:12}})})]}):Xs.jsx("button",{type:"button",role:"menuitem",onMouseEnter:()=>ke(true),onMouseLeave:()=>ke(false),onClick:()=>{le||(st(null),Be(""),xe(true));},disabled:!!le,style:{display:"flex",alignItems:"center",width:"100%",padding:"6px 8px",border:"none",background:ye?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:le?"default":"pointer",textAlign:"left",opacity:le&&le!=="__new__"?.55:1},children:"+ New container"}),$t&&Xs.jsx("div",{style:{padding:"6px 8px",fontSize:11,lineHeight:1.35,color:"#b91c1c"},children:$t})]})]}):Xs.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:uo})]}),qe==="running"&&Xs.jsx("span",{title:bt?`Estimated ~${bt} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:bt?"#111827":"#9ca3af",backgroundColor:bt?"rgba(17, 24, 39, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:bt?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:bt?`~${bt}m`:"~ m"})]}),Xs.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[$s&&!re&&Xs.jsx("button",{type:"button",role:"switch","aria-checked":!Ut,"aria-label":Ut?"Turn Fork back on":"Turn Fork off",title:Ut?"Fork is off \u2014 you're seeing the original app. Turn it back on. Only affects you.":"Turn Fork off to see the original app. Only affects you.",onClick:()=>{Ts(!Ut);},onMouseEnter:()=>Jr(true),onMouseLeave:()=>Jr(false),style:{position:"relative",width:26,height:15,borderRadius:999,border:"none",padding:0,marginRight:6,flexShrink:0,cursor:"pointer",backgroundColor:Ut?Wr?"#9ca3af":"#d1d5db":Wr?"#374151":"#111827",transition:"background-color 0.18s ease",outline:"none",boxSizing:"border-box"},children:Xs.jsx("span",{"aria-hidden":true,style:{position:"absolute",top:2,left:Ut?2:13,width:11,height:11,borderRadius:"50%",backgroundColor:"#ffffff",boxShadow:"0 1px 2px rgba(15, 23, 42, 0.25)",transition:"left 0.18s cubic-bezier(0.16, 1, 0.3, 1)"}})}),!N&&Xs.jsxs(Xs.Fragment,{children:[Xr&&Xs.jsx("button",{onClick:Ke?Ps:Ms,onMouseEnter:()=>de(true),onMouseLeave:()=>de(false),title:Ke?"Redock to sidebar":"Pop out into window",style:{padding:6,borderRadius:6,color:fe?"#4b5563":"#9ca3af",backgroundColor:fe?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:Ke?Xs.jsx(lucideReact.PictureInPicture,{style:{width:16,height:16}}):Xs.jsx(lucideReact.PictureInPicture2,{style:{width:16,height:16}})}),Xs.jsx("button",{onClick:co,onMouseEnter:()=>ee(true),onMouseLeave:()=>ee(false),style:{padding:6,borderRadius:6,color:Z?"#4b5563":"#9ca3af",backgroundColor:Z?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:Xs.jsx(lucideReact.X,{style:{width:16,height:16}})})]})]})]}),Xs.jsxs("div",{ref:yn,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[pt&&Xs.jsx("div",{onClick:()=>gt(null),style:{position:"fixed",inset:0,zIndex:10}}),!re&&!Xe&&Xs.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[Pt.length===0&&Xs.jsx("div",{style:{padding:"24px 20px",textAlign:"center",fontSize:13,color:"#6b7280"},children:"No forks yet. Describe a feature below to start one."}),Pt.length>0&&Xs.jsx("div",{style:{display:"flex",flexDirection:"column"},children:Ks.map((s,v)=>{let C=o[s.id],z=C?C.events.find(ne=>{let Ws=ne.data;return ne.type==="status"&&Ws.summary})?.data?.summary??C.fork.summary:void 0,se=s.customName||z||s.summary||"Untitled fork",be=!!zr.find(ne=>ne.id===s.id)?.unread,Qe=o[s.id]?.state??s.status,Le=Qe==="running"||Qe==="building"||Qe==="pending",Rn=!!s.revertedAt,po=!!s.disabledAt;return Xs.jsxs(ar.Fragment,{children:[Xs.jsxs("div",{style:{position:"relative"},children:[It===s.id?Xs.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"10px 16px"},children:[Xs.jsx("input",{autoFocus:true,value:Ne,disabled:Je,onChange:ne=>we(ne.target.value),onKeyDown:ne=>{ne.key==="Enter"&&io(),ne.key==="Escape"&&(Ct(null),we(""));},style:{flex:1,fontSize:13.5,fontWeight:600,color:"#111827",border:"1px solid #d1d5db",borderRadius:6,padding:"5px 8px",outline:"none",fontFamily:"inherit",minWidth:0}}),Xs.jsx("button",{onClick:io,disabled:Je,style:{padding:"4px 10px",fontSize:12,fontWeight:500,borderRadius:6,border:"1px solid #e5e7eb",background:"#111827",color:"#ffffff",cursor:Je?"default":"pointer",opacity:Je?.5:1,flexShrink:0},children:"Save"}),Xs.jsx("button",{onClick:()=>{Ct(null),we("");},disabled:Je,style:{padding:"4px 8px",fontSize:12,fontWeight:500,borderRadius:6,border:"none",background:"transparent",color:"#6b7280",cursor:Je?"default":"pointer",flexShrink:0},children:"Cancel"})]}):Xs.jsxs("button",{onClick:()=>{Ze(false),Ye(s.id);},style:{textAlign:"left",padding:"12px 72px 12px 16px",background:"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"flex-start",gap:8,width:"100%",transition:"background 0.12s",fontFamily:"inherit"},onMouseEnter:ne=>{ne.currentTarget.style.background="#fafafa";},onMouseLeave:ne=>{ne.currentTarget.style.background="transparent";},children:[be&&Xs.jsx("span",{"aria-label":"Not viewed yet",title:"Not viewed yet",style:{width:7,height:7,borderRadius:"50%",backgroundColor:"#111827",flexShrink:0,marginTop:5}}),Xs.jsxs("div",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:5,alignItems:"flex-start"},children:[Xs.jsx("span",{style:{fontSize:13.5,fontWeight:600,color:Rn||po?"#9ca3af":"#111827",textDecoration:Rn?"line-through":"none",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:"100%"},children:se}),Xs.jsx("span",{style:{fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, "Liberation Mono", "Courier New", monospace',fontSize:10,color:"#9ca3af",background:"#f8f9fa",borderRadius:5,padding:"1px 6px",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:"100%",boxSizing:"border-box"},children:s.targetId})]}),Rn&&Xs.jsx("span",{style:{fontSize:10,fontWeight:600,color:"#9ca3af",border:"1px solid #e5e7eb",borderRadius:4,padding:"1px 5px",flexShrink:0,alignSelf:"center"},children:"removed"}),po&&!Rn&&Xs.jsx("span",{style:{fontSize:10,fontWeight:600,color:"#6b7280",background:"#f3f4f6",border:"1px solid #e5e7eb",borderRadius:5,padding:"3px 8px",flexShrink:0,alignSelf:"center"},children:"disabled"}),$e?.forkId===s.id&&Xs.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:5,background:"#f3f4f6",border:"1px solid #e5e7eb",color:"#374151",borderRadius:999,padding:"2px 9px",fontSize:11,fontWeight:600,flexShrink:0},children:[Xs.jsx("svg",{width:"9",height:"9",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",style:{animation:"__fork-spin 2s linear infinite"},children:Xs.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),$e.disabling?"Disabling":"Enabling"]}),Le&&Xs.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:5,background:"#fff7ed",border:"1px solid #fed7aa",color:"#c2410c",borderRadius:999,padding:"2px 9px",fontSize:11,fontWeight:600,flexShrink:0},children:[Xs.jsx("span",{style:{width:6,height:6,borderRadius:"50%",background:"#f59e0b",animation:"__fork-pulse 1.4s ease-in-out infinite"}}),"Running"]}),Qe==="error"&&Xs.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:5,background:"#fef2f2",border:"1px solid #fecaca",color:"#b91c1c",borderRadius:999,padding:"2px 9px",fontSize:11,fontWeight:600,flexShrink:0},children:"Failed"})]}),It!==s.id&&Xs.jsxs("div",{style:{position:"absolute",top:0,bottom:0,right:10,display:"flex",alignItems:"center",gap:8,pointerEvents:"none"},children:[Xs.jsx("span",{style:{fontSize:11.5,color:"#9ca3af",flexShrink:0},children:yr(s.updatedAt)}),Xs.jsx("button",{"aria-label":"Fork actions",onClick:ne=>{ne.stopPropagation(),gt(pt===s.id?null:s.id);},style:{padding:4,borderRadius:6,border:"none",background:pt===s.id?"#f3f4f6":"transparent",color:"#9ca3af",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"auto"},onMouseEnter:ne=>{ne.currentTarget.style.background="#f3f4f6",ne.currentTarget.style.color="#4b5563";},onMouseLeave:ne=>{pt!==s.id&&(ne.currentTarget.style.background="transparent"),ne.currentTarget.style.color="#9ca3af";},children:Xs.jsx(lucideReact.MoreHorizontal,{style:{width:15,height:15}})})]}),pt===s.id&&Xs.jsxs("div",{style:{position:"absolute",top:32,right:8,zIndex:20,background:"#ffffff",border:"1px solid #e5e7eb",borderRadius:8,boxShadow:"0 8px 24px rgba(0,0,0,0.10)",padding:4,minWidth:130,display:"flex",flexDirection:"column"},children:[R&&Xs.jsx("button",{onClick:ne=>{ne.stopPropagation(),gt(null),Ct(s.id),we(s.customName??se);},style:{padding:"6px 10px",fontSize:12,fontWeight:500,textAlign:"left",border:"none",borderRadius:6,background:"transparent",color:"#111827",cursor:"pointer"},onMouseEnter:ne=>ne.currentTarget.style.background="#f3f4f6",onMouseLeave:ne=>ne.currentTarget.style.background="transparent",children:"Rename"}),U&&Xs.jsx("button",{onClick:ne=>{ne.stopPropagation(),ao(s.id,!s.disabledAt);},disabled:Ge||Le,style:{padding:"6px 10px",fontSize:12,fontWeight:500,textAlign:"left",border:"none",borderRadius:6,background:"transparent",color:"#111827",cursor:Ge||Le?"default":"pointer",opacity:Ge||Le?.5:1},onMouseEnter:ne=>ne.currentTarget.style.background="#f3f4f6",onMouseLeave:ne=>ne.currentTarget.style.background="transparent",children:s.disabledAt?"Enable":"Disable"}),b&&E&&Xs.jsx("button",{onClick:ne=>{ne.stopPropagation(),js(s.id);},disabled:ve||Y!==null||Le,style:{padding:"6px 10px",fontSize:12,fontWeight:500,textAlign:"left",border:"none",borderRadius:6,background:"transparent",color:"#b91c1c",cursor:ve||Y||Le?"default":"pointer",opacity:ve||Y||Le?.5:1},onMouseEnter:ne=>ne.currentTarget.style.background="#fef2f2",onMouseLeave:ne=>ne.currentTarget.style.background="transparent",children:"Delete"})]})]}),(B?.forkId===s.id||ot===s.id||$e?.forkId===s.id)&&!re&&Xs.jsxs("div",{style:{padding:"2px 16px 12px 16px"},children:[fo,An]}),v<Pt.length-1&&Xs.jsx("div",{style:{height:1,background:"#f3f4f6",margin:"0 16px",flexShrink:0}})]},s.id)})}),!B&&!ot&&An&&Xs.jsx("div",{style:{padding:"0 16px 12px 16px"},children:An})]}),re&&jt.length>0&&Xs.jsxs("div",{style:{margin:"16px 16px 0 16px"},children:[jt.map((s,v)=>Xs.jsx("div",{style:{marginBottom:v<jt.length-1?12:0},children:s.type==="user"?Xs.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:Xs.jsxs("div",{style:{backgroundColor:"#f3f4f6",borderRadius:12,padding:"10px 14px",fontSize:13,color:s.reverted?"#9ca3af":"#374151",textDecoration:s.reverted?"line-through":"none",lineHeight:1.5,maxWidth:"85%"},children:[s.attachments&&s.attachments.length>0&&Xs.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginBottom:6},children:s.attachments.map((C,z)=>Xs.jsx("img",{src:C.dataUrl,alt:"attachment",style:{maxWidth:150,maxHeight:110,borderRadius:8,border:"1px solid #e5e7eb",display:"block",objectFit:"cover"}},z))}),s.selectedElement&&Xs.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:4,background:"#eef2ff",border:"1px solid #c7d2fe",color:"#4338ca",borderRadius:999,padding:"2px 8px",fontSize:10.5,fontWeight:500,marginRight:6,maxWidth:"100%"},children:[Xs.jsx(lucideReact.MousePointer2,{style:{width:10,height:10,flexShrink:0}}),Xs.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:s.selectedElement.label})]}),s.text]})}):K==="item"&&v===jt.length-1?Xs.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:12,padding:12,borderRadius:8,border:"1px solid #e4e4e7",background:"#ffffff"},children:[Xs.jsx("div",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,flexShrink:0,borderRadius:6,background:"#f4f4f5",color:"#0a0a0a"},children:Xs.jsx(lucideReact.BadgeCheck,{style:{width:16,height:16}})}),Xs.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,flex:1,minWidth:0},children:[Xs.jsx("div",{style:{fontSize:13,fontWeight:500,color:"#0a0a0a",lineHeight:1.3},children:"Feature applied"}),Xs.jsx("div",{style:{fontSize:13,color:"#71717a",lineHeight:1.4},children:s.text})]}),A&&qe!=="running"&&Xs.jsx("button",{onClick:C=>{C.stopPropagation(),so();},disabled:h,style:{padding:"4px 10px",fontSize:12,fontWeight:500,borderRadius:6,border:"1px solid #e4e4e7",background:"#ffffff",color:"#0a0a0a",cursor:h?"default":"pointer",opacity:h?.4:1,height:28,flexShrink:0},children:"Undo"})]}):Xs.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:8,background:"#ffffff",border:"1px solid #e5e7eb",borderRadius:10,boxShadow:"0 1px 2px rgba(0, 0, 0, 0.03)",padding:"9px 12px",maxWidth:"90%",boxSizing:"border-box"},children:[Xs.jsx("span",{style:{width:7,height:7,borderRadius:"50%",background:"#94a3b8",flexShrink:0}}),Xs.jsx("span",{style:{fontSize:12.5,fontWeight:600,color:s.reverted?"#9ca3af":"#334155",textDecoration:s.reverted?"line-through":"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:s.text}),s.reverted&&Xs.jsx("span",{style:{fontSize:10,fontWeight:600,color:"#9ca3af",border:"1px solid #e5e7eb",borderRadius:4,padding:"1px 5px",flexShrink:0},children:"removed"}),s.timestamp&&Xs.jsx("span",{style:{fontSize:11,color:"#9ca3af",flexShrink:0},children:yr(s.timestamp)}),b&&E&&s.promptId&&!s.reverted&&v!==jt.length-1&&qe!=="running"&&Xs.jsx("span",{style:{display:"inline-flex",gap:4,flexShrink:0},children:Xs.jsx("button",{onClick:C=>{C.stopPropagation(),Ds(s,"revert_to");},disabled:ve||Y!==null,title:"Go back to this point \u2014 discard every later change",style:{padding:"1px 6px",fontSize:10,fontWeight:500,borderRadius:4,border:"1px solid #e5e7eb",background:"#ffffff",color:"#6b7280",cursor:ve||Y?"default":"pointer",opacity:Y===s.promptId?.5:1},children:"To here"})}),A&&v===jt.length-1&&qe!=="running"&&Xs.jsxs("button",{onClick:C=>{C.stopPropagation(),so();},onMouseEnter:()=>$(v),onMouseLeave:()=>$(null),disabled:h,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:g===v?"rgba(0,0,0,0.06)":"transparent",color:g===v?"#6b7280":"#d1d5db",cursor:h?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:h?.4:1,flexShrink:0},children:[Xs.jsx(lucideReact.Undo2,{style:{width:12,height:12}}),g===v&&Xs.jsx("span",{style:{position:"absolute",bottom:"calc(100% + 4px)",right:0,fontSize:10,fontWeight:500,color:"#fff",background:"#374151",borderRadius:4,padding:"2px 6px",whiteSpace:"nowrap",pointerEvents:"none",lineHeight:"16px"},children:"Undo"})]})]})},v)),($e?.forkId===re||Yt?.disabledAt)&&Xs.jsx("div",{style:{marginTop:24,background:"#f9fafb",border:"1px solid #f3f4f6",borderRadius:10,padding:"10px 12px",textAlign:"center"},children:$e?.forkId===re?Xs.jsxs(Xs.Fragment,{children:[Xs.jsx("div",{style:{fontSize:13,fontWeight:600,color:"#111827"},children:$e.disabling?"Disabling This Fork":"Re-enabling This Fork"}),Xs.jsx("div",{style:{fontSize:12,color:"#9ca3af",fontStyle:"italic",marginTop:3,animation:"__fork-pulse 1.2s ease-in-out infinite"},children:$e.disabling?"The agent is removing this change from the app (~2m). You can re-enable it later.":"The agent is restoring this change (~2m)."})]}):Xs.jsxs(Xs.Fragment,{children:[Xs.jsx("div",{style:{fontSize:13,fontWeight:600,color:"#111827"},children:"This Fork Is Disabled"}),Xs.jsx("div",{style:{fontSize:12,color:"#6b7280",marginTop:3,lineHeight:1.5},children:"Its change has been removed from the app."}),Xs.jsx("button",{onClick:()=>re&&ao(re,false),disabled:Ge,style:{marginTop:8,padding:"5px 14px",fontSize:12,fontWeight:500,borderRadius:7,border:"1px solid #e5e7eb",background:"#ffffff",color:"#111827",cursor:Ge?"default":"pointer",opacity:Ge?.5:1,transition:"background 0.12s"},onMouseEnter:s=>s.currentTarget.style.background="#f9fafb",onMouseLeave:s=>s.currentTarget.style.background="#ffffff",children:"Enable"})]})}),fo,An]}),qe==="running"&&Xs.jsx("div",{style:{margin:"12px 16px 0 16px"},children:Xs.jsxs("div",{onClick:()=>I(!d),style:{background:"#ffffff",border:"1px solid #e5e7eb",borderRadius:10,boxShadow:"0 1px 2px rgba(0, 0, 0, 0.03)",overflow:"hidden",cursor:"pointer",transition:"all 0.3s cubic-bezier(0.22, 1, 0.36, 1)"},children:[Xs.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"9px 12px"},children:[Xs.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[Xs.jsx("span",{style:{width:7,height:7,borderRadius:"50%",background:"#f59e0b",flexShrink:0,animation:"__fork-pulse 1.4s ease-in-out infinite"}}),Xs.jsx(ha,{events:Bt},re??"__compose__")]}),Xs.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,marginLeft:8},children:[Bt[0]?.timestamp&&Xs.jsx("span",{style:{fontSize:11,color:"#9ca3af"},children:yr(Bt[0].timestamp)}),Xs.jsx("div",{style:{color:"#9ca3af",transition:"transform 0.2s ease",transform:d?"rotate(180deg)":"rotate(0deg)",display:"flex"},children:Xs.jsx(lucideReact.ChevronDown,{style:{width:14,height:14}})})]})]}),Xs.jsx("div",{style:{maxHeight:d?320:0,opacity:d?1:0,transition:"max-height 0.35s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.25s ease",overflow:"hidden"},children:Xs.jsx("div",{style:{background:"#1a1a2e",borderTop:"1px solid #e5e7eb",maxHeight:320,overflowY:"auto"},children:Xs.jsx(Lo,{events:Bt},re??"__compose__")})})]})}),qe==="error"&&Xs.jsxs("div",{style:{padding:"20px 16px",textAlign:"center"},children:[Xs.jsx("div",{style:{width:36,height:36,backgroundColor:"#fef2f2",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 10px auto"},children:Xs.jsx(lucideReact.X,{style:{width:18,height:18,color:"#ef4444"}})}),Xs.jsx("p",{style:{fontSize:12,color:"#6b7280",marginBottom:10,maxWidth:260,margin:"0 auto 10px auto"},children:Ls??r}),Xs.jsxs("button",{onClick:()=>{let s=Gn?.prompt||Sn.current;s&&w(s,Xt);},onMouseEnter:()=>pe(true),onMouseLeave:()=>pe(false),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,color:"#111827",backgroundColor:te?"#e5e7eb":"#f3f4f6",border:"none",cursor:"pointer",transition:"background-color 0.15s",fontFamily:"inherit"},children:[Xs.jsx(lucideReact.RotateCcw,{style:{width:12,height:12}})," Try Again"]})]})]}),!(re?qe==="running"||Yt?.disabledAt:Xe&&e==="running")&&Xs.jsxs("div",{style:{padding:"8px 12px 12px 12px",flexShrink:0,position:"relative"},children:[Lr&&Xs.jsx("div",{style:{position:"absolute",top:-42,left:"50%",transform:"translateX(-50%)",background:"#111827",color:"#ffffff",fontSize:12,fontWeight:500,padding:"7px 14px",borderRadius:999,boxShadow:"0 4px 16px rgba(0, 0, 0, 0.22)",whiteSpace:"nowrap",maxWidth:hr-32,overflow:"hidden",textOverflow:"ellipsis",pointerEvents:"none",zIndex:5},children:Lr}),Xs.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6,borderRadius:14,padding:"10px 10px 8px 12px",background:"#ffffff",border:"1px solid #e5e7eb",boxShadow:"0 1px 2px rgba(0, 0, 0, 0.03)"},children:[(at.length>0||yt)&&Xs.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6,alignItems:"center"},children:[at.map(s=>Xs.jsxs("div",{onMouseEnter:()=>Dr(s.id),onMouseLeave:()=>Dr(null),style:{position:"relative",width:44,height:44,borderRadius:8,overflow:"hidden",border:"1px solid #e5e7eb",flexShrink:0},children:[Xs.jsx("img",{src:s.dataUrl,alt:"attachment",style:{width:"100%",height:"100%",objectFit:"cover",display:"block"}}),Xs.jsx("button",{onClick:()=>Jn(v=>v.filter(C=>C.id!==s.id)),title:"Remove image",style:{position:"absolute",top:2,right:2,width:15,height:15,borderRadius:"50%",background:"rgba(17, 24, 39, 0.78)",color:"#ffffff",border:"none",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,opacity:Es===s.id?1:.6,transition:"opacity 0.12s"},children:Xs.jsx(lucideReact.X,{style:{width:9,height:9}})})]},s.id)),yt&&Xs.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:5,background:"#eef2ff",border:"1px solid #c7d2fe",color:"#4338ca",borderRadius:999,padding:"4px 6px 4px 9px",fontSize:11,fontWeight:500,maxWidth:"100%",minWidth:0},children:[Xs.jsx(lucideReact.MousePointer2,{style:{width:11,height:11,flexShrink:0}}),Xs.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:Ln(yt)}),Xs.jsx("button",{onClick:()=>Vn(null),title:"Remove element context",style:{width:14,height:14,borderRadius:"50%",background:"transparent",color:"#6366f1",border:"none",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,flexShrink:0},children:Xs.jsx(lucideReact.X,{style:{width:10,height:10}})})]})]}),Xs.jsx("textarea",{ref:_t,value:_,onChange:s=>H(s.target.value),onPaste:s=>{let v=Oo(s.nativeEvent);v.length>0&&(s.preventDefault(),Zr(v));},onKeyDown:s=>{s.key==="Enter"&&!s.shiftKey&&(s.preventDefault(),to()),s.key==="Escape"&&!N&&co();},placeholder:re?"Iterate on this feature...":"Start building a new Fork...",rows:1,style:{width:"100%",backgroundColor:"transparent",fontSize:13,color:"#111827",border:"none",outline:"none",padding:0,fontFamily:"inherit",resize:"none",lineHeight:1.5,maxHeight:160,overflow:"auto",boxSizing:"border-box"}}),Xs.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2},children:[Xs.jsx("button",{onClick:()=>Or.current?.click(),onMouseEnter:()=>Ur(true),onMouseLeave:()=>Ur(false),title:"Attach an image",style:{width:28,height:28,borderRadius:8,display:"flex",alignItems:"center",justifyContent:"center",background:Fs?"rgba(0, 0, 0, 0.05)":"transparent",color:"#6b7280",border:"none",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.12s"},children:Xs.jsx(lucideReact.ImagePlus,{style:{width:16,height:16}})}),Xs.jsx("button",{onClick:Us,onMouseEnter:()=>Nr(true),onMouseLeave:()=>Nr(false),title:kt?"Cancel element selection":"Select an element on the page",style:{width:28,height:28,borderRadius:8,display:"flex",alignItems:"center",justifyContent:"center",background:kt?"#eef2ff":As?"rgba(0, 0, 0, 0.05)":"transparent",color:kt?"#4f46e5":"#6b7280",border:"none",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.12s, color 0.12s"},children:Xs.jsx(lucideReact.MousePointer2,{style:{width:16,height:16}})}),Xs.jsx("div",{style:{flex:1}}),Xs.jsx("button",{onClick:Ns,onMouseEnter:()=>Br(true),onMouseLeave:()=>Br(false),title:Ht?"Stop voice input":"Voice input",style:{width:28,height:28,borderRadius:8,display:"flex",alignItems:"center",justifyContent:"center",background:Ht?"#fef2f2":Rs?"rgba(0, 0, 0, 0.05)":"transparent",color:Ht?"#dc2626":"#6b7280",border:"none",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.12s, color 0.12s",animation:Ht?"__fork-pulse 1.4s ease-in-out infinite":void 0},children:Xs.jsx(lucideReact.Mic,{style:{width:16,height:16}})}),Xs.jsx("button",{onClick:to,disabled:!Dt,onMouseEnter:()=>me(true),onMouseLeave:()=>me(false),title:"Send",style:{width:28,height:28,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:Dt?1:.35,transform:oe&&Dt?"scale(1.08)":"scale(1)",background:Dt?"#111827":"rgba(0, 0, 0, 0.12)",border:"none",cursor:Dt?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s, background 0.15s",padding:0,marginLeft:4},children:Xs.jsx(lucideReact.ArrowUp,{style:{width:14,height:14}})})]})]}),Xs.jsx("input",{ref:Or,type:"file",accept:"image/*",multiple:true,style:{display:"none"},onChange:s=>{let v=Array.from(s.target.files??[]);s.target.value="",Zr(v);}})]})]})]});return N?Yn:Ke&&Mt?Vs.createPortal(Yn,Mt.document.body):Xs.jsx(ya,{children:Yn})}function Vo(e){if("target"in e&&e.target)return e.target;if("boundaryId"in e&&e.boundaryId)return {type:"boundary",id:e.boundaryId,title:e.title};if("slotId"in e&&e.slotId)return {type:"slot",id:e.slotId,title:e.title??e.slotLabel};throw new Error("Fork chat target requires either target, slotId, or boundaryId.")}function kr(e){let{apiKey:t,userId:n,userHash:r,baseUrl:o,appId:i,adminContext:a,refreshModuleManifest:l,queueBoundaryAnimation:u,trackForkActivity:w,recordForkActivityEvent:A}=Ee(),[b,E]=ar.useState({}),[U,R]=ar.useState(null),[p,f]=ar.useState("idle"),[T,x]=ar.useState(false),[k,L]=ar.useState(null),N=ar.useRef(new Map),K=ar.useCallback((d,I)=>{E(h=>{let g=h[d]??{forkId:d,state:"running",fork:I.fork,events:[],error:null};return {...h,[d]:{...g,...I}}});},[]),_=ar.useCallback((d,I)=>{E(h=>{let c=h[d];return c?{...h,[d]:{...c,events:[...c.events,I]}}:h});},[]),H=ar.useCallback(d=>{let I=N.current.get(d);I&&(I.close(),N.current.delete(d));},[]),j=ar.useCallback(()=>{f("prompting"),L(null),x(false),R(null);},[]),W=ar.useCallback(()=>{f("idle"),x(false),L(null),R(null);for(let d of N.current.values())d.close();N.current.clear(),E({});},[]),M=ar.useCallback((d,I)=>{H(d.id);let h=new URLSearchParams({key:t});n&&h.set("userId",n),r&&h.set("userHash",r),a.isAdmin&&a.containerId&&h.set("containerId",a.containerId);let c=new EventSource(`${o}/api/v1/forks/${d.id}/events?${h.toString()}`);N.current.set(d.id,c),c.onmessage=g=>{try{let $=JSON.parse(g.data);if(A(d.id,$),_(d.id,$),$.type==="complete"){let B=$.data;u(I,d.id),l().catch(()=>{}).finally(()=>{let D={...d,status:"complete",moduleUrl:B.moduleUrl,cssUrls:B.cssUrls,summary:B.summary,completedAt:new Date().toISOString()};K(d.id,{state:"complete",fork:D}),H(d.id);});}else if($.type==="error"){let B=$.data;K(d.id,{state:"error",error:B.error||"Unknown error"}),H(d.id);}}catch{}},c.onerror=()=>{let g={Authorization:`Bearer ${t}`,...ue()};n&&(g["X-Fork-User-Id"]=n),r&&(g["X-Fork-User-Hash"]=r),fetch(`${o}/api/v1/forks/${d.id}`,{headers:g}).then($=>$.json()).then($=>{$.status==="complete"?(u(I,$.id),l().catch(()=>{}),K(d.id,{state:"complete",fork:$})):$.status==="error"?K(d.id,{state:"error",fork:$,error:$.error||"Fork generation failed"}):K(d.id,{fork:$});}).catch(()=>{K(d.id,{state:"error",error:"Connection lost"});}),H(d.id);};},[a.containerId,a.isAdmin,t,_,o,H,u,A,l,K,r,n]),S=ar.useCallback(async(d,I,h)=>{try{if(!i)throw new Error("ForkProvider requires appId for module boundary prompts.");x(!0),L(null),R(null);let c;if(h?.forkId){let g={prompt:d};n&&(g.userId=n),r&&(g.userHash=r),h?.attachments?.length&&(g.attachments=h.attachments),h?.selectedElement&&(g.selectedElement=h.selectedElement);let $=await fetch(`${o}/api/v1/forks/${encodeURIComponent(h.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...ue()},body:JSON.stringify(g)});if(!$.ok){let B=await $.json().catch(()=>({}));throw new Error(B.error||`API error: ${$.status}`)}c=await $.json();}else {let g={userId:n,prompt:d,boundaryId:e,appId:i};I?g.containerId=I:a.isAdmin&&a.containerId&&(g.containerId=a.containerId),r&&(g.userHash=r),h?.forceNew&&(g.force_new=!0),h?.attachments?.length&&(g.attachments=h.attachments),h?.selectedElement&&(g.selectedElement=h.selectedElement);let $=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...ue()},body:JSON.stringify(g)});if(!$.ok){let B=await $.json().catch(()=>({}));throw new Error(B.error||`API error: ${$.status}`)}c=await $.json();}E(g=>({...g,[c.id]:{forkId:c.id,state:"running",fork:c,events:[],error:null}})),R(c.id),x(!1),w(c,{targetKind:"module",targetId:e}),M(c,c.boundaryId??e);}catch(c){L(c.message),x(false);}},[a.containerId,a.isAdmin,t,i,o,e,M,w,r,n]),O=ar.useCallback(async d=>{try{let I={Authorization:`Bearer ${t}`,...ue()};n&&(I["X-Fork-User-Id"]=n),r&&(I["X-Fork-User-Hash"]=r);let h=await fetch(`${o}/api/v1/forks/${d}`,{headers:I});if(!h.ok)return;let c=await h.json(),g=c.boundaryId??e;if(w(c,{targetKind:"module",targetId:g}),c.status==="complete"){E($=>({...$,[c.id]:{forkId:c.id,state:"complete",fork:c,events:[],error:null}})),R(c.id);return}if(c.status==="error"){E($=>({...$,[c.id]:{forkId:c.id,state:"error",fork:c,events:[],error:c.error||"Fork generation failed"}})),R(c.id);return}if(c.status!=="pending"&&c.status!=="running"&&c.status!=="building")return;E($=>({...$,[c.id]:{forkId:c.id,state:"running",fork:c,events:[],error:null}})),R(c.id),M(c,g);}catch{}},[t,o,e,M,w,r,n]),V=ar.useCallback(async d=>{try{if(!i)throw new Error("ForkProvider requires appId for boundary undo.");let I={userId:n,boundaryId:e,appId:i};r&&(I.userHash=r),d&&(I.fork_id=d);let h=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(I)});if(!h.ok){let g=await h.json().catch(()=>({}));throw new Error(g.error||`API error: ${h.status}`)}let c=await h.json();if(await l().catch(()=>{}),c.removed)E(g=>{let $={};for(let[B,D]of Object.entries(g))(D.fork.boundaryId??e)!==e&&($[B]=D);return $}),R(null),f("prompting");else if(c.fork){let g=c.fork;K(g.id,{state:"complete",fork:g}),R(g.id);}return c}catch(I){throw L(I.message),I}},[t,i,o,e,l,K,r,n]),q=ar.useCallback(async(d,I,h="remove_step")=>{let c={Authorization:`Bearer ${t}`,...ue()};n&&(c["X-Fork-User-Id"]=n),r&&(c["X-Fork-User-Hash"]=r);let g=new URLSearchParams({mode:h});I&&g.set("prompt_id",I);let $=await fetch(`${o}/api/v1/forks/${encodeURIComponent(d)}/revert-plan?${g.toString()}`,{headers:c});if(!$.ok){let B=await $.json().catch(()=>({}));throw new Error(B.error||`API error: ${$.status}`)}return $.json()},[t,o,r,n]),Q=ar.useCallback(async d=>{try{let I={userId:n,mode:d.mode,strategy:d.strategy};d.promptId&&(I.prompt_id=d.promptId),r&&(I.userHash=r);let h=await fetch(`${o}/api/v1/forks/${encodeURIComponent(d.forkId)}/revert`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...ue()},body:JSON.stringify(I)});if(!h.ok){let g=await h.json().catch(()=>({}));throw new Error(g.error||`API error: ${h.status}`)}let c=await h.json();return c.agentic?(await O(c.fork.id),c):(await l().catch(()=>{}),c.removed?(E(g=>{let $={};for(let[B,D]of Object.entries(g))(D.fork.boundaryId??e)!==e&&($[B]=D);return $}),R(null),f("prompting")):c.fork&&(K(c.fork.id,{state:"complete",fork:c.fork}),R(c.fork.id)),c)}catch(I){throw L(I.message),I}},[O,t,o,e,l,K,r,n]),Z=ar.useCallback(async(d,I)=>{let h={userId:n,name:I};r&&(h.userHash=r);let c=await fetch(`${o}/api/v1/forks/${encodeURIComponent(d)}/name`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...ue()},body:JSON.stringify(h)});if(!c.ok){let g=await c.json().catch(()=>({}));throw new Error(g.error||`API error: ${c.status}`)}return c.json()},[t,o,r,n]),ee=ar.useCallback(async d=>{try{let I={Authorization:`Bearer ${t}`,...ue()};n&&(I["X-Fork-User-Id"]=n),r&&(I["X-Fork-User-Hash"]=r);let h=await fetch(`${o}/api/v1/forks/${d}`,{headers:I});if(!h.ok)return;let c=await h.json();E(g=>({...g,[c.id]:{forkId:c.id,state:"running",fork:c,events:[],error:null}})),M(c,c.boundaryId??e);}catch{}},[t,o,e,M,r,n]),fe=ar.useCallback(async(d,I)=>{let h={userId:n,disabled:I};r&&(h.userHash=r);let c=await fetch(`${o}/api/v1/forks/${encodeURIComponent(d)}/disabled`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...ue()},body:JSON.stringify(h)});if(!c.ok){let $=await c.json().catch(()=>({}));throw new Error($.error||`API error: ${c.status}`)}let g=await c.json();return g?.agentic&&g?.fork?.id?(await ee(g.fork.id),g):(await l().catch(()=>{}),g)},[O,t,o,l,r,n]),de=U?b[U]??null:null,oe=T?"running":k?"error":de?de.state:p,me=de?.fork??null,te=de?.events??[],pe=k??de?.error??null;return {state:oe,fork:me,events:te,error:pe,runs:b,open:j,close:W,startFork:S,undoFork:V,planRevert:q,revertFork:Q,setForkDisabled:fe,renameFork:Z,adoptRunningFork:O}}var va=0;function Go(e){let{state:t,fork:n,events:r,error:o,runs:i,open:a,close:l,startFork:u,undoFork:w,planRevert:A,revertFork:b,setForkDisabled:E,renameFork:U,adoptRunningFork:R}=kr(e),[p,f]=ar.useState(false),T=ar.useRef(null),x=ar.useRef(t),k=ar.useCallback(()=>{T.current!==null&&(clearTimeout(T.current),T.current=null);},[]),L=ar.useCallback(()=>{k(),f(true),a();},[k,a]),N=ar.useCallback(()=>{k(),f(false),l();},[k,l]),K=ar.useCallback(async H=>{k(),f(true),await R(H);},[R,k]),_=Object.values(i).filter(H=>H.state==="running").length;return ar.useEffect(()=>{let H=x.current;x.current=t,t==="complete"&&H==="running"&&p&&_===0&&(k(),T.current=setTimeout(()=>{T.current=null,f(false),l();},va)),(t==="running"||t==="prompting")&&k();},[t,p,_,k,l]),ar.useEffect(()=>k,[k]),{state:t,fork:n,events:r,error:o,runs:i,isOpen:p,open:L,close:N,submit:u,undo:w,planRevert:A,revertFork:b,setForkDisabled:E,renameFork:U,adoptRunningFork:K}}function br(){let{apiKey:e,userId:t,userHash:n,baseUrl:r,adminContext:o,setSlotFork:i,clearSlotFork:a,skipAnimationForSlot:l,trackForkActivity:u,recordForkActivityEvent:w,refreshModuleManifest:A}=Ee(),[b,E]=ar.useState({}),[U,R]=ar.useState(null),[p,f]=ar.useState("idle"),[T,x]=ar.useState(false),[k,L]=ar.useState(null),N=ar.useRef(new Map),K=ar.useCallback((d,I)=>{E(h=>{let g=h[d]??{forkId:d,state:"running",fork:I.fork,events:[],error:null};return {...h,[d]:{...g,...I}}});},[]),_=ar.useCallback((d,I)=>{E(h=>{let c=h[d];return c?{...h,[d]:{...c,events:[...c.events,I]}}:h});},[]),H=ar.useCallback(d=>{let I=N.current.get(d);I&&(I.close(),N.current.delete(d));},[]),j=ar.useCallback(()=>{f("prompting"),L(null),x(false),R(null);},[]),W=ar.useCallback(()=>{f("idle"),x(false),L(null),R(null);for(let d of N.current.values())d.close();N.current.clear(),E({});},[]),M=ar.useCallback((d,I)=>{H(d.id);let h=new URLSearchParams({key:e});t&&h.set("userId",t),n&&h.set("userHash",n),o.isAdmin&&o.containerId&&h.set("containerId",o.containerId);let c=new EventSource(`${r}/api/v1/forks/${d.id}/events?${h.toString()}`);N.current.set(d.id,c),c.onmessage=g=>{try{let $=JSON.parse(g.data);if(w(d.id,$),_(d.id,$),$.type==="complete"){let B=$.data,D={...d,status:"complete",bundleUrl:B.bundleUrl,summary:B.summary,revealPending:!0,completedAt:new Date().toISOString()};K(d.id,{state:"complete",fork:D});let Y=I??d.slotId;Y&&B.bundleUrl&&i(Y,D),H(d.id);}else if($.type==="error"){let B=$.data;K(d.id,{state:"error",error:B.error||"Unknown error"}),H(d.id);}}catch{}},c.onerror=()=>{let g={Authorization:`Bearer ${e}`,...ue()};t&&(g["X-Fork-User-Id"]=t),n&&(g["X-Fork-User-Hash"]=n),fetch(`${r}/api/v1/forks/${d.id}`,{headers:g}).then($=>$.json()).then($=>{if($.status==="complete"){K(d.id,{state:"complete",fork:{...$,revealPending:true}});let B=I??$.slotId;B&&$.bundleUrl&&i(B,{...$,revealPending:true});}else $.status==="error"?K(d.id,{state:"error",fork:$,error:$.error||"Fork generation failed"}):K(d.id,{fork:$});}).catch(()=>{K(d.id,{state:"error",error:"Connection lost"});}),H(d.id);};},[o.containerId,o.isAdmin,e,_,r,H,w,i,K,n,t]),S=ar.useCallback(async(d,I,h,c)=>{try{x(!0),L(null),R(null);let g;if(c?.forkId){let B={prompt:d};t&&(B.userId=t),n&&(B.userHash=n),c?.attachments?.length&&(B.attachments=c.attachments),c?.selectedElement&&(B.selectedElement=c.selectedElement);let D=await fetch(`${r}/api/v1/forks/${encodeURIComponent(c.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...ue()},body:JSON.stringify(B)});if(!D.ok){let Y=await D.json().catch(()=>({}));throw new Error(Y.error||`API error: ${D.status}`)}g=await D.json();}else {let B={userId:t,prompt:d};I&&(B.slotId=I),h?B.containerId=h:o.isAdmin&&o.containerId&&(B.containerId=o.containerId),n&&(B.userHash=n),c?.forceNew&&(B.force_new=!0),c?.attachments?.length&&(B.attachments=c.attachments),c?.selectedElement&&(B.selectedElement=c.selectedElement);let D=await fetch(`${r}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...ue()},body:JSON.stringify(B)});if(!D.ok){let Y=await D.json().catch(()=>({}));throw new Error(Y.error||`API error: ${D.status}`)}g=await D.json();}E(B=>({...B,[g.id]:{forkId:g.id,state:"running",fork:g,events:[],error:null}})),R(g.id),x(!1);let $=I??g.slotId;$&&u(g,{targetKind:"slot",targetId:$}),M(g,I);}catch(g){L(g.message),x(false);}},[o.containerId,o.isAdmin,e,r,M,u,n,t]),O=ar.useCallback(async d=>{try{let I={Authorization:`Bearer ${e}`,...ue()};t&&(I["X-Fork-User-Id"]=t),n&&(I["X-Fork-User-Hash"]=n);let h=await fetch(`${r}/api/v1/forks/${d}`,{headers:I});if(!h.ok)return;let c=await h.json();if(c.slotId&&u(c,{targetKind:"slot",targetId:c.slotId}),c.status==="complete"){E(g=>({...g,[c.id]:{forkId:c.id,state:"complete",fork:c,events:[],error:null}})),R(c.id);return}if(c.status==="error"){E(g=>({...g,[c.id]:{forkId:c.id,state:"error",fork:c,events:[],error:c.error||"Fork generation failed"}})),R(c.id);return}if(c.status!=="pending"&&c.status!=="running"&&c.status!=="building")return;E(g=>({...g,[c.id]:{forkId:c.id,state:"running",fork:c,events:[],error:null}})),R(c.id),M(c,c.slotId);}catch{}},[e,r,M,u,n,t]),V=ar.useCallback(async(d,I)=>{try{let h={userId:t,slotId:d};n&&(h.userHash=n),I&&(h.fork_id=I);let c=await fetch(`${r}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(h)});if(!c.ok){let $=await c.json().catch(()=>({}));throw new Error($.error||`API error: ${c.status}`)}let g=await c.json();if(l(d),g.removed)a(d),E($=>{let B={};for(let[D,Y]of Object.entries($))Y.fork.slotId!==d&&(B[D]=Y);return B}),R(null),f("prompting");else if(g.fork){i(d,g.fork);let $=g.fork;K($.id,{state:"complete",fork:$});}return g}catch(h){throw L(h.message),h}},[e,t,n,r,a,i,l,K]),q=ar.useCallback(async(d,I,h="remove_step")=>{let c={Authorization:`Bearer ${e}`,...ue()};t&&(c["X-Fork-User-Id"]=t),n&&(c["X-Fork-User-Hash"]=n);let g=new URLSearchParams({mode:h});I&&g.set("prompt_id",I);let $=await fetch(`${r}/api/v1/forks/${encodeURIComponent(d)}/revert-plan?${g.toString()}`,{headers:c});if(!$.ok){let B=await $.json().catch(()=>({}));throw new Error(B.error||`API error: ${$.status}`)}return $.json()},[e,r,n,t]),Q=ar.useCallback(async(d,I)=>{try{let h={userId:t,mode:I.mode,strategy:I.strategy};I.promptId&&(h.prompt_id=I.promptId),n&&(h.userHash=n);let c=await fetch(`${r}/api/v1/forks/${encodeURIComponent(I.forkId)}/revert`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...ue()},body:JSON.stringify(h)});if(!c.ok){let $=await c.json().catch(()=>({}));throw new Error($.error||`API error: ${c.status}`)}let g=await c.json();return g.agentic?(await O(g.fork.id),g):(l(d),g.removed?(a(d),E($=>{let B={};for(let[D,Y]of Object.entries($))Y.fork.slotId!==d&&(B[D]=Y);return B}),R(null),f("prompting")):g.fork&&(i(d,g.fork),K(g.fork.id,{state:"complete",fork:g.fork})),g)}catch(h){throw L(h.message),h}},[O,e,r,a,i,l,K,n,t]),Z=ar.useCallback(async(d,I)=>{let h={userId:t,name:I};n&&(h.userHash=n);let c=await fetch(`${r}/api/v1/forks/${encodeURIComponent(d)}/name`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...ue()},body:JSON.stringify(h)});if(!c.ok){let g=await c.json().catch(()=>({}));throw new Error(g.error||`API error: ${c.status}`)}return c.json()},[e,r,n,t]),ee=ar.useCallback(async d=>{try{let I={Authorization:`Bearer ${e}`,...ue()};t&&(I["X-Fork-User-Id"]=t),n&&(I["X-Fork-User-Hash"]=n);let h=await fetch(`${r}/api/v1/forks/${d}`,{headers:I});if(!h.ok)return;let c=await h.json();E(g=>({...g,[c.id]:{forkId:c.id,state:"running",fork:c,events:[],error:null}})),M(c,c.slotId);}catch{}},[e,r,M,n,t]),fe=ar.useCallback(async(d,I)=>{let h={userId:t,disabled:I};n&&(h.userHash=n);let c=await fetch(`${r}/api/v1/forks/${encodeURIComponent(d)}/disabled`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...ue()},body:JSON.stringify(h)});if(!c.ok){let $=await c.json().catch(()=>({}));throw new Error($.error||`API error: ${c.status}`)}let g=await c.json();return g?.agentic&&g?.fork?.id?(await ee(g.fork.id),g):(await A().catch(()=>{}),g)},[O,e,r,A,n,t]),de=U?b[U]??null:null,oe=T?"running":k?"error":de?de.state:p,me=de?.fork??null,te=de?.events??[],pe=k??de?.error??null;return {state:oe,fork:me,events:te,error:pe,runs:b,open:j,close:W,startFork:S,undoFork:V,planRevert:q,revertFork:Q,setForkDisabled:fe,renameFork:Z,adoptRunningFork:O}}var xa=0;function Qo(){let{state:e,fork:t,events:n,error:r,runs:o,open:i,close:a,startFork:l,undoFork:u,planRevert:w,revertFork:A,setForkDisabled:b,renameFork:E,adoptRunningFork:U}=br(),[R,p]=ar.useState(false),f=ar.useRef(null),T=ar.useRef(e),x=ar.useCallback(()=>{f.current!==null&&(clearTimeout(f.current),f.current=null);},[]),k=ar.useCallback(()=>{x(),p(true),i();},[x,i]),L=ar.useCallback(()=>{x(),p(false),a();},[x,a]),N=ar.useCallback(async _=>{x(),p(true),await U(_);},[U,x]),K=Object.values(o).filter(_=>_.state==="running").length;return ar.useEffect(()=>{let _=T.current;T.current=e,e==="complete"&&_==="running"&&R&&K===0&&(x(),f.current=setTimeout(()=>{f.current=null,p(false),a();},xa)),(e==="running"||e==="prompting")&&x();},[e,R,K,x,a]),ar.useEffect(()=>x,[x]),{state:e,fork:t,events:n,error:r,runs:o,isOpen:R,open:k,close:L,submit:l,undo:u,planRevert:w,revertFork:A,setForkDisabled:b,renameFork:E,adoptRunningFork:N}}var Fa=new Set(["pending","running","building"]);function vr(e){let t=Vo(e),n=Qo(),r=Go(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:i,userId:a,userHash:l,appId:u,activitySummary:w,forkActivities:A}=Ee(),b=t.type==="slot"?n:r,E=t.type==="slot"?"slot":"boundary",U=t.id,R=t.title,p=t.type==="slot"?"slot":"module",f=A.find(j=>j.targetKind===p&&j.targetId===t.id&&Fa.has(j.status)),T=A.find(j=>j.targetKind===p&&j.targetId===t.id&&j.status==="complete"&&j.unread),x=ar.useCallback(()=>{let j=f??T;if(j){b.adoptRunningFork(j.id);return}b.open();},[b,f,T]),k=ar.useCallback((j,W,M,S)=>t.type==="slot"?n.submit(j,W??t.id,M,S):r.submit(j,M,S),[r,n,t]),L=ar.useCallback((j,W)=>t.type==="slot"?n.undo(j??t.id,W):r.undo(W),[r,n,t]),N=ar.useCallback((j,W,M="remove_step")=>t.type==="slot"?n.planRevert(j,W,M):r.planRevert(j,W,M),[r,n,t]),K=ar.useCallback(j=>t.type==="slot"?n.revertFork(t.id,j):r.revertFork(j),[r,n,t]),_=ar.useCallback((j,W)=>t.type==="slot"?n.setForkDisabled(j,W):r.setForkDisabled(j,W),[r,n,t]),H=ar.useCallback((j,W)=>t.type==="slot"?n.renameFork(j,W):r.renameFork(j,W),[r,n,t]);return {...b,open:x,target:t,targetId:U,targetLabel:R,historyMode:E,submit:k,undo:L,planRevert:N,revert:K,buttonProps:{onClick:x,hasNotification:w.unreadCompletedCount>0,activity:w},panelProps:{state:b.state,fork:b.fork,events:b.events,error:b.error,runs:b.runs,...t.type==="slot"?{slotId:U,targetLabel:R,historyMode:E}:{targetId:U,targetLabel:R,historyMode:E},onSubmit:k,onUndo:L,onPlanRevert:N,onRevert:K,onSetForkDisabled:_,onRenameFork:H,onClose:b.close,baseUrl:o,apiKey:i,userId:a,userHash:l,appId:u}}}function ln(e){let{embedded:t,completeVariant:n}=e,r=vr(e);return t?Xs.jsx(Un,{...r.panelProps,embedded:true,completeVariant:n}):r.isOpen?Xs.jsx(Un,{...r.panelProps,completeVariant:n}):Xs.jsx(fr,{...r.buttonProps})}function Aa({boundaryId:e,title:t}){return Xs.jsx(ln,{boundaryId:e,title:t})}function Sr(e){let t=Array.from(e.children).filter(r=>r instanceof HTMLElement);return t.length===1?t[0]:getComputedStyle(e).display==="contents"?null:e}function es(e){let t=e.getBoundingClientRect(),n=e.cloneNode(true);n.setAttribute("data-fork-clone-overlay","true"),n.style.position="fixed",n.style.top=`${t.top}px`,n.style.left=`${t.left}px`,n.style.width=`${t.width}px`,n.style.height=`${t.height}px`,n.style.flex="none",n.style.minHeight="auto",n.style.zIndex="9998",n.style.pointerEvents="none",n.style.overflow="hidden";let r=getComputedStyle(e).backgroundColor;n.style.backgroundColor=r&&r!=="rgba(0, 0, 0, 0)"&&r!=="transparent"?r:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(n);let o=e.querySelectorAll("*"),i=n.querySelectorAll("*");for(let a=0;a<o.length;a+=1)o[a].scrollTop!==0&&(i[a].scrollTop=o[a].scrollTop),o[a].scrollLeft!==0&&(i[a].scrollLeft=o[a].scrollLeft);return n}function xr(e){let t=[],n=e.querySelectorAll("*");for(let r of n){if(!(r instanceof HTMLElement))continue;let o=r.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(r.tagName))continue;let i=getComputedStyle(r),a=parseFloat(i.borderTopLeftRadius)||0;t.push({tag:r.tagName,className:r.className||"",text:(r.textContent||"").slice(0,50).trim(),rect:o,borderRadius:a});}return t}function ts(e,t){let n=[];for(let r of t)if(!(e.find(a=>a.tag===r.tag&&a.className===r.className&&Math.abs(a.rect.top-r.rect.top)<20&&Math.abs(a.rect.left-r.rect.left)<20)||n.some(a=>r.rect.top>=a.rect.top&&r.rect.left>=a.rect.left&&r.rect.right<=a.rect.right&&r.rect.bottom<=a.rect.bottom))){for(let a=n.length-1;a>=0;a-=1){let l=n[a];l.rect.top>=r.rect.top&&l.rect.left>=r.rect.left&&l.rect.right<=r.rect.right&&l.rect.bottom<=r.rect.bottom&&n.splice(a,1);}n.push({rect:r.rect,borderRadius:r.borderRadius});}return n}function ns(e,t){let n=[];for(let r of e)if(!(t.find(a=>a.tag===r.tag&&a.className===r.className&&Math.abs(a.rect.top-r.rect.top)<20&&Math.abs(a.rect.left-r.rect.left)<20)||n.some(a=>r.rect.top>=a.rect.top&&r.rect.left>=a.rect.left&&r.rect.right<=a.rect.right&&r.rect.bottom<=a.rect.bottom))){for(let a=n.length-1;a>=0;a-=1){let l=n[a];l.rect.top>=r.rect.top&&l.rect.left>=r.rect.left&&l.rect.right<=r.rect.right&&l.rect.bottom<=r.rect.bottom&&n.splice(a,1);}n.push({rect:r.rect,borderRadius:r.borderRadius});}return n}function rs(e,t,n,r,o){let i=Math.max(0,Math.min(o,n/2,r/2));return i===0?`M ${e} ${t} L ${e+n} ${t} L ${e+n} ${t+r} L ${e} ${t+r} Z`:[`M ${e+i} ${t}`,`L ${e+n-i} ${t}`,`A ${i} ${i} 0 0 1 ${e+n} ${t+i}`,`L ${e+n} ${t+r-i}`,`A ${i} ${i} 0 0 1 ${e+n-i} ${t+r}`,`L ${e+i} ${t+r}`,`A ${i} ${i} 0 0 1 ${e} ${t+r-i}`,`L ${e} ${t+i}`,`A ${i} ${i} 0 0 1 ${e+i} ${t}`,"Z"].join(" ")}function Fr(e){let t="http://www.w3.org/2000/svg",n=document.createElement("div");n.setAttribute("data-fork-highlights","true"),n.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let r=document.createElementNS(t,"svg");r.setAttribute("width","100%"),r.setAttribute("height","100%"),r.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");r.appendChild(o);let i=[];for(let A=0;A<e.length;A+=1){let{rect:b,borderRadius:E}=e[A],U=b.left-.5,R=b.top-.5,p=b.width+1,f=b.height+1,T=Math.min(E+.5,p/2,f/2),x=rs(U,R,p,f,T),k=`__fork-glow-${A}`,L=document.createElementNS(t,"filter");L.setAttribute("id",k),L.setAttribute("x","-100%"),L.setAttribute("y","-100%"),L.setAttribute("width","300%"),L.setAttribute("height","300%");let N=document.createElementNS(t,"feGaussianBlur");N.setAttribute("in","SourceGraphic"),N.setAttribute("stdDeviation","8"),L.appendChild(N),o.appendChild(L);let K=`__fork-mask-${A}`,_=document.createElementNS(t,"mask");_.setAttribute("id",K),_.setAttribute("maskUnits","userSpaceOnUse"),_.setAttribute("x",String(U-200)),_.setAttribute("y",String(R-200)),_.setAttribute("width",String(p+400)),_.setAttribute("height",String(f+400));let H=document.createElementNS(t,"rect");H.setAttribute("x",String(U-200)),H.setAttribute("y",String(R-200)),H.setAttribute("width",String(p+400)),H.setAttribute("height",String(f+400)),H.setAttribute("fill","white"),_.appendChild(H);let j=document.createElementNS(t,"path");j.setAttribute("d",x),j.setAttribute("fill","black"),_.appendChild(j),o.appendChild(_);let W=document.createElementNS(t,"g");W.setAttribute("mask",`url(#${K})`),W.setAttribute("opacity","0");let M=document.createElementNS(t,"g");M.setAttribute("filter",`url(#${k})`);let S=document.createElementNS(t,"path");S.setAttribute("d",x),S.setAttribute("fill","none"),S.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),S.setAttribute("stroke-width","6"),S.setAttribute("stroke-linecap","round"),M.appendChild(S),W.appendChild(M),r.appendChild(W);let O=document.createElementNS(t,"path");O.setAttribute("d",x),O.setAttribute("fill","none"),O.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),O.setAttribute("stroke-width","2"),O.setAttribute("stroke-linecap","round"),O.setAttribute("opacity","0"),r.appendChild(O),i.push(S,O),S.__group=W;}n.appendChild(r),document.body.appendChild(n);let a=[];for(let A=0;A<i.length;A+=2){let b=i[A],E=i[A+1],U=b.__group;if(!U)continue;let R=E.getTotalLength(),p=b.getTotalLength();if(R<=0)continue;let f=R*.35;E.setAttribute("stroke-dasharray",`${f} ${R-f}`),E.setAttribute("stroke-dashoffset","0"),a.push(E.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*R,opacity:.92,offset:.06},{strokeDashoffset:-2*R,opacity:.92,offset:.92},{strokeDashoffset:-2.25*R,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let T=p*.35;b.setAttribute("stroke-dasharray",`${T} ${p-T}`),b.setAttribute("stroke-dashoffset","0"),a.push(b.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*p,offset:.06},{strokeDashoffset:-2*p,offset:.92},{strokeDashoffset:-2.25*p,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),a.push(U.animate([{opacity:0,offset:0},{opacity:.92,offset:.06},{opacity:.92,offset:.92},{opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));}let l=false,u=()=>{if(l)return;l=true,clearTimeout(w);for(let b of a)try{b.cancel();}catch{}let A=n.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});A.onfinish=()=>n.remove(),window.removeEventListener("click",u);},w=setTimeout(u,14500);return setTimeout(()=>{l||window.addEventListener("click",u);},500),u}function os(e){let t="http://www.w3.org/2000/svg",n=document.createElement("div");n.setAttribute("data-fork-removed","true"),n.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let r=document.createElementNS(t,"svg");r.setAttribute("width","100%"),r.setAttribute("height","100%"),r.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs"),i=document.createElementNS(t,"filter");i.setAttribute("id","__fork-removed-shadow"),i.setAttribute("x","-10%"),i.setAttribute("y","-10%"),i.setAttribute("width","120%"),i.setAttribute("height","120%");let a=document.createElementNS(t,"feDropShadow");a.setAttribute("dx","0"),a.setAttribute("dy","1"),a.setAttribute("stdDeviation","2"),a.setAttribute("flood-color","rgba(0,0,0,0.15)"),i.appendChild(a),o.appendChild(i),r.appendChild(o);for(let{rect:l,borderRadius:u}of e){let w=document.createElementNS(t,"path");w.setAttribute("d",rs(l.left,l.top,l.width,l.height,u)),w.setAttribute("fill","none"),w.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),w.setAttribute("stroke-width","1.5"),w.setAttribute("stroke-dasharray","8 4"),w.setAttribute("stroke-linecap","round"),w.setAttribute("filter","url(#__fork-removed-shadow)"),w.setAttribute("opacity","0"),r.appendChild(w),w.animate([{opacity:0,offset:0},{opacity:.6,offset:.08},{opacity:.05,offset:.45},{opacity:.6,offset:.85},{opacity:.05,offset:1}],{duration:5e3,easing:"ease-in-out",fill:"forwards"});}return n.appendChild(r),document.body.appendChild(n),n}function as(e,t){if(Ea(t.selector))return is(e,t);let r=is(e,t);if(r)return r;try{let i=document.querySelector(t.selector);if(i instanceof HTMLElement&&i!==e&&e.contains(i))return i}catch{}if(ss(t.selector))try{let i=e.querySelector(t.selector);if(i instanceof HTMLElement&&i!==e)return i}catch{}if(t.textHint){let i=t.textHint.trim();if(i){let a=Rr(e,A=>A===i);if(a)return a;let l=i.toLowerCase(),u=Rr(e,A=>A.toLowerCase()===l);if(u)return u;let w=Rr(e,A=>A.toLowerCase().includes(l));if(w)return w}}let o=Ia(t.selector);if(o&&o!==t.selector&&ss(o))try{let i=e.querySelector(o);if(i instanceof HTMLElement&&i!==e)return i}catch{}return null}function ss(e){let t=e.split(/\s+|>|~|\+/),n=t[t.length-1]??"";return /[#\[]|:not\(|:nth-/.test(n)}function is(e,t){let n=Array.from(e.querySelectorAll("[data-fork-new]"));if(n.length===0)return null;let r=Ar(t.label),o=Ar(t.textHint);return n.find(a=>{let l=Ar(a.getAttribute("data-fork-new"));return !!l&&(l===r||l===o)})??null}function Ea(e){return e.trim()==="[data-fork-new]"}function Ar(e){return e?.trim().replace(/\s+/g," ").toLowerCase()||null}function Ia(e){return e.replace(/\[class[\*~|^$]?=("[^"]*"|'[^']*'|[^\]]+)\]/g,"").replace(/\.[A-Za-z_][\w-]*/g,"").replace(/\s+/g," ").trim()}function Rr(e,t){let n=null,r=1/0,o=e.querySelectorAll("*");for(let i of o){let a=i.textContent?.trim();if(!a||!t(a))continue;let l=i.getBoundingClientRect();if(l.width<4||l.height<4)continue;let u=l.width*l.height;u<r&&(n=i,r=u);}return n}var Er=2147483600,Ca=1600,Ta=3e4,$a=300,dt=10;function Ma(e){let n=getComputedStyle(e).borderTopLeftRadius;if(!n)return 4;if(n.endsWith("%")){let a=parseFloat(n);if(!Number.isFinite(a)||a<=0)return 4;let l=e.getBoundingClientRect(),u=Math.min(l.width,l.height);return Math.max(4,a/100*u)}let r=parseFloat(n);if(!Number.isFinite(r)||r<=0)return 4;let o=e.getBoundingClientRect(),i=Math.min(o.width,o.height)/2;return r>=i?i:Math.min(r,16)}function Pa(e,t,n,r){let i=window.innerWidth,a=window.innerHeight,l=e;l==="top"&&t.top<r+dt+8?l="bottom":l==="bottom"&&a-t.bottom<r+dt+8?l="top":l==="left"&&t.left<n+dt+8?l="right":l==="right"&&i-t.right<n+dt+8&&(l="left");let u=0,w=0;return l==="top"?(u=t.top-r-dt,w=t.left+t.width/2-n/2):l==="bottom"?(u=t.bottom+dt,w=t.left+t.width/2-n/2):l==="left"?(u=t.top+t.height/2-r/2,w=t.left-n-dt):(u=t.top+t.height/2-r/2,w=t.right+dt),w=Math.max(8,Math.min(w,i-n-8)),u=Math.max(8,Math.min(u,a-r-8)),{top:u,left:w,placement:l}}function _a(e){let t=document.createElement("div");t.setAttribute("data-fork-highlight-outline","true"),t.style.cssText=["position:fixed","pointer-events:none",`z-index:${Er}`,"border:1.5px solid rgba(59,130,246,0.85)","box-sizing:border-box","opacity:0","transition:opacity 200ms ease-out"].join(";");let n=document.createElement("div");n.setAttribute("data-fork-highlight-glow","true"),n.style.cssText=["position:fixed","pointer-events:none",`z-index:${Er-1}`,"box-sizing:border-box","border:1px solid rgba(59,130,246,0.36)","box-shadow:0 0 0 4px rgba(59,130,246,0.16), 0 0 18px 2px rgba(59,130,246,0.31)","opacity:0","transition:opacity 200ms ease-out"].join(";");let r=document.createElement("div");return r.setAttribute("data-fork-highlight-tooltip","true"),r.style.cssText=["position:fixed","pointer-events:none",`z-index:${Er+1}`,"padding:6px 10px","font:500 12px/1.2 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif","color:#ffffff","background:linear-gradient(135deg,#64748b,#475569)","border-radius:999px","box-shadow:0 4px 14px rgba(71,85,105,0.31),0 1px 2px rgba(0,0,0,0.1)","white-space:nowrap","opacity:0","transform:translateY(-2px)","transition:opacity 200ms ease-out, transform 200ms ease-out"].join(";"),r.textContent=`New: ${e}`,{outline:t,glow:n,tooltip:r}}function La(){if(document.getElementById("__fork-highlight-keyframes"))return;let e=document.createElement("style");e.id="__fork-highlight-keyframes",e.textContent=`
|
|
63
|
+
`}),Xs.jsxs("div",{className:"__fork-panel",style:zs,children:[Xs.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0 16px",height:54,boxSizing:"border-box",borderBottom:"1px solid rgba(229, 231, 235, 0.8)",flexShrink:0},children:[Xs.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:[re||Xe?Xs.jsxs(Xs.Fragment,{children:[Xs.jsx("button",{onClick:()=>{ot(null),st(false),it.current=false;},style:{width:30,height:30,borderRadius:9,background:"#ffffff",border:"1px solid #e5e7eb",color:"#111827",cursor:"pointer",display:"inline-flex",alignItems:"center",justifyContent:"center",padding:0,flexShrink:0,transition:"background 0.12s, border-color 0.12s"},onMouseEnter:s=>{s.currentTarget.style.background="#f9fafb",s.currentTarget.style.borderColor="#d1d5db";},onMouseLeave:s=>{s.currentTarget.style.background="#ffffff",s.currentTarget.style.borderColor="#e5e7eb";},title:"Back to all forks",children:Xs.jsx(lucideReact.ChevronLeft,{style:{width:15,height:15}})}),(()=>{let s=re?o[re]:void 0,C=(s?s.events.find(z=>{let se=z.data;return z.type==="status"&&se.summary})?.data?.summary??s.fork.summary:void 0)||Yt?.summary||"New Feature";return Xs.jsx("span",{style:{fontSize:13.5,fontWeight:700,color:"#111827",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},title:C,children:C})})()]}):Xs.jsxs(Xs.Fragment,{children:[Xs.jsx("span",{onDoubleClick:async s=>{if(s.stopPropagation(),!zn&&confirm("Kill all forks in this container?")){$t(true);try{let v=await Es();`${v?.deleted??0}`,hn([]),ot(null),st(!1),H("");}catch(v){console.error("[Fork] Reset failed:",v);}finally{$t(false);}}},style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:4,margin:-4,cursor:"pointer",flexShrink:0},children:Xs.jsx($n,{style:{width:16,height:16,color:"#111827",pointerEvents:"none"}})}),qe==="running"?Xs.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:Os}):Wt.length===0&&!vn?Xs.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:"Fork"}):vn?Xs.jsxs("div",{ref:Fn,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[Xs.jsxs("button",{type:"button",onClick:()=>{ie(s=>!s);},onMouseEnter:()=>ce(true),onMouseLeave:()=>ce(false),"aria-haspopup":"menu","aria-expanded":G,style:{display:"inline-flex",alignItems:"center",gap:4,padding:"3px 6px",border:"1px solid transparent",borderRadius:6,background:ae||G?"#f3f4f6":"transparent",fontSize:13,fontWeight:600,color:"#111827",fontFamily:"inherit",cursor:"pointer",maxWidth:180,minWidth:0,transition:"background-color 0.12s"},children:[Xs.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:uo}),Xs.jsx(lucideReact.ChevronDown,{style:{width:12,height:12,color:"#6b7280",flexShrink:0,transform:G?"rotate(180deg)":void 0,transition:"transform 0.15s"}})]}),G&&Xs.jsxs("div",{role:"menu",style:{position:"absolute",top:"calc(100% + 4px)",left:0,minWidth:200,maxWidth:260,background:"#ffffff",border:"1px solid #e5e7eb",borderRadius:8,boxShadow:"0 4px 12px rgba(0,0,0,0.08), 0 1px 3px rgba(0,0,0,0.06)",padding:4,zIndex:2147483001},children:[Wt.map(s=>{let v=s.id===Te,C=Se===s.id,z=le===s.id;return Xs.jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>$e(s.id),onMouseLeave:()=>$e(null),onClick:()=>{s.id!==Te&&Bs(s.id);},disabled:!!le,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:C?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:le?"default":"pointer",textAlign:"left",fontWeight:v?600:400,opacity:le&&!z?.55:1},children:[Xs.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:v&&Xs.jsx(lucideReact.Check,{style:{width:12,height:12}})}),Xs.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:z?"Switching...":s.name})]},s.id)}),Xs.jsx("div",{style:{height:1,background:"#e5e7eb",margin:"4px 0"}}),_e?Xs.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"4px 4px"},children:[Xs.jsx("input",{ref:De,type:"text",value:Ae,placeholder:"Container name",disabled:le==="__new__",onChange:s=>Be(s.target.value),onKeyDown:s=>{s.key==="Enter"?(s.preventDefault(),oo(Ae)):s.key==="Escape"&&(s.preventDefault(),s.stopPropagation(),xe(false),Be(""));},style:{flex:1,minWidth:0,padding:"5px 8px",border:"1px solid #d1d5db",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",background:"#ffffff",outline:"none"},onFocus:s=>{s.currentTarget.style.borderColor="#111827",s.currentTarget.style.boxShadow="0 0 0 2px rgba(17,24,39,0.15)";},onBlur:s=>{s.currentTarget.style.borderColor="#d1d5db",s.currentTarget.style.boxShadow="none";}}),Xs.jsx("button",{type:"button",onClick:()=>{oo(Ae);},disabled:!Ae.trim()||le==="__new__",title:"Create",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:26,height:26,border:"none",borderRadius:4,background:!Ae.trim()||le==="__new__"?"#e5e7eb":"#111827",color:!Ae.trim()||le==="__new__"?"#9ca3af":"#ffffff",cursor:!Ae.trim()||le==="__new__"?"default":"pointer",flexShrink:0},children:le==="__new__"?Xs.jsx("span",{style:{width:10,height:10,border:"1.5px solid currentColor",borderTopColor:"transparent",borderRadius:"50%",animation:"__fork-spin 0.7s linear infinite"}}):Xs.jsx(lucideReact.Check,{style:{width:12,height:12}})})]}):Xs.jsx("button",{type:"button",role:"menuitem",onMouseEnter:()=>ke(true),onMouseLeave:()=>ke(false),onClick:()=>{le||(rt(null),Be(""),xe(true));},disabled:!!le,style:{display:"flex",alignItems:"center",width:"100%",padding:"6px 8px",border:"none",background:ye?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:le?"default":"pointer",textAlign:"left",opacity:le&&le!=="__new__"?.55:1},children:"+ New container"}),Mt&&Xs.jsx("div",{style:{padding:"6px 8px",fontSize:11,lineHeight:1.35,color:"#b91c1c"},children:Mt})]})]}):Xs.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:uo})]}),qe==="running"&&Xs.jsx("span",{title:bt?`Estimated ~${bt} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:bt?"#111827":"#9ca3af",backgroundColor:bt?"rgba(17, 24, 39, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:bt?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:bt?`~${bt}m`:"~ m"})]}),Xs.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[$s&&!re&&Xs.jsx("button",{type:"button",role:"switch","aria-checked":!Ut,"aria-label":Ut?"Turn Fork back on":"Turn Fork off",title:Ut?"Fork is off \u2014 you're seeing the original app. Turn it back on. Only affects you.":"Turn Fork off to see the original app. Only affects you.",onClick:()=>{Ts(!Ut);},onMouseEnter:()=>Jr(true),onMouseLeave:()=>Jr(false),style:{position:"relative",width:26,height:15,borderRadius:999,border:"none",padding:0,marginRight:6,flexShrink:0,cursor:"pointer",backgroundColor:Ut?Wr?"#9ca3af":"#d1d5db":Wr?"#374151":"#111827",transition:"background-color 0.18s ease",outline:"none",boxSizing:"border-box"},children:Xs.jsx("span",{"aria-hidden":true,style:{position:"absolute",top:2,left:Ut?2:13,width:11,height:11,borderRadius:"50%",backgroundColor:"#ffffff",boxShadow:"0 1px 2px rgba(15, 23, 42, 0.25)",transition:"left 0.18s cubic-bezier(0.16, 1, 0.3, 1)"}})}),!N&&Xs.jsxs(Xs.Fragment,{children:[Xr&&Xs.jsx("button",{onClick:Ke?Ps:Ms,onMouseEnter:()=>de(true),onMouseLeave:()=>de(false),title:Ke?"Redock to sidebar":"Pop out into window",style:{padding:6,borderRadius:6,color:fe?"#4b5563":"#9ca3af",backgroundColor:fe?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:Ke?Xs.jsx(lucideReact.PictureInPicture,{style:{width:16,height:16}}):Xs.jsx(lucideReact.PictureInPicture2,{style:{width:16,height:16}})}),Xs.jsx("button",{onClick:co,onMouseEnter:()=>ee(true),onMouseLeave:()=>ee(false),style:{padding:6,borderRadius:6,color:Z?"#4b5563":"#9ca3af",backgroundColor:Z?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:Xs.jsx(lucideReact.X,{style:{width:16,height:16}})})]})]})]}),Xs.jsxs("div",{ref:yn,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[pt&&Xs.jsx("div",{onClick:()=>gt(null),style:{position:"fixed",inset:0,zIndex:10}}),!re&&!Xe&&Xs.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[Jt.length===0&&Xs.jsx("div",{style:{padding:"24px 20px",textAlign:"center",fontSize:13,color:"#6b7280"},children:"No forks yet. Describe a feature below to start one."}),Jt.length>0&&Xs.jsx("div",{style:{display:"flex",flexDirection:"column"},children:Ks.map((s,v)=>{let C=o[s.id],z=C?C.events.find(ne=>{let Ws=ne.data;return ne.type==="status"&&Ws.summary})?.data?.summary??C.fork.summary:void 0,se=s.customName||z||s.summary||"Untitled fork",be=!!zr.find(ne=>ne.id===s.id)?.unread,Ye=o[s.id]?.state??s.status,Le=Ye==="running"||Ye==="building"||Ye==="pending",Rn=!!s.revertedAt,po=!!s.disabledAt;return Xs.jsxs(ar.Fragment,{children:[Xs.jsxs("div",{style:{position:"relative"},children:[Ct===s.id?Xs.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"10px 16px"},children:[Xs.jsx("input",{autoFocus:true,value:Ne,disabled:Je,onChange:ne=>we(ne.target.value),onKeyDown:ne=>{ne.key==="Enter"&&io(),ne.key==="Escape"&&(Tt(null),we(""));},style:{flex:1,fontSize:13.5,fontWeight:600,color:"#111827",border:"1px solid #d1d5db",borderRadius:6,padding:"5px 8px",outline:"none",fontFamily:"inherit",minWidth:0}}),Xs.jsx("button",{onClick:io,disabled:Je,style:{padding:"4px 10px",fontSize:12,fontWeight:500,borderRadius:6,border:"1px solid #e5e7eb",background:"#111827",color:"#ffffff",cursor:Je?"default":"pointer",opacity:Je?.5:1,flexShrink:0},children:"Save"}),Xs.jsx("button",{onClick:()=>{Tt(null),we("");},disabled:Je,style:{padding:"4px 8px",fontSize:12,fontWeight:500,borderRadius:6,border:"none",background:"transparent",color:"#6b7280",cursor:Je?"default":"pointer",flexShrink:0},children:"Cancel"})]}):Xs.jsxs("button",{onClick:()=>{st(false),ot(s.id);},style:{textAlign:"left",padding:"12px 72px 12px 16px",background:"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"flex-start",gap:8,width:"100%",transition:"background 0.12s",fontFamily:"inherit"},onMouseEnter:ne=>{ne.currentTarget.style.background="#fafafa";},onMouseLeave:ne=>{ne.currentTarget.style.background="transparent";},children:[be&&Xs.jsx("span",{"aria-label":"Not viewed yet",title:"Not viewed yet",style:{width:7,height:7,borderRadius:"50%",backgroundColor:"#111827",flexShrink:0,marginTop:5}}),Xs.jsxs("div",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:5,alignItems:"flex-start"},children:[Xs.jsx("span",{style:{fontSize:13.5,fontWeight:600,color:Rn||po?"#9ca3af":"#111827",textDecoration:Rn?"line-through":"none",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:"100%"},children:se}),Xs.jsx("span",{style:{fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, "Liberation Mono", "Courier New", monospace',fontSize:10,color:"#9ca3af",background:"#f8f9fa",borderRadius:5,padding:"1px 6px",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:"100%",boxSizing:"border-box"},children:s.targetId})]}),Rn&&Xs.jsx("span",{style:{fontSize:10,fontWeight:600,color:"#9ca3af",border:"1px solid #e5e7eb",borderRadius:5,padding:"3px 8px",flexShrink:0,alignSelf:"center"},children:"removed"}),po&&!Rn&&Xs.jsx("span",{style:{fontSize:10,fontWeight:600,color:"#6b7280",background:"#f3f4f6",border:"1px solid #e5e7eb",borderRadius:5,padding:"3px 8px",flexShrink:0,alignSelf:"center"},children:"disabled"}),Fe?.forkId===s.id&&Xs.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:5,background:"#f3f4f6",border:"1px solid #e5e7eb",color:"#374151",borderRadius:5,padding:"3px 8px",fontSize:10,fontWeight:600,flexShrink:0,alignSelf:"center"},children:[Xs.jsx("svg",{width:"9",height:"9",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",style:{animation:"__fork-spin 2s linear infinite"},children:Xs.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),Fe.kind==="disable"?"Disabling":Fe.kind==="enable"?"Enabling":"Removing"]}),Le&&Xs.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:5,background:"#fff7ed",border:"1px solid #fed7aa",color:"#c2410c",borderRadius:5,padding:"3px 8px",fontSize:10,fontWeight:600,flexShrink:0,alignSelf:"center"},children:[Xs.jsx("span",{style:{width:6,height:6,borderRadius:"50%",background:"#f59e0b",animation:"__fork-pulse 1.4s ease-in-out infinite"}}),"Running"]}),Ye==="error"&&Xs.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:5,background:"#fef2f2",border:"1px solid #fecaca",color:"#b91c1c",borderRadius:5,padding:"3px 8px",fontSize:10,fontWeight:600,flexShrink:0,alignSelf:"center"},children:"Failed"})]}),Ct!==s.id&&Xs.jsxs("div",{style:{position:"absolute",top:0,bottom:0,right:10,display:"flex",alignItems:"center",gap:8,pointerEvents:"none"},children:[Xs.jsx("span",{style:{fontSize:11.5,color:"#9ca3af",flexShrink:0},children:yr(s.updatedAt)}),Xs.jsx("button",{"aria-label":"Fork actions",onClick:ne=>{ne.stopPropagation(),gt(pt===s.id?null:s.id);},style:{padding:4,borderRadius:6,border:"none",background:pt===s.id?"#f3f4f6":"transparent",color:"#9ca3af",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"auto"},onMouseEnter:ne=>{ne.currentTarget.style.background="#f3f4f6",ne.currentTarget.style.color="#4b5563";},onMouseLeave:ne=>{pt!==s.id&&(ne.currentTarget.style.background="transparent"),ne.currentTarget.style.color="#9ca3af";},children:Xs.jsx(lucideReact.MoreHorizontal,{style:{width:15,height:15}})})]}),pt===s.id&&Xs.jsxs("div",{style:{position:"absolute",top:32,right:8,zIndex:20,background:"#ffffff",border:"1px solid #e5e7eb",borderRadius:8,boxShadow:"0 8px 24px rgba(0,0,0,0.10)",padding:4,minWidth:130,display:"flex",flexDirection:"column"},children:[R&&Xs.jsx("button",{onClick:ne=>{ne.stopPropagation(),gt(null),Tt(s.id),we(s.customName??se);},style:{padding:"6px 10px",fontSize:12,fontWeight:500,textAlign:"left",border:"none",borderRadius:6,background:"transparent",color:"#111827",cursor:"pointer"},onMouseEnter:ne=>ne.currentTarget.style.background="#f3f4f6",onMouseLeave:ne=>ne.currentTarget.style.background="transparent",children:"Rename"}),O&&Xs.jsx("button",{onClick:ne=>{ne.stopPropagation(),ao(s.id,!s.disabledAt);},disabled:Ge||Le,style:{padding:"6px 10px",fontSize:12,fontWeight:500,textAlign:"left",border:"none",borderRadius:6,background:"transparent",color:"#111827",cursor:Ge||Le?"default":"pointer",opacity:Ge||Le?.5:1},onMouseEnter:ne=>ne.currentTarget.style.background="#f3f4f6",onMouseLeave:ne=>ne.currentTarget.style.background="transparent",children:s.disabledAt?"Enable":"Disable"}),b&&I&&Xs.jsx("button",{onClick:ne=>{ne.stopPropagation(),js(s.id);},disabled:ve||Y!==null||Le,style:{padding:"6px 10px",fontSize:12,fontWeight:500,textAlign:"left",border:"none",borderRadius:6,background:"transparent",color:"#b91c1c",cursor:ve||Y||Le?"default":"pointer",opacity:ve||Y||Le?.5:1},onMouseEnter:ne=>ne.currentTarget.style.background="#fef2f2",onMouseLeave:ne=>ne.currentTarget.style.background="transparent",children:"Delete"})]})]}),(B?.forkId===s.id||nt===s.id||Fe?.forkId===s.id)&&!re&&Xs.jsxs("div",{style:{padding:"2px 16px 12px 16px"},children:[fo,An]}),Xs.jsx("div",{style:{height:1,background:"#f3f4f6",margin:"0 16px",flexShrink:0}})]},s.id)})}),!B&&!nt&&An&&Xs.jsx("div",{style:{padding:"0 16px 12px 16px"},children:An})]}),re&&jt.length>0&&Xs.jsxs("div",{style:{margin:"16px 16px 0 16px"},children:[jt.map((s,v)=>Xs.jsx("div",{style:{marginBottom:v<jt.length-1?12:0},children:s.type==="user"?Xs.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:Xs.jsxs("div",{style:{backgroundColor:"#f3f4f6",borderRadius:12,padding:"10px 14px",fontSize:13,color:s.reverted?"#9ca3af":"#374151",textDecoration:s.reverted?"line-through":"none",lineHeight:1.5,maxWidth:"85%"},children:[s.attachments&&s.attachments.length>0&&Xs.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginBottom:6},children:s.attachments.map((C,z)=>Xs.jsx("img",{src:C.dataUrl,alt:"attachment",style:{maxWidth:150,maxHeight:110,borderRadius:8,border:"1px solid #e5e7eb",display:"block",objectFit:"cover"}},z))}),s.selectedElement&&Xs.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:4,background:"#eef2ff",border:"1px solid #c7d2fe",color:"#4338ca",borderRadius:999,padding:"2px 8px",fontSize:10.5,fontWeight:500,marginRight:6,maxWidth:"100%"},children:[Xs.jsx(lucideReact.MousePointer2,{style:{width:10,height:10,flexShrink:0}}),Xs.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:s.selectedElement.label})]}),s.text]})}):K==="item"&&v===jt.length-1?Xs.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:12,padding:12,borderRadius:8,border:"1px solid #e4e4e7",background:"#ffffff"},children:[Xs.jsx("div",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,flexShrink:0,borderRadius:6,background:"#f4f4f5",color:"#0a0a0a"},children:Xs.jsx(lucideReact.BadgeCheck,{style:{width:16,height:16}})}),Xs.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,flex:1,minWidth:0},children:[Xs.jsx("div",{style:{fontSize:13,fontWeight:500,color:"#0a0a0a",lineHeight:1.3},children:"Feature applied"}),Xs.jsx("div",{style:{fontSize:13,color:"#71717a",lineHeight:1.4},children:s.text})]}),A&&qe!=="running"&&Xs.jsx("button",{onClick:C=>{C.stopPropagation(),so();},disabled:h,style:{padding:"4px 10px",fontSize:12,fontWeight:500,borderRadius:6,border:"1px solid #e4e4e7",background:"#ffffff",color:"#0a0a0a",cursor:h?"default":"pointer",opacity:h?.4:1,height:28,flexShrink:0},children:"Undo"})]}):Xs.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:8,background:"#ffffff",border:"1px solid #e5e7eb",borderRadius:10,boxShadow:"0 1px 2px rgba(0, 0, 0, 0.03)",padding:"9px 12px",maxWidth:"90%",boxSizing:"border-box"},children:[Xs.jsx("span",{style:{width:7,height:7,borderRadius:"50%",background:"#94a3b8",flexShrink:0}}),Xs.jsx("span",{style:{fontSize:12.5,fontWeight:600,color:s.reverted?"#9ca3af":"#334155",textDecoration:s.reverted?"line-through":"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:s.text}),s.reverted&&Xs.jsx("span",{style:{fontSize:10,fontWeight:600,color:"#9ca3af",border:"1px solid #e5e7eb",borderRadius:5,padding:"3px 8px",flexShrink:0},children:"removed"}),s.timestamp&&Xs.jsx("span",{style:{fontSize:11,color:"#9ca3af",flexShrink:0},children:yr(s.timestamp)}),b&&I&&s.promptId&&!s.reverted&&v!==jt.length-1&&qe!=="running"&&Xs.jsx("span",{style:{display:"inline-flex",gap:4,flexShrink:0},children:Xs.jsx("button",{onClick:C=>{C.stopPropagation(),Ds(s,"revert_to");},disabled:ve||Y!==null,title:"Go back to this point \u2014 discard every later change",style:{padding:"1px 6px",fontSize:10,fontWeight:500,borderRadius:4,border:"1px solid #e5e7eb",background:"#ffffff",color:"#6b7280",cursor:ve||Y?"default":"pointer",opacity:Y===s.promptId?.5:1},children:"To here"})}),A&&v===jt.length-1&&qe!=="running"&&Xs.jsxs("button",{onClick:C=>{C.stopPropagation(),so();},onMouseEnter:()=>$(v),onMouseLeave:()=>$(null),disabled:h,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:g===v?"rgba(0,0,0,0.06)":"transparent",color:g===v?"#6b7280":"#d1d5db",cursor:h?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:h?.4:1,flexShrink:0},children:[Xs.jsx(lucideReact.Undo2,{style:{width:12,height:12}}),g===v&&Xs.jsx("span",{style:{position:"absolute",bottom:"calc(100% + 4px)",right:0,fontSize:10,fontWeight:500,color:"#fff",background:"#374151",borderRadius:4,padding:"2px 6px",whiteSpace:"nowrap",pointerEvents:"none",lineHeight:"16px"},children:"Undo"})]})]})},v)),(Fe?.forkId===re||Yt?.disabledAt)&&Xs.jsx("div",{style:{marginTop:24,background:"#f9fafb",border:"1px solid #f3f4f6",borderRadius:10,padding:"10px 12px",textAlign:"center"},children:Fe?.forkId===re?Xs.jsxs(Xs.Fragment,{children:[Xs.jsx("div",{style:{fontSize:13,fontWeight:600,color:"#111827"},children:Fe.kind==="disable"?"Disabling This Fork":Fe.kind==="enable"?"Re-enabling This Fork":"Removing This Fork"}),Xs.jsx("div",{style:{fontSize:12,color:"#9ca3af",fontStyle:"italic",marginTop:3,animation:"__fork-pulse 1.2s ease-in-out infinite"},children:Fe.kind==="disable"?"The agent is removing this change from the app (~2m). You can re-enable it later.":Fe.kind==="enable"?"The agent is restoring this change (~2m).":"The agent is removing this change while keeping later work (~2m)."})]}):Xs.jsxs(Xs.Fragment,{children:[Xs.jsx("div",{style:{fontSize:13,fontWeight:600,color:"#111827"},children:"This Fork Is Disabled"}),Xs.jsx("div",{style:{fontSize:12,color:"#6b7280",marginTop:3,lineHeight:1.5},children:"Its change has been removed from the app."}),Xs.jsx("button",{onClick:()=>re&&ao(re,false),disabled:Ge,style:{marginTop:8,padding:"5px 14px",fontSize:12,fontWeight:500,borderRadius:7,border:"1px solid #e5e7eb",background:"#ffffff",color:"#111827",cursor:Ge?"default":"pointer",opacity:Ge?.5:1,transition:"background 0.12s"},onMouseEnter:s=>s.currentTarget.style.background="#f9fafb",onMouseLeave:s=>s.currentTarget.style.background="#ffffff",children:"Enable"})]})}),fo,An]}),qe==="running"&&Xs.jsx("div",{style:{margin:"12px 16px 0 16px"},children:Xs.jsxs("div",{onClick:()=>E(!d),style:{background:"#ffffff",border:"1px solid #e5e7eb",borderRadius:10,boxShadow:"0 1px 2px rgba(0, 0, 0, 0.03)",overflow:"hidden",cursor:"pointer",transition:"all 0.3s cubic-bezier(0.22, 1, 0.36, 1)"},children:[Xs.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"9px 12px"},children:[Xs.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[Xs.jsx("span",{style:{width:7,height:7,borderRadius:"50%",background:"#f59e0b",flexShrink:0,animation:"__fork-pulse 1.4s ease-in-out infinite"}}),Xs.jsx(ha,{events:Bt},re??"__compose__")]}),Xs.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,marginLeft:8},children:[Bt[0]?.timestamp&&Xs.jsx("span",{style:{fontSize:11,color:"#9ca3af"},children:yr(Bt[0].timestamp)}),Xs.jsx("div",{style:{color:"#9ca3af",transition:"transform 0.2s ease",transform:d?"rotate(180deg)":"rotate(0deg)",display:"flex"},children:Xs.jsx(lucideReact.ChevronDown,{style:{width:14,height:14}})})]})]}),Xs.jsx("div",{style:{maxHeight:d?320:0,opacity:d?1:0,transition:"max-height 0.35s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.25s ease",overflow:"hidden"},children:Xs.jsx("div",{style:{background:"#1a1a2e",borderTop:"1px solid #e5e7eb",maxHeight:320,overflowY:"auto"},children:Xs.jsx(Lo,{events:Bt},re??"__compose__")})})]})}),qe==="error"&&Xs.jsxs("div",{style:{padding:"20px 16px",textAlign:"center"},children:[Xs.jsx("div",{style:{width:36,height:36,backgroundColor:"#fef2f2",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 10px auto"},children:Xs.jsx(lucideReact.X,{style:{width:18,height:18,color:"#ef4444"}})}),Xs.jsx("p",{style:{fontSize:12,color:"#6b7280",marginBottom:10,maxWidth:260,margin:"0 auto 10px auto"},children:Ls??r}),Xs.jsxs("button",{onClick:()=>{let s=Gn?.prompt||Sn.current;s&&w(s,Xt);},onMouseEnter:()=>pe(true),onMouseLeave:()=>pe(false),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,color:"#111827",backgroundColor:te?"#e5e7eb":"#f3f4f6",border:"none",cursor:"pointer",transition:"background-color 0.15s",fontFamily:"inherit"},children:[Xs.jsx(lucideReact.RotateCcw,{style:{width:12,height:12}})," Try Again"]})]})]}),!(re?qe==="running"||Yt?.disabledAt:Xe&&e==="running")&&Xs.jsxs("div",{style:{padding:"8px 12px 12px 12px",flexShrink:0,position:"relative"},children:[Lr&&Xs.jsx("div",{style:{position:"absolute",top:-42,left:"50%",transform:"translateX(-50%)",background:"#111827",color:"#ffffff",fontSize:12,fontWeight:500,padding:"7px 14px",borderRadius:999,boxShadow:"0 4px 16px rgba(0, 0, 0, 0.22)",whiteSpace:"nowrap",maxWidth:hr-32,overflow:"hidden",textOverflow:"ellipsis",pointerEvents:"none",zIndex:5},children:Lr}),Xs.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6,borderRadius:14,padding:"10px 10px 8px 12px",background:"#ffffff",border:"1px solid #e5e7eb",boxShadow:"0 1px 2px rgba(0, 0, 0, 0.03)"},children:[(at.length>0||yt)&&Xs.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6,alignItems:"center"},children:[at.map(s=>Xs.jsxs("div",{onMouseEnter:()=>Dr(s.id),onMouseLeave:()=>Dr(null),style:{position:"relative",width:44,height:44,borderRadius:8,overflow:"hidden",border:"1px solid #e5e7eb",flexShrink:0},children:[Xs.jsx("img",{src:s.dataUrl,alt:"attachment",style:{width:"100%",height:"100%",objectFit:"cover",display:"block"}}),Xs.jsx("button",{onClick:()=>Jn(v=>v.filter(C=>C.id!==s.id)),title:"Remove image",style:{position:"absolute",top:2,right:2,width:15,height:15,borderRadius:"50%",background:"rgba(17, 24, 39, 0.78)",color:"#ffffff",border:"none",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,opacity:Is===s.id?1:.6,transition:"opacity 0.12s"},children:Xs.jsx(lucideReact.X,{style:{width:9,height:9}})})]},s.id)),yt&&Xs.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:5,background:"#eef2ff",border:"1px solid #c7d2fe",color:"#4338ca",borderRadius:999,padding:"4px 6px 4px 9px",fontSize:11,fontWeight:500,maxWidth:"100%",minWidth:0},children:[Xs.jsx(lucideReact.MousePointer2,{style:{width:11,height:11,flexShrink:0}}),Xs.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:Ln(yt)}),Xs.jsx("button",{onClick:()=>Vn(null),title:"Remove element context",style:{width:14,height:14,borderRadius:"50%",background:"transparent",color:"#6366f1",border:"none",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,flexShrink:0},children:Xs.jsx(lucideReact.X,{style:{width:10,height:10}})})]})]}),Xs.jsx("textarea",{ref:_t,value:_,onChange:s=>H(s.target.value),onPaste:s=>{let v=Oo(s.nativeEvent);v.length>0&&(s.preventDefault(),Zr(v));},onKeyDown:s=>{s.key==="Enter"&&!s.shiftKey&&(s.preventDefault(),to()),s.key==="Escape"&&!N&&co();},placeholder:re?"Iterate on this feature...":"Start building a new Fork...",rows:1,style:{width:"100%",backgroundColor:"transparent",fontSize:13,color:"#111827",border:"none",outline:"none",padding:0,fontFamily:"inherit",resize:"none",lineHeight:1.5,maxHeight:160,overflow:"auto",boxSizing:"border-box"}}),Xs.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2},children:[Xs.jsx("button",{onClick:()=>Or.current?.click(),onMouseEnter:()=>Ur(true),onMouseLeave:()=>Ur(false),title:"Attach an image",style:{width:28,height:28,borderRadius:8,display:"flex",alignItems:"center",justifyContent:"center",background:Fs?"rgba(0, 0, 0, 0.05)":"transparent",color:"#6b7280",border:"none",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.12s"},children:Xs.jsx(lucideReact.ImagePlus,{style:{width:16,height:16}})}),Xs.jsx("button",{onClick:Us,onMouseEnter:()=>Nr(true),onMouseLeave:()=>Nr(false),title:kt?"Cancel element selection":"Select an element on the page",style:{width:28,height:28,borderRadius:8,display:"flex",alignItems:"center",justifyContent:"center",background:kt?"#eef2ff":As?"rgba(0, 0, 0, 0.05)":"transparent",color:kt?"#4f46e5":"#6b7280",border:"none",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.12s, color 0.12s"},children:Xs.jsx(lucideReact.MousePointer2,{style:{width:16,height:16}})}),Xs.jsx("div",{style:{flex:1}}),Xs.jsx("button",{onClick:Ns,onMouseEnter:()=>Br(true),onMouseLeave:()=>Br(false),title:Ht?"Stop voice input":"Voice input",style:{width:28,height:28,borderRadius:8,display:"flex",alignItems:"center",justifyContent:"center",background:Ht?"#fef2f2":Rs?"rgba(0, 0, 0, 0.05)":"transparent",color:Ht?"#dc2626":"#6b7280",border:"none",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.12s, color 0.12s",animation:Ht?"__fork-pulse 1.4s ease-in-out infinite":void 0},children:Xs.jsx(lucideReact.Mic,{style:{width:16,height:16}})}),Xs.jsx("button",{onClick:to,disabled:!Dt,onMouseEnter:()=>me(true),onMouseLeave:()=>me(false),title:"Send",style:{width:28,height:28,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:Dt?1:.35,transform:oe&&Dt?"scale(1.08)":"scale(1)",background:Dt?"#111827":"rgba(0, 0, 0, 0.12)",border:"none",cursor:Dt?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s, background 0.15s",padding:0,marginLeft:4},children:Xs.jsx(lucideReact.ArrowUp,{style:{width:14,height:14}})})]})]}),Xs.jsx("input",{ref:Or,type:"file",accept:"image/*",multiple:true,style:{display:"none"},onChange:s=>{let v=Array.from(s.target.files??[]);s.target.value="",Zr(v);}})]})]})]});return N?Yn:Ke&&Pt?Vs.createPortal(Yn,Pt.document.body):Xs.jsx(ya,{children:Yn})}function Vo(e){if("target"in e&&e.target)return e.target;if("boundaryId"in e&&e.boundaryId)return {type:"boundary",id:e.boundaryId,title:e.title};if("slotId"in e&&e.slotId)return {type:"slot",id:e.slotId,title:e.title??e.slotLabel};throw new Error("Fork chat target requires either target, slotId, or boundaryId.")}function kr(e){let{apiKey:t,userId:n,userHash:r,baseUrl:o,appId:i,adminContext:a,refreshModuleManifest:l,queueBoundaryAnimation:u,trackForkActivity:w,recordForkActivityEvent:A}=Ee(),[b,I]=ar.useState({}),[O,R]=ar.useState(null),[p,f]=ar.useState("idle"),[T,x]=ar.useState(false),[k,L]=ar.useState(null),N=ar.useRef(new Map),K=ar.useCallback((d,E)=>{I(h=>{let g=h[d]??{forkId:d,state:"running",fork:E.fork,events:[],error:null};return {...h,[d]:{...g,...E}}});},[]),_=ar.useCallback((d,E)=>{I(h=>{let c=h[d];return c?{...h,[d]:{...c,events:[...c.events,E]}}:h});},[]),H=ar.useCallback(d=>{let E=N.current.get(d);E&&(E.close(),N.current.delete(d));},[]),j=ar.useCallback(()=>{f("prompting"),L(null),x(false),R(null);},[]),W=ar.useCallback(()=>{f("idle"),x(false),L(null),R(null);for(let d of N.current.values())d.close();N.current.clear(),I({});},[]),M=ar.useCallback((d,E)=>{H(d.id);let h=new URLSearchParams({key:t});n&&h.set("userId",n),r&&h.set("userHash",r),a.isAdmin&&a.containerId&&h.set("containerId",a.containerId);let c=new EventSource(`${o}/api/v1/forks/${d.id}/events?${h.toString()}`);N.current.set(d.id,c),c.onmessage=g=>{try{let $=JSON.parse(g.data);if(A(d.id,$),_(d.id,$),$.type==="complete"){let B=$.data;u(E,d.id),l().catch(()=>{}).finally(()=>{let D={...d,status:"complete",moduleUrl:B.moduleUrl,cssUrls:B.cssUrls,summary:B.summary,completedAt:new Date().toISOString()};K(d.id,{state:"complete",fork:D}),H(d.id);});}else if($.type==="error"){let B=$.data;K(d.id,{state:"error",error:B.error||"Unknown error"}),H(d.id);}}catch{}},c.onerror=()=>{let g={Authorization:`Bearer ${t}`,...ue()};n&&(g["X-Fork-User-Id"]=n),r&&(g["X-Fork-User-Hash"]=r),fetch(`${o}/api/v1/forks/${d.id}`,{headers:g}).then($=>$.json()).then($=>{$.status==="complete"?(u(E,$.id),l().catch(()=>{}),K(d.id,{state:"complete",fork:$})):$.status==="error"?K(d.id,{state:"error",fork:$,error:$.error||"Fork generation failed"}):K(d.id,{fork:$});}).catch(()=>{K(d.id,{state:"error",error:"Connection lost"});}),H(d.id);};},[a.containerId,a.isAdmin,t,_,o,H,u,A,l,K,r,n]),S=ar.useCallback(async(d,E,h)=>{try{if(!i)throw new Error("ForkProvider requires appId for module boundary prompts.");x(!0),L(null),R(null);let c;if(h?.forkId){let g={prompt:d};n&&(g.userId=n),r&&(g.userHash=r),h?.attachments?.length&&(g.attachments=h.attachments),h?.selectedElement&&(g.selectedElement=h.selectedElement);let $=await fetch(`${o}/api/v1/forks/${encodeURIComponent(h.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...ue()},body:JSON.stringify(g)});if(!$.ok){let B=await $.json().catch(()=>({}));throw new Error(B.error||`API error: ${$.status}`)}c=await $.json();}else {let g={userId:n,prompt:d,boundaryId:e,appId:i};E?g.containerId=E:a.isAdmin&&a.containerId&&(g.containerId=a.containerId),r&&(g.userHash=r),h?.forceNew&&(g.force_new=!0),h?.attachments?.length&&(g.attachments=h.attachments),h?.selectedElement&&(g.selectedElement=h.selectedElement);let $=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...ue()},body:JSON.stringify(g)});if(!$.ok){let B=await $.json().catch(()=>({}));throw new Error(B.error||`API error: ${$.status}`)}c=await $.json();}I(g=>({...g,[c.id]:{forkId:c.id,state:"running",fork:c,events:[],error:null}})),R(c.id),x(!1),w(c,{targetKind:"module",targetId:e}),M(c,c.boundaryId??e);}catch(c){L(c.message),x(false);}},[a.containerId,a.isAdmin,t,i,o,e,M,w,r,n]),U=ar.useCallback(async d=>{try{let E={Authorization:`Bearer ${t}`,...ue()};n&&(E["X-Fork-User-Id"]=n),r&&(E["X-Fork-User-Hash"]=r);let h=await fetch(`${o}/api/v1/forks/${d}`,{headers:E});if(!h.ok)return;let c=await h.json(),g=c.boundaryId??e;if(w(c,{targetKind:"module",targetId:g}),c.status==="complete"){I($=>({...$,[c.id]:{forkId:c.id,state:"complete",fork:c,events:[],error:null}})),R(c.id);return}if(c.status==="error"){I($=>({...$,[c.id]:{forkId:c.id,state:"error",fork:c,events:[],error:c.error||"Fork generation failed"}})),R(c.id);return}if(c.status!=="pending"&&c.status!=="running"&&c.status!=="building")return;I($=>({...$,[c.id]:{forkId:c.id,state:"running",fork:c,events:[],error:null}})),R(c.id),M(c,g);}catch{}},[t,o,e,M,w,r,n]),X=ar.useCallback(async d=>{try{if(!i)throw new Error("ForkProvider requires appId for boundary undo.");let E={userId:n,boundaryId:e,appId:i};r&&(E.userHash=r),d&&(E.fork_id=d);let h=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(E)});if(!h.ok){let g=await h.json().catch(()=>({}));throw new Error(g.error||`API error: ${h.status}`)}let c=await h.json();if(await l().catch(()=>{}),c.removed)I(g=>{let $={};for(let[B,D]of Object.entries(g))(D.fork.boundaryId??e)!==e&&($[B]=D);return $}),R(null),f("prompting");else if(c.fork){let g=c.fork;K(g.id,{state:"complete",fork:g}),R(g.id);}return c}catch(E){throw L(E.message),E}},[t,i,o,e,l,K,r,n]),V=ar.useCallback(async d=>{try{let E={Authorization:`Bearer ${t}`,...ue()};n&&(E["X-Fork-User-Id"]=n),r&&(E["X-Fork-User-Hash"]=r);let h=await fetch(`${o}/api/v1/forks/${d}`,{headers:E});if(!h.ok)return;let c=await h.json();I(g=>({...g,[c.id]:{forkId:c.id,state:"running",fork:c,events:[],error:null}})),M(c,c.boundaryId??e);}catch{}},[t,o,e,M,r,n]),Q=ar.useCallback(async(d,E,h="remove_step")=>{let c={Authorization:`Bearer ${t}`,...ue()};n&&(c["X-Fork-User-Id"]=n),r&&(c["X-Fork-User-Hash"]=r);let g=new URLSearchParams({mode:h});E&&g.set("prompt_id",E);let $=await fetch(`${o}/api/v1/forks/${encodeURIComponent(d)}/revert-plan?${g.toString()}`,{headers:c});if(!$.ok){let B=await $.json().catch(()=>({}));throw new Error(B.error||`API error: ${$.status}`)}return $.json()},[t,o,r,n]),Z=ar.useCallback(async d=>{try{let E={userId:n,mode:d.mode,strategy:d.strategy};d.promptId&&(E.prompt_id=d.promptId),r&&(E.userHash=r);let h=await fetch(`${o}/api/v1/forks/${encodeURIComponent(d.forkId)}/revert`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...ue()},body:JSON.stringify(E)});if(!h.ok){let g=await h.json().catch(()=>({}));throw new Error(g.error||`API error: ${h.status}`)}let c=await h.json();return c.agentic?(await V(c.fork.id),c):(await l().catch(()=>{}),c.removed?(I(g=>{let $={};for(let[B,D]of Object.entries(g))(D.fork.boundaryId??e)!==e&&($[B]=D);return $}),R(null),f("prompting")):c.fork&&(K(c.fork.id,{state:"complete",fork:c.fork}),R(c.fork.id)),c)}catch(E){throw L(E.message),E}},[V,t,o,e,l,K,r,n]),ee=ar.useCallback(async(d,E)=>{let h={userId:n,name:E};r&&(h.userHash=r);let c=await fetch(`${o}/api/v1/forks/${encodeURIComponent(d)}/name`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...ue()},body:JSON.stringify(h)});if(!c.ok){let g=await c.json().catch(()=>({}));throw new Error(g.error||`API error: ${c.status}`)}return c.json()},[t,o,r,n]),fe=ar.useCallback(async(d,E)=>{let h={userId:n,disabled:E};r&&(h.userHash=r);let c=await fetch(`${o}/api/v1/forks/${encodeURIComponent(d)}/disabled`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...ue()},body:JSON.stringify(h)});if(!c.ok){let $=await c.json().catch(()=>({}));throw new Error($.error||`API error: ${c.status}`)}let g=await c.json();return g?.agentic&&g?.fork?.id?(await V(g.fork.id),g):(await l().catch(()=>{}),g)},[U,t,o,l,r,n]),de=O?b[O]??null:null,oe=T?"running":k?"error":de?de.state:p,me=de?.fork??null,te=de?.events??[],pe=k??de?.error??null;return {state:oe,fork:me,events:te,error:pe,runs:b,open:j,close:W,startFork:S,undoFork:X,planRevert:Q,revertFork:Z,setForkDisabled:fe,renameFork:ee,adoptRunningFork:U}}var va=0;function Go(e){let{state:t,fork:n,events:r,error:o,runs:i,open:a,close:l,startFork:u,undoFork:w,planRevert:A,revertFork:b,setForkDisabled:I,renameFork:O,adoptRunningFork:R}=kr(e),[p,f]=ar.useState(false),T=ar.useRef(null),x=ar.useRef(t),k=ar.useCallback(()=>{T.current!==null&&(clearTimeout(T.current),T.current=null);},[]),L=ar.useCallback(()=>{k(),f(true),a();},[k,a]),N=ar.useCallback(()=>{k(),f(false),l();},[k,l]),K=ar.useCallback(async H=>{k(),f(true),await R(H);},[R,k]),_=Object.values(i).filter(H=>H.state==="running").length;return ar.useEffect(()=>{let H=x.current;x.current=t,t==="complete"&&H==="running"&&p&&_===0&&(k(),T.current=setTimeout(()=>{T.current=null,f(false),l();},va)),(t==="running"||t==="prompting")&&k();},[t,p,_,k,l]),ar.useEffect(()=>k,[k]),{state:t,fork:n,events:r,error:o,runs:i,isOpen:p,open:L,close:N,submit:u,undo:w,planRevert:A,revertFork:b,setForkDisabled:I,renameFork:O,adoptRunningFork:K}}function br(){let{apiKey:e,userId:t,userHash:n,baseUrl:r,adminContext:o,setSlotFork:i,clearSlotFork:a,skipAnimationForSlot:l,trackForkActivity:u,recordForkActivityEvent:w,refreshModuleManifest:A}=Ee(),[b,I]=ar.useState({}),[O,R]=ar.useState(null),[p,f]=ar.useState("idle"),[T,x]=ar.useState(false),[k,L]=ar.useState(null),N=ar.useRef(new Map),K=ar.useCallback((d,E)=>{I(h=>{let g=h[d]??{forkId:d,state:"running",fork:E.fork,events:[],error:null};return {...h,[d]:{...g,...E}}});},[]),_=ar.useCallback((d,E)=>{I(h=>{let c=h[d];return c?{...h,[d]:{...c,events:[...c.events,E]}}:h});},[]),H=ar.useCallback(d=>{let E=N.current.get(d);E&&(E.close(),N.current.delete(d));},[]),j=ar.useCallback(()=>{f("prompting"),L(null),x(false),R(null);},[]),W=ar.useCallback(()=>{f("idle"),x(false),L(null),R(null);for(let d of N.current.values())d.close();N.current.clear(),I({});},[]),M=ar.useCallback((d,E)=>{H(d.id);let h=new URLSearchParams({key:e});t&&h.set("userId",t),n&&h.set("userHash",n),o.isAdmin&&o.containerId&&h.set("containerId",o.containerId);let c=new EventSource(`${r}/api/v1/forks/${d.id}/events?${h.toString()}`);N.current.set(d.id,c),c.onmessage=g=>{try{let $=JSON.parse(g.data);if(w(d.id,$),_(d.id,$),$.type==="complete"){let B=$.data,D={...d,status:"complete",bundleUrl:B.bundleUrl,summary:B.summary,revealPending:!0,completedAt:new Date().toISOString()};K(d.id,{state:"complete",fork:D});let Y=E??d.slotId;Y&&B.bundleUrl&&i(Y,D),H(d.id);}else if($.type==="error"){let B=$.data;K(d.id,{state:"error",error:B.error||"Unknown error"}),H(d.id);}}catch{}},c.onerror=()=>{let g={Authorization:`Bearer ${e}`,...ue()};t&&(g["X-Fork-User-Id"]=t),n&&(g["X-Fork-User-Hash"]=n),fetch(`${r}/api/v1/forks/${d.id}`,{headers:g}).then($=>$.json()).then($=>{if($.status==="complete"){K(d.id,{state:"complete",fork:{...$,revealPending:true}});let B=E??$.slotId;B&&$.bundleUrl&&i(B,{...$,revealPending:true});}else $.status==="error"?K(d.id,{state:"error",fork:$,error:$.error||"Fork generation failed"}):K(d.id,{fork:$});}).catch(()=>{K(d.id,{state:"error",error:"Connection lost"});}),H(d.id);};},[o.containerId,o.isAdmin,e,_,r,H,w,i,K,n,t]),S=ar.useCallback(async(d,E,h,c)=>{try{x(!0),L(null),R(null);let g;if(c?.forkId){let B={prompt:d};t&&(B.userId=t),n&&(B.userHash=n),c?.attachments?.length&&(B.attachments=c.attachments),c?.selectedElement&&(B.selectedElement=c.selectedElement);let D=await fetch(`${r}/api/v1/forks/${encodeURIComponent(c.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...ue()},body:JSON.stringify(B)});if(!D.ok){let Y=await D.json().catch(()=>({}));throw new Error(Y.error||`API error: ${D.status}`)}g=await D.json();}else {let B={userId:t,prompt:d};E&&(B.slotId=E),h?B.containerId=h:o.isAdmin&&o.containerId&&(B.containerId=o.containerId),n&&(B.userHash=n),c?.forceNew&&(B.force_new=!0),c?.attachments?.length&&(B.attachments=c.attachments),c?.selectedElement&&(B.selectedElement=c.selectedElement);let D=await fetch(`${r}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...ue()},body:JSON.stringify(B)});if(!D.ok){let Y=await D.json().catch(()=>({}));throw new Error(Y.error||`API error: ${D.status}`)}g=await D.json();}I(B=>({...B,[g.id]:{forkId:g.id,state:"running",fork:g,events:[],error:null}})),R(g.id),x(!1);let $=E??g.slotId;$&&u(g,{targetKind:"slot",targetId:$}),M(g,E);}catch(g){L(g.message),x(false);}},[o.containerId,o.isAdmin,e,r,M,u,n,t]),U=ar.useCallback(async d=>{try{let E={Authorization:`Bearer ${e}`,...ue()};t&&(E["X-Fork-User-Id"]=t),n&&(E["X-Fork-User-Hash"]=n);let h=await fetch(`${r}/api/v1/forks/${d}`,{headers:E});if(!h.ok)return;let c=await h.json();if(c.slotId&&u(c,{targetKind:"slot",targetId:c.slotId}),c.status==="complete"){I(g=>({...g,[c.id]:{forkId:c.id,state:"complete",fork:c,events:[],error:null}})),R(c.id);return}if(c.status==="error"){I(g=>({...g,[c.id]:{forkId:c.id,state:"error",fork:c,events:[],error:c.error||"Fork generation failed"}})),R(c.id);return}if(c.status!=="pending"&&c.status!=="running"&&c.status!=="building")return;I(g=>({...g,[c.id]:{forkId:c.id,state:"running",fork:c,events:[],error:null}})),R(c.id),M(c,c.slotId);}catch{}},[e,r,M,u,n,t]),X=ar.useCallback(async(d,E)=>{try{let h={userId:t,slotId:d};n&&(h.userHash=n),E&&(h.fork_id=E);let c=await fetch(`${r}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(h)});if(!c.ok){let $=await c.json().catch(()=>({}));throw new Error($.error||`API error: ${c.status}`)}let g=await c.json();if(l(d),g.removed)a(d),I($=>{let B={};for(let[D,Y]of Object.entries($))Y.fork.slotId!==d&&(B[D]=Y);return B}),R(null),f("prompting");else if(g.fork){i(d,g.fork);let $=g.fork;K($.id,{state:"complete",fork:$});}return g}catch(h){throw L(h.message),h}},[e,t,n,r,a,i,l,K]),V=ar.useCallback(async d=>{try{let E={Authorization:`Bearer ${e}`,...ue()};t&&(E["X-Fork-User-Id"]=t),n&&(E["X-Fork-User-Hash"]=n);let h=await fetch(`${r}/api/v1/forks/${d}`,{headers:E});if(!h.ok)return;let c=await h.json();I(g=>({...g,[c.id]:{forkId:c.id,state:"running",fork:c,events:[],error:null}})),M(c,c.slotId);}catch{}},[e,r,M,n,t]),Q=ar.useCallback(async(d,E,h="remove_step")=>{let c={Authorization:`Bearer ${e}`,...ue()};t&&(c["X-Fork-User-Id"]=t),n&&(c["X-Fork-User-Hash"]=n);let g=new URLSearchParams({mode:h});E&&g.set("prompt_id",E);let $=await fetch(`${r}/api/v1/forks/${encodeURIComponent(d)}/revert-plan?${g.toString()}`,{headers:c});if(!$.ok){let B=await $.json().catch(()=>({}));throw new Error(B.error||`API error: ${$.status}`)}return $.json()},[e,r,n,t]),Z=ar.useCallback(async(d,E)=>{try{let h={userId:t,mode:E.mode,strategy:E.strategy};E.promptId&&(h.prompt_id=E.promptId),n&&(h.userHash=n);let c=await fetch(`${r}/api/v1/forks/${encodeURIComponent(E.forkId)}/revert`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...ue()},body:JSON.stringify(h)});if(!c.ok){let $=await c.json().catch(()=>({}));throw new Error($.error||`API error: ${c.status}`)}let g=await c.json();return g.agentic?(await V(g.fork.id),g):(l(d),g.removed?(a(d),I($=>{let B={};for(let[D,Y]of Object.entries($))Y.fork.slotId!==d&&(B[D]=Y);return B}),R(null),f("prompting")):g.fork&&(i(d,g.fork),K(g.fork.id,{state:"complete",fork:g.fork})),g)}catch(h){throw L(h.message),h}},[V,e,r,a,i,l,K,n,t]),ee=ar.useCallback(async(d,E)=>{let h={userId:t,name:E};n&&(h.userHash=n);let c=await fetch(`${r}/api/v1/forks/${encodeURIComponent(d)}/name`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...ue()},body:JSON.stringify(h)});if(!c.ok){let g=await c.json().catch(()=>({}));throw new Error(g.error||`API error: ${c.status}`)}return c.json()},[e,r,n,t]),fe=ar.useCallback(async(d,E)=>{let h={userId:t,disabled:E};n&&(h.userHash=n);let c=await fetch(`${r}/api/v1/forks/${encodeURIComponent(d)}/disabled`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...ue()},body:JSON.stringify(h)});if(!c.ok){let $=await c.json().catch(()=>({}));throw new Error($.error||`API error: ${c.status}`)}let g=await c.json();return g?.agentic&&g?.fork?.id?(await V(g.fork.id),g):(await A().catch(()=>{}),g)},[U,e,r,A,n,t]),de=O?b[O]??null:null,oe=T?"running":k?"error":de?de.state:p,me=de?.fork??null,te=de?.events??[],pe=k??de?.error??null;return {state:oe,fork:me,events:te,error:pe,runs:b,open:j,close:W,startFork:S,undoFork:X,planRevert:Q,revertFork:Z,setForkDisabled:fe,renameFork:ee,adoptRunningFork:U}}var xa=0;function Qo(){let{state:e,fork:t,events:n,error:r,runs:o,open:i,close:a,startFork:l,undoFork:u,planRevert:w,revertFork:A,setForkDisabled:b,renameFork:I,adoptRunningFork:O}=br(),[R,p]=ar.useState(false),f=ar.useRef(null),T=ar.useRef(e),x=ar.useCallback(()=>{f.current!==null&&(clearTimeout(f.current),f.current=null);},[]),k=ar.useCallback(()=>{x(),p(true),i();},[x,i]),L=ar.useCallback(()=>{x(),p(false),a();},[x,a]),N=ar.useCallback(async _=>{x(),p(true),await O(_);},[O,x]),K=Object.values(o).filter(_=>_.state==="running").length;return ar.useEffect(()=>{let _=T.current;T.current=e,e==="complete"&&_==="running"&&R&&K===0&&(x(),f.current=setTimeout(()=>{f.current=null,p(false),a();},xa)),(e==="running"||e==="prompting")&&x();},[e,R,K,x,a]),ar.useEffect(()=>x,[x]),{state:e,fork:t,events:n,error:r,runs:o,isOpen:R,open:k,close:L,submit:l,undo:u,planRevert:w,revertFork:A,setForkDisabled:b,renameFork:I,adoptRunningFork:N}}var Fa=new Set(["pending","running","building"]);function vr(e){let t=Vo(e),n=Qo(),r=Go(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:i,userId:a,userHash:l,appId:u,activitySummary:w,forkActivities:A}=Ee(),b=t.type==="slot"?n:r,I=t.type==="slot"?"slot":"boundary",O=t.id,R=t.title,p=t.type==="slot"?"slot":"module",f=A.find(j=>j.targetKind===p&&j.targetId===t.id&&Fa.has(j.status)),T=A.find(j=>j.targetKind===p&&j.targetId===t.id&&j.status==="complete"&&j.unread),x=ar.useCallback(()=>{let j=f??T;if(j){b.adoptRunningFork(j.id);return}b.open();},[b,f,T]),k=ar.useCallback((j,W,M,S)=>t.type==="slot"?n.submit(j,W??t.id,M,S):r.submit(j,M,S),[r,n,t]),L=ar.useCallback((j,W)=>t.type==="slot"?n.undo(j??t.id,W):r.undo(W),[r,n,t]),N=ar.useCallback((j,W,M="remove_step")=>t.type==="slot"?n.planRevert(j,W,M):r.planRevert(j,W,M),[r,n,t]),K=ar.useCallback(j=>t.type==="slot"?n.revertFork(t.id,j):r.revertFork(j),[r,n,t]),_=ar.useCallback((j,W)=>t.type==="slot"?n.setForkDisabled(j,W):r.setForkDisabled(j,W),[r,n,t]),H=ar.useCallback((j,W)=>t.type==="slot"?n.renameFork(j,W):r.renameFork(j,W),[r,n,t]);return {...b,open:x,target:t,targetId:O,targetLabel:R,historyMode:I,submit:k,undo:L,planRevert:N,revert:K,buttonProps:{onClick:x,hasNotification:w.unreadCompletedCount>0,activity:w},panelProps:{state:b.state,fork:b.fork,events:b.events,error:b.error,runs:b.runs,...t.type==="slot"?{slotId:O,targetLabel:R,historyMode:I}:{targetId:O,targetLabel:R,historyMode:I},onSubmit:k,onUndo:L,onPlanRevert:N,onRevert:K,onSetForkDisabled:_,onRenameFork:H,onClose:b.close,baseUrl:o,apiKey:i,userId:a,userHash:l,appId:u}}}function ln(e){let{embedded:t,completeVariant:n}=e,r=vr(e);return t?Xs.jsx(Un,{...r.panelProps,embedded:true,completeVariant:n}):r.isOpen?Xs.jsx(Un,{...r.panelProps,completeVariant:n}):Xs.jsx(fr,{...r.buttonProps})}function Aa({boundaryId:e,title:t}){return Xs.jsx(ln,{boundaryId:e,title:t})}function Sr(e){let t=Array.from(e.children).filter(r=>r instanceof HTMLElement);return t.length===1?t[0]:getComputedStyle(e).display==="contents"?null:e}function es(e){let t=e.getBoundingClientRect(),n=e.cloneNode(true);n.setAttribute("data-fork-clone-overlay","true"),n.style.position="fixed",n.style.top=`${t.top}px`,n.style.left=`${t.left}px`,n.style.width=`${t.width}px`,n.style.height=`${t.height}px`,n.style.flex="none",n.style.minHeight="auto",n.style.zIndex="9998",n.style.pointerEvents="none",n.style.overflow="hidden";let r=getComputedStyle(e).backgroundColor;n.style.backgroundColor=r&&r!=="rgba(0, 0, 0, 0)"&&r!=="transparent"?r:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(n);let o=e.querySelectorAll("*"),i=n.querySelectorAll("*");for(let a=0;a<o.length;a+=1)o[a].scrollTop!==0&&(i[a].scrollTop=o[a].scrollTop),o[a].scrollLeft!==0&&(i[a].scrollLeft=o[a].scrollLeft);return n}function xr(e){let t=[],n=e.querySelectorAll("*");for(let r of n){if(!(r instanceof HTMLElement))continue;let o=r.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(r.tagName))continue;let i=getComputedStyle(r),a=parseFloat(i.borderTopLeftRadius)||0;t.push({tag:r.tagName,className:r.className||"",text:(r.textContent||"").slice(0,50).trim(),rect:o,borderRadius:a});}return t}function ts(e,t){let n=[];for(let r of t)if(!(e.find(a=>a.tag===r.tag&&a.className===r.className&&Math.abs(a.rect.top-r.rect.top)<20&&Math.abs(a.rect.left-r.rect.left)<20)||n.some(a=>r.rect.top>=a.rect.top&&r.rect.left>=a.rect.left&&r.rect.right<=a.rect.right&&r.rect.bottom<=a.rect.bottom))){for(let a=n.length-1;a>=0;a-=1){let l=n[a];l.rect.top>=r.rect.top&&l.rect.left>=r.rect.left&&l.rect.right<=r.rect.right&&l.rect.bottom<=r.rect.bottom&&n.splice(a,1);}n.push({rect:r.rect,borderRadius:r.borderRadius});}return n}function ns(e,t){let n=[];for(let r of e)if(!(t.find(a=>a.tag===r.tag&&a.className===r.className&&Math.abs(a.rect.top-r.rect.top)<20&&Math.abs(a.rect.left-r.rect.left)<20)||n.some(a=>r.rect.top>=a.rect.top&&r.rect.left>=a.rect.left&&r.rect.right<=a.rect.right&&r.rect.bottom<=a.rect.bottom))){for(let a=n.length-1;a>=0;a-=1){let l=n[a];l.rect.top>=r.rect.top&&l.rect.left>=r.rect.left&&l.rect.right<=r.rect.right&&l.rect.bottom<=r.rect.bottom&&n.splice(a,1);}n.push({rect:r.rect,borderRadius:r.borderRadius});}return n}function rs(e,t,n,r,o){let i=Math.max(0,Math.min(o,n/2,r/2));return i===0?`M ${e} ${t} L ${e+n} ${t} L ${e+n} ${t+r} L ${e} ${t+r} Z`:[`M ${e+i} ${t}`,`L ${e+n-i} ${t}`,`A ${i} ${i} 0 0 1 ${e+n} ${t+i}`,`L ${e+n} ${t+r-i}`,`A ${i} ${i} 0 0 1 ${e+n-i} ${t+r}`,`L ${e+i} ${t+r}`,`A ${i} ${i} 0 0 1 ${e} ${t+r-i}`,`L ${e} ${t+i}`,`A ${i} ${i} 0 0 1 ${e+i} ${t}`,"Z"].join(" ")}function Fr(e){let t="http://www.w3.org/2000/svg",n=document.createElement("div");n.setAttribute("data-fork-highlights","true"),n.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let r=document.createElementNS(t,"svg");r.setAttribute("width","100%"),r.setAttribute("height","100%"),r.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");r.appendChild(o);let i=[];for(let A=0;A<e.length;A+=1){let{rect:b,borderRadius:I}=e[A],O=b.left-.5,R=b.top-.5,p=b.width+1,f=b.height+1,T=Math.min(I+.5,p/2,f/2),x=rs(O,R,p,f,T),k=`__fork-glow-${A}`,L=document.createElementNS(t,"filter");L.setAttribute("id",k),L.setAttribute("x","-100%"),L.setAttribute("y","-100%"),L.setAttribute("width","300%"),L.setAttribute("height","300%");let N=document.createElementNS(t,"feGaussianBlur");N.setAttribute("in","SourceGraphic"),N.setAttribute("stdDeviation","8"),L.appendChild(N),o.appendChild(L);let K=`__fork-mask-${A}`,_=document.createElementNS(t,"mask");_.setAttribute("id",K),_.setAttribute("maskUnits","userSpaceOnUse"),_.setAttribute("x",String(O-200)),_.setAttribute("y",String(R-200)),_.setAttribute("width",String(p+400)),_.setAttribute("height",String(f+400));let H=document.createElementNS(t,"rect");H.setAttribute("x",String(O-200)),H.setAttribute("y",String(R-200)),H.setAttribute("width",String(p+400)),H.setAttribute("height",String(f+400)),H.setAttribute("fill","white"),_.appendChild(H);let j=document.createElementNS(t,"path");j.setAttribute("d",x),j.setAttribute("fill","black"),_.appendChild(j),o.appendChild(_);let W=document.createElementNS(t,"g");W.setAttribute("mask",`url(#${K})`),W.setAttribute("opacity","0");let M=document.createElementNS(t,"g");M.setAttribute("filter",`url(#${k})`);let S=document.createElementNS(t,"path");S.setAttribute("d",x),S.setAttribute("fill","none"),S.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),S.setAttribute("stroke-width","6"),S.setAttribute("stroke-linecap","round"),M.appendChild(S),W.appendChild(M),r.appendChild(W);let U=document.createElementNS(t,"path");U.setAttribute("d",x),U.setAttribute("fill","none"),U.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),U.setAttribute("stroke-width","2"),U.setAttribute("stroke-linecap","round"),U.setAttribute("opacity","0"),r.appendChild(U),i.push(S,U),S.__group=W;}n.appendChild(r),document.body.appendChild(n);let a=[];for(let A=0;A<i.length;A+=2){let b=i[A],I=i[A+1],O=b.__group;if(!O)continue;let R=I.getTotalLength(),p=b.getTotalLength();if(R<=0)continue;let f=R*.35;I.setAttribute("stroke-dasharray",`${f} ${R-f}`),I.setAttribute("stroke-dashoffset","0"),a.push(I.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*R,opacity:.92,offset:.06},{strokeDashoffset:-2*R,opacity:.92,offset:.92},{strokeDashoffset:-2.25*R,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let T=p*.35;b.setAttribute("stroke-dasharray",`${T} ${p-T}`),b.setAttribute("stroke-dashoffset","0"),a.push(b.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*p,offset:.06},{strokeDashoffset:-2*p,offset:.92},{strokeDashoffset:-2.25*p,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),a.push(O.animate([{opacity:0,offset:0},{opacity:.92,offset:.06},{opacity:.92,offset:.92},{opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));}let l=false,u=()=>{if(l)return;l=true,clearTimeout(w);for(let b of a)try{b.cancel();}catch{}let A=n.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});A.onfinish=()=>n.remove(),window.removeEventListener("click",u);},w=setTimeout(u,14500);return setTimeout(()=>{l||window.addEventListener("click",u);},500),u}function os(e){let t="http://www.w3.org/2000/svg",n=document.createElement("div");n.setAttribute("data-fork-removed","true"),n.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let r=document.createElementNS(t,"svg");r.setAttribute("width","100%"),r.setAttribute("height","100%"),r.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs"),i=document.createElementNS(t,"filter");i.setAttribute("id","__fork-removed-shadow"),i.setAttribute("x","-10%"),i.setAttribute("y","-10%"),i.setAttribute("width","120%"),i.setAttribute("height","120%");let a=document.createElementNS(t,"feDropShadow");a.setAttribute("dx","0"),a.setAttribute("dy","1"),a.setAttribute("stdDeviation","2"),a.setAttribute("flood-color","rgba(0,0,0,0.15)"),i.appendChild(a),o.appendChild(i),r.appendChild(o);for(let{rect:l,borderRadius:u}of e){let w=document.createElementNS(t,"path");w.setAttribute("d",rs(l.left,l.top,l.width,l.height,u)),w.setAttribute("fill","none"),w.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),w.setAttribute("stroke-width","1.5"),w.setAttribute("stroke-dasharray","8 4"),w.setAttribute("stroke-linecap","round"),w.setAttribute("filter","url(#__fork-removed-shadow)"),w.setAttribute("opacity","0"),r.appendChild(w),w.animate([{opacity:0,offset:0},{opacity:.6,offset:.08},{opacity:.05,offset:.45},{opacity:.6,offset:.85},{opacity:.05,offset:1}],{duration:5e3,easing:"ease-in-out",fill:"forwards"});}return n.appendChild(r),document.body.appendChild(n),n}function as(e,t){if(Ia(t.selector))return is(e,t);let r=is(e,t);if(r)return r;try{let i=document.querySelector(t.selector);if(i instanceof HTMLElement&&i!==e&&e.contains(i))return i}catch{}if(ss(t.selector))try{let i=e.querySelector(t.selector);if(i instanceof HTMLElement&&i!==e)return i}catch{}if(t.textHint){let i=t.textHint.trim();if(i){let a=Rr(e,A=>A===i);if(a)return a;let l=i.toLowerCase(),u=Rr(e,A=>A.toLowerCase()===l);if(u)return u;let w=Rr(e,A=>A.toLowerCase().includes(l));if(w)return w}}let o=Ea(t.selector);if(o&&o!==t.selector&&ss(o))try{let i=e.querySelector(o);if(i instanceof HTMLElement&&i!==e)return i}catch{}return null}function ss(e){let t=e.split(/\s+|>|~|\+/),n=t[t.length-1]??"";return /[#\[]|:not\(|:nth-/.test(n)}function is(e,t){let n=Array.from(e.querySelectorAll("[data-fork-new]"));if(n.length===0)return null;let r=Ar(t.label),o=Ar(t.textHint);return n.find(a=>{let l=Ar(a.getAttribute("data-fork-new"));return !!l&&(l===r||l===o)})??null}function Ia(e){return e.trim()==="[data-fork-new]"}function Ar(e){return e?.trim().replace(/\s+/g," ").toLowerCase()||null}function Ea(e){return e.replace(/\[class[\*~|^$]?=("[^"]*"|'[^']*'|[^\]]+)\]/g,"").replace(/\.[A-Za-z_][\w-]*/g,"").replace(/\s+/g," ").trim()}function Rr(e,t){let n=null,r=1/0,o=e.querySelectorAll("*");for(let i of o){let a=i.textContent?.trim();if(!a||!t(a))continue;let l=i.getBoundingClientRect();if(l.width<4||l.height<4)continue;let u=l.width*l.height;u<r&&(n=i,r=u);}return n}var Ir=2147483600,Ca=1600,Ta=3e4,$a=300,dt=10;function Ma(e){let n=getComputedStyle(e).borderTopLeftRadius;if(!n)return 4;if(n.endsWith("%")){let a=parseFloat(n);if(!Number.isFinite(a)||a<=0)return 4;let l=e.getBoundingClientRect(),u=Math.min(l.width,l.height);return Math.max(4,a/100*u)}let r=parseFloat(n);if(!Number.isFinite(r)||r<=0)return 4;let o=e.getBoundingClientRect(),i=Math.min(o.width,o.height)/2;return r>=i?i:Math.min(r,16)}function Pa(e,t,n,r){let i=window.innerWidth,a=window.innerHeight,l=e;l==="top"&&t.top<r+dt+8?l="bottom":l==="bottom"&&a-t.bottom<r+dt+8?l="top":l==="left"&&t.left<n+dt+8?l="right":l==="right"&&i-t.right<n+dt+8&&(l="left");let u=0,w=0;return l==="top"?(u=t.top-r-dt,w=t.left+t.width/2-n/2):l==="bottom"?(u=t.bottom+dt,w=t.left+t.width/2-n/2):l==="left"?(u=t.top+t.height/2-r/2,w=t.left-n-dt):(u=t.top+t.height/2-r/2,w=t.right+dt),w=Math.max(8,Math.min(w,i-n-8)),u=Math.max(8,Math.min(u,a-r-8)),{top:u,left:w,placement:l}}function _a(e){let t=document.createElement("div");t.setAttribute("data-fork-highlight-outline","true"),t.style.cssText=["position:fixed","pointer-events:none",`z-index:${Ir}`,"border:1.5px solid rgba(59,130,246,0.85)","box-sizing:border-box","opacity:0","transition:opacity 200ms ease-out"].join(";");let n=document.createElement("div");n.setAttribute("data-fork-highlight-glow","true"),n.style.cssText=["position:fixed","pointer-events:none",`z-index:${Ir-1}`,"box-sizing:border-box","border:1px solid rgba(59,130,246,0.36)","box-shadow:0 0 0 4px rgba(59,130,246,0.16), 0 0 18px 2px rgba(59,130,246,0.31)","opacity:0","transition:opacity 200ms ease-out"].join(";");let r=document.createElement("div");return r.setAttribute("data-fork-highlight-tooltip","true"),r.style.cssText=["position:fixed","pointer-events:none",`z-index:${Ir+1}`,"padding:6px 10px","font:500 12px/1.2 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif","color:#ffffff","background:linear-gradient(135deg,#64748b,#475569)","border-radius:999px","box-shadow:0 4px 14px rgba(71,85,105,0.31),0 1px 2px rgba(0,0,0,0.1)","white-space:nowrap","opacity:0","transform:translateY(-2px)","transition:opacity 200ms ease-out, transform 200ms ease-out"].join(";"),r.textContent=`New: ${e}`,{outline:t,glow:n,tooltip:r}}function La(){if(document.getElementById("__fork-highlight-keyframes"))return;let e=document.createElement("style");e.id="__fork-highlight-keyframes",e.textContent=`
|
|
64
64
|
@keyframes __fork-highlight-pulse {
|
|
65
65
|
0%, 100% { box-shadow: 0 0 0 3px rgba(59,130,246,0.11), 0 0 12px 1px rgba(59,130,246,0.22); }
|
|
66
66
|
50% { box-shadow: 0 0 0 6px rgba(59,130,246,0.25), 0 0 22px 4px rgba(59,130,246,0.49); }
|
|
67
67
|
}
|
|
68
|
-
`,document.head.appendChild(e);}function ls(e,t,n="top"){La();let{outline:r,glow:o,tooltip:i}=_a(t),a=Ma(e);r.style.borderRadius=`${a}px`,o.style.borderRadius=`${a+1}px`,o.style.animation=`__fork-highlight-pulse ${Ca}ms ease-in-out infinite`,document.body.append(o,r,i);let l=()=>{let p=e.getBoundingClientRect();if(p.width===0&&p.height===0)return;r.style.top=`${p.top}px`,r.style.left=`${p.left}px`,r.style.width=`${p.width}px`,r.style.height=`${p.height}px`,o.style.top=`${p.top-1}px`,o.style.left=`${p.left-1}px`,o.style.width=`${p.width+2}px`,o.style.height=`${p.height+2}px`;let f=i.getBoundingClientRect(),T=f.width||i.offsetWidth||80,x=f.height||i.offsetHeight||26,k=Pa(n,p,T,x);i.style.top=`${k.top}px`,i.style.left=`${k.left}px`;};l(),requestAnimationFrame(()=>{r.style.opacity="1",o.style.opacity="1",i.style.opacity="1",i.style.transform="translateY(0)",requestAnimationFrame(l);});let u=false,w=new ResizeObserver(l);w.observe(e);let A=()=>l(),b=()=>l();window.addEventListener("scroll",A,true),window.addEventListener("resize",b);let E=()=>{u||(u=true,clearTimeout(R),w.disconnect(),window.removeEventListener("scroll",A,true),window.removeEventListener("resize",b),window.removeEventListener("click",U,true),r.style.opacity="0",o.style.opacity="0",i.style.opacity="0",i.style.transform="translateY(-2px)",setTimeout(()=>{r.remove(),o.remove(),i.remove();},$a));},U=()=>E();setTimeout(()=>{u||window.addEventListener("click",U,{once:true,capture:true});},250);let R=setTimeout(E,Ta);return E}var Ha="fork:highlight:v1:seen";function cs(e){return `${Ha}:${e}`}function ds(e){if(typeof window>"u")return new Set;try{let t=window.localStorage.getItem(e);if(!t)return new Set;let n=JSON.parse(t);return Array.isArray(n)?new Set(n.filter(r=>typeof r=="string")):new Set}catch{return new Set}}function Oa(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify([...t].slice(-200)));}catch{}}var us=new Set;function fs(e,t,n){return `${n}::${e}:${t}`}function Ir(e,t,n){let r=fs(e,t,n);return us.has(r)?true:ds(cs(n)).has(`${e}:${t}`)}function ps(e,t,n){let r=fs(e,t,n);us.add(r);let o=cs(n),i=`${e}:${t}`,a=ds(o);a.has(i)||(a.add(i),Oa(o,a));}var un=new Map,fn=new Map,Cr=new Map;function Na(e){for(let t of e)fn.set(t,(fn.get(t)??0)+1);}function Ba(e){if(!(typeof document>"u"))for(let t of e){let n=(fn.get(t)??0)-1;if(n>0){fn.set(t,n);continue}fn.delete(t),un.delete(t);let r=document.querySelector(`link[data-fork-override-href="${CSS.escape(t)}"]`);r&&r.remove();}}function Da(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function ms(e){let t=e.getBoundingClientRect();if(t.width<=0||t.height<=0)return false;let n=window.innerWidth||document.documentElement.clientWidth,r=window.innerHeight||document.documentElement.clientHeight;return t.bottom>0&&t.right>0&&t.top<r&&t.left<n}function hs(e,t){let n=(t?e[t]:void 0)??e.default;if(typeof n!="function"){let r=t||"default";throw new Error(`Fork boundary module is missing a React component export: ${r}`)}return n}function ja(e){if(!e||typeof document>"u")return Promise.resolve();let t=un.get(e);if(t)return t;let n=document.querySelector(`link[data-fork-override-href="${e}"]`);if(n instanceof HTMLLinkElement){let o=n.sheet?Promise.resolve():new Promise((i,a)=>{let l=()=>{n.removeEventListener("load",l),n.removeEventListener("error",u),i();},u=()=>{n.removeEventListener("load",l),n.removeEventListener("error",u),a(new Error(`Failed to load boundary stylesheet: ${e}`));};n.addEventListener("load",l,{once:true}),n.addEventListener("error",u,{once:true});});return un.set(e,o),o}let r=new Promise((o,i)=>{let a=document.createElement("link");a.rel="stylesheet",a.href=e,a.setAttribute("data-fork-override-href",e),a.onload=()=>o(),a.onerror=()=>{a.remove(),i(new Error(`Failed to load boundary stylesheet: ${e}`));},document.head.appendChild(a);}).catch(o=>{throw un.delete(e),o});return un.set(e,r),r}var dn=null;function za(){if(dn)return dn;try{dn=new Function("u","return import(/*webpackIgnore:true*//*@vite-ignore*/u)");}catch{dn=e=>import(/*webpackIgnore:true*//*@vite-ignore*/e);}return dn}function Ka(e){let t=Cr.get(e);if(t)return t;let n=za()(e).catch(r=>{throw Cr.delete(e),r});return Cr.set(e,n),n}async function Wa(e,t,n){if(e)try{await Promise.all(e.cssUrls.map(i=>ja(i)));let o=await Ka(e.moduleUrl);return hs(o,n)}catch(o){console.error(`[Fork] Failed to load override for boundary "${e.boundaryId}", falling back to original module.`,o);}let r=await t();return hs(r,n)}function Ja(e){function t(n){let{appId:r,moduleOverridesEnabled:o,moduleManifestReady:i,moduleManifestVersion:a,registerBoundary:l,getBoundaryOverride:u,consumeBoundaryAnimation:w,highlightScope:A}=Ee(),[b,E]=ar.useState(null),[U,R]=ar.useState(null),p=ar.useRef(null),f=ar.useRef(null),T=ar.useRef(null),x=ar.useRef(false),k=ar.useRef(null),L=ar.useRef(null),N=ar.useRef(null),K=ar.useRef(false),_=ar.useRef(false),H=u(e.id),j=H?`override:${H.id}`:"original",W=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if(ar.useEffect(()=>()=>{L.current&&(clearTimeout(L.current),L.current=null),k.current&&(k.current.remove(),k.current=null),N.current&&(N.current(),N.current=null);},[]),ar.useEffect(()=>{l({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[r,l,e.id,e.exportName,W]),ar.useEffect(()=>{let M=H?.cssUrls??[];if(M.length!==0)return Na(M),()=>Ba(M)},[H?.cssUrls.join("|")]),ar.useEffect(()=>{if(o&&!i&&!b||f.current===j&&b)return;let M=false;return R(null),Wa(H,e.original,e.exportName).then(S=>{if(M)return;let O=H?.id?w(e.id,H.id):false;if(K.current=O,O&&p.current){let V=Sr(p.current);if(V){let q=xr(V);q.length>0&&(T.current=q,x.current=true,L.current&&(clearTimeout(L.current),L.current=null),k.current&&k.current.remove(),k.current=es(V));}}f.current=j,ar.startTransition(()=>{E(()=>S);});}).catch(S=>{M||R(Da(S));}),()=>{M=true;}},[w,j,o,i,a,H?.id,H?.moduleUrl,H?.integrity,H?.cssUrls.join("|"),e.exportName,e.original,b]),ar.useEffect(()=>{if(!b||!p.current)return;let M=false,S=null,O=()=>{if(M||!p.current)return false;let V=H?.highlightHint,q=H?.id,Q=H?.createdAt?String(H.createdAt):"";if(!V||!q||Ir(q,Q,A))return false;let Z=Array.from(p.current.querySelectorAll("[data-fork-new]"));Z.length,Z.map(fe=>fe.getAttribute("data-fork-new")),V.label,V.textHint,V.selector;let ee=as(p.current,V);return ee?.tagName,ee?.getAttribute("data-fork-new"),ee?.getAttribute("aria-label"),ee?.textContent?.trim().slice(0,60),!ee||!ms(ee)?(ee&&ms(ee),ee?.getBoundingClientRect(),false):(ps(q,Q,A),k.current&&(k.current.remove(),k.current=null),N.current&&N.current(),N.current=ls(ee,V.label,V.position??"top"),true)};return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(M||!p.current)return;let V=K.current,q=!_.current;_.current=true;let Q=V||q,Z=Q?O():false;if(Q&&!Z&&H?.highlightHint&&H?.id&&!Ir(H.id,String(H.createdAt??""),A)){let I=[150,400,800],h=0,c=()=>{if(M||h>=I.length)return;let g=I[h];h+=1,S=setTimeout(()=>{if(O()){Z=true;return}c();},g);};c();}let ee=x.current,fe=!!H?.highlightHint,de=T.current;if(T.current=null,x.current=false,Z||fe||!ee){k.current&&(k.current.remove(),k.current=null);return}let oe=Sr(p.current);if(!de||!oe){k.current&&(k.current.remove(),k.current=null);return}let me=xr(oe),te=ts(de,me),pe=ns(de,me),d=k.current;if(pe.length>0&&d){let I=os(pe);L.current=setTimeout(()=>{L.current=null;let h=400;d.animate([{opacity:1},{opacity:0}],{duration:h,fill:"forwards"}),I.animate([{opacity:1},{opacity:0}],{duration:h,fill:"forwards"}),setTimeout(()=>{d.remove(),I.remove(),k.current===d&&(k.current=null),te.length>0&&Fr(te);},h);},3500);}else d&&(d.remove(),k.current===d&&(k.current=null)),te.length>0&&Fr(te);});}),()=>{M=true,S!==null&&(clearTimeout(S),S=null);}},[b,H?.id,H?.createdAt,H?.highlightHint,A]),U)throw U;return b?Xs.jsx("div",{ref:p,"data-fork-boundary":e.id,style:{display:"contents"},children:Xs.jsx(b,{...n})}):Xs.jsx(Xs.Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function Xa({slotId:e,title:t,slotLabel:n}){return Xs.jsx(ln,{slotId:e,title:t,slotLabel:n})}function Ya(e){return e.replace(/\/+$/,"")}function Za(e){return {namespace:e.namespace||"default",type:e.type,id:e.id}}function pn(e,t="value"){let n=Za(e);return `${n.namespace}:${n.type}:${n.id}:${t}`}function $r(e){if(Array.isArray(e))return e.map($r);if(!e||typeof e!="object")return e;let t=e,n={};for(let r of Object.keys(t).sort())n[r]=$r(t[r]);return n}function vs(e){return JSON.stringify($r(e))}function ys(e){let t={Authorization:`Bearer ${e.apiKey}`,"Content-Type":"application/json","X-Fork-App-Id":e.appId,...e.extraHeaders??{}};return e.userId&&(t["X-Fork-User-Id"]=e.userId),e.userHash&&(t["X-Fork-User-Hash"]=e.userHash),t}async function ks(e){let t=await e.json().catch(()=>({}));if(!e.ok){let n=typeof t.error=="string"?t.error:`Fork data API ${e.status}`;throw new Error(n)}return t}function ws(e){let t=Ya(e.baseUrl),n={appId:e.appId,containerId:e.containerId},r=async(i,a)=>{let l=a&&typeof a=="object"&&!Array.isArray(a)?a:{},u=await fetch(`${t}/api/v1/data${i}`,{method:"POST",headers:ys(e),body:JSON.stringify({...n,...l})});return ks(u)},o=async(i,a)=>{let l=new URLSearchParams({appId:e.appId,containerId:e.containerId});for(let[w,A]of Object.entries(a))A&&l.set(w,A);let u=await fetch(`${t}/api/v1/data${i}?${l.toString()}`,{headers:ys(e)});return ks(u)};return {listFeatures(){return o("/features",{})},ensureFeature(i){return r("/features",i)},queryValues(i){return r("/values/query",i)},setValues(i){return r("/values",i)},listOptions(i){return o("/options",{featureId:i.featureId,featureKey:i.featureKey,includeArchived:i.includeArchived?"true":void 0})},setOptions(i){return r("/options",i)},ensureLlmJobs(i){return r("/llm/ensure",i)},queryLlmJobs(i){return r("/llm/jobs/query",i)}}}function jn(e){let{apiKey:t,appId:n,baseUrl:r,currentContainerId:o,userHash:i,userId:a}=Ee(),l=e||o;return ar.useMemo(()=>{if(!n||!l)return null;let u=ue();return ws({apiKey:t,appId:n,baseUrl:r,containerId:l,userId:a,userHash:i,extraHeaders:u})},[t,n,r,l,i,a])}function Qa(e){let t=jn(e.containerId),[n,r]=ar.useState(null),[o,i]=ar.useState([]),[a,l]=ar.useState(false),[u,w]=ar.useState(null),A=vs({featureId:e.featureId,featureKey:e.featureKey,entities:e.entities,valueKeys:e.valueKeys,enabled:e.enabled!==false}),b=ar.useCallback(async()=>{if(!(!t||e.enabled===false)&&!(!e.featureId&&!e.featureKey)){l(true);try{let R=await t.queryValues({featureId:e.featureId,featureKey:e.featureKey,entities:e.entities,valueKeys:e.valueKeys});r(R.feature),i(R.values),w(null);}catch(R){w(R instanceof Error?R:new Error(String(R)));}finally{l(false);}}},[t,A]);ar.useEffect(()=>{b();},[b]),ar.useEffect(()=>{if(!e.pollMs||e.pollMs<=0)return;let R=setInterval(()=>{b();},e.pollMs);return ()=>clearInterval(R)},[e.pollMs,b]);let E=ar.useMemo(()=>new Map(o.map(R=>[pn(R.entity,R.valueKey),R])),[o]),U=ar.useCallback((R,p="value")=>E.get(pn(R,p))??null,[E]);return {feature:n,values:o,byKey:E,getValue:U,loading:a,error:u,refresh:b}}function el(e){let t=jn(e),n=ar.useCallback(async i=>{if(!t)throw new Error("Fork data is unavailable until appId and containerId are resolved");return t.ensureFeature(i)},[t]),r=ar.useCallback(async i=>{if(!t)throw new Error("Fork data is unavailable until appId and containerId are resolved");return t.setValues(i)},[t]),o=ar.useCallback(async i=>{if(!t)throw new Error("Fork data is unavailable until appId and containerId are resolved");return t.setOptions(i)},[t]);return {client:t,ensureFeature:n,setValues:r,setOptions:o}}function bs(e){return e.some(t=>t.status==="queued"||t.status==="running")}function tl(e){let t=jn(e.containerId),[n,r]=ar.useState(null),[o,i]=ar.useState([]),[a,l]=ar.useState([]),[u,w]=ar.useState(false),[A,b]=ar.useState(null),E=ar.useRef(""),U=vs({featureId:e.featureId,featureKey:e.featureKey,kind:e.kind,config:e.config,forkId:e.forkId,targetKind:e.targetKind,targetId:e.targetId,operation:e.operation,model:e.model,prompt:e.prompt,system:e.system,promptHash:e.promptHash,outputFormat:e.outputFormat,maxTokens:e.maxTokens,temperature:e.temperature,force:e.force,jobs:e.jobs,enabled:e.enabled!==false}),R=ar.useCallback(async()=>{if(!(!t||e.enabled===false)&&!(!e.featureId&&!e.featureKey)&&!(!e.jobs||e.jobs.length===0)){w(true);try{let x=await t.ensureLlmJobs(e);E.current=U,r(x.feature),i(x.jobs),l(x.values),b(null);}catch(x){b(x instanceof Error?x:new Error(String(x)));}finally{w(false);}}},[t,U]),p=ar.useCallback(async()=>{if(!t)return;let x=o.map(k=>k.id);try{if(x.length>0){let k=await t.queryLlmJobs({jobIds:x});i(k.jobs);}if(e.featureId||e.featureKey){let k=await t.queryValues({featureId:e.featureId,featureKey:e.featureKey,entities:e.jobs.map(L=>L.entity),valueKeys:Array.from(new Set(e.jobs.map(L=>L.valueKey||"value")))});r(k.feature),l(k.values);}b(null);}catch(k){b(k instanceof Error?k:new Error(String(k)));}},[t,o,U]);ar.useEffect(()=>{E.current!==U&&R();},[R,U]),ar.useEffect(()=>{let x=e.pollMs??3e3;if(x<=0||!bs(o))return;let k=setInterval(()=>{p();},x);return ()=>clearInterval(k)},[e.pollMs,o,p]);let f=ar.useMemo(()=>new Map(a.map(x=>[pn(x.entity,x.valueKey),x])),[a]),T=ar.useCallback((x,k="value")=>f.get(pn(x,k))??null,[f]);return {feature:n,jobs:o,values:a,byKey:f,getValue:T,loading:u,error:A,ensure:R,refresh:p,running:bs(o)}}exports.ForkBoundaryUI=Aa;exports.ForkButton=fr;exports.ForkChatInterface=ln;exports.ForkPanel=Un;exports.ForkProvider=gi;exports.ForkSlot=Ei;exports.ForkUI=Xa;exports.clearCachedManifest=Qs;exports.createForkDataClient=ws;exports.forkEntityValueKey=pn;exports.forkable=Ja;exports.loadManifest=nr;exports.manifestDiffers=ei;exports.readCachedManifest=Ys;exports.registerForkShared=Qn;exports.useBoundaryFork=kr;exports.useFork=br;exports.useForkChatPanel=vr;exports.useForkDataClient=jn;exports.useForkDataMutation=el;exports.useForkFeatureValues=Qa;exports.useForkLlmJobs=tl;exports.writeCachedManifest=Zs;
|
|
68
|
+
`,document.head.appendChild(e);}function ls(e,t,n="top"){La();let{outline:r,glow:o,tooltip:i}=_a(t),a=Ma(e);r.style.borderRadius=`${a}px`,o.style.borderRadius=`${a+1}px`,o.style.animation=`__fork-highlight-pulse ${Ca}ms ease-in-out infinite`,document.body.append(o,r,i);let l=()=>{let p=e.getBoundingClientRect();if(p.width===0&&p.height===0)return;r.style.top=`${p.top}px`,r.style.left=`${p.left}px`,r.style.width=`${p.width}px`,r.style.height=`${p.height}px`,o.style.top=`${p.top-1}px`,o.style.left=`${p.left-1}px`,o.style.width=`${p.width+2}px`,o.style.height=`${p.height+2}px`;let f=i.getBoundingClientRect(),T=f.width||i.offsetWidth||80,x=f.height||i.offsetHeight||26,k=Pa(n,p,T,x);i.style.top=`${k.top}px`,i.style.left=`${k.left}px`;};l(),requestAnimationFrame(()=>{r.style.opacity="1",o.style.opacity="1",i.style.opacity="1",i.style.transform="translateY(0)",requestAnimationFrame(l);});let u=false,w=new ResizeObserver(l);w.observe(e);let A=()=>l(),b=()=>l();window.addEventListener("scroll",A,true),window.addEventListener("resize",b);let I=()=>{u||(u=true,clearTimeout(R),w.disconnect(),window.removeEventListener("scroll",A,true),window.removeEventListener("resize",b),window.removeEventListener("click",O,true),r.style.opacity="0",o.style.opacity="0",i.style.opacity="0",i.style.transform="translateY(-2px)",setTimeout(()=>{r.remove(),o.remove(),i.remove();},$a));},O=()=>I();setTimeout(()=>{u||window.addEventListener("click",O,{once:true,capture:true});},250);let R=setTimeout(I,Ta);return I}var Ha="fork:highlight:v1:seen";function cs(e){return `${Ha}:${e}`}function ds(e){if(typeof window>"u")return new Set;try{let t=window.localStorage.getItem(e);if(!t)return new Set;let n=JSON.parse(t);return Array.isArray(n)?new Set(n.filter(r=>typeof r=="string")):new Set}catch{return new Set}}function Oa(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify([...t].slice(-200)));}catch{}}var us=new Set;function fs(e,t,n){return `${n}::${e}:${t}`}function Er(e,t,n){let r=fs(e,t,n);return us.has(r)?true:ds(cs(n)).has(`${e}:${t}`)}function ps(e,t,n){let r=fs(e,t,n);us.add(r);let o=cs(n),i=`${e}:${t}`,a=ds(o);a.has(i)||(a.add(i),Oa(o,a));}var un=new Map,fn=new Map,Cr=new Map;function Na(e){for(let t of e)fn.set(t,(fn.get(t)??0)+1);}function Ba(e){if(!(typeof document>"u"))for(let t of e){let n=(fn.get(t)??0)-1;if(n>0){fn.set(t,n);continue}fn.delete(t),un.delete(t);let r=document.querySelector(`link[data-fork-override-href="${CSS.escape(t)}"]`);r&&r.remove();}}function Da(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function ms(e){let t=e.getBoundingClientRect();if(t.width<=0||t.height<=0)return false;let n=window.innerWidth||document.documentElement.clientWidth,r=window.innerHeight||document.documentElement.clientHeight;return t.bottom>0&&t.right>0&&t.top<r&&t.left<n}function hs(e,t){let n=(t?e[t]:void 0)??e.default;if(typeof n!="function"){let r=t||"default";throw new Error(`Fork boundary module is missing a React component export: ${r}`)}return n}function ja(e){if(!e||typeof document>"u")return Promise.resolve();let t=un.get(e);if(t)return t;let n=document.querySelector(`link[data-fork-override-href="${e}"]`);if(n instanceof HTMLLinkElement){let o=n.sheet?Promise.resolve():new Promise((i,a)=>{let l=()=>{n.removeEventListener("load",l),n.removeEventListener("error",u),i();},u=()=>{n.removeEventListener("load",l),n.removeEventListener("error",u),a(new Error(`Failed to load boundary stylesheet: ${e}`));};n.addEventListener("load",l,{once:true}),n.addEventListener("error",u,{once:true});});return un.set(e,o),o}let r=new Promise((o,i)=>{let a=document.createElement("link");a.rel="stylesheet",a.href=e,a.setAttribute("data-fork-override-href",e),a.onload=()=>o(),a.onerror=()=>{a.remove(),i(new Error(`Failed to load boundary stylesheet: ${e}`));},document.head.appendChild(a);}).catch(o=>{throw un.delete(e),o});return un.set(e,r),r}var dn=null;function za(){if(dn)return dn;try{dn=new Function("u","return import(/*webpackIgnore:true*//*@vite-ignore*/u)");}catch{dn=e=>import(/*webpackIgnore:true*//*@vite-ignore*/e);}return dn}function Ka(e){let t=Cr.get(e);if(t)return t;let n=za()(e).catch(r=>{throw Cr.delete(e),r});return Cr.set(e,n),n}async function Wa(e,t,n){if(e)try{await Promise.all(e.cssUrls.map(i=>ja(i)));let o=await Ka(e.moduleUrl);return hs(o,n)}catch(o){console.error(`[Fork] Failed to load override for boundary "${e.boundaryId}", falling back to original module.`,o);}let r=await t();return hs(r,n)}function Ja(e){function t(n){let{appId:r,moduleOverridesEnabled:o,moduleManifestReady:i,moduleManifestVersion:a,registerBoundary:l,getBoundaryOverride:u,consumeBoundaryAnimation:w,highlightScope:A}=Ee(),[b,I]=ar.useState(null),[O,R]=ar.useState(null),p=ar.useRef(null),f=ar.useRef(null),T=ar.useRef(null),x=ar.useRef(false),k=ar.useRef(null),L=ar.useRef(null),N=ar.useRef(null),K=ar.useRef(false),_=ar.useRef(false),H=u(e.id),j=H?`override:${H.id}`:"original",W=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if(ar.useEffect(()=>()=>{L.current&&(clearTimeout(L.current),L.current=null),k.current&&(k.current.remove(),k.current=null),N.current&&(N.current(),N.current=null);},[]),ar.useEffect(()=>{l({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[r,l,e.id,e.exportName,W]),ar.useEffect(()=>{let M=H?.cssUrls??[];if(M.length!==0)return Na(M),()=>Ba(M)},[H?.cssUrls.join("|")]),ar.useEffect(()=>{if(o&&!i&&!b||f.current===j&&b)return;let M=false;return R(null),Wa(H,e.original,e.exportName).then(S=>{if(M)return;let U=H?.id?w(e.id,H.id):false;if(K.current=U,U&&p.current){let X=Sr(p.current);if(X){let V=xr(X);V.length>0&&(T.current=V,x.current=true,L.current&&(clearTimeout(L.current),L.current=null),k.current&&k.current.remove(),k.current=es(X));}}f.current=j,ar.startTransition(()=>{I(()=>S);});}).catch(S=>{M||R(Da(S));}),()=>{M=true;}},[w,j,o,i,a,H?.id,H?.moduleUrl,H?.integrity,H?.cssUrls.join("|"),e.exportName,e.original,b]),ar.useEffect(()=>{if(!b||!p.current)return;let M=false,S=null,U=()=>{if(M||!p.current)return false;let X=H?.highlightHint,V=H?.id,Q=H?.createdAt?String(H.createdAt):"";if(!X||!V||Er(V,Q,A))return false;let Z=Array.from(p.current.querySelectorAll("[data-fork-new]"));Z.length,Z.map(fe=>fe.getAttribute("data-fork-new")),X.label,X.textHint,X.selector;let ee=as(p.current,X);return ee?.tagName,ee?.getAttribute("data-fork-new"),ee?.getAttribute("aria-label"),ee?.textContent?.trim().slice(0,60),!ee||!ms(ee)?(ee&&ms(ee),ee?.getBoundingClientRect(),false):(ps(V,Q,A),k.current&&(k.current.remove(),k.current=null),N.current&&N.current(),N.current=ls(ee,X.label,X.position??"top"),true)};return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(M||!p.current)return;let X=K.current,V=!_.current;_.current=true;let Q=X||V,Z=Q?U():false;if(Q&&!Z&&H?.highlightHint&&H?.id&&!Er(H.id,String(H.createdAt??""),A)){let E=[150,400,800],h=0,c=()=>{if(M||h>=E.length)return;let g=E[h];h+=1,S=setTimeout(()=>{if(U()){Z=true;return}c();},g);};c();}let ee=x.current,fe=!!H?.highlightHint,de=T.current;if(T.current=null,x.current=false,Z||fe||!ee){k.current&&(k.current.remove(),k.current=null);return}let oe=Sr(p.current);if(!de||!oe){k.current&&(k.current.remove(),k.current=null);return}let me=xr(oe),te=ts(de,me),pe=ns(de,me),d=k.current;if(pe.length>0&&d){let E=os(pe);L.current=setTimeout(()=>{L.current=null;let h=400;d.animate([{opacity:1},{opacity:0}],{duration:h,fill:"forwards"}),E.animate([{opacity:1},{opacity:0}],{duration:h,fill:"forwards"}),setTimeout(()=>{d.remove(),E.remove(),k.current===d&&(k.current=null),te.length>0&&Fr(te);},h);},3500);}else d&&(d.remove(),k.current===d&&(k.current=null)),te.length>0&&Fr(te);});}),()=>{M=true,S!==null&&(clearTimeout(S),S=null);}},[b,H?.id,H?.createdAt,H?.highlightHint,A]),O)throw O;return b?Xs.jsx("div",{ref:p,"data-fork-boundary":e.id,style:{display:"contents"},children:Xs.jsx(b,{...n})}):Xs.jsx(Xs.Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function Xa({slotId:e,title:t,slotLabel:n}){return Xs.jsx(ln,{slotId:e,title:t,slotLabel:n})}function Ya(e){return e.replace(/\/+$/,"")}function Za(e){return {namespace:e.namespace||"default",type:e.type,id:e.id}}function pn(e,t="value"){let n=Za(e);return `${n.namespace}:${n.type}:${n.id}:${t}`}function $r(e){if(Array.isArray(e))return e.map($r);if(!e||typeof e!="object")return e;let t=e,n={};for(let r of Object.keys(t).sort())n[r]=$r(t[r]);return n}function vs(e){return JSON.stringify($r(e))}function ys(e){let t={Authorization:`Bearer ${e.apiKey}`,"Content-Type":"application/json","X-Fork-App-Id":e.appId,...e.extraHeaders??{}};return e.userId&&(t["X-Fork-User-Id"]=e.userId),e.userHash&&(t["X-Fork-User-Hash"]=e.userHash),t}async function ks(e){let t=await e.json().catch(()=>({}));if(!e.ok){let n=typeof t.error=="string"?t.error:`Fork data API ${e.status}`;throw new Error(n)}return t}function ws(e){let t=Ya(e.baseUrl),n={appId:e.appId,containerId:e.containerId},r=async(i,a)=>{let l=a&&typeof a=="object"&&!Array.isArray(a)?a:{},u=await fetch(`${t}/api/v1/data${i}`,{method:"POST",headers:ys(e),body:JSON.stringify({...n,...l})});return ks(u)},o=async(i,a)=>{let l=new URLSearchParams({appId:e.appId,containerId:e.containerId});for(let[w,A]of Object.entries(a))A&&l.set(w,A);let u=await fetch(`${t}/api/v1/data${i}?${l.toString()}`,{headers:ys(e)});return ks(u)};return {listFeatures(){return o("/features",{})},ensureFeature(i){return r("/features",i)},queryValues(i){return r("/values/query",i)},setValues(i){return r("/values",i)},listOptions(i){return o("/options",{featureId:i.featureId,featureKey:i.featureKey,includeArchived:i.includeArchived?"true":void 0})},setOptions(i){return r("/options",i)},ensureLlmJobs(i){return r("/llm/ensure",i)},queryLlmJobs(i){return r("/llm/jobs/query",i)}}}function jn(e){let{apiKey:t,appId:n,baseUrl:r,currentContainerId:o,userHash:i,userId:a}=Ee(),l=e||o;return ar.useMemo(()=>{if(!n||!l)return null;let u=ue();return ws({apiKey:t,appId:n,baseUrl:r,containerId:l,userId:a,userHash:i,extraHeaders:u})},[t,n,r,l,i,a])}function Qa(e){let t=jn(e.containerId),[n,r]=ar.useState(null),[o,i]=ar.useState([]),[a,l]=ar.useState(false),[u,w]=ar.useState(null),A=vs({featureId:e.featureId,featureKey:e.featureKey,entities:e.entities,valueKeys:e.valueKeys,enabled:e.enabled!==false}),b=ar.useCallback(async()=>{if(!(!t||e.enabled===false)&&!(!e.featureId&&!e.featureKey)){l(true);try{let R=await t.queryValues({featureId:e.featureId,featureKey:e.featureKey,entities:e.entities,valueKeys:e.valueKeys});r(R.feature),i(R.values),w(null);}catch(R){w(R instanceof Error?R:new Error(String(R)));}finally{l(false);}}},[t,A]);ar.useEffect(()=>{b();},[b]),ar.useEffect(()=>{if(!e.pollMs||e.pollMs<=0)return;let R=setInterval(()=>{b();},e.pollMs);return ()=>clearInterval(R)},[e.pollMs,b]);let I=ar.useMemo(()=>new Map(o.map(R=>[pn(R.entity,R.valueKey),R])),[o]),O=ar.useCallback((R,p="value")=>I.get(pn(R,p))??null,[I]);return {feature:n,values:o,byKey:I,getValue:O,loading:a,error:u,refresh:b}}function el(e){let t=jn(e),n=ar.useCallback(async i=>{if(!t)throw new Error("Fork data is unavailable until appId and containerId are resolved");return t.ensureFeature(i)},[t]),r=ar.useCallback(async i=>{if(!t)throw new Error("Fork data is unavailable until appId and containerId are resolved");return t.setValues(i)},[t]),o=ar.useCallback(async i=>{if(!t)throw new Error("Fork data is unavailable until appId and containerId are resolved");return t.setOptions(i)},[t]);return {client:t,ensureFeature:n,setValues:r,setOptions:o}}function bs(e){return e.some(t=>t.status==="queued"||t.status==="running")}function tl(e){let t=jn(e.containerId),[n,r]=ar.useState(null),[o,i]=ar.useState([]),[a,l]=ar.useState([]),[u,w]=ar.useState(false),[A,b]=ar.useState(null),I=ar.useRef(""),O=vs({featureId:e.featureId,featureKey:e.featureKey,kind:e.kind,config:e.config,forkId:e.forkId,targetKind:e.targetKind,targetId:e.targetId,operation:e.operation,model:e.model,prompt:e.prompt,system:e.system,promptHash:e.promptHash,outputFormat:e.outputFormat,maxTokens:e.maxTokens,temperature:e.temperature,force:e.force,jobs:e.jobs,enabled:e.enabled!==false}),R=ar.useCallback(async()=>{if(!(!t||e.enabled===false)&&!(!e.featureId&&!e.featureKey)&&!(!e.jobs||e.jobs.length===0)){w(true);try{let x=await t.ensureLlmJobs(e);I.current=O,r(x.feature),i(x.jobs),l(x.values),b(null);}catch(x){b(x instanceof Error?x:new Error(String(x)));}finally{w(false);}}},[t,O]),p=ar.useCallback(async()=>{if(!t)return;let x=o.map(k=>k.id);try{if(x.length>0){let k=await t.queryLlmJobs({jobIds:x});i(k.jobs);}if(e.featureId||e.featureKey){let k=await t.queryValues({featureId:e.featureId,featureKey:e.featureKey,entities:e.jobs.map(L=>L.entity),valueKeys:Array.from(new Set(e.jobs.map(L=>L.valueKey||"value")))});r(k.feature),l(k.values);}b(null);}catch(k){b(k instanceof Error?k:new Error(String(k)));}},[t,o,O]);ar.useEffect(()=>{I.current!==O&&R();},[R,O]),ar.useEffect(()=>{let x=e.pollMs??3e3;if(x<=0||!bs(o))return;let k=setInterval(()=>{p();},x);return ()=>clearInterval(k)},[e.pollMs,o,p]);let f=ar.useMemo(()=>new Map(a.map(x=>[pn(x.entity,x.valueKey),x])),[a]),T=ar.useCallback((x,k="value")=>f.get(pn(x,k))??null,[f]);return {feature:n,jobs:o,values:a,byKey:f,getValue:T,loading:u,error:A,ensure:R,refresh:p,running:bs(o)}}exports.ForkBoundaryUI=Aa;exports.ForkButton=fr;exports.ForkChatInterface=ln;exports.ForkPanel=Un;exports.ForkProvider=gi;exports.ForkSlot=Ii;exports.ForkUI=Xa;exports.clearCachedManifest=Qs;exports.createForkDataClient=ws;exports.forkEntityValueKey=pn;exports.forkable=Ja;exports.loadManifest=nr;exports.manifestDiffers=ei;exports.readCachedManifest=Ys;exports.registerForkShared=Qn;exports.useBoundaryFork=kr;exports.useFork=br;exports.useForkChatPanel=vr;exports.useForkDataClient=jn;exports.useForkDataMutation=el;exports.useForkFeatureValues=Qa;exports.useForkLlmJobs=tl;exports.writeCachedManifest=Zs;
|