@fork-api/chat-sdk 0.1.158 → 0.1.160
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.js +7 -7
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import*as
|
|
2
|
-
`);return ct&&er===o||(er=o,ct=(async()=>{try{let i=await fetch(`${t}/api/v1/preview/auto-activate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,"X-Fork-User-Id":r.userId,"X-Fork-User-Hash":r.userHash},body:JSON.stringify({appId:r.appId})});if(i.status===204)return null;if(!i.ok){let f=await i.json().catch(()=>({}));return console.warn(`[fork-preview] auto admin activate failed (${i.status}): ${f.error??"unknown"}`),null}let s=await i.json(),l={preview_session_id:s.preview_session_id,tenant_id:s.tenant_id,app_id:s.app_id,target:s.target,operator_id:s.operator_id,container_id:s.container_id??null,container_name:s.container_name??"Fork",fork_id:s.fork_id??null,expires_at:s.expires_at};return Mt(l),l}catch(i){return console.warn("[fork-preview] auto admin activate threw",i),null}finally{er=null,ct=null;}})()),ct}function On(){return Ne()}function Dn(){return null}function Tt(){return useSyncExternalStore(Qt,On,Dn)}function re(){let e=Ne();if(!e)return {};let t={"X-Fork-Preview-Session":e.preview_session_id};return e.fork_id&&(t["X-Fork-Preview-Fork-Id"]=e.fork_id),t}async function Lt(e){let t=new URLSearchParams({app:e.appId,user:e.userId});e.containerId&&t.set("containerId",e.containerId);let r=`${e.baseUrl}/api/v1/manifest?${t.toString()}`,n={Authorization:`Bearer ${e.apiKey}`,"X-Fork-App-Id":e.appId,"X-Fork-User-Id":e.userId,...e.extraHeaders??{}};e.userHash&&(n["X-Fork-User-Hash"]=e.userHash),e.previous?.etag&&(n["If-None-Match"]=e.previous.etag);let o=await fetch(r,{headers:n,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(),s={};for(let[l,f]of Object.entries(i.modules)){let w=f.moduleUrl??f.bundleUrl??null,y=f.legacyModuleUrl??f.legacyBundleUrl??null;s[l]={forkId:f.forkId,moduleUrl:w,legacyModuleUrl:y,bundleUrl:f.bundleUrl??w,legacyBundleUrl:f.legacyBundleUrl??y,cssUrls:f.cssUrls??[],integrity:f.integrity,metadata:f.metadata,buildId:f.buildId,updatedAt:f.updatedAt};}return {containerId:i.containerId,slots:i.slots,modules:s,generatedAt:i.generatedAt,etag:o.headers.get("ETag")??void 0}}var jn="fork:manifest:v1";function or(e,t,r){return `${jn}:${e}:${t}:${r}`}function zn(e,t,r){if(typeof window>"u")return null;try{let n=window.localStorage.getItem(or(e,t,r));return n?JSON.parse(n):null}catch{return null}}function Kn(e,t,r,n){if(!(typeof window>"u"))try{window.localStorage.setItem(or(e,t,r),JSON.stringify(n));}catch{}}function Wn(e,t,r){if(!(typeof window>"u"))try{window.localStorage.removeItem(or(e,t,r));}catch{}}function Vn(e,t){if(!e||!t)return e!==t;if(e.containerId!==t.containerId)return true;let r=Object.entries(e.slots),n=Object.entries(t.slots);if(r.length!==n.length)return true;for(let[s,l]of r){let f=t.slots[s];if(!f||f.forkId!==l.forkId||f.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[s,l]of o){let f=t.modules[s];if(!f||f.forkId!==l.forkId||f.buildId!==l.buildId)return true}return false}var Vr=createContext(null),Gn=12e3,qn=45e3,jr="fork:activity:v1",Yn=new Set(["pending","running","building"]),Zn="Setting up environment";function Se(e){return Yn.has(e)}function Qn(e,t){return t?.targetId?t:e.boundaryId?{targetKind:"module",targetId:e.boundaryId}:e.slotId?{targetKind:"slot",targetId:e.slotId}:null}function eo(e,t){let r=Qn(e,t);if(!r)return null;let n=new Date().toISOString();return {id:e.id,status:e.status,targetKind:r.targetKind,targetId:r.targetId,summary:e.summary??null,estimateMinutes:e.estimateMinutes??null,createdAt:e.createdAt||n,updatedAt:e.completedAt||n,completedAt:e.completedAt??null}}function zr(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 Bt(e,t){let r=typeof t.summary=="string"&&t.summary.trim()?t.summary.trim():void 0,n=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:r??n??null,estimateMinutes:o??i??null,latestMessage:t.latestMessage??e?.latestMessage??null,unread:t.unread??e?.unread??false}}function dt(e){return `${e.id}:${e.completedAt||e.updatedAt}`}function Je(e){if(typeof window>"u")return new Set;try{let t=window.localStorage.getItem(e);if(!t)return new Set;let r=JSON.parse(t);return Array.isArray(r)?new Set(r.filter(n=>typeof n=="string")):new Set}catch{return new Set}}function Ge(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify([...t].slice(-200)));}catch{}}function to(e){if(e.estimateMinutes)return `~${e.estimateMinutes}m`}function ro(e){let t=e.data&&typeof e.data=="object"?e.data:{};if(e.type==="status"){let r=typeof t.status=="string"?t.status:"running",n=typeof t.summary=="string"?t.summary:void 0;return {status:r,latestMessage:Se(r)?"Building":void 0,summary:n,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 no(e){let t=e.filter(o=>Se(o.status)),r=e.filter(o=>o.status==="complete"&&o.unread),n=[...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:r.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():Zn,detail:i?to(o):void 0,count:1,runningCount:1,unreadCompletedCount:r.length,latest:o}}if(r.length>1)return {state:"complete",label:`${r.length} forks ready`,count:r.length,runningCount:0,unreadCompletedCount:r.length,latest:r[0]};if(r.length===1){let o=r[0];return {state:"complete",label:o.summary||"Fork ready",count:1,runningCount:0,unreadCompletedCount:1,latest:o}}return {state:n?.status==="error"?"error":"idle",label:"Fork",count:0,runningCount:0,unreadCompletedCount:0,latest:n}}function ut(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function oo(e,t){let r={};for(let[n,o]of Object.entries(t.boundaries||{}))r[n]={...o,moduleUrl:ut(e,o.moduleUrl),cssUrls:Array.isArray(o.cssUrls)?o.cssUrls.map(i=>ut(e,i)):[]};return r}function Kr(e,t,r,n){let o={};for(let[i,s]of Object.entries(t.slots)){let l=s.bundleUrl??s.legacyBundleUrl;l&&(o[i]={id:s.forkId,userId:r,prompt:"",status:"complete",slotId:i,appId:n,bundleUrl:ut(e,l),createdAt:s.updatedAt,completedAt:s.updatedAt});}return o}function Wr(e,t){let r={};for(let[n,o]of Object.entries(t.modules)){let i=o.moduleUrl??o.legacyModuleUrl??o.bundleUrl??"";i&&(r[n]={id:o.forkId,boundaryId:n,moduleUrl:ut(e,i),cssUrls:(o.cssUrls??[]).map(s=>ut(e,s)),integrity:o.integrity,metadata:o.metadata,createdAt:o.updatedAt});}return r}function so(e){let{apiKey:t,baseUrl:r,children:n,appId:o,shared:i}=e,s="userId"in e?e.userId:void 0,l="authUrl"in e?e.authUrl:void 0,[f]=useState(()=>(nt(t),tr(t))),[w,y]=useState({}),[p,v]=useState(s?{userId:s,userHash:void 0}:null),[_,C]=useState(!!s||f),[b,A]=useState({}),[O,g]=useState(!o),[P,L]=useState(0),[B,U]=useState(null),[S,k]=useState([]),[h,E]=useState(()=>typeof document>"u"?true:document.visibilityState!=="hidden"),m=useRef(new Map),c=useRef(new Map),[I,D]=useState(0),N=useRef(new Set),R=useRef(new Map),x=useRef(void 0),H=useRef(new Map),Z=useRef([]),G=useRef(new Set),we=useRef(false);Gt(),useEffect(()=>{return rr(t,r).then(()=>{}),()=>{}},[]);let j=Tt();useEffect(()=>{f||j||!o||!p?.userHash||nr(t,r,{appId:o,userId:p.userId,userHash:p.userHash});},[t,o,p?.userHash,p?.userId,r,f,j?.preview_session_id]),i&&x.current!==i&&(qt(i),x.current=i),useEffect(()=>{l&&(f||(C(false),fetch(l,{credentials:"include"}).then(d=>{if(!d.ok)throw new Error(`Auth endpoint returned ${d.status}`);return d.json()}).then(d=>{if(!d.userId||typeof d.userId!="string")throw new Error("authUrl response must include userId");v({userId:d.userId,userHash:typeof d.userHash=="string"?d.userHash:void 0});}).catch(d=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",d.message);}).finally(()=>{C(true);})));},[l,f]),useEffect(()=>{!l&&s&&(v({userId:s,userHash:void 0}),C(true));},[s,l]);let ne=p?.userId??"",fe=p?.userHash,q=j?"":ne,ie=j?void 0:fe,Ze=!!o,xe=useCallback(async()=>{if(!Ze){U(null),A({}),g(true),L(u=>u+1);return}if(!_){g(false);return}if(!j&&!q||!o){U(null),A({}),g(true),L(u=>u+1);return}if(g(false),!j){try{let u=await Lt({baseUrl:r,apiKey:t,appId:o,userId:q,userHash:ie});u&&(U(u.containerId),y(Kr(r,u,q,o)),A(Wr(r,u)));}catch(u){console.error("[ForkProvider] Failed to fetch fork manifest:",u.message),U(null),y({}),A({});}finally{L(u=>u+1),g(true);}return}if(U(j.container_id??null),j.container_id){try{let u=await Lt({baseUrl:r,apiKey:t,appId:o,userId:q,containerId:j.container_id,extraHeaders:re()});u&&(y(Kr(r,u,q,o)),A(Wr(r,u)));}catch(u){console.error("[ForkProvider] Failed to fetch preview container manifest:",u.message),y({}),A({});}finally{L(u=>u+1),g(true);}return}let d=new URLSearchParams({appId:o,userId:q});ie&&d.set("userHash",ie);try{let u=await fetch(`${r}/api/v1/boundaries/manifest?${d.toString()}`,{headers:{Authorization:`Bearer ${t}`,...re()}});if(!u.ok)throw new Error(`${u.status}`);let M=await u.json();A(oo(r,M));}catch(u){console.error("[ForkProvider] Failed to fetch module override manifest:",u.message),A({});}finally{L(u=>u+1),g(true);}},[t,o,r,_,Ze,ie,q,j?.preview_session_id,j?.fork_id,j?.container_id]);useEffect(()=>{if(!q||o&&(!j||j.container_id))return;let d=new URLSearchParams({userId:q});ie&&d.set("userHash",ie),fetch(`${r}/api/v1/forks/active?${d.toString()}`,{headers:{Authorization:`Bearer ${t}`,...re()}}).then(u=>{if(!u.ok)throw new Error(`${u.status}`);return u.json()}).then(u=>{u&&typeof u=="object"&&y(u);}).catch(()=>{});},[t,o,q,ie,r,j?.preview_session_id,j?.fork_id]),useEffect(()=>{xe();},[xe]);let Ee=useCallback((d,u)=>{y(M=>({...M,[d]:u}));},[]),me=useCallback(d=>{y(u=>{let M={...u};return delete M[d],M});},[]),$e=useCallback(d=>{N.current.add(d);},[]),He=useCallback(d=>N.current.has(d)?(N.current.delete(d),true):false,[]),Ce=useCallback((d,u)=>{R.current.set(d,u);},[]),Re=useCallback((d,u)=>R.current.get(d)!==u?false:(R.current.delete(d),true),[]),Oe=useCallback(d=>{if(!o)return;let u=JSON.stringify(d);m.current.get(d.id)===u||c.current.get(d.id)?.signature===u||(c.current.set(d.id,{boundary:d,signature:u}),D(Q=>Q+1));},[o]);useEffect(()=>{if(!o||c.current.size===0)return;let d=setTimeout(()=>{let u=Array.from(c.current.values());u.length!==0&&fetch(`${r}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:o,boundaries:u.map(M=>M.boundary)})}).then(M=>{if(!M.ok)throw new Error(`${M.status}`)}).then(()=>{for(let M of u)c.current.get(M.boundary.id)?.signature===M.signature&&(c.current.delete(M.boundary.id),m.current.set(M.boundary.id,M.signature));}).catch(M=>{console.error("[ForkProvider] Failed to register module boundaries:",M.message);});},50);return ()=>{clearTimeout(d);}},[t,o,r,I]);let Vt=useCallback(d=>b[d],[b]),xt=j?`preview:${j.preview_session_id}`:q,At=`${t}:${o||"no-app"}:${B||"no-container"}:${xt||"anonymous"}`,ve=`${jr}:seen:${At}`,K=`${jr}:tracked:${At}`;useEffect(()=>{Z.current=S;},[S]);let De=useCallback(()=>{let d={Authorization:`Bearer ${t}`,...re()};return o&&(d["X-Fork-App-Id"]=o),!j&&q&&(d["X-Fork-User-Id"]=q),!j&&ie&&(d["X-Fork-User-Hash"]=ie),d},[t,o,j,ie,q]),Pe=useCallback(async()=>{if(!B)return;let d=new URLSearchParams({container_id:B}),u=await fetch(`${r}/api/v1/forks?${d.toString()}`,{headers:De()}).catch(()=>null);if(!u||!u.ok)return;let M=await u.json().catch(()=>({})),Q=Array.isArray(M.forks)?M.forks:[],V=Je(ve),z=Je(K),oe=false,ae=new Map(Z.current.map(X=>[X.id,X])),ke=[];for(let X of Q){let le=zr(X);Se(le.status)&&!z.has(le.id)&&(z.add(le.id),oe=true);let te=ae.get(le.id),se=te?Se(te.status):false,pe=dt(le);le.status==="complete"&&(z.has(le.id)||se)&&!V.has(pe)&&!G.current.has(pe)&&!te?.unread&&(we.current||z.has(le.id)||se)&&(G.current.add(pe),ke.push(le));}if(k(X=>{let le=new Map(X.map(de=>[de.id,de])),te=new Set,se=new Map;for(let de of Q){let ge=zr(de);te.add(ge.id);let Be=le.get(ge.id),Y=Be?Se(Be.status):false,it=dt(ge),Me=ge.status==="complete"&&(z.has(ge.id)||Y)&&!V.has(it),et=Bt(Be,{...ge,unread:Me});se.set(ge.id,et);}for(let de of X)te.has(de.id)||(Se(de.status)||de.unread)&&se.set(de.id,de);let pe=[...se.values()].sort((de,ge)=>Date.parse(ge.updatedAt)-Date.parse(de.updatedAt));return Z.current=pe,pe}),oe&&Ge(K,z),ke.length>0){for(let X of ke)X.targetKind==="module"&&Ce(X.targetId,X.id);xe().catch(()=>{});}we.current=true;},[ve,K,r,De,B,xe,Ce]),_t=useCallback((d,u)=>{let M=eo(d,u);if(!M)return;let Q=d.containerId??d._containerId;if(Q&&!B&&U(Q),Se(M.status)){let oe=Je(K);oe.has(M.id)||(oe.add(M.id),Ge(K,oe));}let V=new Map(Z.current.map(oe=>[oe.id,oe]));V.set(M.id,Bt(V.get(M.id),M));let z=[...V.values()].sort((oe,ae)=>Date.parse(ae.updatedAt)-Date.parse(oe.updatedAt));Z.current=z,k(z);},[K,B]),je=useCallback((d,u)=>{let M=ro(u),Q=Je(ve),V=Je(K),z=Z.current.find(te=>te.id===d),oe=z?Se(z.status):false;M.status&&Se(M.status)&&!V.has(d)&&(V.add(d),Ge(K,V));let ae=z?Bt(z,{...z,...M}):null,ke=ae?dt(ae):null,X=!!(ae&&ae.status==="complete"&&(V.has(d)||oe)&&ke&&!Q.has(ke)&&!G.current.has(ke)&&!z?.unread),le=u.type==="complete"&&z?.targetKind==="module"?z.targetId:null;if(k(te=>{let se=te.find(Y=>Y.id===d);if(!se)return te;let pe=Bt(se,{...se,...M}),de=pe.status==="complete"&&(V.has(d)||Se(se.status))&&!Q.has(dt(pe)),ge={...pe,unread:de},Be=te.map(Y=>Y.id===d?ge:Y).sort((Y,it)=>Date.parse(it.updatedAt)-Date.parse(Y.updatedAt));return Z.current=Be,Be}),X&&ae&&ke&&G.current.add(ke),u.type==="complete"){let te=u.data&&typeof u.data=="object"?u.data:{},se=typeof te.boundaryId=="string"?te.boundaryId:le;se&&Ce(se,d),xe().catch(()=>{});}},[ve,K,xe,Ce]),Qe=useCallback(d=>{let u=Je(ve),M=Je(K),Q=false,V=false;for(let z of Z.current){if(z.status!=="complete"||d&&z.id!==d)continue;let oe=dt(z);u.has(oe)||(u.add(oe),Q=true),M.delete(z.id)&&(V=true);}k(z=>{let oe=z.map(ae=>ae.status!=="complete"||d&&ae.id!==d?ae:{...ae,unread:false});return Z.current=oe,oe}),Q&&Ge(ve,u),V&&Ge(K,M);},[ve,K]);useEffect(()=>{we.current=false,G.current.clear(),k([]);for(let d of H.current.values())d.close();H.current.clear(),B&&Pe();},[B,Pe]),useEffect(()=>{if(typeof document>"u")return;let d=()=>{let u=document.visibilityState!=="hidden";E(u),u&&B&&Pe();};return document.addEventListener("visibilitychange",d),window.addEventListener("focus",d),window.addEventListener("online",d),()=>{document.removeEventListener("visibilitychange",d),window.removeEventListener("focus",d),window.removeEventListener("online",d);}},[B,Pe]),useEffect(()=>{let d=S.filter(Q=>Se(Q.status));if(!B||d.length===0)return;let u=h?Gn:qn,M=window.setInterval(()=>{Pe();},u);return ()=>window.clearInterval(M)},[B,h,S,Pe]),useEffect(()=>{for(let d of H.current.values())d.close();H.current.clear();},[t,r,j?.preview_session_id,ie,q]),useEffect(()=>{let d=new Set(S.filter(u=>Se(u.status)).map(u=>u.id));for(let[u,M]of H.current.entries())d.has(u)||(M.close(),H.current.delete(u));for(let u of d){if(H.current.has(u))continue;let M=new URLSearchParams({key:t});j?(M.set("previewSessionId",j.preview_session_id),M.set("previewForkId",u)):q&&M.set("userId",q),ie&&M.set("userHash",ie);let Q=new EventSource(`${r}/api/v1/forks/${u}/events?${M.toString()}`);Q.onmessage=V=>{try{je(u,JSON.parse(V.data));}catch{}},Q.onerror=()=>{Q.close(),H.current.delete(u);},H.current.set(u,Q);}},[t,r,S,j,je,ie,q]),useEffect(()=>()=>{for(let d of H.current.values())d.close();H.current.clear();},[]);let Ie=no(S),ze=useCallback(async()=>{if(!q)throw new Error("Reset requires a resolved user identity.");let d=new URLSearchParams({userId:q});ie&&d.set("userHash",ie);let u={Authorization:`Bearer ${t}`,...re()};o&&(u["X-Fork-App-Id"]=o);let M=await fetch(`${r}/api/v1/forks/all?${d.toString()}`,{method:"DELETE",headers:u});if(!M.ok){let V=await M.json().catch(()=>({}));throw new Error(V.error||`API error: ${M.status}`)}let Q=await M.json().catch(()=>({}));y({}),A({}),g(true),L(V=>V+1),k([]),G.current.clear(),Ge(ve,new Set),Ge(K,new Set),N.current.clear(),R.current.clear();try{for(let V=sessionStorage.length-1;V>=0;V-=1){let z=sessionStorage.key(V);z&&z.startsWith("__fork_animated_")&&sessionStorage.removeItem(z);}}catch{}return Q},[ve,K,t,o,r,ie,q]);return jsx(Vr.Provider,{value:{apiKey:t,userId:q,userHash:ie,baseUrl:r,appId:o,forks:w,moduleOverridesEnabled:Ze,moduleManifestReady:O,moduleManifestVersion:P,currentContainerId:B,forkActivities:S,activitySummary:Ie,previewSession:j,trackForkActivity:_t,recordForkActivityEvent:je,markForkActivitySeen:Qe,refreshForkActivities:Pe,setSlotFork:Ee,clearSlotFork:me,skipAnimationForSlot:$e,shouldSkipAnimation:He,queueBoundaryAnimation:Ce,consumeBoundaryAnimation:Re,registerBoundary:Oe,getBoundaryOverride:Vt,refreshModuleManifest:xe,resetAllForks:ze},children:n})}function ye(){let e=useContext(Vr);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function Nt(e){return ye().forks[e]}var ft=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,r){let n=this.values.get(t);if(Object.is(n,r))return;if(n!==void 0&&r!==null&&n!==null&&typeof n=="object"&&typeof r=="object")try{if(JSON.stringify(n)===JSON.stringify(r))return}catch{}this.values.set(t,r),this.snapshots.set(t,r);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,r){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(r),()=>{this.listeners.get(t)?.delete(r);}}useValue(t){let r=window.__FORK_REACT__;return r?.useSyncExternalStore?r.useSyncExternalStore(n=>this.subscribe(t,n),()=>this.getSnapshot(t)):(console.warn("[ForkBridge] React.useSyncExternalStore not available, returning static value"),this.values.get(t))}emit(t,...r){let n=this.eventHandlers.get(t);n&&n.forEach(o=>o(...r));}on(t,r){return this.eventHandlers.has(t)||this.eventHandlers.set(t,new Set),this.eventHandlers.get(t).add(r),()=>{this.eventHandlers.get(t)?.delete(r);}}destroy(){this.listeners.clear(),this.eventHandlers.clear(),this.values.clear(),this.snapshots.clear();let t=window.__FORK_BRIDGE__;t&&delete t[this.slotId];}};function ar(e,t){let r;try{r=Children.only(e);}catch{let o=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 n=r.type;if(typeof n=="string")throw new Error(`<ForkSlot slotId="${t}"> child must be a React component (function or class), not an HTML element <${n}>. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`);if(typeof n=="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 r}var Jr=new Set;function Gr(e){let t=[],r=e.querySelectorAll("*");for(let n of r){if(!(n instanceof HTMLElement))continue;let o=n.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(n.tagName))continue;let i=getComputedStyle(n),s=parseFloat(i.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:s});}return t}function uo(e,t){let r=[];for(let n of t)if(!e.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)&&!r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom)){for(let s=r.length-1;s>=0;s--){let l=r[s];l.rect.top>=n.rect.top&&l.rect.left>=n.rect.left&&l.rect.right<=n.rect.right&&l.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function fo(e,t){let r=[];for(let n of e)if(!t.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)&&!r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom)){for(let s=r.length-1;s>=0;s--){let l=r[s];l.rect.top>=n.rect.top&&l.rect.left>=n.rect.left&&l.rect.right<=n.rect.right&&l.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Yr(e,t,r,n,o){return o=Math.max(0,Math.min(o,r/2,n/2)),o===0?`M ${e} ${t} L ${e+r} ${t} L ${e+r} ${t+n} L ${e} ${t+n} Z`:[`M ${e+o} ${t}`,`L ${e+r-o} ${t}`,`A ${o} ${o} 0 0 1 ${e+r} ${t+o}`,`L ${e+r} ${t+n-o}`,`A ${o} ${o} 0 0 1 ${e+r-o} ${t+n}`,`L ${e+o} ${t+n}`,`A ${o} ${o} 0 0 1 ${e} ${t+n-o}`,`L ${e} ${t+o}`,`A ${o} ${o} 0 0 1 ${e+o} ${t}`,"Z"].join(" ")}function qr(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-highlights","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");n.appendChild(o);let i=[];for(let y=0;y<e.length;y++){let{rect:p,borderRadius:v}=e[y],_=p.left-.5,C=p.top-.5,b=p.width+1,A=p.height+1,O=Math.min(v+.5,b/2,A/2),g=Yr(_,C,b,A,O),P=`__fork-glow-${y}`,L=document.createElementNS(t,"filter");L.setAttribute("id",P),L.setAttribute("x","-100%"),L.setAttribute("y","-100%"),L.setAttribute("width","300%"),L.setAttribute("height","300%");let B=document.createElementNS(t,"feGaussianBlur");B.setAttribute("in","SourceGraphic"),B.setAttribute("stdDeviation","8"),L.appendChild(B),o.appendChild(L);let U=`__fork-mask-${y}`,S=document.createElementNS(t,"mask");S.setAttribute("id",U),S.setAttribute("maskUnits","userSpaceOnUse"),S.setAttribute("x",String(_-200)),S.setAttribute("y",String(C-200)),S.setAttribute("width",String(b+400)),S.setAttribute("height",String(A+400));let k=document.createElementNS(t,"rect");k.setAttribute("x",String(_-200)),k.setAttribute("y",String(C-200)),k.setAttribute("width",String(b+400)),k.setAttribute("height",String(A+400)),k.setAttribute("fill","white"),S.appendChild(k);let h=document.createElementNS(t,"path");h.setAttribute("d",g),h.setAttribute("fill","black"),S.appendChild(h),o.appendChild(S);let E=document.createElementNS(t,"g");E.setAttribute("mask",`url(#${U})`),E.setAttribute("opacity","0");let m=document.createElementNS(t,"g");m.setAttribute("filter",`url(#${P})`);let c=document.createElementNS(t,"path");c.setAttribute("d",g),c.setAttribute("fill","none"),c.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),c.setAttribute("stroke-width","6"),c.setAttribute("stroke-linecap","round"),m.appendChild(c),E.appendChild(m),n.appendChild(E);let I=document.createElementNS(t,"path");I.setAttribute("d",g),I.setAttribute("fill","none"),I.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),I.setAttribute("stroke-width","2"),I.setAttribute("stroke-linecap","round"),I.setAttribute("opacity","0"),n.appendChild(I),i.push(c,I),c.__group=E;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let y=0;y<i.length;y+=2){let p=i[y],v=i[y+1],_=p.__group,C=v.getTotalLength(),b=p.getTotalLength();if(C<=0)continue;let A=C*.35;v.setAttribute("stroke-dasharray",`${A} ${C-A}`),v.setAttribute("stroke-dashoffset","0"),s.push(v.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*C,opacity:.92,offset:.06},{strokeDashoffset:-2*C,opacity:.92,offset:.92},{strokeDashoffset:-2.25*C,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let O=b*.35;p.setAttribute("stroke-dasharray",`${O} ${b-O}`),p.setAttribute("stroke-dashoffset","0"),s.push(p.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*b,offset:.06},{strokeDashoffset:-2*b,offset:.92},{strokeDashoffset:-2.25*b,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(_.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,f=()=>{if(l)return;l=true,clearTimeout(w);for(let p of s)try{p.cancel();}catch{}let y=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});y.onfinish=()=>r.remove(),window.removeEventListener("click",f);},w=setTimeout(f,14500);return setTimeout(()=>{l||window.addEventListener("click",f);},500),f}function po(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-removed","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.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 s=document.createElementNS(t,"feDropShadow");s.setAttribute("dx","0"),s.setAttribute("dy","1"),s.setAttribute("stdDeviation","2"),s.setAttribute("flood-color","rgba(0,0,0,0.15)"),i.appendChild(s),o.appendChild(i),n.appendChild(o);for(let{rect:l,borderRadius:f}of e){let w=l.left,y=l.top,p=l.width,v=l.height,_=Math.min(f,p/2,v/2),C=Yr(w,y,p,v,_),b=document.createElementNS(t,"path");b.setAttribute("d",C),b.setAttribute("fill","none"),b.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),b.setAttribute("stroke-width","1.5"),b.setAttribute("stroke-dasharray","8 4"),b.setAttribute("stroke-linecap","round"),b.setAttribute("filter","url(#__fork-removed-shadow)"),b.setAttribute("opacity","0"),n.appendChild(b),b.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 r.appendChild(n),document.body.appendChild(r),r}function mo(e,t){if(e===t)return true;let r=Object.keys(e);if(r.length!==Object.keys(t).length)return false;for(let n of r)if(!Object.is(e[n],t[n]))return false;return true}var go=ir__default.memo(function({component:t,containerRef:r,wrapperStyle:n,hostProps:o}){return jsx("div",{ref:r,style:n,children:jsx(t,{...o})})},(e,t)=>e.component===t.component&&mo(e.hostProps,t.hostProps)),sr=class extends ir__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 Zr({slotId:e,children:t,githubRepo:r,shared:n,events:o}){ar(t,e);let i=Nt(e),{baseUrl:s,apiKey:l,appId:f,shouldSkipAnimation:w}=ye(),[y,p]=useState(null),v=useRef(null),_=useRef(null),C=useRef(null),b=useRef(false),A=useRef(null),O=useRef(null),g=!!(n||o),P=useRef(null);g&&!P.current&&(P.current=new ft(e));let L=useRef(o);if(L.current=o,useEffect(()=>{if(g)return ()=>{P.current?.destroy(),P.current=null;}},[g,e]),g&&P.current&&n)for(let[h,E]of Object.entries(n))P.current.set(h,E);useEffect(()=>{if(!g)return;P.current||(P.current=new ft(e));let h=P.current,E=Object.keys(L.current||{}).map(m=>h.on(m,(...c)=>L.current?.[m]?.(...c)));return ()=>E.forEach(m=>m())},[g,e]),useEffect(()=>{if(Jr.has(e))return;Jr.add(e);let h={id:e,appId:f,label:e,eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:r,mode:"direct",sharedKeys:n?Object.keys(n):[],eventNames:o?Object.keys(o):[],propsShape:"",callbackNames:[]};fetch(`${s}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json"},body:JSON.stringify(h)}).catch(()=>{});},[e,s,l,r,f]);let B=i?.id||null;useEffect(()=>{if(i?.bundleUrl,v.current,_.current,!i?.bundleUrl||!B){return}let h=`${s}${i.bundleUrl.replace("bundle.js","component.js")}`,E=`__fork_animated_${e}`,m=sessionStorage.getItem(E),c=w(e),I=!c&&m!==B;if(c&&B&&sessionStorage.setItem(E,B),I&&_.current){let H=Gr(_.current);C.current=H,b.current=true,`${e}${H.length}`;}window.__FORK_REACT__=ir__default,window.__FORK_REACT_DOM__=Tn,window.__FORK_REACT_JSX__=Ln;let D=Date.now(),N=`${s}${i.bundleUrl.replace("bundle.js","component.css")}?t=${D}`,R=document.createElement("link");R.rel="stylesheet",R.href=N,R.dataset.forkSlot=e,document.head.appendChild(R);let x=document.createElement("script");return x.src=h+"?t="+D,x.onload=()=>{let H=window.__FORK_EXPORT__;if(H?.default){if(_.current&&C.current&&b.current){let Z=_.current.getBoundingClientRect(),G=_.current.cloneNode(true);G.setAttribute("data-fork-clone-overlay","true"),G.style.position="fixed",G.style.top=`${Z.top}px`,G.style.left=`${Z.left}px`,G.style.width=`${Z.width}px`,G.style.height=`${Z.height}px`,G.style.flex="none",G.style.minHeight="auto",G.style.zIndex="9998",G.style.pointerEvents="none",G.style.overflow="hidden";let we=getComputedStyle(_.current).backgroundColor;G.style.backgroundColor=we&&we!=="rgba(0, 0, 0, 0)"&&we!=="transparent"?we:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(G);let j=_.current.querySelectorAll("*"),ne=G.querySelectorAll("*");for(let fe=0;fe<j.length;fe++)j[fe].scrollTop!==0&&(ne[fe].scrollTop=j[fe].scrollTop),j[fe].scrollLeft!==0&&(ne[fe].scrollLeft=j[fe].scrollLeft);A.current=G;}p(()=>H.default),v.current=B;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},x.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(x),()=>{x.remove(),R.remove(),O.current&&(clearTimeout(O.current),O.current=null),A.current&&(A.current.remove(),A.current=null);}},[B,s,e]),useEffect(()=>{if(!b.current||!y||!_.current){`${e}${b.current}`,_.current;return}let h=C.current;if(!h){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!_.current)return;let E=Gr(_.current),m=uo(h,E),c=fo(h,E),I=A.current;if(`${e}${m.length}${c.length}`,c.length>0&&I){let D=po(c);O.current=setTimeout(()=>{O.current=null;let N=400;I.animate([{opacity:1},{opacity:0}],{duration:N,fill:"forwards"}),D.animate([{opacity:1},{opacity:0}],{duration:N,fill:"forwards"}),setTimeout(()=>{I.remove(),D.remove(),A.current=null,m.length>0&&(qr(m));},N);},3500);}else I&&(I.remove(),A.current=null),m.length>0&&(qr(m));C.current=null,b.current=false,B&&(sessionStorage.setItem(`__fork_animated_${e}`,B),`${e}`);});});},[y]);let U={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!i||i.status!=="complete"||!i.bundleUrl)return jsx("div",{ref:_,style:U,children:t});if(!y)return jsx("div",{ref:_,style:U,children:t});let k=t?.props??{};return jsx(sr,{slotId:e,resetKey:B,fallback:jsx("div",{ref:_,style:U,children:t}),children:jsx(go,{component:y,containerRef:_,wrapperStyle:U,hostProps:k})})}var en=new Set;function ko(e){return `{ ${Object.entries(e).map(([r,n])=>n==null?`${r}: unknown`:Array.isArray(n)?`${r}: ${n.length>0?typeof n[0]:"unknown"}[]`:`${r}: ${typeof n}`).join("; ")} }`}function tn(e,t=new Set){return Children.forEach(e,r=>{if(!isValidElement(r))return;let n=r.props;for(let[o,i]of Object.entries(n))typeof i=="function"&&/^on[A-Z]/.test(o)&&t.add(o);n.children&&tn(n.children,t);}),t}function bo({slotId:e,props:t,children:r,allowedFetches:n,githubRepo:o,callbacks:i,mode:s="iframe",shared:l,events:f}){if(ar(r,e),s==="direct")return jsx(Zr,{slotId:e,githubRepo:o,shared:l,events:f,children:r});let w=Nt(e),{baseUrl:y,apiKey:p,appId:v}=ye(),_=useRef(null),C=useRef(false),b=useRef(null),A=useRef(i);A.current=i;let O=useRef(t);O.current=t;let g=useRef(n);g.current=n,useEffect(()=>{if(typeof process<"u")return;let U=tn(r),S=new Set(i?Object.keys(i):[]),k=[...U].filter(h=>!S.has(h));k.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:
|
|
1
|
+
import*as ar from'react';import ar__default,{createContext,useSyncExternalStore,useState,useRef,useEffect,useCallback,startTransition,Children,useContext,isValidElement}from'react';import*as Ln from'react-dom';import {createPortal}from'react-dom';import*as Bn from'react/jsx-runtime';import {jsx,Fragment,jsxs}from'react/jsx-runtime';import*as Nn from'react/jsx-dev-runtime';import {ChevronDown,Check,PictureInPicture,PictureInPicture2,X,User,BadgeCheck,Undo2,RotateCcw,ArrowUp,Loader2,AlertCircle,Sparkles,Package,Wrench,MessageSquare,Code,Terminal,FileSearch,Pencil}from'lucide-react';var We="__FORK_SHARED__";function qt(){var t,r,n,o;let e=globalThis;return e[We]||(e[We]={}),(t=e[We]).react||(t.react=ar),(r=e[We])["react-dom"]||(r["react-dom"]=Ln),(n=e[We])["react/jsx-runtime"]||(n["react/jsx-runtime"]=Bn),(o=e[We])["react/jsx-dev-runtime"]||(o["react/jsx-dev-runtime"]=Nn),e[We]}function Yt(e){return Object.assign(qt(),e)}var Un="__fork_preview_session__";function It(e){return `${Un}${e}`}var ee={apiKey:null,session:null},Zt=new Set;function Mt(){for(let e of Zt)try{e();}catch(t){console.error("[fork-preview] subscriber threw",t);}}function Ur(e){let t=Date.parse(e.expires_at);return Number.isFinite(t)?t<=Date.now():true}function Hn(e){if(typeof window>"u")return null;try{let t=window.sessionStorage.getItem(It(e));if(!t)return null;let r=JSON.parse(t);return !r||typeof r!="object"||typeof r.preview_session_id!="string"?null:Ur(r)?(window.sessionStorage.removeItem(It(e)),null):r}catch{return null}}function Qt(e,t){if(!(typeof window>"u"))try{t?window.sessionStorage.setItem(It(e),JSON.stringify(t)):window.sessionStorage.removeItem(It(e));}catch{}}function nt(e){ee.apiKey!==e&&(ee.apiKey=e,ee.session=Hn(e),Mt());}function Ne(){return ee.session?Ur(ee.session)?(Tt(null),null):ee.session:null}function Tt(e){ee.session=e,ee.apiKey&&Qt(ee.apiKey,e),Mt();}function lt(e){ee.session&&ee.session.fork_id!==e&&(ee.session={...ee.session,fork_id:e},ee.apiKey&&Qt(ee.apiKey,ee.session),Mt());}function Ve(e,t){ee.session&&(ee.session.container_id===e&&ee.session.container_name===t||(ee.session={...ee.session,container_id:e,container_name:t??ee.session.container_name??"Fork",fork_id:null},ee.apiKey&&Qt(ee.apiKey,ee.session),Mt()));}function er(e){return Zt.add(e),()=>{Zt.delete(e);}}var Hr="__fork_preview";function Or(){if(typeof window>"u")return null;let e=window.location.hash;if(!e||e.length<2)return null;let r=new URLSearchParams(e.slice(1)).get(Hr);return typeof r=="string"&&r.length>0?r:null}function rr(e){if(typeof window>"u")return false;try{let t=window.sessionStorage.getItem(`__fork_preview_session__${e}`);if(t){let r=JSON.parse(t),n=typeof r?.expires_at=="string"?Date.parse(r.expires_at):NaN;if(Number.isFinite(n)&&n>Date.now())return !0;window.sessionStorage.removeItem(`__fork_preview_session__${e}`);}}catch{}return jr()!==null}function Dr(){if(typeof window>"u")return;let e=window.location.hash;if(!e||e.length<2)return;let t=new URLSearchParams(e.slice(1));t.delete(Hr);let r=t.toString(),n=r?`#${r}`:"";try{window.history.replaceState(null,"",window.location.pathname+window.location.search+n);}catch{}}var Xe=null,tr=null,ct=null;function jr(){if(Xe)return Xe;let e=Or();return e?(Xe=e,Dr(),Xe):null}async function nr(e,t){nt(e);let r=Ne();if(r)return Xe=null,r;let n=Xe??Or();if(Xe=null,!n)return null;Dr();try{let o=await fetch(`${t}/api/v1/preview/activate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({token:n})});if(!o.ok){let l=await o.json().catch(()=>({}));return console.warn(`[fork-preview] activate failed (${o.status}): ${l.error??"unknown"}`),null}let i=await o.json(),s={preview_session_id:i.preview_session_id,tenant_id:i.tenant_id,app_id:i.app_id,target:i.target,operator_id:i.operator_id,container_id:i.container_id??null,container_name:i.container_name??"Fork",fork_id:i.fork_id??null,expires_at:i.expires_at};return Tt(s),s}catch(o){return console.warn("[fork-preview] activate threw",o),null}}async function or(e,t,r){nt(e);let n=Ne();if(n)return n;if(!r.appId||!r.userId||!r.userHash)return null;let o=[e,t,r.appId,r.userId].join(`
|
|
2
|
+
`);return ct&&tr===o||(tr=o,ct=(async()=>{try{let i=await fetch(`${t}/api/v1/preview/auto-activate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,"X-Fork-User-Id":r.userId,"X-Fork-User-Hash":r.userHash},body:JSON.stringify({appId:r.appId})});if(i.status===204)return null;if(!i.ok){let f=await i.json().catch(()=>({}));return console.warn(`[fork-preview] auto admin activate failed (${i.status}): ${f.error??"unknown"}`),null}let s=await i.json(),l={preview_session_id:s.preview_session_id,tenant_id:s.tenant_id,app_id:s.app_id,target:s.target,operator_id:s.operator_id,container_id:s.container_id??null,container_name:s.container_name??"Fork",fork_id:s.fork_id??null,expires_at:s.expires_at};return Tt(l),l}catch(i){return console.warn("[fork-preview] auto admin activate threw",i),null}finally{tr=null,ct=null;}})()),ct}function Dn(){return Ne()}function jn(){return null}function Lt(){return useSyncExternalStore(er,Dn,jn)}function re(){let e=Ne();if(!e)return {};let t={"X-Fork-Preview-Session":e.preview_session_id};return e.fork_id&&(t["X-Fork-Preview-Fork-Id"]=e.fork_id),t}async function Bt(e){let t=new URLSearchParams({app:e.appId,user:e.userId});e.containerId&&t.set("containerId",e.containerId);let r=`${e.baseUrl}/api/v1/manifest?${t.toString()}`,n={Authorization:`Bearer ${e.apiKey}`,"X-Fork-App-Id":e.appId,"X-Fork-User-Id":e.userId,...e.extraHeaders??{}};e.userHash&&(n["X-Fork-User-Hash"]=e.userHash),e.previous?.etag&&(n["If-None-Match"]=e.previous.etag);let o=await fetch(r,{headers:n,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(),s={};for(let[l,f]of Object.entries(i.modules)){let w=f.moduleUrl??f.bundleUrl??null,y=f.legacyModuleUrl??f.legacyBundleUrl??null;s[l]={forkId:f.forkId,moduleUrl:w,legacyModuleUrl:y,bundleUrl:f.bundleUrl??w,legacyBundleUrl:f.legacyBundleUrl??y,cssUrls:f.cssUrls??[],integrity:f.integrity,metadata:f.metadata,buildId:f.buildId,updatedAt:f.updatedAt};}return {containerId:i.containerId,slots:i.slots,modules:s,generatedAt:i.generatedAt,etag:o.headers.get("ETag")??void 0}}var zn="fork:manifest:v1";function sr(e,t,r){return `${zn}:${e}:${t}:${r}`}function Kn(e,t,r){if(typeof window>"u")return null;try{let n=window.localStorage.getItem(sr(e,t,r));return n?JSON.parse(n):null}catch{return null}}function Wn(e,t,r,n){if(!(typeof window>"u"))try{window.localStorage.setItem(sr(e,t,r),JSON.stringify(n));}catch{}}function Vn(e,t,r){if(!(typeof window>"u"))try{window.localStorage.removeItem(sr(e,t,r));}catch{}}function Xn(e,t){if(!e||!t)return e!==t;if(e.containerId!==t.containerId)return true;let r=Object.entries(e.slots),n=Object.entries(t.slots);if(r.length!==n.length)return true;for(let[s,l]of r){let f=t.slots[s];if(!f||f.forkId!==l.forkId||f.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[s,l]of o){let f=t.modules[s];if(!f||f.forkId!==l.forkId||f.buildId!==l.buildId)return true}return false}var Xr=createContext(null),qn=12e3,Yn=45e3,zr="fork:activity:v1",Zn=new Set(["pending","running","building"]),Qn="Setting up environment";function Se(e){return Zn.has(e)}function eo(e,t){return t?.targetId?t:e.boundaryId?{targetKind:"module",targetId:e.boundaryId}:e.slotId?{targetKind:"slot",targetId:e.slotId}:null}function to(e,t){let r=eo(e,t);if(!r)return null;let n=new Date().toISOString();return {id:e.id,status:e.status,targetKind:r.targetKind,targetId:r.targetId,summary:e.summary??null,estimateMinutes:e.estimateMinutes??null,createdAt:e.createdAt||n,updatedAt:e.completedAt||n,completedAt:e.completedAt??null}}function Kr(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 Nt(e,t){let r=typeof t.summary=="string"&&t.summary.trim()?t.summary.trim():void 0,n=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:r??n??null,estimateMinutes:o??i??null,latestMessage:t.latestMessage??e?.latestMessage??null,unread:t.unread??e?.unread??false}}function dt(e){return `${e.id}:${e.completedAt||e.updatedAt}`}function Je(e){if(typeof window>"u")return new Set;try{let t=window.localStorage.getItem(e);if(!t)return new Set;let r=JSON.parse(t);return Array.isArray(r)?new Set(r.filter(n=>typeof n=="string")):new Set}catch{return new Set}}function Ge(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify([...t].slice(-200)));}catch{}}function ro(e){if(e.estimateMinutes)return `~${e.estimateMinutes}m`}function no(e){let t=e.data&&typeof e.data=="object"?e.data:{};if(e.type==="status"){let r=typeof t.status=="string"?t.status:"running",n=typeof t.summary=="string"?t.summary:void 0;return {status:r,latestMessage:Se(r)?"Building":void 0,summary:n,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 oo(e){let t=e.filter(o=>Se(o.status)),r=e.filter(o=>o.status==="complete"&&o.unread),n=[...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:r.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():Qn,detail:i?ro(o):void 0,count:1,runningCount:1,unreadCompletedCount:r.length,latest:o}}if(r.length>1)return {state:"complete",label:`${r.length} forks ready`,count:r.length,runningCount:0,unreadCompletedCount:r.length,latest:r[0]};if(r.length===1){let o=r[0];return {state:"complete",label:o.summary||"Fork ready",count:1,runningCount:0,unreadCompletedCount:1,latest:o}}return {state:n?.status==="error"?"error":"idle",label:"Fork",count:0,runningCount:0,unreadCompletedCount:0,latest:n}}function ut(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function so(e,t){let r={};for(let[n,o]of Object.entries(t.boundaries||{}))r[n]={...o,moduleUrl:ut(e,o.moduleUrl),cssUrls:Array.isArray(o.cssUrls)?o.cssUrls.map(i=>ut(e,i)):[]};return r}function Wr(e,t,r,n){let o={};for(let[i,s]of Object.entries(t.slots)){let l=s.bundleUrl??s.legacyBundleUrl;l&&(o[i]={id:s.forkId,userId:r,prompt:"",status:"complete",slotId:i,appId:n,bundleUrl:ut(e,l),createdAt:s.updatedAt,completedAt:s.updatedAt});}return o}function Vr(e,t){let r={};for(let[n,o]of Object.entries(t.modules)){let i=o.moduleUrl??o.legacyModuleUrl??o.bundleUrl??"";i&&(r[n]={id:o.forkId,boundaryId:n,moduleUrl:ut(e,i),cssUrls:(o.cssUrls??[]).map(s=>ut(e,s)),integrity:o.integrity,metadata:o.metadata,createdAt:o.updatedAt});}return r}function io(e){let{apiKey:t,baseUrl:r,children:n,appId:o,shared:i}=e,s="userId"in e?e.userId:void 0,l="authUrl"in e?e.authUrl:void 0,[f]=useState(()=>(nt(t),rr(t))),[w,y]=useState({}),[p,v]=useState(s?{userId:s,userHash:void 0}:null),[_,C]=useState(!!s||f),[b,A]=useState({}),[O,g]=useState(!o),[P,L]=useState(0),[B,U]=useState(null),[S,k]=useState([]),[h,E]=useState(()=>typeof document>"u"?true:document.visibilityState!=="hidden"),m=useRef(new Map),c=useRef(new Map),[I,D]=useState(0),N=useRef(new Set),R=useRef(new Map),x=useRef(void 0),H=useRef(new Map),Z=useRef([]),G=useRef(new Set),we=useRef(false);qt(),useEffect(()=>{return nr(t,r).then(()=>{}),()=>{}},[]);let j=Lt();useEffect(()=>{f||j||!o||!p?.userHash||or(t,r,{appId:o,userId:p.userId,userHash:p.userHash});},[t,o,p?.userHash,p?.userId,r,f,j?.preview_session_id]),i&&x.current!==i&&(Yt(i),x.current=i),useEffect(()=>{l&&(f||(C(false),fetch(l,{credentials:"include"}).then(d=>{if(!d.ok)throw new Error(`Auth endpoint returned ${d.status}`);return d.json()}).then(d=>{if(!d.userId||typeof d.userId!="string")throw new Error("authUrl response must include userId");v({userId:d.userId,userHash:typeof d.userHash=="string"?d.userHash:void 0});}).catch(d=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",d.message);}).finally(()=>{C(true);})));},[l,f]),useEffect(()=>{!l&&s&&(v({userId:s,userHash:void 0}),C(true));},[s,l]);let ne=p?.userId??"",fe=p?.userHash,q=j?"":ne,ie=j?void 0:fe,Ze=!!o,xe=useCallback(async()=>{if(!Ze){U(null),A({}),g(true),L(u=>u+1);return}if(!_){g(false);return}if(!j&&!q||!o){U(null),A({}),g(true),L(u=>u+1);return}if(g(false),!j){try{let u=await Bt({baseUrl:r,apiKey:t,appId:o,userId:q,userHash:ie});u&&(U(u.containerId),y(Wr(r,u,q,o)),A(Vr(r,u)));}catch(u){console.error("[ForkProvider] Failed to fetch fork manifest:",u.message),U(null),y({}),A({});}finally{L(u=>u+1),g(true);}return}if(U(j.container_id??null),j.container_id){try{let u=await Bt({baseUrl:r,apiKey:t,appId:o,userId:q,containerId:j.container_id,extraHeaders:re()});u&&(y(Wr(r,u,q,o)),A(Vr(r,u)));}catch(u){console.error("[ForkProvider] Failed to fetch preview container manifest:",u.message),y({}),A({});}finally{L(u=>u+1),g(true);}return}let d=new URLSearchParams({appId:o,userId:q});ie&&d.set("userHash",ie);try{let u=await fetch(`${r}/api/v1/boundaries/manifest?${d.toString()}`,{headers:{Authorization:`Bearer ${t}`,...re()}});if(!u.ok)throw new Error(`${u.status}`);let M=await u.json();A(so(r,M));}catch(u){console.error("[ForkProvider] Failed to fetch module override manifest:",u.message),A({});}finally{L(u=>u+1),g(true);}},[t,o,r,_,Ze,ie,q,j?.preview_session_id,j?.fork_id,j?.container_id]);useEffect(()=>{if(!q||o&&(!j||j.container_id))return;let d=new URLSearchParams({userId:q});ie&&d.set("userHash",ie),fetch(`${r}/api/v1/forks/active?${d.toString()}`,{headers:{Authorization:`Bearer ${t}`,...re()}}).then(u=>{if(!u.ok)throw new Error(`${u.status}`);return u.json()}).then(u=>{u&&typeof u=="object"&&y(u);}).catch(()=>{});},[t,o,q,ie,r,j?.preview_session_id,j?.fork_id]),useEffect(()=>{xe();},[xe]);let Ee=useCallback((d,u)=>{y(M=>({...M,[d]:u}));},[]),me=useCallback(d=>{y(u=>{let M={...u};return delete M[d],M});},[]),$e=useCallback(d=>{N.current.add(d);},[]),He=useCallback(d=>N.current.has(d)?(N.current.delete(d),true):false,[]),Ce=useCallback((d,u)=>{R.current.set(d,u);},[]),Re=useCallback((d,u)=>R.current.get(d)!==u?false:(R.current.delete(d),true),[]),Oe=useCallback(d=>{if(!o)return;let u=JSON.stringify(d);m.current.get(d.id)===u||c.current.get(d.id)?.signature===u||(c.current.set(d.id,{boundary:d,signature:u}),D(Q=>Q+1));},[o]);useEffect(()=>{if(!o||c.current.size===0)return;let d=setTimeout(()=>{let u=Array.from(c.current.values());u.length!==0&&fetch(`${r}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:o,boundaries:u.map(M=>M.boundary)})}).then(M=>{if(!M.ok)throw new Error(`${M.status}`)}).then(()=>{for(let M of u)c.current.get(M.boundary.id)?.signature===M.signature&&(c.current.delete(M.boundary.id),m.current.set(M.boundary.id,M.signature));}).catch(M=>{console.error("[ForkProvider] Failed to register module boundaries:",M.message);});},50);return ()=>{clearTimeout(d);}},[t,o,r,I]);let Xt=useCallback(d=>b[d],[b]),At=j?`preview:${j.preview_session_id}`:q,_t=`${t}:${o||"no-app"}:${B||"no-container"}:${At||"anonymous"}`,ve=`${zr}:seen:${_t}`,K=`${zr}:tracked:${_t}`;useEffect(()=>{Z.current=S;},[S]);let De=useCallback(()=>{let d={Authorization:`Bearer ${t}`,...re()};return o&&(d["X-Fork-App-Id"]=o),!j&&q&&(d["X-Fork-User-Id"]=q),!j&&ie&&(d["X-Fork-User-Hash"]=ie),d},[t,o,j,ie,q]),Pe=useCallback(async()=>{if(!B)return;let d=new URLSearchParams({container_id:B}),u=await fetch(`${r}/api/v1/forks?${d.toString()}`,{headers:De()}).catch(()=>null);if(!u||!u.ok)return;let M=await u.json().catch(()=>({})),Q=Array.isArray(M.forks)?M.forks:[],V=Je(ve),z=Je(K),oe=false,ae=new Map(Z.current.map(X=>[X.id,X])),ke=[];for(let X of Q){let le=Kr(X);Se(le.status)&&!z.has(le.id)&&(z.add(le.id),oe=true);let te=ae.get(le.id),se=te?Se(te.status):false,pe=dt(le);le.status==="complete"&&(z.has(le.id)||se)&&!V.has(pe)&&!G.current.has(pe)&&!te?.unread&&(we.current||z.has(le.id)||se)&&(G.current.add(pe),ke.push(le));}if(k(X=>{let le=new Map(X.map(de=>[de.id,de])),te=new Set,se=new Map;for(let de of Q){let ge=Kr(de);te.add(ge.id);let Be=le.get(ge.id),Y=Be?Se(Be.status):false,it=dt(ge),Me=ge.status==="complete"&&(z.has(ge.id)||Y)&&!V.has(it),et=Nt(Be,{...ge,unread:Me});se.set(ge.id,et);}for(let de of X)te.has(de.id)||(Se(de.status)||de.unread)&&se.set(de.id,de);let pe=[...se.values()].sort((de,ge)=>Date.parse(ge.updatedAt)-Date.parse(de.updatedAt));return Z.current=pe,pe}),oe&&Ge(K,z),ke.length>0){for(let X of ke)X.targetKind==="module"&&Ce(X.targetId,X.id);xe().catch(()=>{});}we.current=true;},[ve,K,r,De,B,xe,Ce]),Ct=useCallback((d,u)=>{let M=to(d,u);if(!M)return;let Q=d.containerId??d._containerId;if(Q&&!B&&U(Q),Se(M.status)){let oe=Je(K);oe.has(M.id)||(oe.add(M.id),Ge(K,oe));}let V=new Map(Z.current.map(oe=>[oe.id,oe]));V.set(M.id,Nt(V.get(M.id),M));let z=[...V.values()].sort((oe,ae)=>Date.parse(ae.updatedAt)-Date.parse(oe.updatedAt));Z.current=z,k(z);},[K,B]),je=useCallback((d,u)=>{let M=no(u),Q=Je(ve),V=Je(K),z=Z.current.find(te=>te.id===d),oe=z?Se(z.status):false;M.status&&Se(M.status)&&!V.has(d)&&(V.add(d),Ge(K,V));let ae=z?Nt(z,{...z,...M}):null,ke=ae?dt(ae):null,X=!!(ae&&ae.status==="complete"&&(V.has(d)||oe)&&ke&&!Q.has(ke)&&!G.current.has(ke)&&!z?.unread),le=u.type==="complete"&&z?.targetKind==="module"?z.targetId:null;if(k(te=>{let se=te.find(Y=>Y.id===d);if(!se)return te;let pe=Nt(se,{...se,...M}),de=pe.status==="complete"&&(V.has(d)||Se(se.status))&&!Q.has(dt(pe)),ge={...pe,unread:de},Be=te.map(Y=>Y.id===d?ge:Y).sort((Y,it)=>Date.parse(it.updatedAt)-Date.parse(Y.updatedAt));return Z.current=Be,Be}),X&&ae&&ke&&G.current.add(ke),u.type==="complete"){let te=u.data&&typeof u.data=="object"?u.data:{},se=typeof te.boundaryId=="string"?te.boundaryId:le;se&&Ce(se,d),xe().catch(()=>{});}},[ve,K,xe,Ce]),Qe=useCallback(d=>{let u=Je(ve),M=Je(K),Q=false,V=false;for(let z of Z.current){if(z.status!=="complete"||d&&z.id!==d)continue;let oe=dt(z);u.has(oe)||(u.add(oe),Q=true),M.delete(z.id)&&(V=true);}k(z=>{let oe=z.map(ae=>ae.status!=="complete"||d&&ae.id!==d?ae:{...ae,unread:false});return Z.current=oe,oe}),Q&&Ge(ve,u),V&&Ge(K,M);},[ve,K]);useEffect(()=>{we.current=false,G.current.clear(),k([]);for(let d of H.current.values())d.close();H.current.clear(),B&&Pe();},[B,Pe]),useEffect(()=>{if(typeof document>"u")return;let d=()=>{let u=document.visibilityState!=="hidden";E(u),u&&B&&Pe();};return document.addEventListener("visibilitychange",d),window.addEventListener("focus",d),window.addEventListener("online",d),()=>{document.removeEventListener("visibilitychange",d),window.removeEventListener("focus",d),window.removeEventListener("online",d);}},[B,Pe]),useEffect(()=>{let d=S.filter(Q=>Se(Q.status));if(!B||d.length===0)return;let u=h?qn:Yn,M=window.setInterval(()=>{Pe();},u);return ()=>window.clearInterval(M)},[B,h,S,Pe]),useEffect(()=>{for(let d of H.current.values())d.close();H.current.clear();},[t,r,j?.preview_session_id,ie,q]),useEffect(()=>{let d=new Set(S.filter(u=>Se(u.status)).map(u=>u.id));for(let[u,M]of H.current.entries())d.has(u)||(M.close(),H.current.delete(u));for(let u of d){if(H.current.has(u))continue;let M=new URLSearchParams({key:t});j?(M.set("previewSessionId",j.preview_session_id),M.set("previewForkId",u)):q&&M.set("userId",q),ie&&M.set("userHash",ie);let Q=new EventSource(`${r}/api/v1/forks/${u}/events?${M.toString()}`);Q.onmessage=V=>{try{je(u,JSON.parse(V.data));}catch{}},Q.onerror=()=>{Q.close(),H.current.delete(u);},H.current.set(u,Q);}},[t,r,S,j,je,ie,q]),useEffect(()=>()=>{for(let d of H.current.values())d.close();H.current.clear();},[]);let Ie=oo(S),ze=useCallback(async()=>{if(!q)throw new Error("Reset requires a resolved user identity.");let d=new URLSearchParams({userId:q});ie&&d.set("userHash",ie);let u={Authorization:`Bearer ${t}`,...re()};o&&(u["X-Fork-App-Id"]=o);let M=await fetch(`${r}/api/v1/forks/all?${d.toString()}`,{method:"DELETE",headers:u});if(!M.ok){let V=await M.json().catch(()=>({}));throw new Error(V.error||`API error: ${M.status}`)}let Q=await M.json().catch(()=>({}));y({}),A({}),g(true),L(V=>V+1),k([]),G.current.clear(),Ge(ve,new Set),Ge(K,new Set),N.current.clear(),R.current.clear();try{for(let V=sessionStorage.length-1;V>=0;V-=1){let z=sessionStorage.key(V);z&&z.startsWith("__fork_animated_")&&sessionStorage.removeItem(z);}}catch{}return Q},[ve,K,t,o,r,ie,q]);return jsx(Xr.Provider,{value:{apiKey:t,userId:q,userHash:ie,baseUrl:r,appId:o,forks:w,moduleOverridesEnabled:Ze,moduleManifestReady:O,moduleManifestVersion:P,currentContainerId:B,forkActivities:S,activitySummary:Ie,previewSession:j,trackForkActivity:Ct,recordForkActivityEvent:je,markForkActivitySeen:Qe,refreshForkActivities:Pe,setSlotFork:Ee,clearSlotFork:me,skipAnimationForSlot:$e,shouldSkipAnimation:He,queueBoundaryAnimation:Ce,consumeBoundaryAnimation:Re,registerBoundary:Oe,getBoundaryOverride:Xt,refreshModuleManifest:xe,resetAllForks:ze},children:n})}function ye(){let e=useContext(Xr);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function Ut(e){return ye().forks[e]}var ft=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,r){let n=this.values.get(t);if(Object.is(n,r))return;if(n!==void 0&&r!==null&&n!==null&&typeof n=="object"&&typeof r=="object")try{if(JSON.stringify(n)===JSON.stringify(r))return}catch{}this.values.set(t,r),this.snapshots.set(t,r);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,r){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(r),()=>{this.listeners.get(t)?.delete(r);}}useValue(t){let r=window.__FORK_REACT__;return r?.useSyncExternalStore?r.useSyncExternalStore(n=>this.subscribe(t,n),()=>this.getSnapshot(t)):(console.warn("[ForkBridge] React.useSyncExternalStore not available, returning static value"),this.values.get(t))}emit(t,...r){let n=this.eventHandlers.get(t);n&&n.forEach(o=>o(...r));}on(t,r){return this.eventHandlers.has(t)||this.eventHandlers.set(t,new Set),this.eventHandlers.get(t).add(r),()=>{this.eventHandlers.get(t)?.delete(r);}}destroy(){this.listeners.clear(),this.eventHandlers.clear(),this.values.clear(),this.snapshots.clear();let t=window.__FORK_BRIDGE__;t&&delete t[this.slotId];}};function lr(e,t){let r;try{r=Children.only(e);}catch{let o=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 n=r.type;if(typeof n=="string")throw new Error(`<ForkSlot slotId="${t}"> child must be a React component (function or class), not an HTML element <${n}>. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`);if(typeof n=="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 r}var Gr=new Set;function qr(e){let t=[],r=e.querySelectorAll("*");for(let n of r){if(!(n instanceof HTMLElement))continue;let o=n.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(n.tagName))continue;let i=getComputedStyle(n),s=parseFloat(i.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:s});}return t}function fo(e,t){let r=[];for(let n of t)if(!e.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)&&!r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom)){for(let s=r.length-1;s>=0;s--){let l=r[s];l.rect.top>=n.rect.top&&l.rect.left>=n.rect.left&&l.rect.right<=n.rect.right&&l.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function po(e,t){let r=[];for(let n of e)if(!t.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)&&!r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom)){for(let s=r.length-1;s>=0;s--){let l=r[s];l.rect.top>=n.rect.top&&l.rect.left>=n.rect.left&&l.rect.right<=n.rect.right&&l.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Zr(e,t,r,n,o){return o=Math.max(0,Math.min(o,r/2,n/2)),o===0?`M ${e} ${t} L ${e+r} ${t} L ${e+r} ${t+n} L ${e} ${t+n} Z`:[`M ${e+o} ${t}`,`L ${e+r-o} ${t}`,`A ${o} ${o} 0 0 1 ${e+r} ${t+o}`,`L ${e+r} ${t+n-o}`,`A ${o} ${o} 0 0 1 ${e+r-o} ${t+n}`,`L ${e+o} ${t+n}`,`A ${o} ${o} 0 0 1 ${e} ${t+n-o}`,`L ${e} ${t+o}`,`A ${o} ${o} 0 0 1 ${e+o} ${t}`,"Z"].join(" ")}function Yr(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-highlights","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");n.appendChild(o);let i=[];for(let y=0;y<e.length;y++){let{rect:p,borderRadius:v}=e[y],_=p.left-.5,C=p.top-.5,b=p.width+1,A=p.height+1,O=Math.min(v+.5,b/2,A/2),g=Zr(_,C,b,A,O),P=`__fork-glow-${y}`,L=document.createElementNS(t,"filter");L.setAttribute("id",P),L.setAttribute("x","-100%"),L.setAttribute("y","-100%"),L.setAttribute("width","300%"),L.setAttribute("height","300%");let B=document.createElementNS(t,"feGaussianBlur");B.setAttribute("in","SourceGraphic"),B.setAttribute("stdDeviation","8"),L.appendChild(B),o.appendChild(L);let U=`__fork-mask-${y}`,S=document.createElementNS(t,"mask");S.setAttribute("id",U),S.setAttribute("maskUnits","userSpaceOnUse"),S.setAttribute("x",String(_-200)),S.setAttribute("y",String(C-200)),S.setAttribute("width",String(b+400)),S.setAttribute("height",String(A+400));let k=document.createElementNS(t,"rect");k.setAttribute("x",String(_-200)),k.setAttribute("y",String(C-200)),k.setAttribute("width",String(b+400)),k.setAttribute("height",String(A+400)),k.setAttribute("fill","white"),S.appendChild(k);let h=document.createElementNS(t,"path");h.setAttribute("d",g),h.setAttribute("fill","black"),S.appendChild(h),o.appendChild(S);let E=document.createElementNS(t,"g");E.setAttribute("mask",`url(#${U})`),E.setAttribute("opacity","0");let m=document.createElementNS(t,"g");m.setAttribute("filter",`url(#${P})`);let c=document.createElementNS(t,"path");c.setAttribute("d",g),c.setAttribute("fill","none"),c.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),c.setAttribute("stroke-width","6"),c.setAttribute("stroke-linecap","round"),m.appendChild(c),E.appendChild(m),n.appendChild(E);let I=document.createElementNS(t,"path");I.setAttribute("d",g),I.setAttribute("fill","none"),I.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),I.setAttribute("stroke-width","2"),I.setAttribute("stroke-linecap","round"),I.setAttribute("opacity","0"),n.appendChild(I),i.push(c,I),c.__group=E;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let y=0;y<i.length;y+=2){let p=i[y],v=i[y+1],_=p.__group,C=v.getTotalLength(),b=p.getTotalLength();if(C<=0)continue;let A=C*.35;v.setAttribute("stroke-dasharray",`${A} ${C-A}`),v.setAttribute("stroke-dashoffset","0"),s.push(v.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*C,opacity:.92,offset:.06},{strokeDashoffset:-2*C,opacity:.92,offset:.92},{strokeDashoffset:-2.25*C,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let O=b*.35;p.setAttribute("stroke-dasharray",`${O} ${b-O}`),p.setAttribute("stroke-dashoffset","0"),s.push(p.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*b,offset:.06},{strokeDashoffset:-2*b,offset:.92},{strokeDashoffset:-2.25*b,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(_.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,f=()=>{if(l)return;l=true,clearTimeout(w);for(let p of s)try{p.cancel();}catch{}let y=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});y.onfinish=()=>r.remove(),window.removeEventListener("click",f);},w=setTimeout(f,14500);return setTimeout(()=>{l||window.addEventListener("click",f);},500),f}function mo(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-removed","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.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 s=document.createElementNS(t,"feDropShadow");s.setAttribute("dx","0"),s.setAttribute("dy","1"),s.setAttribute("stdDeviation","2"),s.setAttribute("flood-color","rgba(0,0,0,0.15)"),i.appendChild(s),o.appendChild(i),n.appendChild(o);for(let{rect:l,borderRadius:f}of e){let w=l.left,y=l.top,p=l.width,v=l.height,_=Math.min(f,p/2,v/2),C=Zr(w,y,p,v,_),b=document.createElementNS(t,"path");b.setAttribute("d",C),b.setAttribute("fill","none"),b.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),b.setAttribute("stroke-width","1.5"),b.setAttribute("stroke-dasharray","8 4"),b.setAttribute("stroke-linecap","round"),b.setAttribute("filter","url(#__fork-removed-shadow)"),b.setAttribute("opacity","0"),n.appendChild(b),b.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 r.appendChild(n),document.body.appendChild(r),r}function go(e,t){if(e===t)return true;let r=Object.keys(e);if(r.length!==Object.keys(t).length)return false;for(let n of r)if(!Object.is(e[n],t[n]))return false;return true}var ho=ar__default.memo(function({component:t,containerRef:r,wrapperStyle:n,hostProps:o}){return jsx("div",{ref:r,style:n,children:jsx(t,{...o})})},(e,t)=>e.component===t.component&&go(e.hostProps,t.hostProps)),ir=class extends ar__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 Qr({slotId:e,children:t,githubRepo:r,shared:n,events:o}){lr(t,e);let i=Ut(e),{baseUrl:s,apiKey:l,appId:f,shouldSkipAnimation:w}=ye(),[y,p]=useState(null),v=useRef(null),_=useRef(null),C=useRef(null),b=useRef(false),A=useRef(null),O=useRef(null),g=!!(n||o),P=useRef(null);g&&!P.current&&(P.current=new ft(e));let L=useRef(o);if(L.current=o,useEffect(()=>{if(g)return ()=>{P.current?.destroy(),P.current=null;}},[g,e]),g&&P.current&&n)for(let[h,E]of Object.entries(n))P.current.set(h,E);useEffect(()=>{if(!g)return;P.current||(P.current=new ft(e));let h=P.current,E=Object.keys(L.current||{}).map(m=>h.on(m,(...c)=>L.current?.[m]?.(...c)));return ()=>E.forEach(m=>m())},[g,e]),useEffect(()=>{if(Gr.has(e))return;Gr.add(e);let h={id:e,appId:f,label:e,eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:r,mode:"direct",sharedKeys:n?Object.keys(n):[],eventNames:o?Object.keys(o):[],propsShape:"",callbackNames:[]};fetch(`${s}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json"},body:JSON.stringify(h)}).catch(()=>{});},[e,s,l,r,f]);let B=i?.id||null;useEffect(()=>{if(i?.bundleUrl,v.current,_.current,!i?.bundleUrl||!B){return}let h=`${s}${i.bundleUrl.replace("bundle.js","component.js")}`,E=`__fork_animated_${e}`,m=sessionStorage.getItem(E),c=w(e),I=!c&&m!==B;if(c&&B&&sessionStorage.setItem(E,B),I&&_.current){let H=qr(_.current);C.current=H,b.current=true,`${e}${H.length}`;}window.__FORK_REACT__=ar__default,window.__FORK_REACT_DOM__=Ln,window.__FORK_REACT_JSX__=Bn;let D=Date.now(),N=`${s}${i.bundleUrl.replace("bundle.js","component.css")}?t=${D}`,R=document.createElement("link");R.rel="stylesheet",R.href=N,R.dataset.forkSlot=e,document.head.appendChild(R);let x=document.createElement("script");return x.src=h+"?t="+D,x.onload=()=>{let H=window.__FORK_EXPORT__;if(H?.default){if(_.current&&C.current&&b.current){let Z=_.current.getBoundingClientRect(),G=_.current.cloneNode(true);G.setAttribute("data-fork-clone-overlay","true"),G.style.position="fixed",G.style.top=`${Z.top}px`,G.style.left=`${Z.left}px`,G.style.width=`${Z.width}px`,G.style.height=`${Z.height}px`,G.style.flex="none",G.style.minHeight="auto",G.style.zIndex="9998",G.style.pointerEvents="none",G.style.overflow="hidden";let we=getComputedStyle(_.current).backgroundColor;G.style.backgroundColor=we&&we!=="rgba(0, 0, 0, 0)"&&we!=="transparent"?we:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(G);let j=_.current.querySelectorAll("*"),ne=G.querySelectorAll("*");for(let fe=0;fe<j.length;fe++)j[fe].scrollTop!==0&&(ne[fe].scrollTop=j[fe].scrollTop),j[fe].scrollLeft!==0&&(ne[fe].scrollLeft=j[fe].scrollLeft);A.current=G;}p(()=>H.default),v.current=B;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},x.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(x),()=>{x.remove(),R.remove(),O.current&&(clearTimeout(O.current),O.current=null),A.current&&(A.current.remove(),A.current=null);}},[B,s,e]),useEffect(()=>{if(!b.current||!y||!_.current){`${e}${b.current}`,_.current;return}let h=C.current;if(!h){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!_.current)return;let E=qr(_.current),m=fo(h,E),c=po(h,E),I=A.current;if(`${e}${m.length}${c.length}`,c.length>0&&I){let D=mo(c);O.current=setTimeout(()=>{O.current=null;let N=400;I.animate([{opacity:1},{opacity:0}],{duration:N,fill:"forwards"}),D.animate([{opacity:1},{opacity:0}],{duration:N,fill:"forwards"}),setTimeout(()=>{I.remove(),D.remove(),A.current=null,m.length>0&&(Yr(m));},N);},3500);}else I&&(I.remove(),A.current=null),m.length>0&&(Yr(m));C.current=null,b.current=false,B&&(sessionStorage.setItem(`__fork_animated_${e}`,B),`${e}`);});});},[y]);let U={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!i||i.status!=="complete"||!i.bundleUrl)return jsx("div",{ref:_,style:U,children:t});if(!y)return jsx("div",{ref:_,style:U,children:t});let k=t?.props??{};return jsx(ir,{slotId:e,resetKey:B,fallback:jsx("div",{ref:_,style:U,children:t}),children:jsx(ho,{component:y,containerRef:_,wrapperStyle:U,hostProps:k})})}var tn=new Set;function bo(e){return `{ ${Object.entries(e).map(([r,n])=>n==null?`${r}: unknown`:Array.isArray(n)?`${r}: ${n.length>0?typeof n[0]:"unknown"}[]`:`${r}: ${typeof n}`).join("; ")} }`}function rn(e,t=new Set){return Children.forEach(e,r=>{if(!isValidElement(r))return;let n=r.props;for(let[o,i]of Object.entries(n))typeof i=="function"&&/^on[A-Z]/.test(o)&&t.add(o);n.children&&rn(n.children,t);}),t}function wo({slotId:e,props:t,children:r,allowedFetches:n,githubRepo:o,callbacks:i,mode:s="iframe",shared:l,events:f}){if(lr(r,e),s==="direct")return jsx(Qr,{slotId:e,githubRepo:o,shared:l,events:f,children:r});let w=Ut(e),{baseUrl:y,apiKey:p,appId:v}=ye(),_=useRef(null),C=useRef(false),b=useRef(null),A=useRef(i);A.current=i;let O=useRef(t);O.current=t;let g=useRef(n);g.current=n,useEffect(()=>{if(typeof process<"u")return;let U=rn(r),S=new Set(i?Object.keys(i):[]),k=[...U].filter(h=>!S.has(h));k.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:
|
|
3
3
|
`+k.map(h=>` - ${h}`).join(`
|
|
4
|
-
`)+"\n\nThe forked component will not be able to call these. Add them to the `callbacks` prop of <ForkSlot>.");},[e,r,i]),useEffect(()=>{
|
|
4
|
+
`)+"\n\nThe forked component will not be able to call these. Add them to the `callbacks` prop of <ForkSlot>.");},[e,r,i]),useEffect(()=>{tn.has(e)||(tn.add(e),fetch(`${y}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:v,label:e,propsShape:t?bo(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:o,callbackNames:i?Object.keys(i):[],mode:s||"iframe"})}).catch(()=>{}));},[e,y,p,o,v]);let P=useCallback(U=>{let S=_.current;if(S?.contentWindow&&C.current){let k=A.current?Object.keys(A.current):[];S.contentWindow.postMessage({type:"slot:props",props:U,callbackNames:k},"*"),b.current=null;}else b.current=U;},[]),L=useCallback((U,S)=>{let k=g.current;return !k||k.length===0?false:k.some(h=>{let[E,m]=h.split(" "),c=S.split("?")[0];return U.toUpperCase()===E.toUpperCase()&&c.startsWith(m)})},[]);if(useEffect(()=>{if(!w?.bundleUrl)return;let U=async S=>{if(S.source===_.current?.contentWindow){if(S.data?.type==="slot:ready")C.current=true,_.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:g.current||[]},"*"),g.current,b.current?P(b.current):P(O.current||{});else if(S.data?.type==="slot:event"){let k=S.data.event;k?.navigate&&(window.location.hash=k.navigate);}else if(S.data?.type==="slot:clipboard-write")navigator.clipboard.writeText(S.data.text).catch(k=>{console.warn(`[ForkSlot:${e}] clipboard write failed:`,k.message);});else if(S.data?.type==="slot:callback"){let{name:k,args:h}=S.data,E=A.current?.[k];E?(E(...h||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${k}`);}else if(S.data?.type==="slot:fetch"){let{id:k,method:h,url:E,body:m}=S.data,c=_.current?.contentWindow;if(!c)return;let I=h||"GET";if(!L(I,E)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${k}: ${I} ${E} \u2014 not in allowedFetches`),c.postMessage({type:"slot:fetch-response",id:k,error:`Fetch not allowed: ${I} ${E}`},"*");return}try{let D={method:I};m&&I!=="GET"&&(D.headers={"Content-Type":"application/json"},D.body=JSON.stringify(m));let N=await fetch(E,D),R=await N.json();`${e}${k}${N.status}`,c.postMessage({type:"slot:fetch-response",id:k,data:R,status:N.status},"*");}catch(D){console.error(`[ForkSlot:${e}] fetch #${k} failed:`,D.message),c.postMessage({type:"slot:fetch-response",id:k,error:D.message},"*");}}}};return window.addEventListener("message",U),()=>{window.removeEventListener("message",U),C.current=false;}},[w?.bundleUrl,e,P,L]),useEffect(()=>{w?.bundleUrl&&C.current&&P(t||{});},[t,w?.bundleUrl,P]),!w||w.status!=="complete"||!w.bundleUrl)return `${e}${w?.status||"none"}${w?.bundleUrl||"none"}`,jsx(Fragment,{children:r});`${e}${w.bundleUrl}`;let B=`${y}${w.bundleUrl.replace("/bundle.js","/host")}`;return jsx("iframe",{ref:_,src:B,sandbox:"allow-scripts allow-same-origin allow-forms allow-clipboard-write",title:`Forked ${e}`,style:{width:"100%",border:"none",flex:1,minHeight:0}})}function Ot({style:e={width:20,height:20},...t}){return jsxs("svg",{viewBox:"320 95 270 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:e,...t,children:[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"}),jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M387.096 174.735v188"}),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"}),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"}),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 Ao=5600,dr=2147483002;function _o(e){return !e||e.state!=="complete"||!e.latest?null:`${e.latest.id}:${e.latest.completedAt??e.latest.updatedAt}`}function Co(){return typeof document>"u"?false:!!document.querySelector("[data-fork-clone-overlay], [data-fork-removed], [data-fork-highlights]")}function ur(e,t){let r=Math.min(e.length,t?26:34)*7.4,n=t?Math.min(t.length,24)*6.8+10:0;return Math.round(Math.min(390,Math.max(116,56+r+n)))}function Ro(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:r}){let[n,o]=useState(false),[i,s]=useState(false),[l,f]=useState(null),[w,y]=useState(null),[p,v]=useState(null),_=useRef(0),C=n?48:40,b=_o(r),A=!!(b&&r?.state==="complete"&&r.unreadCompletedCount>0),O=A?b:w?.key??null,g=!!(r&&r.state==="running"&&r.runningCount>0),P=!!(O&&O!==l&&(A||w)),L=g||P,B=A?r?.label:w?.label,U=P?"Built":r?.label??"Fork this app",S=P?B:r?.detail,k=ur(r?.label??"Fork this app",r?.detail),h=ur(U,S),E=P?Math.min(420,Math.max(326,h,w?.width??0,_.current+40)):h,m=P?46:40,c=L?[U,S].filter(Boolean).join(" "):Ro(r,t)??"Fork this app",I=L?`${U}:${S??""}`:"idle",D=(t||r?.state==="complete"&&r.unreadCompletedCount>0)&&!L;useEffect(()=>{if(typeof document>"u")return;let ne=document.createElement("div");return ne.setAttribute("data-fork-button-host","true"),ne.style.position="relative",ne.style.zIndex=String(dr),document.body.appendChild(ne),v(ne),()=>{ne.remove(),v(null);}},[]),useEffect(()=>{g&&(_.current=k);},[k,g]),useEffect(()=>{!A||!b||!r?.label||y(ne=>{if(ne?.key===b)return ne;let fe=Math.min(420,Math.max(326,ur("Built",r.label),_.current+40));return {key:b,label:r.label,width:fe,startedAt:Date.now()}});},[r?.label,b,A]),useEffect(()=>{r?.state==="complete"&&r.unreadCompletedCount===0&&y(null);},[r?.state,r?.unreadCompletedCount]),useEffect(()=>{if(!O||!P||O===l)return;let ne,fe=w?.key===O?w.startedAt:Date.now(),q=()=>{if(Date.now()-fe>=Ao&&!Co()){f(O);return}ne=window.setTimeout(q,250);};return ne=window.setTimeout(q,250),()=>{ne!==void 0&&window.clearTimeout(ne);}},[O,l,w?.key,w?.startedAt,P]);let N=L?{position:"fixed",bottom:24,right:24,zIndex:dr,width:`min(${E}px, calc(100vw - 32px))`,height:m,minWidth:0,maxWidth:"calc(100vw - 32px)",borderRadius:P?12:999,backgroundColor:n?"#ffffff":"rgba(255, 255, 255, 0.92)",border:"1px solid rgba(148, 163, 184, 0.42)",display:"inline-flex",alignItems:"center",justifyContent:P?"flex-start":"center",gap:P?10:8,color:"#111827",boxShadow:n?"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:P?"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:C,height:C,borderRadius:"50%",backgroundColor:n?"rgba(255, 255, 255, 1)":"rgba(255, 255, 255, 0.3)",border:n?"1px solid rgba(156, 163, 175, 1)":"1px solid rgba(156, 163, 175, 0.3)",display:"flex",alignItems:"center",justifyContent:"center",color:n?"#1c4587":"rgba(28, 69, 135, 0.5)",boxShadow:n?"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"},R={minWidth:0,maxWidth:g?286:P?82:S?116:238,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13,fontWeight:650,lineHeight:"16px",letterSpacing:0},x={minWidth:0,maxWidth:P?278:void 0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flexShrink:P?1:0,color:"#64748b",fontSize:g?13:12,fontWeight:650,lineHeight:"16px",letterSpacing:0},H={minWidth:0,flex:P?1:void 0,display:"inline-flex",alignItems:"center",justifyContent:P?"flex-start":void 0,gap:8,animation:"__forkButtonTextSwap 220ms ease-out"},Z={width:8,height:8,borderRadius:"50%",backgroundColor:r?.state==="complete"?"#16a34a":"#ef4444",boxShadow:r?.state==="complete"?"0 0 0 3px rgba(22, 163, 74, 0.14)":"none",animation:P?"__forkButtonBuiltDot 420ms ease-out":void 0,flexShrink:0},j=jsxs(Fragment,{children:[jsx("style",{children:`
|
|
5
5
|
@keyframes __forkButtonSpin { to { transform: rotate(360deg); } }
|
|
6
6
|
@keyframes __forkButtonTextSwap {
|
|
7
7
|
from { opacity: 0; transform: translateY(2px); }
|
|
@@ -16,7 +16,7 @@ import*as ir from'react';import ir__default,{createContext,useSyncExternalStore,
|
|
|
16
16
|
70% { opacity: 1; transform: scale(1.18); }
|
|
17
17
|
100% { opacity: 1; transform: scale(1); }
|
|
18
18
|
}
|
|
19
|
-
`}),jsxs("button",{onClick:e,onMouseEnter:()=>o(true),onMouseLeave:()=>{o(false),s(false);},onMouseDown:()=>s(true),onMouseUp:()=>s(false),style:N,title:c,"aria-label":c,children:[L&&r?jsxs(Fragment,{children:[g?jsx("span",{"aria-hidden":true,style:{width:14,height:14,borderRadius:"50%",border:"2px solid rgba(37, 99, 235, 0.18)",borderTopColor:"#2563eb",animation:"__forkButtonSpin 780ms linear infinite",flexShrink:0,boxSizing:"border-box"}}):jsx("span",{"aria-hidden":true,style:Z}),jsxs("span",{style:H,children:[jsx("span",{style:R,children:U}),S&&jsx("span",{style:x,children:S})]},I)]}):jsx(
|
|
19
|
+
`}),jsxs("button",{onClick:e,onMouseEnter:()=>o(true),onMouseLeave:()=>{o(false),s(false);},onMouseDown:()=>s(true),onMouseUp:()=>s(false),style:N,title:c,"aria-label":c,children:[L&&r?jsxs(Fragment,{children:[g?jsx("span",{"aria-hidden":true,style:{width:14,height:14,borderRadius:"50%",border:"2px solid rgba(37, 99, 235, 0.18)",borderTopColor:"#2563eb",animation:"__forkButtonSpin 780ms linear infinite",flexShrink:0,boxSizing:"border-box"}}):jsx("span",{"aria-hidden":true,style:Z}),jsxs("span",{style:H,children:[jsx("span",{style:R,children:U}),S&&jsx("span",{style:x,children:S})]},I)]}):jsx(Ot,{style:{width:24,height:24,animation:"__forkButtonLogoIn 220ms ease-out"}}),D&&jsx("span",{"aria-hidden":true,style:{position:"absolute",top:2,right:2,width:10,height:10,borderRadius:"50%",backgroundColor:"#2563eb",border:"2px solid #ffffff",boxSizing:"border-box",pointerEvents:"none"}})]})]});return p?createPortal(j,p):j}var Bo={status:Loader2,agent_message:MessageSquare,tool_use:Wrench,build_start:Package,build_complete:Check,build_error:AlertCircle,complete:Sparkles,error:AlertCircle},No={status:"#60a5fa",agent_message:"#a0a0a0",tool_use:"#fbbf24",build_start:"#c084fc",build_complete:"#6b7280",build_error:"#f87171",complete:"#6b7280",error:"#f87171"},Uo={read:FileSearch,write:Pencil,search:FileSearch,shell:Terminal,build:Package},Ho={read:"#60a5fa",write:"#fbbf24",search:"#60a5fa",shell:"#a78bfa",build:"#c084fc"};function mr(e){let t=e.data;switch(e.type){case "status":return `${t.message||t.status||"..."}`;case "agent_message":{let r=String(t.content||"");return /failed:/i.test(r)&&(r.includes("ENOENT")||r.includes("{")||r.includes("/Users/"))?"Adapting approach...":r}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 dn({events:e}){let t=useRef(null);return useEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight);},[e]),jsxs(Fragment,{children:[jsx("style",{children:`
|
|
20
20
|
@keyframes __fork-spin {
|
|
21
21
|
from { transform: rotate(0deg); }
|
|
22
22
|
to { transform: rotate(360deg); }
|
|
@@ -34,7 +34,7 @@ import*as ir from'react';import ir__default,{createContext,useSyncExternalStore,
|
|
|
34
34
|
.__fork-stream::-webkit-scrollbar-thumb:hover {
|
|
35
35
|
background: rgba(255, 255, 255, 0.3);
|
|
36
36
|
}
|
|
37
|
-
`}),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&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"#6b7280",fontSize:"11px"},children:[jsx(Loader2,{style:{width:"12px",height:"12px",animation:"__fork-spin 1s linear infinite",flexShrink:0}}),"Connecting to agent..."]}),e.map((r,n)=>{let o=n===e.length-1,i=r.type==="complete"||r.type==="error"||r.type==="build_complete"||r.type==="build_error",s=o&&!i&&(r.type==="status"||r.type==="tool_use"||r.type==="build_start"),l=Lo[r.type]||Code,f=Bo[r.type]||"#9ca3af";if(r.type==="tool_use"){let w=String(r.data.category||"");l=No[w]||Wrench,f=Uo[w]||"#fbbf24";}return s?l=Loader2:!o&&r.type==="status"&&(l=Check,f="#4ade80"),jsxs("div",{style:{display:"flex",gap:"6px",marginBottom:"6px",lineHeight:1.625},children:[jsx(l,{style:{width:"12px",height:"12px",marginTop:"2px",flexShrink:0,color:f,...s?{animation:"__fork-spin 1s linear infinite"}:{}}}),jsx("span",{style:{color:o&&!i?"#d1d5db":"#6b7280",wordBreak:"break-all"},children:pr(r)})]},n)})]})]})}var fn=35,Xo="Setting up environment",Jo="Built Custom Feature",pn=360,yt=350;function Go(e){let t=Date.parse(e);if(Number.isNaN(t))return "";let r=Math.max(1,Math.round((Date.now()-t)/1e3));if(r<60)return `${r}s`;let n=Math.round(r/60);if(n<60)return `${n}m`;let o=Math.round(n/60);return o<24?`${o}h`:`${Math.round(o/24)}d`}function qo(e){return e.length<=fn?e:e.slice(0,fn-3).trimEnd()+"..."}function Yo({events:e}){let[t,r]=useState("Setting up environment..."),[n,o]=useState(true),i=useRef(t),s=useRef(false);return useEffect(()=>{if(!s.current){for(let f of e)if(f.type==="status"&&String(f.data.message||"").includes("Agent started")){s.current=true;break}}let l="Setting up environment...";if(s.current)for(let f=e.length-1;f>=0;f--){let w=e[f];if(w.type==="tool_use"||w.type==="build_start"||w.type==="build_complete"){l=qo(pr(w));break}}if(l!==i.current){o(false);let f=setTimeout(()=>{r(l),i.current=l,o(true);},200);return ()=>clearTimeout(f)}},[e]),jsx("span",{style:{fontSize:11,color:"#d1d5db",fontWeight:500,opacity:n?1:0,transition:"opacity 0.2s ease",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},children:t})}function Zo({children:e}){let[t,r]=useState(null);return useEffect(()=>{if(typeof document>"u")return;let n=document.createElement("div");n.setAttribute("data-fork-panel-host",""),n.style.cssText="all: initial;",document.body.appendChild(n);let o=n.attachShadow({mode:"open"});return r(o),()=>{n.remove();}},[]),t?createPortal(e,t):null}function zt({state:e,fork:t,events:r,error:n,slotId:o,targetId:i,targetLabel:s,historyMode:l="slot",onSubmit:f,onUndo:w,onClose:y,baseUrl:p,apiKey:v,userId:_,userHash:C,appId:b,embedded:A=false,completeVariant:O="bubble"}){let[g,P]=useState(""),[L,B]=useState([]),[U,S]=useState(false),[k,h]=useState(false),[E,m]=useState(false),[c,I]=useState(false),[D,N]=useState(false),[R,x]=useState(false),[H,Z]=useState(false),[G,we]=useState(false),[j,ne]=useState(false),[fe,q]=useState(null),[ie,Ze]=useState(false),[xe,Ee]=useState([]),[me,$e]=useState(null),[He,Ce]=useState(false),[Re,Oe]=useState(false),[Vt,xt]=useState(false),[At,ve]=useState(null),[K,De]=useState(null),[Pe,_t]=useState(false),[je,Qe]=useState(false),[Ie,ze]=useState(""),d=useRef(null),[u,M]=useState(null),[Q,V]=useState(false),[z,oe]=useState(null),[ae,ke]=useState([]),[X$1,le]=useState(null),[te,se]=useState(false),pe=useRef(false),de=useRef(null),ge=useRef(null),{resetAllForks:Be,previewSession:Y,currentContainerId:it}=ye(),Me=Y?.container_id??it,et=!!(Y&&Q),Ae=z!==null,Cr=useRef(y);useEffect(()=>{Cr.current=y;});let Xt=useRef(null),Ct=useRef(false),Rr=typeof window<"u"&&"documentPictureInPicture"in window,_n=async()=>{if(!(!Rr||Ae))try{let a=await window.documentPictureInPicture.requestWindow({width:pn,height:640});a.document.body.style.margin="0",a.document.body.style.padding="0",a.document.body.style.height="100vh",a.document.body.style.overflow="hidden",a.document.body.style.background="#ffffff";try{let F=document.adoptedStyleSheets??[];F.length>0&&(a.document.adoptedStyleSheets=[...F]);}catch{}a.addEventListener("pagehide",()=>{Xt.current=null,oe(null),Ct.current||Cr.current(),Ct.current=!1;},{once:!0}),Xt.current=a,oe(a);}catch(a){console.warn("[Fork] PiP open failed:",a);}},Cn=()=>{z&&(Ct.current=true,z.close());};useEffect(()=>()=>{Ct.current=true,Xt.current?.close();},[]);let tt=i??o??"",Rn=(s||tt).replace(/[-_]+/g," ").replace(/\b\w/g,a=>a.toUpperCase()),Rt=useRef(""),Er=()=>{let a={Authorization:`Bearer ${v}`,...re()};return b&&(a["X-Fork-App-Id"]=b),!Y&&_&&(a["X-Fork-User-Id"]=_),!Y&&C&&(a["X-Fork-User-Hash"]=C),a},rt=A?true:k&&!E,En=r.find(a=>{let F=a.data;return a.type==="status"&&F.summary})?.data?.summary||t?.summary||Xo,Ke=r.find(a=>{let F=a.data;return (a.type==="status"||a.type==="complete")&&typeof F?.estimateMinutes=="number"})?.data?.estimateMinutes??t?.estimateMinutes;useEffect(()=>{if(l==="none"){S(true);return}if(!p||!v)return;if(!X$1){B([]),S(true);return}let a=new AbortController;return fetch(`${p}/api/v1/forks/${encodeURIComponent(X$1)}/messages`,{headers:Er(),signal:a.signal}).then(F=>F.ok?F.json():[]).then(F=>{if(a.signal.aborted)return;let T=[];for(let ue of F){let Te=ue.forkId??X$1;ue.role==="user"?T.push({type:"user",text:ue.content,forkId:Te}):T.push({type:"applied",text:ue.content,forkId:Te});}B(T),S(true);}).catch(()=>{a.signal.aborted||S(true);}),()=>{a.abort();}},[v,b,p,l,X$1,Y?.fork_id,Y?.preview_session_id,C,_,t?.id,t?.completedAt]),useEffect(()=>{if(l==="none"||!p||!v||!He)return;if(!me){ke([]);return}let a=new AbortController,F=new URLSearchParams({container_id:me});return fetch(`${p}/api/v1/forks?${F.toString()}`,{headers:Er(),signal:a.signal}).then(T=>T.ok?T.json():{forks:[]}).then(T=>{a.signal.aborted||ke(T.forks??[]);}).catch(()=>{}),()=>{a.abort();}},[v,b,p,l,me,He,t?.id,t?.completedAt,Y?.fork_id,Y?.preview_session_id,C,_]),useEffect(()=>{e==="complete"&&we(false);},[e]);let $r=ae.some(a=>a.status==="pending"||a.status==="running"||a.status==="building");useEffect(()=>{if(!$r||!p||!v||!me)return;let a=new URLSearchParams({container_id:me}),F={Authorization:`Bearer ${v}`,...re()};b&&(F["X-Fork-App-Id"]=b);let ue=setInterval(async()=>{try{let Te=await fetch(`${p}/api/v1/forks?${a.toString()}`,{headers:F});if(!Te.ok)return;let In=await Te.json();ke(In.forks??[]);}catch{}},3e3);return ()=>clearInterval(ue)},[$r,p,v,b,me]),useEffect(()=>{if(A&&l==="none"){Ee([]),$e(null),Ce(true),V(false);return}if(Y){let a=false;return Ce(false),V(false),M(null),fetch(`${p}/api/v1/preview/${encodeURIComponent(Y.preview_session_id)}/containers`,{headers:{Authorization:`Bearer ${v}`,...re()}}).then(F=>{if(!F.ok)throw new Error(`${F.status}`);return F.json()}).then(F=>{a||(Ee(F.containers),$e(F.currentContainerId??Y.container_id??null),V(true));}).catch(F=>{a||(V(false),M(F instanceof Error?F.message:String(F)),Me?(Ee([{id:Me,name:Y.container_name||"Primary container",createdAt:"",hasAccess:true,isPrimary:true}]),$e(Me)):(Ee([]),$e(null)));}).finally(()=>{a||Ce(true);}),()=>{a=true;}}Me?(Ee([{id:Me,name:"Primary container",createdAt:""}]),$e(Me)):(Ee([]),$e(null)),Ce(true),V(false);},[v,Me,p,A,l,Y?.container_id,Y?.container_name,Y?.preview_session_id]);let Et=useRef(void 0);useEffect(()=>{if(He){if(Et.current===void 0){Et.current=me;return}Et.current!==me&&(Et.current=me,B([]),S(false));}},[me,He]);let $t=useRef(null);useEffect(()=>{if(!Re)return;let a=T=>{if(!$t.current)return;let ue=typeof T.composedPath=="function"?T.composedPath():[];$t.current.contains(T.target)||ue.includes($t.current)||Oe(false);},F=T=>{T.key==="Escape"&&Oe(false);};return document.addEventListener("mousedown",a,true),document.addEventListener("keydown",F,true),()=>{document.removeEventListener("mousedown",a,true),document.removeEventListener("keydown",F,true);}},[Re]),useEffect(()=>{if(A||!rt||E||Ae)return;let a=F=>{(typeof F.composedPath=="function"?F.composedPath():[]).some(Te=>Te instanceof Element&&Te.hasAttribute("data-fork-panel-host"))||(m(true),h(false),setTimeout(()=>y(),yt));};return document.addEventListener("mousedown",a,true),()=>{document.removeEventListener("mousedown",a,true);}},[A,rt,E,Ae,y]),useEffect(()=>{Re||(Qe(false),ze(""));},[Re]),useEffect(()=>{je&&(d.current?.focus(),d.current?.select());},[je]),useEffect(()=>{if(A)return;let a=requestAnimationFrame(()=>h(true));return ()=>cancelAnimationFrame(a)},[A]),useEffect(()=>{let a=A||Ae;if((a||rt)&&(e==="prompting"||e==="complete")){let F=setTimeout(()=>de.current?.focus(),a?100:yt+100);return ()=>clearTimeout(F)}},[rt,A,Ae,e]),useEffect(()=>{if(e==="complete"&&Rt.current){let F=r.find(T=>T.type==="complete")?.data?.summary||t?.summary||Jo;B(T=>T[T.length-1]?.type==="applied"?T:[...T,{type:"applied",text:F}]),P(""),setTimeout(()=>de.current?.focus(),200);}},[e,Rn,r,t?.summary]),useEffect(()=>{ge.current&&(ge.current.scrollTop=ge.current.scrollHeight);},[L,e]);let Pr=()=>{if(g.trim()){Rt.current=g.trim();let a={},F=te||!X$1;F?(a.forceNew=true,pe.current=true,te||se(true)):a.forkId=X$1,F||B(T=>[...T,{type:"user",text:g.trim(),forkId:X$1}]),f(g.trim(),tt,me,a),P("");}};useEffect(()=>{if(pe.current){if(e==="error"){pe.current=false;return}t?.id&&(le(t.id),se(false),pe.current=false);}},[t?.id,e]),useEffect(()=>{t?.id&&(pe.current||e!=="running"&&e!=="complete"||(le(a=>a??t.id),se(false)));},[t?.id,e]);let Ir=a=>{Ve(a.session.containerId,a.session.containerName),$e(a.session.containerId),Ee(F=>{let T=F.filter(ue=>ue.id!==a.container.id);return [{...a.container,isPrimary:true,hasAccess:true},...T.map(ue=>({...ue,isPrimary:false}))]}),le(null),se(false),pe.current=false,B([]),S(false),Rt.current="";},$n=async a=>{if(!(!Y||!et||K)){De(a),M(null);try{let F=await fetch(`${p}/api/v1/preview/${encodeURIComponent(Y.preview_session_id)}/containers/${encodeURIComponent(a)}/primary`,{method:"POST",headers:{Authorization:`Bearer ${v}`,...re()}});if(!F.ok){let T=await F.json().catch(()=>({}));throw new Error(T.error||`API error: ${F.status}`)}Ir(await F.json()),Oe(!1);}catch(F){M(F instanceof Error?F.message:String(F));}finally{De(null);}}},Mr=async a=>{if(!Y||!et||K)return;let F=a.trim();if(F){De("__new__"),M(null);try{let T=await fetch(`${p}/api/v1/preview/${encodeURIComponent(Y.preview_session_id)}/containers`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${v}`,...re()},body:JSON.stringify({name:F})});if(!T.ok){let ue=await T.json().catch(()=>({}));throw new Error(ue.error||`API error: ${T.status}`)}Ir(await T.json()),Qe(!1),ze(""),Oe(!1);}catch(T){M(T instanceof Error?T.message:String(T));}finally{De(null);}}},Tr=async()=>{if(!(!w||j||!tt)){ne(true);try{let a=await w(tt);B(F=>{let T=[...F];return T.length>=2&&T[T.length-1]?.type==="applied"?T.splice(-2,2):T.length>=1&&T[T.length-1]?.type==="applied"&&T.splice(-1,1),T}),a?.removed&&B([]);}catch{}finally{ne(false);}}},Lr=()=>{if(A){y();return}if(Ae){z?.close();return}m(true),h(false),setTimeout(()=>y(),yt);},Pn=A||Ae?{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:pn,maxWidth:"100vw",background:"#ffffff",boxShadow:rt?"-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:rt?"translateX(0)":"translateX(100%)",transition:`transform ${yt}ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow ${yt}ms ease`,display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'},Br=xe.find(a=>a.id===me)?.name??(He?"Fork":"Loading..."),at=te?[]:X$1?L.filter(a=>a.forkId===X$1||a.forkId==null):L,Jt=jsxs(Fragment,{children:[jsx("style",{children:`
|
|
37
|
+
`}),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&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"#6b7280",fontSize:"11px"},children:[jsx(Loader2,{style:{width:"12px",height:"12px",animation:"__fork-spin 1s linear infinite",flexShrink:0}}),"Connecting to agent..."]}),e.map((r,n)=>{let o=n===e.length-1,i=r.type==="complete"||r.type==="error"||r.type==="build_complete"||r.type==="build_error",s=o&&!i&&(r.type==="status"||r.type==="tool_use"||r.type==="build_start"),l=Bo[r.type]||Code,f=No[r.type]||"#9ca3af";if(r.type==="tool_use"){let w=String(r.data.category||"");l=Uo[w]||Wrench,f=Ho[w]||"#fbbf24";}return s?l=Loader2:!o&&r.type==="status"&&(l=Check,f="#4ade80"),jsxs("div",{style:{display:"flex",gap:"6px",marginBottom:"6px",lineHeight:1.625},children:[jsx(l,{style:{width:"12px",height:"12px",marginTop:"2px",flexShrink:0,color:f,...s?{animation:"__fork-spin 1s linear infinite"}:{}}}),jsx("span",{style:{color:o&&!i?"#d1d5db":"#6b7280",wordBreak:"break-all"},children:mr(r)})]},n)})]})]})}var pn=35,Jo="Setting up environment",Go="Built Custom Feature",mn=360,yt=350;function qo(e){let t=Date.parse(e);if(Number.isNaN(t))return "";let r=Math.max(1,Math.round((Date.now()-t)/1e3));if(r<60)return `${r}s`;let n=Math.round(r/60);if(n<60)return `${n}m`;let o=Math.round(n/60);return o<24?`${o}h`:`${Math.round(o/24)}d`}function Yo(e){return e.length<=pn?e:e.slice(0,pn-3).trimEnd()+"..."}function Zo({events:e}){let[t,r]=useState("Setting up environment..."),[n,o]=useState(true),i=useRef(t),s=useRef(false);return useEffect(()=>{if(!s.current){for(let f of e)if(f.type==="status"&&String(f.data.message||"").includes("Agent started")){s.current=true;break}}let l="Setting up environment...";if(s.current)for(let f=e.length-1;f>=0;f--){let w=e[f];if(w.type==="tool_use"||w.type==="build_start"||w.type==="build_complete"){l=Yo(mr(w));break}}if(l!==i.current){o(false);let f=setTimeout(()=>{r(l),i.current=l,o(true);},200);return ()=>clearTimeout(f)}},[e]),jsx("span",{style:{fontSize:11,color:"#d1d5db",fontWeight:500,opacity:n?1:0,transition:"opacity 0.2s ease",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},children:t})}function Qo({children:e}){let[t,r]=useState(null);return useEffect(()=>{if(typeof document>"u")return;let n=document.createElement("div");n.setAttribute("data-fork-panel-host",""),n.style.cssText="all: initial;",document.body.appendChild(n);let o=n.attachShadow({mode:"open"});return r(o),()=>{n.remove();}},[]),t?createPortal(e,t):null}function Kt({state:e,fork:t,events:r,error:n,slotId:o,targetId:i,targetLabel:s,historyMode:l="slot",onSubmit:f,onUndo:w,onClose:y,baseUrl:p,apiKey:v,userId:_,userHash:C,appId:b,embedded:A=false,completeVariant:O="bubble"}){let[g,P]=useState(""),[L,B]=useState([]),[U,S]=useState(false),[k,h]=useState(false),[E,m]=useState(false),[c,I]=useState(false),[D,N]=useState(false),[R,x]=useState(false),[H,Z]=useState(false),[G,we]=useState(false),[j,ne]=useState(false),[fe,q]=useState(null),[ie,Ze]=useState(false),[xe,Ee]=useState([]),[me,$e]=useState(null),[He,Ce]=useState(false),[Re,Oe]=useState(false),[Xt,At]=useState(false),[_t,ve]=useState(null),[K,De]=useState(null),[Pe,Ct]=useState(false),[je,Qe]=useState(false),[Ie,ze]=useState(""),d=useRef(null),[u,M]=useState(null),[Q,V]=useState(false),[z,oe]=useState(null),[ae,ke]=useState([]),[X$1,le]=useState(null),[te,se]=useState(false),pe=useRef(false),de=useRef(null),ge=useRef(null),{resetAllForks:Be,previewSession:Y,currentContainerId:it}=ye(),Me=Y?.container_id??it,et=!!(Y&&Q),Ae=z!==null,Rr=useRef(y);useEffect(()=>{Rr.current=y;});let Jt=useRef(null),Rt=useRef(false),Er=typeof window<"u"&&"documentPictureInPicture"in window,Cn=async()=>{if(!(!Er||Ae))try{let a=await window.documentPictureInPicture.requestWindow({width:mn,height:640});a.document.body.style.margin="0",a.document.body.style.padding="0",a.document.body.style.height="100vh",a.document.body.style.overflow="hidden",a.document.body.style.background="#ffffff";try{let F=document.adoptedStyleSheets??[];F.length>0&&(a.document.adoptedStyleSheets=[...F]);}catch{}a.addEventListener("pagehide",()=>{Jt.current=null,oe(null),Rt.current||Rr.current(),Rt.current=!1;},{once:!0}),Jt.current=a,oe(a);}catch(a){console.warn("[Fork] PiP open failed:",a);}},Rn=()=>{z&&(Rt.current=true,z.close());};useEffect(()=>()=>{Rt.current=true,Jt.current?.close();},[]);let tt=i??o??"",En=(s||tt).replace(/[-_]+/g," ").replace(/\b\w/g,a=>a.toUpperCase()),Et=useRef(""),$r=()=>{let a={Authorization:`Bearer ${v}`,...re()};return b&&(a["X-Fork-App-Id"]=b),!Y&&_&&(a["X-Fork-User-Id"]=_),!Y&&C&&(a["X-Fork-User-Hash"]=C),a},rt=A?true:k&&!E,$n=r.find(a=>{let F=a.data;return a.type==="status"&&F.summary})?.data?.summary||t?.summary||Jo,Ke=r.find(a=>{let F=a.data;return (a.type==="status"||a.type==="complete")&&typeof F?.estimateMinutes=="number"})?.data?.estimateMinutes??t?.estimateMinutes;useEffect(()=>{if(l==="none"){S(true);return}if(!p||!v)return;if(!X$1){B([]),S(true);return}let a=new AbortController;return fetch(`${p}/api/v1/forks/${encodeURIComponent(X$1)}/messages`,{headers:$r(),signal:a.signal}).then(F=>F.ok?F.json():[]).then(F=>{if(a.signal.aborted)return;let T=[];for(let ue of F){let Te=ue.forkId??X$1;ue.role==="user"?T.push({type:"user",text:ue.content,forkId:Te}):T.push({type:"applied",text:ue.content,forkId:Te});}B(T),S(true);}).catch(()=>{a.signal.aborted||S(true);}),()=>{a.abort();}},[v,b,p,l,X$1,Y?.fork_id,Y?.preview_session_id,C,_,t?.id,t?.completedAt]),useEffect(()=>{if(l==="none"||!p||!v||!He)return;if(!me){ke([]);return}let a=new AbortController,F=new URLSearchParams({container_id:me});return fetch(`${p}/api/v1/forks?${F.toString()}`,{headers:$r(),signal:a.signal}).then(T=>T.ok?T.json():{forks:[]}).then(T=>{a.signal.aborted||ke(T.forks??[]);}).catch(()=>{}),()=>{a.abort();}},[v,b,p,l,me,He,t?.id,t?.completedAt,Y?.fork_id,Y?.preview_session_id,C,_]),useEffect(()=>{e==="complete"&&we(false);},[e]);let Pr=ae.some(a=>a.status==="pending"||a.status==="running"||a.status==="building");useEffect(()=>{if(!Pr||!p||!v||!me)return;let a=new URLSearchParams({container_id:me}),F={Authorization:`Bearer ${v}`,...re()};b&&(F["X-Fork-App-Id"]=b);let ue=setInterval(async()=>{try{let Te=await fetch(`${p}/api/v1/forks?${a.toString()}`,{headers:F});if(!Te.ok)return;let Mn=await Te.json();ke(Mn.forks??[]);}catch{}},3e3);return ()=>clearInterval(ue)},[Pr,p,v,b,me]),useEffect(()=>{if(A&&l==="none"){Ee([]),$e(null),Ce(true),V(false);return}if(Y){let a=false;return Ce(false),V(false),M(null),fetch(`${p}/api/v1/preview/${encodeURIComponent(Y.preview_session_id)}/containers`,{headers:{Authorization:`Bearer ${v}`,...re()}}).then(F=>{if(!F.ok)throw new Error(`${F.status}`);return F.json()}).then(F=>{a||(Ee(F.containers),$e(F.currentContainerId??Y.container_id??null),V(true));}).catch(F=>{a||(V(false),M(F instanceof Error?F.message:String(F)),Me?(Ee([{id:Me,name:Y.container_name||"Primary container",createdAt:"",hasAccess:true,isPrimary:true}]),$e(Me)):(Ee([]),$e(null)));}).finally(()=>{a||Ce(true);}),()=>{a=true;}}Me?(Ee([{id:Me,name:"Primary container",createdAt:""}]),$e(Me)):(Ee([]),$e(null)),Ce(true),V(false);},[v,Me,p,A,l,Y?.container_id,Y?.container_name,Y?.preview_session_id]);let $t=useRef(void 0);useEffect(()=>{if(He){if($t.current===void 0){$t.current=me;return}$t.current!==me&&($t.current=me,B([]),S(false));}},[me,He]);let Pt=useRef(null);useEffect(()=>{if(!Re)return;let a=T=>{if(!Pt.current)return;let ue=typeof T.composedPath=="function"?T.composedPath():[];Pt.current.contains(T.target)||ue.includes(Pt.current)||Oe(false);},F=T=>{T.key==="Escape"&&Oe(false);};return document.addEventListener("mousedown",a,true),document.addEventListener("keydown",F,true),()=>{document.removeEventListener("mousedown",a,true),document.removeEventListener("keydown",F,true);}},[Re]),useEffect(()=>{if(A||!rt||E||Ae)return;let a=F=>{(typeof F.composedPath=="function"?F.composedPath():[]).some(Te=>Te instanceof Element&&Te.hasAttribute("data-fork-panel-host"))||(m(true),h(false),setTimeout(()=>y(),yt));};return document.addEventListener("mousedown",a,true),()=>{document.removeEventListener("mousedown",a,true);}},[A,rt,E,Ae,y]),useEffect(()=>{Re||(Qe(false),ze(""));},[Re]),useEffect(()=>{je&&(d.current?.focus(),d.current?.select());},[je]),useEffect(()=>{if(A)return;let a=requestAnimationFrame(()=>h(true));return ()=>cancelAnimationFrame(a)},[A]),useEffect(()=>{let a=A||Ae;if((a||rt)&&(e==="prompting"||e==="complete")){let F=setTimeout(()=>de.current?.focus(),a?100:yt+100);return ()=>clearTimeout(F)}},[rt,A,Ae,e]),useEffect(()=>{if(e==="complete"&&Et.current){let F=r.find(T=>T.type==="complete")?.data?.summary||t?.summary||Go;B(T=>T[T.length-1]?.type==="applied"?T:[...T,{type:"applied",text:F}]),P(""),setTimeout(()=>de.current?.focus(),200);}},[e,En,r,t?.summary]),useEffect(()=>{ge.current&&(ge.current.scrollTop=ge.current.scrollHeight);},[L,e]);let Ir=()=>{if(g.trim()){Et.current=g.trim();let a={},F=te||!X$1;F?(a.forceNew=true,pe.current=true,te||se(true)):a.forkId=X$1,F||B(T=>[...T,{type:"user",text:g.trim(),forkId:X$1}]),f(g.trim(),tt,me,a),P("");}};useEffect(()=>{if(pe.current){if(e==="error"){pe.current=false;return}t?.id&&(le(t.id),se(false),pe.current=false);}},[t?.id,e]),useEffect(()=>{t?.id&&(pe.current||e!=="running"&&e!=="complete"||(le(a=>a??t.id),se(false)));},[t?.id,e]);let Mr=a=>{Ve(a.session.containerId,a.session.containerName),$e(a.session.containerId),Ee(F=>{let T=F.filter(ue=>ue.id!==a.container.id);return [{...a.container,isPrimary:true,hasAccess:true},...T.map(ue=>({...ue,isPrimary:false}))]}),le(null),se(false),pe.current=false,B([]),S(false),Et.current="";},Pn=async a=>{if(!(!Y||!et||K)){De(a),M(null);try{let F=await fetch(`${p}/api/v1/preview/${encodeURIComponent(Y.preview_session_id)}/containers/${encodeURIComponent(a)}/primary`,{method:"POST",headers:{Authorization:`Bearer ${v}`,...re()}});if(!F.ok){let T=await F.json().catch(()=>({}));throw new Error(T.error||`API error: ${F.status}`)}Mr(await F.json()),Oe(!1);}catch(F){M(F instanceof Error?F.message:String(F));}finally{De(null);}}},Tr=async a=>{if(!Y||!et||K)return;let F=a.trim();if(F){De("__new__"),M(null);try{let T=await fetch(`${p}/api/v1/preview/${encodeURIComponent(Y.preview_session_id)}/containers`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${v}`,...re()},body:JSON.stringify({name:F})});if(!T.ok){let ue=await T.json().catch(()=>({}));throw new Error(ue.error||`API error: ${T.status}`)}Mr(await T.json()),Qe(!1),ze(""),Oe(!1);}catch(T){M(T instanceof Error?T.message:String(T));}finally{De(null);}}},Lr=async()=>{if(!(!w||j||!tt)){ne(true);try{let a=await w(tt);B(F=>{let T=[...F];return T.length>=2&&T[T.length-1]?.type==="applied"?T.splice(-2,2):T.length>=1&&T[T.length-1]?.type==="applied"&&T.splice(-1,1),T}),a?.removed&&B([]);}catch{}finally{ne(false);}}},Br=()=>{if(A){y();return}if(Ae){z?.close();return}m(true),h(false),setTimeout(()=>y(),yt);},In=A||Ae?{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:mn,maxWidth:"100vw",background:"#ffffff",boxShadow:rt?"-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:rt?"translateX(0)":"translateX(100%)",transition:`transform ${yt}ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow ${yt}ms ease`,display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'},Nr=xe.find(a=>a.id===me)?.name??(He?"Fork":"Loading..."),at=te?[]:X$1?L.filter(a=>a.forkId===X$1||a.forkId==null):L,Gt=jsxs(Fragment,{children:[jsx("style",{children:`
|
|
38
38
|
@keyframes __fork-pulse {
|
|
39
39
|
0%, 100% { opacity: 1; }
|
|
40
40
|
50% { opacity: 0.5; }
|
|
@@ -56,5 +56,5 @@ import*as ir from'react';import ir__default,{createContext,useSyncExternalStore,
|
|
|
56
56
|
scrollbar-width: thin;
|
|
57
57
|
scrollbar-color: rgba(0, 0, 0, 0.12) transparent;
|
|
58
58
|
}
|
|
59
|
-
`}),jsxs("div",{className:"__fork-panel",style:Pn,children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderBottom:"1px solid rgba(229, 231, 235, 0.8)",flexShrink:0},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:[jsx("span",{onDoubleClick:async a=>{if(a.stopPropagation(),!ie&&confirm("Kill all forks in this container?")){Ze(true);try{let F=await Be();`${F?.deleted??0}`,ke([]),le(null),se(!1),P("");}catch(F){console.error("[Fork] Reset failed:",F);}finally{Ze(false);}}},style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:4,margin:-4,cursor:"pointer",flexShrink:0},children:jsx(Ht,{style:{width:16,height:16,color:"#1c4587",pointerEvents:"none"}})}),e==="running"?jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:En}):xe.length===0&&!et?jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:"Fork"}):et?jsxs("div",{ref:$t,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[jsxs("button",{type:"button",onClick:()=>{Oe(a=>!a);},onMouseEnter:()=>xt(true),onMouseLeave:()=>xt(false),"aria-haspopup":"menu","aria-expanded":Re,style:{display:"inline-flex",alignItems:"center",gap:4,padding:"3px 6px",border:"1px solid transparent",borderRadius:6,background:Vt||Re?"#f3f4f6":"transparent",fontSize:13,fontWeight:600,color:"#111827",fontFamily:"inherit",cursor:"pointer",maxWidth:180,minWidth:0,transition:"background-color 0.12s"},children:[jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:Br}),jsx(ChevronDown,{style:{width:12,height:12,color:"#6b7280",flexShrink:0,transform:Re?"rotate(180deg)":void 0,transition:"transform 0.15s"}})]}),Re&&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:[xe.map(a=>{let F=a.id===me,T=At===a.id,ue=K===a.id;return jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>ve(a.id),onMouseLeave:()=>ve(null),onClick:()=>{a.id!==me&&$n(a.id);},disabled:!!K,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:T?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:K?"default":"pointer",textAlign:"left",fontWeight:F?600:400,opacity:K&&!ue?.55:1},children:[jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:F&&jsx(Check,{style:{width:12,height:12}})}),jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:ue?"Switching...":a.name})]},a.id)}),jsx("div",{style:{height:1,background:"#e5e7eb",margin:"4px 0"}}),je?jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"4px 4px"},children:[jsx("input",{ref:d,type:"text",value:Ie,placeholder:"Container name",disabled:K==="__new__",onChange:a=>ze(a.target.value),onKeyDown:a=>{a.key==="Enter"?(a.preventDefault(),Mr(Ie)):a.key==="Escape"&&(a.preventDefault(),a.stopPropagation(),Qe(false),ze(""));},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:a=>{a.currentTarget.style.borderColor="#1c4587",a.currentTarget.style.boxShadow="0 0 0 2px rgba(28,69,135,0.15)";},onBlur:a=>{a.currentTarget.style.borderColor="#d1d5db",a.currentTarget.style.boxShadow="none";}}),jsx("button",{type:"button",onClick:()=>{Mr(Ie);},disabled:!Ie.trim()||K==="__new__",title:"Create",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:26,height:26,border:"none",borderRadius:4,background:!Ie.trim()||K==="__new__"?"#e5e7eb":"#1c4587",color:!Ie.trim()||K==="__new__"?"#9ca3af":"#ffffff",cursor:!Ie.trim()||K==="__new__"?"default":"pointer",flexShrink:0},children:K==="__new__"?jsx("span",{style:{width:10,height:10,border:"1.5px solid currentColor",borderTopColor:"transparent",borderRadius:"50%",animation:"__fork-spin 0.7s linear infinite"}}):jsx(Check,{style:{width:12,height:12}})})]}):jsx("button",{type:"button",role:"menuitem",onMouseEnter:()=>_t(true),onMouseLeave:()=>_t(false),onClick:()=>{K||(M(null),ze(""),Qe(true));},disabled:!!K,style:{display:"flex",alignItems:"center",width:"100%",padding:"6px 8px",border:"none",background:Pe?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:K?"default":"pointer",textAlign:"left",opacity:K&&K!=="__new__"?.55:1},children:"+ New container"}),u&&jsx("div",{style:{padding:"6px 8px",fontSize:11,lineHeight:1.35,color:"#b91c1c"},children:u})]})]}):jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:Br}),e==="running"&&jsx("span",{title:Ke?`Estimated ~${Ke} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:Ke?"#1c4587":"#9ca3af",backgroundColor:Ke?"rgba(28, 69, 135, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:Ke?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:Ke?`~${Ke}m`:"~ m"})]}),!A&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[Rr&&jsx("button",{onClick:Ae?Cn:_n,onMouseEnter:()=>N(true),onMouseLeave:()=>N(false),title:Ae?"Redock to sidebar":"Pop out into window",style:{padding:6,borderRadius:6,color:D?"#4b5563":"#9ca3af",backgroundColor:D?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:Ae?jsx(PictureInPicture,{style:{width:16,height:16}}):jsx(PictureInPicture2,{style:{width:16,height:16}})}),jsx("button",{onClick:Lr,onMouseEnter:()=>I(true),onMouseLeave:()=>I(false),style:{padding:6,borderRadius:6,color:c?"#4b5563":"#9ca3af",backgroundColor:c?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:jsx(X,{style:{width:16,height:16}})})]})]}),jsxs("div",{ref:ge,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[(X$1||te)&&jsxs("div",{style:{padding:"10px 12px 6px 12px",display:"flex",alignItems:"center",gap:8,borderBottom:"1px solid #f3f4f6"},children:[jsx("button",{onClick:()=>{le(null),se(false),pe.current=false;},style:{fontSize:12,color:"#374151",background:"transparent",border:"none",padding:"2px 4px",cursor:"pointer",display:"inline-flex",alignItems:"center",gap:4},title:"Back to all forks",children:"\u2190 All forks"}),(()=>{let F=(X$1?ae.find(T=>T.id===X$1)?.targetId:null)??tt;return F?jsxs("span",{style:{fontSize:11,color:"#9ca3af",fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, "Liberation Mono", "Courier New", monospace',whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1},title:`Forking ${F}`,children:["Forking ",jsx("span",{style:{color:"#6b7280"},children:F})]}):null})()]}),!X$1&&!te&&jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[jsx("div",{style:{padding:"12px 16px 10px 16px",borderBottom:"1px solid #f3f4f6"},children:jsx("span",{style:{fontSize:12,fontWeight:600,color:"#111827"},children:"Forks"})}),ae.length===0&&jsx("div",{style:{padding:"24px 20px",textAlign:"center",fontSize:13,color:"#6b7280"},children:"No forks yet. Describe a feature below to start one."}),ae.length>0&&jsx("div",{style:{display:"flex",flexDirection:"column"},children:ae.map(a=>{let F=a.summary||"Untitled fork";return jsxs("button",{onClick:()=>{se(false),le(a.id);},style:{textAlign:"left",padding:"10px 16px",background:"#ffffff",border:"none",borderBottom:"1px solid #f3f4f6",cursor:"pointer",display:"flex",flexDirection:"column",gap:2},onMouseEnter:T=>T.currentTarget.style.background="#fafafa",onMouseLeave:T=>T.currentTarget.style.background="#ffffff",children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[jsx("span",{style:{fontSize:13,fontWeight:500,color:"#111827",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1},children:F}),jsx("span",{style:{fontSize:11,color:"#9ca3af",flexShrink:0},children:Go(a.updatedAt)})]}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:11,color:"#6b7280"},children:[jsx("span",{style:{fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, "Liberation Mono", "Courier New", monospace',whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:a.targetId}),jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),jsxs("span",{children:[a.promptCount," prompt",a.promptCount===1?"":"s"]}),a.status==="running"||a.status==="building"?jsxs(Fragment,{children:[jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),jsx("span",{style:{color:"#2563eb"},children:"running"})]}):null]})]},a.id)})})]}),X$1&&at.length>0&&jsx("div",{style:{padding:"16px 16px 0 16px"},children:at.map((a,F)=>jsx("div",{style:{marginBottom:F<at.length-1?10:0},children:a.type==="user"?jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexDirection:"row-reverse"},children:[jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:jsx(User,{style:{width:13,height:13,color:"#6b7280"}})}),jsx("div",{style:{backgroundColor:"#f3f4f6",borderRadius:"12px 4px 12px 12px",padding:"8px 12px",fontSize:13,color:"#374151",lineHeight:1.5,maxWidth:"75%"},children:a.text})]}):O==="item"&&F===at.length-1?jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:12,padding:12,borderRadius:8,border:"1px solid #e4e4e7",background:"#ffffff"},children:[jsx("div",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,flexShrink:0,borderRadius:6,background:"#f4f4f5",color:"#0a0a0a"},children:jsx(BadgeCheck,{style:{width:16,height:16}})}),jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,flex:1,minWidth:0},children:[jsx("div",{style:{fontSize:13,fontWeight:500,color:"#0a0a0a",lineHeight:1.3},children:"Feature applied"}),jsx("div",{style:{fontSize:13,color:"#71717a",lineHeight:1.4},children:a.text})]}),w&&e!=="running"&&jsx("button",{onClick:T=>{T.stopPropagation(),Tr();},disabled:j,style:{padding:"4px 10px",fontSize:12,fontWeight:500,borderRadius:6,border:"1px solid #e4e4e7",background:"#ffffff",color:"#0a0a0a",cursor:j?"default":"pointer",opacity:j?.4:1,height:28,flexShrink:0},children:"Undo"})]}):jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#f0fdf4",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:jsx(Check,{style:{width:13,height:13,color:"#9ca3af"}})}),jsxs("div",{style:{backgroundColor:"#f9fafb",borderRadius:"4px 12px 12px 12px",padding:"8px 12px",fontSize:13,color:"#6b7280",fontWeight:500,display:"flex",alignItems:"center",gap:6,maxWidth:"75%"},children:[jsx("span",{style:{flex:1},children:a.text}),w&&F===at.length-1&&e!=="running"&&jsxs("button",{onClick:T=>{T.stopPropagation(),Tr();},onMouseEnter:()=>q(F),onMouseLeave:()=>q(null),disabled:j,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:fe===F?"rgba(0,0,0,0.06)":"transparent",color:fe===F?"#6b7280":"#d1d5db",cursor:j?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:j?.4:1,flexShrink:0},children:[jsx(Undo2,{style:{width:12,height:12}}),fe===F&&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"})]})]})]})},F))}),e==="running"&&(X$1||te)&&jsx("div",{style:{padding:16},children:jsxs("div",{onClick:()=>we(!G),style:{backgroundColor:"#1a1a2e",borderRadius:12,overflow:"hidden",cursor:"pointer",transition:"all 0.3s cubic-bezier(0.22, 1, 0.36, 1)"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"#6b7280",strokeWidth:"2.5",strokeLinecap:"round",style:{animation:"__fork-spin 2s linear infinite",flexShrink:0},children:jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),jsx(Yo,{events:r})]}),jsx("div",{style:{color:"#6b7280",flexShrink:0,marginLeft:8,transition:"transform 0.2s ease",transform:G?"rotate(180deg)":"rotate(0deg)"},children:jsx(ChevronDown,{style:{width:14,height:14}})})]}),jsx("div",{style:{maxHeight:G?320:0,opacity:G?1:0,transition:"max-height 0.35s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.25s ease",overflow:"hidden"},children:jsx("div",{style:{borderTop:"1px solid rgba(255,255,255,0.08)",maxHeight:320,overflowY:"auto"},children:jsx(cn,{events:r})})})]})}),e==="error"&&(X$1||te)&&jsxs("div",{style:{padding:"20px 16px",textAlign:"center"},children:[jsx("div",{style:{width:36,height:36,backgroundColor:"#fef2f2",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 10px auto"},children:jsx(X,{style:{width:18,height:18,color:"#ef4444"}})}),jsx("p",{style:{fontSize:12,color:"#6b7280",marginBottom:10,maxWidth:260,margin:"0 auto 10px auto"},children:n}),jsxs("button",{onClick:()=>{let a=t?.prompt||Rt.current;a&&f(a,tt);},onMouseEnter:()=>Z(true),onMouseLeave:()=>Z(false),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,color:"#4f46e5",backgroundColor:H?"#e0e7ff":"#eef2ff",border:"none",cursor:"pointer",transition:"background-color 0.15s",fontFamily:"inherit"},children:[jsx(RotateCcw,{style:{width:12,height:12}})," Try Again"]})]})]}),e!=="running"&&jsx("div",{style:{padding:"8px 12px 12px 12px",borderTop:"1px solid rgba(229, 231, 235, 0.6)",flexShrink:0},children:jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,borderRadius:12,padding:"8px 8px 8px 12px",background:"rgba(0, 0, 0, 0.04)",border:"1px solid rgba(0, 0, 0, 0.06)"},children:[jsx("textarea",{ref:de,value:g,onChange:a=>{P(a.target.value),a.target.style.height="auto",a.target.style.height=Math.min(a.target.scrollHeight,160)+"px";},onKeyDown:a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),Pr()),a.key==="Escape"&&!A&&Lr();},placeholder:X$1?"Iterate on this feature...":"Start building a new Fork...",rows:1,style:{flex:1,backgroundColor:"transparent",fontSize:13,color:"#111827",border:"none",outline:"none",padding:"0 4px 0 0",fontFamily:"inherit",resize:"none",lineHeight:1.5,maxHeight:160,overflow:"auto"}}),jsx("button",{onClick:Pr,disabled:!g.trim(),onMouseEnter:()=>x(true),onMouseLeave:()=>x(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:g.trim()?1:.25,transform:R&&g.trim()?"scale(1.1)":"scale(1)",background:g.trim()?"#1c4587":"rgba(0,0,0,0.12)",border:"none",cursor:g.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:jsx(ArrowUp,{style:{width:13,height:13}})})]})})]})]});return A?Jt:Ae&&z?createPortal(Jt,z.document.body):jsx(Zo,{children:Jt})}function hn(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 gr(e){let{apiKey:t,userId:r,userHash:n,baseUrl:o,appId:i,previewSession:s,refreshModuleManifest:l,queueBoundaryAnimation:f,trackForkActivity:w,recordForkActivityEvent:y}=ye(),[p,v]=useState("idle"),[_,C]=useState(null),[b,A]=useState([]),[O,g]=useState(null),P=useRef(null),L=useCallback(()=>{v("prompting"),A([]),g(null),C(null);},[]),B=useCallback(()=>{v("idle"),P.current&&(P.current.close(),P.current=null);},[]);useEffect(()=>{s&&s.target.kind==="module"&&s.target.id===e&&v(h=>h==="idle"?"prompting":h);},[s?.preview_session_id,s?.target.id,e]);let U=useCallback(async(h,E,m)=>{try{if(!i)throw new Error("ForkProvider requires appId for module boundary prompts.");v("running"),A([]),g(null),C(null);let c;if(s){let N=m?.forkId??s.fork_id??void 0,R=await fetch(`${o}/api/v1/preview/${encodeURIComponent(s.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...re()},body:JSON.stringify({prompt:h,...e?{boundary_id:e}:{},...N&&!m?.forceNew?{fork_id:N}:{},...m?.forceNew?{force_new:!0}:{}})});if(!R.ok){let Z=await R.json().catch(()=>({}));throw new Error(Z.error||`API error: ${R.status}`)}let x=await R.json();x.container_id&&Ve(x.container_id,x.container_name),lt(x.fork_id),c=await(await fetch(`${o}/api/v1/forks/${x.fork_id}`,{headers:{Authorization:`Bearer ${t}`,...re()}})).json();}else if(m?.forkId){let N={prompt:h};r&&(N.userId=r),n&&(N.userHash=n);let R=await fetch(`${o}/api/v1/forks/${encodeURIComponent(m.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(N)});if(!R.ok){let x=await R.json().catch(()=>({}));throw new Error(x.error||`API error: ${R.status}`)}c=await R.json();}else {let N={userId:r,prompt:h,boundaryId:e,appId:i};E&&(N.containerId=E),n&&(N.userHash=n),m?.forceNew&&(N.force_new=!0);let R=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(N)});if(!R.ok){let x=await R.json().catch(()=>({}));throw new Error(x.error||`API error: ${R.status}`)}c=await R.json();}C(c),w(c,{targetKind:"module",targetId:e});let I=new URLSearchParams({key:t});s?(I.set("previewSessionId",s.preview_session_id),I.set("previewForkId",c.id)):r&&I.set("userId",r),n&&I.set("userHash",n);let D=new EventSource(`${o}/api/v1/forks/${c.id}/events?${I.toString()}`);P.current=D,D.onmessage=N=>{try{let R=JSON.parse(N.data);if(y(c.id,R),A(x=>[...x,R]),R.type==="complete"){let x=R.data;f(e,c.id),l().catch(()=>{}).finally(()=>{let H={...c,status:"complete",moduleUrl:x.moduleUrl,cssUrls:x.cssUrls,summary:x.summary,completedAt:new Date().toISOString()};C(H),v("complete"),D.close();});}else if(R.type==="error"){let x=R.data;g(x.error||"Unknown error"),v("error"),D.close();}}catch{}},D.onerror=()=>{let N={Authorization:`Bearer ${t}`,...re()};!s&&r&&(N["X-Fork-User-Id"]=r),!s&&n&&(N["X-Fork-User-Hash"]=n),fetch(`${o}/api/v1/forks/${c.id}`,{headers:N}).then(R=>R.json()).then(R=>{C(R),R.status==="complete"?(f(e,R.id),l().catch(()=>{}),v("complete")):R.status==="error"&&(g(R.error||"Fork generation failed"),v("error"));}).catch(()=>{g("Connection lost"),v("error");}),D.close();};}catch(c){g(c.message),v("error");}},[t,i,o,e,s,f,l,y,w,n,r]),S=useCallback(async h=>{try{let E={Authorization:`Bearer ${t}`,...re()};!s&&r&&(E["X-Fork-User-Id"]=r),!s&&n&&(E["X-Fork-User-Hash"]=n);let m=await fetch(`${o}/api/v1/forks/${h}`,{headers:E});if(!m.ok)return;let c=await m.json(),I=c.boundaryId??e;if(w(c,{targetKind:"module",targetId:I}),c.status==="complete"){v("complete"),C(c),g(null),A([]);return}if(c.status==="error"){v("error"),C(c),g(c.error||"Fork generation failed"),A([]);return}if(c.status!=="pending"&&c.status!=="running"&&c.status!=="building")return;v("running"),C(c),g(null),A([]);let D=new URLSearchParams({key:t});s?(D.set("previewSessionId",s.preview_session_id),D.set("previewForkId",c.id)):r&&D.set("userId",r),n&&D.set("userHash",n);let N=new EventSource(`${o}/api/v1/forks/${c.id}/events?${D.toString()}`);P.current&&P.current.close(),P.current=N,N.onmessage=R=>{try{let x=JSON.parse(R.data);if(y(c.id,x),A(H=>[...H,x]),x.type==="complete"){let H=x.data;f(e,c.id),l().catch(()=>{}).finally(()=>{let Z={...c,status:"complete",moduleUrl:H.moduleUrl,cssUrls:H.cssUrls,summary:H.summary,completedAt:new Date().toISOString()};C(Z),v("complete"),N.close();});}else if(x.type==="error"){let H=x.data;g(H.error||"Unknown error"),v("error"),N.close();}}catch{}},N.onerror=()=>{N.close();};}catch{}},[t,o,e,s,f,y,l,w,n,r]),k=useCallback(async()=>{try{if(!i)throw new Error("ForkProvider requires appId for boundary undo.");let h={userId:r,boundaryId:e,appId:i};n&&(h.userHash=n);let E=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(h)});if(!E.ok){let c=await E.json().catch(()=>({}));throw new Error(c.error||`API error: ${E.status}`)}let m=await E.json();return await l().catch(()=>{}),m.removed?(C(null),v("prompting")):m.fork&&(C(m.fork),v("complete")),m}catch(h){throw g(h.message),h}},[t,i,o,e,l,n,r]);return {state:p,fork:_,events:b,error:O,open:L,close:B,startFork:U,undoFork:k,adoptRunningFork:S}}function yn(e){let{state:t,fork:r,events:n,error:o,open:i,close:s,startFork:l,undoFork:f,adoptRunningFork:w}=gr(e),[y,p]=useState(false),v=useCallback(()=>{p(true),i();},[i]),_=useCallback(()=>{p(false),s();},[s]),C=useCallback(async b=>{p(true),await w(b);},[w]);return {state:t,fork:r,events:n,error:o,isOpen:y,open:v,close:_,submit:l,undo:f,adoptRunningFork:C}}function yr(){let{apiKey:e,userId:t,userHash:r,baseUrl:n,previewSession:o,setSlotFork:i,clearSlotFork:s,skipAnimationForSlot:l,trackForkActivity:f,recordForkActivityEvent:w}=ye(),[y,p]=useState("idle"),[v,_]=useState(null),[C,b]=useState([]),[A,O]=useState(null),g=useRef(null),P=useCallback(()=>{p("prompting"),b([]),O(null),_(null);},[]),L=useCallback(()=>{p("idle"),g.current&&(g.current.close(),g.current=null);},[]);useEffect(()=>{o&&o.target.kind==="slot"&&p(k=>k==="idle"?"prompting":k);},[o?.preview_session_id,o?.target.kind]);let B=useCallback(async(k,h,E,m)=>{try{p("running"),b([]),O(null),_(null);let c;if(o){let R=m?.forkId??o.fork_id??void 0,x=await fetch(`${n}/api/v1/preview/${encodeURIComponent(o.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...re()},body:JSON.stringify({prompt:k,...h?{slot_id:h}:{},...R&&!m?.forceNew?{fork_id:R}:{},...m?.forceNew?{force_new:!0}:{}})});if(!x.ok){let G=await x.json().catch(()=>({}));throw new Error(G.error||`API error: ${x.status}`)}let H=await x.json();H.container_id&&Ve(H.container_id,H.container_name),lt(H.fork_id),c=await(await fetch(`${n}/api/v1/forks/${H.fork_id}`,{headers:{Authorization:`Bearer ${e}`,...re()}})).json();}else if(m?.forkId){let R={prompt:k};t&&(R.userId=t),r&&(R.userHash=r);let x=await fetch(`${n}/api/v1/forks/${encodeURIComponent(m.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(R)});if(!x.ok){let H=await x.json().catch(()=>({}));throw new Error(H.error||`API error: ${x.status}`)}c=await x.json();}else {let R={userId:t,prompt:k};h&&(R.slotId=h),E&&(R.containerId=E),r&&(R.userHash=r),m?.forceNew&&(R.force_new=!0);let x=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(R)});if(!x.ok){let H=await x.json().catch(()=>({}));throw new Error(H.error||`API error: ${x.status}`)}c=await x.json();}_(c);let I=h??c.slotId;I&&f(c,{targetKind:"slot",targetId:I});let D=new URLSearchParams({key:e});o?(D.set("previewSessionId",o.preview_session_id),D.set("previewForkId",c.id)):t&&D.set("userId",t),r&&D.set("userHash",r);let N=new EventSource(`${n}/api/v1/forks/${c.id}/events?${D.toString()}`);g.current=N,N.onmessage=R=>{try{let x=JSON.parse(R.data);if(w(c.id,x),b(H=>[...H,x]),x.type==="complete"){let H=x.data,Z={...c,status:"complete",bundleUrl:H.bundleUrl,summary:H.summary,completedAt:new Date().toISOString()};_(Z),p("complete"),h&&H.bundleUrl&&i(h,Z),N.close();}else if(x.type==="error"){let H=x.data;O(H.error||"Unknown error"),p("error"),N.close();}}catch{}},N.onerror=()=>{let R={Authorization:`Bearer ${e}`,...re()};!o&&t&&(R["X-Fork-User-Id"]=t),!o&&r&&(R["X-Fork-User-Hash"]=r),fetch(`${n}/api/v1/forks/${c.id}`,{headers:R}).then(x=>x.json()).then(x=>{_(x),x.status==="complete"?(p("complete"),h&&x.bundleUrl&&i(h,x)):x.status==="error"&&(O(x.error||"Fork generation failed"),p("error"));}).catch(()=>{O("Connection lost"),p("error");}),N.close();};}catch(c){O(c.message),p("error");}},[e,n,o,w,i,f,r,t]),U=useCallback(async k=>{try{let h={Authorization:`Bearer ${e}`,...re()};!o&&t&&(h["X-Fork-User-Id"]=t),!o&&r&&(h["X-Fork-User-Hash"]=r);let E=await fetch(`${n}/api/v1/forks/${k}`,{headers:h});if(!E.ok)return;let m=await E.json();if(m.slotId&&f(m,{targetKind:"slot",targetId:m.slotId}),m.status==="complete"){p("complete"),_(m),O(null),b([]);return}if(m.status==="error"){p("error"),_(m),O(m.error||"Fork generation failed"),b([]);return}if(m.status!=="pending"&&m.status!=="running"&&m.status!=="building")return;p("running"),_(m),O(null),b([]);let c=new URLSearchParams({key:e});o?(c.set("previewSessionId",o.preview_session_id),c.set("previewForkId",m.id)):t&&c.set("userId",t),r&&c.set("userHash",r);let I=new EventSource(`${n}/api/v1/forks/${m.id}/events?${c.toString()}`);g.current&&g.current.close(),g.current=I;let D=m.slotId;I.onmessage=N=>{try{let R=JSON.parse(N.data);if(w(m.id,R),b(x=>[...x,R]),R.type==="complete"){let x=R.data,H={...m,status:"complete",bundleUrl:x.bundleUrl,summary:x.summary,completedAt:new Date().toISOString()};_(H),p("complete"),D&&x.bundleUrl&&i(D,H),I.close();}else if(R.type==="error"){let x=R.data;O(x.error||"Unknown error"),p("error"),I.close();}}catch{}},I.onerror=()=>{I.close();};}catch{}},[e,n,o,w,i,f,r,t]),S=useCallback(async k=>{try{let h={userId:t,slotId:k};r&&(h.userHash=r);let E=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(h)});if(!E.ok){let c=await E.json().catch(()=>({}));throw new Error(c.error||`API error: ${E.status}`)}let m=await E.json();return l(k),m.removed?(s(k),_(null),p("prompting")):m.fork&&(i(k,m.fork),_(m.fork)),m}catch(h){throw O(h.message),h}},[e,t,r,n,s,i]);return {state:y,fork:v,events:C,error:A,open:P,close:L,startFork:B,undoFork:S,adoptRunningFork:U}}function kn(){let{state:e,fork:t,events:r,error:n,open:o,close:i,startFork:s,undoFork:l,adoptRunningFork:f}=yr(),[w,y]=useState(false),p=useCallback(()=>{y(true),o();},[o]),v=useCallback(()=>{y(false),i();},[i]),_=useCallback(async C=>{y(true),await f(C);},[f]);return {state:e,fork:t,events:r,error:n,isOpen:w,open:p,close:v,submit:s,undo:l,adoptRunningFork:_}}var ss=new Set(["pending","running","building"]);function wr(e){let t=hn(e),r=kn(),n=yn(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:i,userId:s,userHash:l,appId:f,activitySummary:w,forkActivities:y,markForkActivitySeen:p}=ye(),v=t.type==="slot"?r:n,_=t.type==="slot"?"slot":"boundary",C=t.id,b=t.title,A=t.type==="slot"?"slot":"module",O=y.find(U=>U.targetKind===A&&U.targetId===t.id&&ss.has(U.status)),g=y.find(U=>U.targetKind===A&&U.targetId===t.id&&U.status==="complete"&&U.unread),P=useCallback(()=>{p();let U=O??g;if(U){v.adoptRunningFork(U.id);return}v.open();},[v,p,O,g]),L=useCallback((U,S,k,h)=>t.type==="slot"?r.submit(U,S??t.id,k,h):n.submit(U,k,h),[n,r,t]),B=useCallback(U=>t.type==="slot"?r.undo(U??t.id):n.undo(),[n,r,t]);return {...v,open:P,target:t,targetId:C,targetLabel:b,historyMode:_,submit:L,undo:B,buttonProps:{onClick:P,hasNotification:w.unreadCompletedCount>0,activity:w},panelProps:{state:v.state,fork:v.fork,events:v.events,error:v.error,...t.type==="slot"?{slotId:C,targetLabel:b,historyMode:_}:{targetId:C,targetLabel:b,historyMode:_},onSubmit:L,onUndo:B,onClose:v.close,baseUrl:o,apiKey:i,userId:s,userHash:l,appId:f}}}function wt(e){let{embedded:t,completeVariant:r}=e,n=wr(e);return t?jsx(zt,{...n.panelProps,embedded:true,completeVariant:r}):n.isOpen?jsx(zt,{...n.panelProps,completeVariant:r}):jsx(ur,{...n.buttonProps})}function is({boundaryId:e,title:t}){return jsx(wt,{boundaryId:e,title:t})}function Sr(e){let t=Array.from(e.children).filter(n=>n instanceof HTMLElement);return t.length===1?t[0]:getComputedStyle(e).display==="contents"?null:e}function bn(e){let t=e.getBoundingClientRect(),r=e.cloneNode(true);r.setAttribute("data-fork-clone-overlay","true"),r.style.position="fixed",r.style.top=`${t.top}px`,r.style.left=`${t.left}px`,r.style.width=`${t.width}px`,r.style.height=`${t.height}px`,r.style.flex="none",r.style.minHeight="auto",r.style.zIndex="9998",r.style.pointerEvents="none",r.style.overflow="hidden";let n=getComputedStyle(e).backgroundColor;r.style.backgroundColor=n&&n!=="rgba(0, 0, 0, 0)"&&n!=="transparent"?n:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(r);let o=e.querySelectorAll("*"),i=r.querySelectorAll("*");for(let s=0;s<o.length;s+=1)o[s].scrollTop!==0&&(i[s].scrollTop=o[s].scrollTop),o[s].scrollLeft!==0&&(i[s].scrollLeft=o[s].scrollLeft);return r}function Fr(e){let t=[],r=e.querySelectorAll("*");for(let n of r){if(!(n instanceof HTMLElement))continue;let o=n.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(n.tagName))continue;let i=getComputedStyle(n),s=parseFloat(i.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:s});}return t}function wn(e,t){let r=[];for(let n of t)if(!(e.find(s=>s.tag===n.tag&&s.className===n.className&&Math.abs(s.rect.top-n.rect.top)<20&&Math.abs(s.rect.left-n.rect.left)<20)||r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom))){for(let s=r.length-1;s>=0;s-=1){let l=r[s];l.rect.top>=n.rect.top&&l.rect.left>=n.rect.left&&l.rect.right<=n.rect.right&&l.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function vn(e,t){let r=[];for(let n of e)if(!(t.find(s=>s.tag===n.tag&&s.className===n.className&&Math.abs(s.rect.top-n.rect.top)<20&&Math.abs(s.rect.left-n.rect.left)<20)||r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom))){for(let s=r.length-1;s>=0;s-=1){let l=r[s];l.rect.top>=n.rect.top&&l.rect.left>=n.rect.left&&l.rect.right<=n.rect.right&&l.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Sn(e,t,r,n,o){let i=Math.max(0,Math.min(o,r/2,n/2));return i===0?`M ${e} ${t} L ${e+r} ${t} L ${e+r} ${t+n} L ${e} ${t+n} Z`:[`M ${e+i} ${t}`,`L ${e+r-i} ${t}`,`A ${i} ${i} 0 0 1 ${e+r} ${t+i}`,`L ${e+r} ${t+n-i}`,`A ${i} ${i} 0 0 1 ${e+r-i} ${t+n}`,`L ${e+i} ${t+n}`,`A ${i} ${i} 0 0 1 ${e} ${t+n-i}`,`L ${e} ${t+i}`,`A ${i} ${i} 0 0 1 ${e+i} ${t}`,"Z"].join(" ")}function xr(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-highlights","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");n.appendChild(o);let i=[];for(let y=0;y<e.length;y+=1){let{rect:p,borderRadius:v}=e[y],_=p.left-.5,C=p.top-.5,b=p.width+1,A=p.height+1,O=Math.min(v+.5,b/2,A/2),g=Sn(_,C,b,A,O),P=`__fork-glow-${y}`,L=document.createElementNS(t,"filter");L.setAttribute("id",P),L.setAttribute("x","-100%"),L.setAttribute("y","-100%"),L.setAttribute("width","300%"),L.setAttribute("height","300%");let B=document.createElementNS(t,"feGaussianBlur");B.setAttribute("in","SourceGraphic"),B.setAttribute("stdDeviation","8"),L.appendChild(B),o.appendChild(L);let U=`__fork-mask-${y}`,S=document.createElementNS(t,"mask");S.setAttribute("id",U),S.setAttribute("maskUnits","userSpaceOnUse"),S.setAttribute("x",String(_-200)),S.setAttribute("y",String(C-200)),S.setAttribute("width",String(b+400)),S.setAttribute("height",String(A+400));let k=document.createElementNS(t,"rect");k.setAttribute("x",String(_-200)),k.setAttribute("y",String(C-200)),k.setAttribute("width",String(b+400)),k.setAttribute("height",String(A+400)),k.setAttribute("fill","white"),S.appendChild(k);let h=document.createElementNS(t,"path");h.setAttribute("d",g),h.setAttribute("fill","black"),S.appendChild(h),o.appendChild(S);let E=document.createElementNS(t,"g");E.setAttribute("mask",`url(#${U})`),E.setAttribute("opacity","0");let m=document.createElementNS(t,"g");m.setAttribute("filter",`url(#${P})`);let c=document.createElementNS(t,"path");c.setAttribute("d",g),c.setAttribute("fill","none"),c.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),c.setAttribute("stroke-width","6"),c.setAttribute("stroke-linecap","round"),m.appendChild(c),E.appendChild(m),n.appendChild(E);let I=document.createElementNS(t,"path");I.setAttribute("d",g),I.setAttribute("fill","none"),I.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),I.setAttribute("stroke-width","2"),I.setAttribute("stroke-linecap","round"),I.setAttribute("opacity","0"),n.appendChild(I),i.push(c,I),c.__group=E;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let y=0;y<i.length;y+=2){let p=i[y],v=i[y+1],_=p.__group;if(!_)continue;let C=v.getTotalLength(),b=p.getTotalLength();if(C<=0)continue;let A=C*.35;v.setAttribute("stroke-dasharray",`${A} ${C-A}`),v.setAttribute("stroke-dashoffset","0"),s.push(v.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*C,opacity:.92,offset:.06},{strokeDashoffset:-2*C,opacity:.92,offset:.92},{strokeDashoffset:-2.25*C,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let O=b*.35;p.setAttribute("stroke-dasharray",`${O} ${b-O}`),p.setAttribute("stroke-dashoffset","0"),s.push(p.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*b,offset:.06},{strokeDashoffset:-2*b,offset:.92},{strokeDashoffset:-2.25*b,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(_.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,f=()=>{if(l)return;l=true,clearTimeout(w);for(let p of s)try{p.cancel();}catch{}let y=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});y.onfinish=()=>r.remove(),window.removeEventListener("click",f);},w=setTimeout(f,14500);return setTimeout(()=>{l||window.addEventListener("click",f);},500),f}function Fn(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-removed","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.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 s=document.createElementNS(t,"feDropShadow");s.setAttribute("dx","0"),s.setAttribute("dy","1"),s.setAttribute("stdDeviation","2"),s.setAttribute("flood-color","rgba(0,0,0,0.15)"),i.appendChild(s),o.appendChild(i),n.appendChild(o);for(let{rect:l,borderRadius:f}of e){let w=document.createElementNS(t,"path");w.setAttribute("d",Sn(l.left,l.top,l.width,l.height,f)),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"),n.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 r.appendChild(n),document.body.appendChild(r),r}var St=new Map,Ft=new Map,Ar=new Map;function cs(e){for(let t of e)Ft.set(t,(Ft.get(t)??0)+1);}function ds(e){if(!(typeof document>"u"))for(let t of e){let r=(Ft.get(t)??0)-1;if(r>0){Ft.set(t,r);continue}Ft.delete(t),St.delete(t);let n=document.querySelector(`link[data-fork-override-href="${CSS.escape(t)}"]`);n&&n.remove();}}function us(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function An(e,t){let r=(t?e[t]:void 0)??e.default;if(typeof r!="function"){let n=t||"default";throw new Error(`Fork boundary module is missing a React component export: ${n}`)}return r}function fs(e){if(!e||typeof document>"u")return Promise.resolve();let t=St.get(e);if(t)return t;let r=document.querySelector(`link[data-fork-override-href="${e}"]`);if(r instanceof HTMLLinkElement){let o=r.sheet?Promise.resolve():new Promise((i,s)=>{let l=()=>{r.removeEventListener("load",l),r.removeEventListener("error",f),i();},f=()=>{r.removeEventListener("load",l),r.removeEventListener("error",f),s(new Error(`Failed to load boundary stylesheet: ${e}`));};r.addEventListener("load",l,{once:true}),r.addEventListener("error",f,{once:true});});return St.set(e,o),o}let n=new Promise((o,i)=>{let s=document.createElement("link");s.rel="stylesheet",s.href=e,s.setAttribute("data-fork-override-href",e),s.onload=()=>o(),s.onerror=()=>{s.remove(),i(new Error(`Failed to load boundary stylesheet: ${e}`));},document.head.appendChild(s);}).catch(o=>{throw St.delete(e),o});return St.set(e,n),n}function ps(e){let t=Ar.get(e);if(t)return t;let r=import(e).catch(n=>{throw Ar.delete(e),n});return Ar.set(e,r),r}async function ms(e,t,r){if(e)try{await Promise.all(e.cssUrls.map(i=>fs(i)));let o=await ps(e.moduleUrl);return An(o,r)}catch(o){console.error(`[Fork] Failed to load override for boundary "${e.boundaryId}", falling back to original module.`,o);}let n=await t();return An(n,r)}function gs(e){function t(r){let{appId:n,moduleOverridesEnabled:o,moduleManifestReady:i,moduleManifestVersion:s,registerBoundary:l,getBoundaryOverride:f,consumeBoundaryAnimation:w}=ye(),[y,p]=useState(null),[v,_]=useState(null),C=useRef(null),b=useRef(null),A=useRef(null),O=useRef(false),g=useRef(null),P=useRef(null),L=f(e.id),B=L?`override:${L.id}`:"original",U=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if(useEffect(()=>()=>{P.current&&(clearTimeout(P.current),P.current=null),g.current&&(g.current.remove(),g.current=null);},[]),useEffect(()=>{l({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[n,l,e.id,e.exportName,U]),useEffect(()=>{let S=L?.cssUrls??[];if(S.length!==0)return cs(S),()=>ds(S)},[L?.cssUrls.join("|")]),useEffect(()=>{if(o&&!i&&!y||b.current===B&&y)return;let S=false;return _(null),ms(L,e.original,e.exportName).then(k=>{if(!S){if(L?.id&&w(e.id,L.id)&&C.current){let h=Sr(C.current);if(h){let E=Fr(h);E.length>0&&(A.current=E,O.current=true,P.current&&(clearTimeout(P.current),P.current=null),g.current&&g.current.remove(),g.current=bn(h));}}b.current=B,startTransition(()=>{p(()=>k);});}}).catch(k=>{S||_(us(k));}),()=>{S=true;}},[w,B,o,i,s,L?.id,L?.moduleUrl,L?.integrity,L?.cssUrls.join("|"),e.exportName,e.original,y]),useEffect(()=>{if(!O.current||!y||!C.current)return;let S=false;return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(S||!C.current)return;let k=A.current,h=Sr(C.current);if(A.current=null,O.current=false,!k||!h){g.current&&(g.current.remove(),g.current=null);return}let E=Fr(h),m=wn(k,E),c=vn(k,E),I=g.current;if(c.length>0&&I){let D=Fn(c);P.current=setTimeout(()=>{P.current=null;let N=400;I.animate([{opacity:1},{opacity:0}],{duration:N,fill:"forwards"}),D.animate([{opacity:1},{opacity:0}],{duration:N,fill:"forwards"}),setTimeout(()=>{I.remove(),D.remove(),g.current===I&&(g.current=null),m.length>0&&xr(m);},N);},3500);}else I&&(I.remove(),g.current===I&&(g.current=null)),m.length>0&&xr(m);});}),()=>{S=true;}},[y]),v)throw v;return y?jsx("div",{ref:C,style:{display:"contents"},children:jsx(y,{...r})}):jsx(Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function ys({slotId:e,title:t,slotLabel:r}){return jsx(wt,{slotId:e,title:t,slotLabel:r})}
|
|
60
|
-
export{
|
|
59
|
+
`}),jsxs("div",{className:"__fork-panel",style:In,children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderBottom:"1px solid rgba(229, 231, 235, 0.8)",flexShrink:0},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:[jsx("span",{onDoubleClick:async a=>{if(a.stopPropagation(),!ie&&confirm("Kill all forks in this container?")){Ze(true);try{let F=await Be();`${F?.deleted??0}`,ke([]),le(null),se(!1),P("");}catch(F){console.error("[Fork] Reset failed:",F);}finally{Ze(false);}}},style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:4,margin:-4,cursor:"pointer",flexShrink:0},children:jsx(Ot,{style:{width:16,height:16,color:"#1c4587",pointerEvents:"none"}})}),e==="running"?jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:$n}):xe.length===0&&!et?jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:"Fork"}):et?jsxs("div",{ref:Pt,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[jsxs("button",{type:"button",onClick:()=>{Oe(a=>!a);},onMouseEnter:()=>At(true),onMouseLeave:()=>At(false),"aria-haspopup":"menu","aria-expanded":Re,style:{display:"inline-flex",alignItems:"center",gap:4,padding:"3px 6px",border:"1px solid transparent",borderRadius:6,background:Xt||Re?"#f3f4f6":"transparent",fontSize:13,fontWeight:600,color:"#111827",fontFamily:"inherit",cursor:"pointer",maxWidth:180,minWidth:0,transition:"background-color 0.12s"},children:[jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:Nr}),jsx(ChevronDown,{style:{width:12,height:12,color:"#6b7280",flexShrink:0,transform:Re?"rotate(180deg)":void 0,transition:"transform 0.15s"}})]}),Re&&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:[xe.map(a=>{let F=a.id===me,T=_t===a.id,ue=K===a.id;return jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>ve(a.id),onMouseLeave:()=>ve(null),onClick:()=>{a.id!==me&&Pn(a.id);},disabled:!!K,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:T?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:K?"default":"pointer",textAlign:"left",fontWeight:F?600:400,opacity:K&&!ue?.55:1},children:[jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:F&&jsx(Check,{style:{width:12,height:12}})}),jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:ue?"Switching...":a.name})]},a.id)}),jsx("div",{style:{height:1,background:"#e5e7eb",margin:"4px 0"}}),je?jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"4px 4px"},children:[jsx("input",{ref:d,type:"text",value:Ie,placeholder:"Container name",disabled:K==="__new__",onChange:a=>ze(a.target.value),onKeyDown:a=>{a.key==="Enter"?(a.preventDefault(),Tr(Ie)):a.key==="Escape"&&(a.preventDefault(),a.stopPropagation(),Qe(false),ze(""));},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:a=>{a.currentTarget.style.borderColor="#1c4587",a.currentTarget.style.boxShadow="0 0 0 2px rgba(28,69,135,0.15)";},onBlur:a=>{a.currentTarget.style.borderColor="#d1d5db",a.currentTarget.style.boxShadow="none";}}),jsx("button",{type:"button",onClick:()=>{Tr(Ie);},disabled:!Ie.trim()||K==="__new__",title:"Create",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:26,height:26,border:"none",borderRadius:4,background:!Ie.trim()||K==="__new__"?"#e5e7eb":"#1c4587",color:!Ie.trim()||K==="__new__"?"#9ca3af":"#ffffff",cursor:!Ie.trim()||K==="__new__"?"default":"pointer",flexShrink:0},children:K==="__new__"?jsx("span",{style:{width:10,height:10,border:"1.5px solid currentColor",borderTopColor:"transparent",borderRadius:"50%",animation:"__fork-spin 0.7s linear infinite"}}):jsx(Check,{style:{width:12,height:12}})})]}):jsx("button",{type:"button",role:"menuitem",onMouseEnter:()=>Ct(true),onMouseLeave:()=>Ct(false),onClick:()=>{K||(M(null),ze(""),Qe(true));},disabled:!!K,style:{display:"flex",alignItems:"center",width:"100%",padding:"6px 8px",border:"none",background:Pe?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:K?"default":"pointer",textAlign:"left",opacity:K&&K!=="__new__"?.55:1},children:"+ New container"}),u&&jsx("div",{style:{padding:"6px 8px",fontSize:11,lineHeight:1.35,color:"#b91c1c"},children:u})]})]}):jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:Nr}),e==="running"&&jsx("span",{title:Ke?`Estimated ~${Ke} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:Ke?"#1c4587":"#9ca3af",backgroundColor:Ke?"rgba(28, 69, 135, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:Ke?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:Ke?`~${Ke}m`:"~ m"})]}),!A&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[Er&&jsx("button",{onClick:Ae?Rn:Cn,onMouseEnter:()=>N(true),onMouseLeave:()=>N(false),title:Ae?"Redock to sidebar":"Pop out into window",style:{padding:6,borderRadius:6,color:D?"#4b5563":"#9ca3af",backgroundColor:D?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:Ae?jsx(PictureInPicture,{style:{width:16,height:16}}):jsx(PictureInPicture2,{style:{width:16,height:16}})}),jsx("button",{onClick:Br,onMouseEnter:()=>I(true),onMouseLeave:()=>I(false),style:{padding:6,borderRadius:6,color:c?"#4b5563":"#9ca3af",backgroundColor:c?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:jsx(X,{style:{width:16,height:16}})})]})]}),jsxs("div",{ref:ge,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[(X$1||te)&&jsxs("div",{style:{padding:"10px 12px 6px 12px",display:"flex",alignItems:"center",gap:8,borderBottom:"1px solid #f3f4f6"},children:[jsx("button",{onClick:()=>{le(null),se(false),pe.current=false;},style:{fontSize:12,color:"#374151",background:"transparent",border:"none",padding:"2px 4px",cursor:"pointer",display:"inline-flex",alignItems:"center",gap:4},title:"Back to all forks",children:"\u2190 All forks"}),(()=>{let F=(X$1?ae.find(T=>T.id===X$1)?.targetId:null)??tt;return F?jsxs("span",{style:{fontSize:11,color:"#9ca3af",fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, "Liberation Mono", "Courier New", monospace',whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1},title:`Forking ${F}`,children:["Forking ",jsx("span",{style:{color:"#6b7280"},children:F})]}):null})()]}),!X$1&&!te&&jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[jsx("div",{style:{padding:"12px 16px 10px 16px",borderBottom:"1px solid #f3f4f6"},children:jsx("span",{style:{fontSize:12,fontWeight:600,color:"#111827"},children:"Forks"})}),ae.length===0&&jsx("div",{style:{padding:"24px 20px",textAlign:"center",fontSize:13,color:"#6b7280"},children:"No forks yet. Describe a feature below to start one."}),ae.length>0&&jsx("div",{style:{display:"flex",flexDirection:"column"},children:ae.map(a=>{let F=a.summary||"Untitled fork";return jsxs("button",{onClick:()=>{se(false),le(a.id);},style:{textAlign:"left",padding:"10px 16px",background:"#ffffff",border:"none",borderBottom:"1px solid #f3f4f6",cursor:"pointer",display:"flex",flexDirection:"column",gap:2},onMouseEnter:T=>T.currentTarget.style.background="#fafafa",onMouseLeave:T=>T.currentTarget.style.background="#ffffff",children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[jsx("span",{style:{fontSize:13,fontWeight:500,color:"#111827",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1},children:F}),jsx("span",{style:{fontSize:11,color:"#9ca3af",flexShrink:0},children:qo(a.updatedAt)})]}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:11,color:"#6b7280"},children:[jsx("span",{style:{fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, "Liberation Mono", "Courier New", monospace',whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:a.targetId}),jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),jsxs("span",{children:[a.promptCount," prompt",a.promptCount===1?"":"s"]}),a.status==="running"||a.status==="building"?jsxs(Fragment,{children:[jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),jsx("span",{style:{color:"#2563eb"},children:"running"})]}):null]})]},a.id)})})]}),X$1&&at.length>0&&jsx("div",{style:{padding:"16px 16px 0 16px"},children:at.map((a,F)=>jsx("div",{style:{marginBottom:F<at.length-1?10:0},children:a.type==="user"?jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexDirection:"row-reverse"},children:[jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:jsx(User,{style:{width:13,height:13,color:"#6b7280"}})}),jsx("div",{style:{backgroundColor:"#f3f4f6",borderRadius:"12px 4px 12px 12px",padding:"8px 12px",fontSize:13,color:"#374151",lineHeight:1.5,maxWidth:"75%"},children:a.text})]}):O==="item"&&F===at.length-1?jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:12,padding:12,borderRadius:8,border:"1px solid #e4e4e7",background:"#ffffff"},children:[jsx("div",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,flexShrink:0,borderRadius:6,background:"#f4f4f5",color:"#0a0a0a"},children:jsx(BadgeCheck,{style:{width:16,height:16}})}),jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,flex:1,minWidth:0},children:[jsx("div",{style:{fontSize:13,fontWeight:500,color:"#0a0a0a",lineHeight:1.3},children:"Feature applied"}),jsx("div",{style:{fontSize:13,color:"#71717a",lineHeight:1.4},children:a.text})]}),w&&e!=="running"&&jsx("button",{onClick:T=>{T.stopPropagation(),Lr();},disabled:j,style:{padding:"4px 10px",fontSize:12,fontWeight:500,borderRadius:6,border:"1px solid #e4e4e7",background:"#ffffff",color:"#0a0a0a",cursor:j?"default":"pointer",opacity:j?.4:1,height:28,flexShrink:0},children:"Undo"})]}):jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#f0fdf4",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:jsx(Check,{style:{width:13,height:13,color:"#9ca3af"}})}),jsxs("div",{style:{backgroundColor:"#f9fafb",borderRadius:"4px 12px 12px 12px",padding:"8px 12px",fontSize:13,color:"#6b7280",fontWeight:500,display:"flex",alignItems:"center",gap:6,maxWidth:"75%"},children:[jsx("span",{style:{flex:1},children:a.text}),w&&F===at.length-1&&e!=="running"&&jsxs("button",{onClick:T=>{T.stopPropagation(),Lr();},onMouseEnter:()=>q(F),onMouseLeave:()=>q(null),disabled:j,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:fe===F?"rgba(0,0,0,0.06)":"transparent",color:fe===F?"#6b7280":"#d1d5db",cursor:j?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:j?.4:1,flexShrink:0},children:[jsx(Undo2,{style:{width:12,height:12}}),fe===F&&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"})]})]})]})},F))}),e==="running"&&(X$1||te)&&jsx("div",{style:{padding:16},children:jsxs("div",{onClick:()=>we(!G),style:{backgroundColor:"#1a1a2e",borderRadius:12,overflow:"hidden",cursor:"pointer",transition:"all 0.3s cubic-bezier(0.22, 1, 0.36, 1)"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"#6b7280",strokeWidth:"2.5",strokeLinecap:"round",style:{animation:"__fork-spin 2s linear infinite",flexShrink:0},children:jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),jsx(Zo,{events:r})]}),jsx("div",{style:{color:"#6b7280",flexShrink:0,marginLeft:8,transition:"transform 0.2s ease",transform:G?"rotate(180deg)":"rotate(0deg)"},children:jsx(ChevronDown,{style:{width:14,height:14}})})]}),jsx("div",{style:{maxHeight:G?320:0,opacity:G?1:0,transition:"max-height 0.35s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.25s ease",overflow:"hidden"},children:jsx("div",{style:{borderTop:"1px solid rgba(255,255,255,0.08)",maxHeight:320,overflowY:"auto"},children:jsx(dn,{events:r})})})]})}),e==="error"&&(X$1||te)&&jsxs("div",{style:{padding:"20px 16px",textAlign:"center"},children:[jsx("div",{style:{width:36,height:36,backgroundColor:"#fef2f2",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 10px auto"},children:jsx(X,{style:{width:18,height:18,color:"#ef4444"}})}),jsx("p",{style:{fontSize:12,color:"#6b7280",marginBottom:10,maxWidth:260,margin:"0 auto 10px auto"},children:n}),jsxs("button",{onClick:()=>{let a=t?.prompt||Et.current;a&&f(a,tt);},onMouseEnter:()=>Z(true),onMouseLeave:()=>Z(false),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,color:"#4f46e5",backgroundColor:H?"#e0e7ff":"#eef2ff",border:"none",cursor:"pointer",transition:"background-color 0.15s",fontFamily:"inherit"},children:[jsx(RotateCcw,{style:{width:12,height:12}})," Try Again"]})]})]}),e!=="running"&&jsx("div",{style:{padding:"8px 12px 12px 12px",borderTop:"1px solid rgba(229, 231, 235, 0.6)",flexShrink:0},children:jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,borderRadius:12,padding:"8px 8px 8px 12px",background:"rgba(0, 0, 0, 0.04)",border:"1px solid rgba(0, 0, 0, 0.06)"},children:[jsx("textarea",{ref:de,value:g,onChange:a=>{P(a.target.value),a.target.style.height="auto",a.target.style.height=Math.min(a.target.scrollHeight,160)+"px";},onKeyDown:a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),Ir()),a.key==="Escape"&&!A&&Br();},placeholder:X$1?"Iterate on this feature...":"Start building a new Fork...",rows:1,style:{flex:1,backgroundColor:"transparent",fontSize:13,color:"#111827",border:"none",outline:"none",padding:"0 4px 0 0",fontFamily:"inherit",resize:"none",lineHeight:1.5,maxHeight:160,overflow:"auto"}}),jsx("button",{onClick:Ir,disabled:!g.trim(),onMouseEnter:()=>x(true),onMouseLeave:()=>x(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:g.trim()?1:.25,transform:R&&g.trim()?"scale(1.1)":"scale(1)",background:g.trim()?"#1c4587":"rgba(0,0,0,0.12)",border:"none",cursor:g.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:jsx(ArrowUp,{style:{width:13,height:13}})})]})})]})]});return A?Gt:Ae&&z?createPortal(Gt,z.document.body):jsx(Qo,{children:Gt})}function yn(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 hr(e){let{apiKey:t,userId:r,userHash:n,baseUrl:o,appId:i,previewSession:s,refreshModuleManifest:l,queueBoundaryAnimation:f,trackForkActivity:w,recordForkActivityEvent:y}=ye(),[p,v]=useState("idle"),[_,C]=useState(null),[b,A]=useState([]),[O,g]=useState(null),P=useRef(null),L=useCallback(()=>{v("prompting"),A([]),g(null),C(null);},[]),B=useCallback(()=>{v("idle"),P.current&&(P.current.close(),P.current=null);},[]);useEffect(()=>{s&&s.target.kind==="module"&&s.target.id===e&&v(h=>h==="idle"?"prompting":h);},[s?.preview_session_id,s?.target.id,e]);let U=useCallback(async(h,E,m)=>{try{if(!i)throw new Error("ForkProvider requires appId for module boundary prompts.");v("running"),A([]),g(null),C(null);let c;if(s){let N=m?.forkId??s.fork_id??void 0,R=await fetch(`${o}/api/v1/preview/${encodeURIComponent(s.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...re()},body:JSON.stringify({prompt:h,...e?{boundary_id:e}:{},...N&&!m?.forceNew?{fork_id:N}:{},...m?.forceNew?{force_new:!0}:{}})});if(!R.ok){let Z=await R.json().catch(()=>({}));throw new Error(Z.error||`API error: ${R.status}`)}let x=await R.json();x.container_id&&Ve(x.container_id,x.container_name),lt(x.fork_id),c=await(await fetch(`${o}/api/v1/forks/${x.fork_id}`,{headers:{Authorization:`Bearer ${t}`,...re()}})).json();}else if(m?.forkId){let N={prompt:h};r&&(N.userId=r),n&&(N.userHash=n);let R=await fetch(`${o}/api/v1/forks/${encodeURIComponent(m.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(N)});if(!R.ok){let x=await R.json().catch(()=>({}));throw new Error(x.error||`API error: ${R.status}`)}c=await R.json();}else {let N={userId:r,prompt:h,boundaryId:e,appId:i};E&&(N.containerId=E),n&&(N.userHash=n),m?.forceNew&&(N.force_new=!0);let R=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(N)});if(!R.ok){let x=await R.json().catch(()=>({}));throw new Error(x.error||`API error: ${R.status}`)}c=await R.json();}C(c),w(c,{targetKind:"module",targetId:e});let I=new URLSearchParams({key:t});s?(I.set("previewSessionId",s.preview_session_id),I.set("previewForkId",c.id)):r&&I.set("userId",r),n&&I.set("userHash",n);let D=new EventSource(`${o}/api/v1/forks/${c.id}/events?${I.toString()}`);P.current=D,D.onmessage=N=>{try{let R=JSON.parse(N.data);if(y(c.id,R),A(x=>[...x,R]),R.type==="complete"){let x=R.data;f(e,c.id),l().catch(()=>{}).finally(()=>{let H={...c,status:"complete",moduleUrl:x.moduleUrl,cssUrls:x.cssUrls,summary:x.summary,completedAt:new Date().toISOString()};C(H),v("complete"),D.close();});}else if(R.type==="error"){let x=R.data;g(x.error||"Unknown error"),v("error"),D.close();}}catch{}},D.onerror=()=>{let N={Authorization:`Bearer ${t}`,...re()};!s&&r&&(N["X-Fork-User-Id"]=r),!s&&n&&(N["X-Fork-User-Hash"]=n),fetch(`${o}/api/v1/forks/${c.id}`,{headers:N}).then(R=>R.json()).then(R=>{C(R),R.status==="complete"?(f(e,R.id),l().catch(()=>{}),v("complete")):R.status==="error"&&(g(R.error||"Fork generation failed"),v("error"));}).catch(()=>{g("Connection lost"),v("error");}),D.close();};}catch(c){g(c.message),v("error");}},[t,i,o,e,s,f,l,y,w,n,r]),S=useCallback(async h=>{try{let E={Authorization:`Bearer ${t}`,...re()};!s&&r&&(E["X-Fork-User-Id"]=r),!s&&n&&(E["X-Fork-User-Hash"]=n);let m=await fetch(`${o}/api/v1/forks/${h}`,{headers:E});if(!m.ok)return;let c=await m.json(),I=c.boundaryId??e;if(w(c,{targetKind:"module",targetId:I}),c.status==="complete"){v("complete"),C(c),g(null),A([]);return}if(c.status==="error"){v("error"),C(c),g(c.error||"Fork generation failed"),A([]);return}if(c.status!=="pending"&&c.status!=="running"&&c.status!=="building")return;v("running"),C(c),g(null),A([]);let D=new URLSearchParams({key:t});s?(D.set("previewSessionId",s.preview_session_id),D.set("previewForkId",c.id)):r&&D.set("userId",r),n&&D.set("userHash",n);let N=new EventSource(`${o}/api/v1/forks/${c.id}/events?${D.toString()}`);P.current&&P.current.close(),P.current=N,N.onmessage=R=>{try{let x=JSON.parse(R.data);if(y(c.id,x),A(H=>[...H,x]),x.type==="complete"){let H=x.data;f(e,c.id),l().catch(()=>{}).finally(()=>{let Z={...c,status:"complete",moduleUrl:H.moduleUrl,cssUrls:H.cssUrls,summary:H.summary,completedAt:new Date().toISOString()};C(Z),v("complete"),N.close();});}else if(x.type==="error"){let H=x.data;g(H.error||"Unknown error"),v("error"),N.close();}}catch{}},N.onerror=()=>{N.close();};}catch{}},[t,o,e,s,f,y,l,w,n,r]),k=useCallback(async()=>{try{if(!i)throw new Error("ForkProvider requires appId for boundary undo.");let h={userId:r,boundaryId:e,appId:i};n&&(h.userHash=n);let E=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(h)});if(!E.ok){let c=await E.json().catch(()=>({}));throw new Error(c.error||`API error: ${E.status}`)}let m=await E.json();return await l().catch(()=>{}),m.removed?(C(null),v("prompting")):m.fork&&(C(m.fork),v("complete")),m}catch(h){throw g(h.message),h}},[t,i,o,e,l,n,r]);return {state:p,fork:_,events:b,error:O,open:L,close:B,startFork:U,undoFork:k,adoptRunningFork:S}}function kn(e){let{state:t,fork:r,events:n,error:o,open:i,close:s,startFork:l,undoFork:f,adoptRunningFork:w}=hr(e),[y,p]=useState(false),v=useCallback(()=>{p(true),i();},[i]),_=useCallback(()=>{p(false),s();},[s]),C=useCallback(async b=>{p(true),await w(b);},[w]);return {state:t,fork:r,events:n,error:o,isOpen:y,open:v,close:_,submit:l,undo:f,adoptRunningFork:C}}function kr(){let{apiKey:e,userId:t,userHash:r,baseUrl:n,previewSession:o,setSlotFork:i,clearSlotFork:s,skipAnimationForSlot:l,trackForkActivity:f,recordForkActivityEvent:w}=ye(),[y,p]=useState("idle"),[v,_]=useState(null),[C,b]=useState([]),[A,O]=useState(null),g=useRef(null),P=useCallback(()=>{p("prompting"),b([]),O(null),_(null);},[]),L=useCallback(()=>{p("idle"),g.current&&(g.current.close(),g.current=null);},[]);useEffect(()=>{o&&o.target.kind==="slot"&&p(k=>k==="idle"?"prompting":k);},[o?.preview_session_id,o?.target.kind]);let B=useCallback(async(k,h,E,m)=>{try{p("running"),b([]),O(null),_(null);let c;if(o){let R=m?.forkId??o.fork_id??void 0,x=await fetch(`${n}/api/v1/preview/${encodeURIComponent(o.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...re()},body:JSON.stringify({prompt:k,...h?{slot_id:h}:{},...R&&!m?.forceNew?{fork_id:R}:{},...m?.forceNew?{force_new:!0}:{}})});if(!x.ok){let G=await x.json().catch(()=>({}));throw new Error(G.error||`API error: ${x.status}`)}let H=await x.json();H.container_id&&Ve(H.container_id,H.container_name),lt(H.fork_id),c=await(await fetch(`${n}/api/v1/forks/${H.fork_id}`,{headers:{Authorization:`Bearer ${e}`,...re()}})).json();}else if(m?.forkId){let R={prompt:k};t&&(R.userId=t),r&&(R.userHash=r);let x=await fetch(`${n}/api/v1/forks/${encodeURIComponent(m.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(R)});if(!x.ok){let H=await x.json().catch(()=>({}));throw new Error(H.error||`API error: ${x.status}`)}c=await x.json();}else {let R={userId:t,prompt:k};h&&(R.slotId=h),E&&(R.containerId=E),r&&(R.userHash=r),m?.forceNew&&(R.force_new=!0);let x=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(R)});if(!x.ok){let H=await x.json().catch(()=>({}));throw new Error(H.error||`API error: ${x.status}`)}c=await x.json();}_(c);let I=h??c.slotId;I&&f(c,{targetKind:"slot",targetId:I});let D=new URLSearchParams({key:e});o?(D.set("previewSessionId",o.preview_session_id),D.set("previewForkId",c.id)):t&&D.set("userId",t),r&&D.set("userHash",r);let N=new EventSource(`${n}/api/v1/forks/${c.id}/events?${D.toString()}`);g.current=N,N.onmessage=R=>{try{let x=JSON.parse(R.data);if(w(c.id,x),b(H=>[...H,x]),x.type==="complete"){let H=x.data,Z={...c,status:"complete",bundleUrl:H.bundleUrl,summary:H.summary,completedAt:new Date().toISOString()};_(Z),p("complete"),h&&H.bundleUrl&&i(h,Z),N.close();}else if(x.type==="error"){let H=x.data;O(H.error||"Unknown error"),p("error"),N.close();}}catch{}},N.onerror=()=>{let R={Authorization:`Bearer ${e}`,...re()};!o&&t&&(R["X-Fork-User-Id"]=t),!o&&r&&(R["X-Fork-User-Hash"]=r),fetch(`${n}/api/v1/forks/${c.id}`,{headers:R}).then(x=>x.json()).then(x=>{_(x),x.status==="complete"?(p("complete"),h&&x.bundleUrl&&i(h,x)):x.status==="error"&&(O(x.error||"Fork generation failed"),p("error"));}).catch(()=>{O("Connection lost"),p("error");}),N.close();};}catch(c){O(c.message),p("error");}},[e,n,o,w,i,f,r,t]),U=useCallback(async k=>{try{let h={Authorization:`Bearer ${e}`,...re()};!o&&t&&(h["X-Fork-User-Id"]=t),!o&&r&&(h["X-Fork-User-Hash"]=r);let E=await fetch(`${n}/api/v1/forks/${k}`,{headers:h});if(!E.ok)return;let m=await E.json();if(m.slotId&&f(m,{targetKind:"slot",targetId:m.slotId}),m.status==="complete"){p("complete"),_(m),O(null),b([]);return}if(m.status==="error"){p("error"),_(m),O(m.error||"Fork generation failed"),b([]);return}if(m.status!=="pending"&&m.status!=="running"&&m.status!=="building")return;p("running"),_(m),O(null),b([]);let c=new URLSearchParams({key:e});o?(c.set("previewSessionId",o.preview_session_id),c.set("previewForkId",m.id)):t&&c.set("userId",t),r&&c.set("userHash",r);let I=new EventSource(`${n}/api/v1/forks/${m.id}/events?${c.toString()}`);g.current&&g.current.close(),g.current=I;let D=m.slotId;I.onmessage=N=>{try{let R=JSON.parse(N.data);if(w(m.id,R),b(x=>[...x,R]),R.type==="complete"){let x=R.data,H={...m,status:"complete",bundleUrl:x.bundleUrl,summary:x.summary,completedAt:new Date().toISOString()};_(H),p("complete"),D&&x.bundleUrl&&i(D,H),I.close();}else if(R.type==="error"){let x=R.data;O(x.error||"Unknown error"),p("error"),I.close();}}catch{}},I.onerror=()=>{I.close();};}catch{}},[e,n,o,w,i,f,r,t]),S=useCallback(async k=>{try{let h={userId:t,slotId:k};r&&(h.userHash=r);let E=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(h)});if(!E.ok){let c=await E.json().catch(()=>({}));throw new Error(c.error||`API error: ${E.status}`)}let m=await E.json();return l(k),m.removed?(s(k),_(null),p("prompting")):m.fork&&(i(k,m.fork),_(m.fork)),m}catch(h){throw O(h.message),h}},[e,t,r,n,s,i]);return {state:y,fork:v,events:C,error:A,open:P,close:L,startFork:B,undoFork:S,adoptRunningFork:U}}function bn(){let{state:e,fork:t,events:r,error:n,open:o,close:i,startFork:s,undoFork:l,adoptRunningFork:f}=kr(),[w,y]=useState(false),p=useCallback(()=>{y(true),o();},[o]),v=useCallback(()=>{y(false),i();},[i]),_=useCallback(async C=>{y(true),await f(C);},[f]);return {state:e,fork:t,events:r,error:n,isOpen:w,open:p,close:v,submit:s,undo:l,adoptRunningFork:_}}var is=new Set(["pending","running","building"]);function vr(e){let t=yn(e),r=bn(),n=kn(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:i,userId:s,userHash:l,appId:f,activitySummary:w,forkActivities:y,markForkActivitySeen:p}=ye(),v=t.type==="slot"?r:n,_=t.type==="slot"?"slot":"boundary",C=t.id,b=t.title,A=t.type==="slot"?"slot":"module",O=y.find(U=>U.targetKind===A&&U.targetId===t.id&&is.has(U.status)),g=y.find(U=>U.targetKind===A&&U.targetId===t.id&&U.status==="complete"&&U.unread),P=useCallback(()=>{p();let U=O??g;if(U){v.adoptRunningFork(U.id);return}v.open();},[v,p,O,g]),L=useCallback((U,S,k,h)=>t.type==="slot"?r.submit(U,S??t.id,k,h):n.submit(U,k,h),[n,r,t]),B=useCallback(U=>t.type==="slot"?r.undo(U??t.id):n.undo(),[n,r,t]);return {...v,open:P,target:t,targetId:C,targetLabel:b,historyMode:_,submit:L,undo:B,buttonProps:{onClick:P,hasNotification:w.unreadCompletedCount>0,activity:w},panelProps:{state:v.state,fork:v.fork,events:v.events,error:v.error,...t.type==="slot"?{slotId:C,targetLabel:b,historyMode:_}:{targetId:C,targetLabel:b,historyMode:_},onSubmit:L,onUndo:B,onClose:v.close,baseUrl:o,apiKey:i,userId:s,userHash:l,appId:f}}}function wt(e){let{embedded:t,completeVariant:r}=e,n=vr(e);return t?jsx(Kt,{...n.panelProps,embedded:true,completeVariant:r}):n.isOpen?jsx(Kt,{...n.panelProps,completeVariant:r}):jsx(fr,{...n.buttonProps})}function as({boundaryId:e,title:t}){return jsx(wt,{boundaryId:e,title:t})}function Fr(e){let t=Array.from(e.children).filter(n=>n instanceof HTMLElement);return t.length===1?t[0]:getComputedStyle(e).display==="contents"?null:e}function wn(e){let t=e.getBoundingClientRect(),r=e.cloneNode(true);r.setAttribute("data-fork-clone-overlay","true"),r.style.position="fixed",r.style.top=`${t.top}px`,r.style.left=`${t.left}px`,r.style.width=`${t.width}px`,r.style.height=`${t.height}px`,r.style.flex="none",r.style.minHeight="auto",r.style.zIndex="9998",r.style.pointerEvents="none",r.style.overflow="hidden";let n=getComputedStyle(e).backgroundColor;r.style.backgroundColor=n&&n!=="rgba(0, 0, 0, 0)"&&n!=="transparent"?n:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(r);let o=e.querySelectorAll("*"),i=r.querySelectorAll("*");for(let s=0;s<o.length;s+=1)o[s].scrollTop!==0&&(i[s].scrollTop=o[s].scrollTop),o[s].scrollLeft!==0&&(i[s].scrollLeft=o[s].scrollLeft);return r}function xr(e){let t=[],r=e.querySelectorAll("*");for(let n of r){if(!(n instanceof HTMLElement))continue;let o=n.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(n.tagName))continue;let i=getComputedStyle(n),s=parseFloat(i.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:s});}return t}function vn(e,t){let r=[];for(let n of t)if(!(e.find(s=>s.tag===n.tag&&s.className===n.className&&Math.abs(s.rect.top-n.rect.top)<20&&Math.abs(s.rect.left-n.rect.left)<20)||r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom))){for(let s=r.length-1;s>=0;s-=1){let l=r[s];l.rect.top>=n.rect.top&&l.rect.left>=n.rect.left&&l.rect.right<=n.rect.right&&l.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Sn(e,t){let r=[];for(let n of e)if(!(t.find(s=>s.tag===n.tag&&s.className===n.className&&Math.abs(s.rect.top-n.rect.top)<20&&Math.abs(s.rect.left-n.rect.left)<20)||r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom))){for(let s=r.length-1;s>=0;s-=1){let l=r[s];l.rect.top>=n.rect.top&&l.rect.left>=n.rect.left&&l.rect.right<=n.rect.right&&l.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Fn(e,t,r,n,o){let i=Math.max(0,Math.min(o,r/2,n/2));return i===0?`M ${e} ${t} L ${e+r} ${t} L ${e+r} ${t+n} L ${e} ${t+n} Z`:[`M ${e+i} ${t}`,`L ${e+r-i} ${t}`,`A ${i} ${i} 0 0 1 ${e+r} ${t+i}`,`L ${e+r} ${t+n-i}`,`A ${i} ${i} 0 0 1 ${e+r-i} ${t+n}`,`L ${e+i} ${t+n}`,`A ${i} ${i} 0 0 1 ${e} ${t+n-i}`,`L ${e} ${t+i}`,`A ${i} ${i} 0 0 1 ${e+i} ${t}`,"Z"].join(" ")}function Ar(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-highlights","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");n.appendChild(o);let i=[];for(let y=0;y<e.length;y+=1){let{rect:p,borderRadius:v}=e[y],_=p.left-.5,C=p.top-.5,b=p.width+1,A=p.height+1,O=Math.min(v+.5,b/2,A/2),g=Fn(_,C,b,A,O),P=`__fork-glow-${y}`,L=document.createElementNS(t,"filter");L.setAttribute("id",P),L.setAttribute("x","-100%"),L.setAttribute("y","-100%"),L.setAttribute("width","300%"),L.setAttribute("height","300%");let B=document.createElementNS(t,"feGaussianBlur");B.setAttribute("in","SourceGraphic"),B.setAttribute("stdDeviation","8"),L.appendChild(B),o.appendChild(L);let U=`__fork-mask-${y}`,S=document.createElementNS(t,"mask");S.setAttribute("id",U),S.setAttribute("maskUnits","userSpaceOnUse"),S.setAttribute("x",String(_-200)),S.setAttribute("y",String(C-200)),S.setAttribute("width",String(b+400)),S.setAttribute("height",String(A+400));let k=document.createElementNS(t,"rect");k.setAttribute("x",String(_-200)),k.setAttribute("y",String(C-200)),k.setAttribute("width",String(b+400)),k.setAttribute("height",String(A+400)),k.setAttribute("fill","white"),S.appendChild(k);let h=document.createElementNS(t,"path");h.setAttribute("d",g),h.setAttribute("fill","black"),S.appendChild(h),o.appendChild(S);let E=document.createElementNS(t,"g");E.setAttribute("mask",`url(#${U})`),E.setAttribute("opacity","0");let m=document.createElementNS(t,"g");m.setAttribute("filter",`url(#${P})`);let c=document.createElementNS(t,"path");c.setAttribute("d",g),c.setAttribute("fill","none"),c.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),c.setAttribute("stroke-width","6"),c.setAttribute("stroke-linecap","round"),m.appendChild(c),E.appendChild(m),n.appendChild(E);let I=document.createElementNS(t,"path");I.setAttribute("d",g),I.setAttribute("fill","none"),I.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),I.setAttribute("stroke-width","2"),I.setAttribute("stroke-linecap","round"),I.setAttribute("opacity","0"),n.appendChild(I),i.push(c,I),c.__group=E;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let y=0;y<i.length;y+=2){let p=i[y],v=i[y+1],_=p.__group;if(!_)continue;let C=v.getTotalLength(),b=p.getTotalLength();if(C<=0)continue;let A=C*.35;v.setAttribute("stroke-dasharray",`${A} ${C-A}`),v.setAttribute("stroke-dashoffset","0"),s.push(v.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*C,opacity:.92,offset:.06},{strokeDashoffset:-2*C,opacity:.92,offset:.92},{strokeDashoffset:-2.25*C,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let O=b*.35;p.setAttribute("stroke-dasharray",`${O} ${b-O}`),p.setAttribute("stroke-dashoffset","0"),s.push(p.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*b,offset:.06},{strokeDashoffset:-2*b,offset:.92},{strokeDashoffset:-2.25*b,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(_.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,f=()=>{if(l)return;l=true,clearTimeout(w);for(let p of s)try{p.cancel();}catch{}let y=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});y.onfinish=()=>r.remove(),window.removeEventListener("click",f);},w=setTimeout(f,14500);return setTimeout(()=>{l||window.addEventListener("click",f);},500),f}function xn(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-removed","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.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 s=document.createElementNS(t,"feDropShadow");s.setAttribute("dx","0"),s.setAttribute("dy","1"),s.setAttribute("stdDeviation","2"),s.setAttribute("flood-color","rgba(0,0,0,0.15)"),i.appendChild(s),o.appendChild(i),n.appendChild(o);for(let{rect:l,borderRadius:f}of e){let w=document.createElementNS(t,"path");w.setAttribute("d",Fn(l.left,l.top,l.width,l.height,f)),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"),n.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 r.appendChild(n),document.body.appendChild(r),r}var Ft=new Map,xt=new Map,_r=new Map;function ds(e){for(let t of e)xt.set(t,(xt.get(t)??0)+1);}function us(e){if(!(typeof document>"u"))for(let t of e){let r=(xt.get(t)??0)-1;if(r>0){xt.set(t,r);continue}xt.delete(t),Ft.delete(t);let n=document.querySelector(`link[data-fork-override-href="${CSS.escape(t)}"]`);n&&n.remove();}}function fs(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function _n(e,t){let r=(t?e[t]:void 0)??e.default;if(typeof r!="function"){let n=t||"default";throw new Error(`Fork boundary module is missing a React component export: ${n}`)}return r}function ps(e){if(!e||typeof document>"u")return Promise.resolve();let t=Ft.get(e);if(t)return t;let r=document.querySelector(`link[data-fork-override-href="${e}"]`);if(r instanceof HTMLLinkElement){let o=r.sheet?Promise.resolve():new Promise((i,s)=>{let l=()=>{r.removeEventListener("load",l),r.removeEventListener("error",f),i();},f=()=>{r.removeEventListener("load",l),r.removeEventListener("error",f),s(new Error(`Failed to load boundary stylesheet: ${e}`));};r.addEventListener("load",l,{once:true}),r.addEventListener("error",f,{once:true});});return Ft.set(e,o),o}let n=new Promise((o,i)=>{let s=document.createElement("link");s.rel="stylesheet",s.href=e,s.setAttribute("data-fork-override-href",e),s.onload=()=>o(),s.onerror=()=>{s.remove(),i(new Error(`Failed to load boundary stylesheet: ${e}`));},document.head.appendChild(s);}).catch(o=>{throw Ft.delete(e),o});return Ft.set(e,n),n}var St=null;function ms(){if(St)return St;try{St=new Function("u","return import(/*webpackIgnore:true*//*@vite-ignore*/u)");}catch{St=e=>import(/*webpackIgnore:true*//*@vite-ignore*/e);}return St}function gs(e){let t=_r.get(e);if(t)return t;let r=ms()(e).catch(n=>{throw _r.delete(e),n});return _r.set(e,r),r}async function hs(e,t,r){if(e)try{await Promise.all(e.cssUrls.map(i=>ps(i)));let o=await gs(e.moduleUrl);return _n(o,r)}catch(o){console.error(`[Fork] Failed to load override for boundary "${e.boundaryId}", falling back to original module.`,o);}let n=await t();return _n(n,r)}function ys(e){function t(r){let{appId:n,moduleOverridesEnabled:o,moduleManifestReady:i,moduleManifestVersion:s,registerBoundary:l,getBoundaryOverride:f,consumeBoundaryAnimation:w}=ye(),[y,p]=useState(null),[v,_]=useState(null),C=useRef(null),b=useRef(null),A=useRef(null),O=useRef(false),g=useRef(null),P=useRef(null),L=f(e.id),B=L?`override:${L.id}`:"original",U=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if(useEffect(()=>()=>{P.current&&(clearTimeout(P.current),P.current=null),g.current&&(g.current.remove(),g.current=null);},[]),useEffect(()=>{l({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[n,l,e.id,e.exportName,U]),useEffect(()=>{let S=L?.cssUrls??[];if(S.length!==0)return ds(S),()=>us(S)},[L?.cssUrls.join("|")]),useEffect(()=>{if(o&&!i&&!y||b.current===B&&y)return;let S=false;return _(null),hs(L,e.original,e.exportName).then(k=>{if(!S){if(L?.id&&w(e.id,L.id)&&C.current){let h=Fr(C.current);if(h){let E=xr(h);E.length>0&&(A.current=E,O.current=true,P.current&&(clearTimeout(P.current),P.current=null),g.current&&g.current.remove(),g.current=wn(h));}}b.current=B,startTransition(()=>{p(()=>k);});}}).catch(k=>{S||_(fs(k));}),()=>{S=true;}},[w,B,o,i,s,L?.id,L?.moduleUrl,L?.integrity,L?.cssUrls.join("|"),e.exportName,e.original,y]),useEffect(()=>{if(!O.current||!y||!C.current)return;let S=false;return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(S||!C.current)return;let k=A.current,h=Fr(C.current);if(A.current=null,O.current=false,!k||!h){g.current&&(g.current.remove(),g.current=null);return}let E=xr(h),m=vn(k,E),c=Sn(k,E),I=g.current;if(c.length>0&&I){let D=xn(c);P.current=setTimeout(()=>{P.current=null;let N=400;I.animate([{opacity:1},{opacity:0}],{duration:N,fill:"forwards"}),D.animate([{opacity:1},{opacity:0}],{duration:N,fill:"forwards"}),setTimeout(()=>{I.remove(),D.remove(),g.current===I&&(g.current=null),m.length>0&&Ar(m);},N);},3500);}else I&&(I.remove(),g.current===I&&(g.current=null)),m.length>0&&Ar(m);});}),()=>{S=true;}},[y]),v)throw v;return y?jsx("div",{ref:C,style:{display:"contents"},children:jsx(y,{...r})}):jsx(Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function bs({slotId:e,title:t,slotLabel:r}){return jsx(wt,{slotId:e,title:t,slotLabel:r})}
|
|
60
|
+
export{as as ForkBoundaryUI,fr as ForkButton,wt as ForkChatInterface,Kt as ForkPanel,io as ForkProvider,wo as ForkSlot,bs as ForkUI,Vn as clearCachedManifest,ys as forkable,Bt as loadManifest,Xn as manifestDiffers,Kn as readCachedManifest,Yt as registerForkShared,hr as useBoundaryFork,kr as useFork,vr as useForkChatPanel,Lt as usePreviewSession,Wn as writeCachedManifest};
|