@fork-api/chat-sdk 0.1.148 → 0.1.152

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @fork-api/chat-sdk
2
2
 
3
- React SDK for [Fork](https://withfork.co) let your users customize your UI with AI.
3
+ React SDK for [Fork](https://withfork.co). Let your users customize your UI with AI.
4
4
 
5
5
  ## Install
6
6
 
package/dist/index.cjs CHANGED
@@ -1,6 +1,7 @@
1
- 'use strict';var Bt=require('react'),hn=require('react-dom'),yn=require('react/jsx-runtime'),kn=require('react/jsx-dev-runtime'),lucideReact=require('lucide-react');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var Bt__namespace=/*#__PURE__*/_interopNamespace(Bt);var hn__namespace=/*#__PURE__*/_interopNamespace(hn);var yn__namespace=/*#__PURE__*/_interopNamespace(yn);var kn__namespace=/*#__PURE__*/_interopNamespace(kn);var be="__FORK_SHARED__";function Ct(){var t,r,n,o;let e=globalThis;return e[be]||(e[be]={}),(t=e[be]).react||(t.react=Bt__namespace),(r=e[be])["react-dom"]||(r["react-dom"]=hn__namespace),(n=e[be])["react/jsx-runtime"]||(n["react/jsx-runtime"]=yn__namespace),(o=e[be])["react/jsx-dev-runtime"]||(o["react/jsx-dev-runtime"]=kn__namespace),e[be]}function Et(e){return Object.assign(Ct(),e)}var bn="__fork_preview_session__";function it(e){return `${bn}${e}`}var H={apiKey:null,session:null},At=new Set;function at(){for(let e of At)try{e();}catch(t){console.error("[fork-preview] subscriber threw",t);}}function gr(e){let t=Date.parse(e.expires_at);return Number.isFinite(t)?t<=Date.now():true}function wn(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:gr(r)?(window.sessionStorage.removeItem(it(e)),null):r}catch{return null}}function $t(e,t){if(!(typeof window>"u"))try{t?window.sessionStorage.setItem(it(e),JSON.stringify(t)):window.sessionStorage.removeItem(it(e));}catch{}}function Oe(e){H.apiKey!==e&&(H.apiKey=e,H.session=wn(e),at());}function we(){return H.session?gr(H.session)?(Pt(null),null):H.session:null}function Pt(e){H.session=e,H.apiKey&&$t(H.apiKey,e),at();}function Ue(e){H.session&&H.session.fork_id!==e&&(H.session={...H.session,fork_id:e},H.apiKey&&$t(H.apiKey,H.session),at());}function ve(e,t){H.session&&(H.session.container_id===e&&H.session.container_name===t||(H.session={...H.session,container_id:e,container_name:t??H.session.container_name??"Fork",fork_id:null},H.apiKey&&$t(H.apiKey,H.session),at()));}function Mt(e){return At.add(e),()=>{At.delete(e);}}var mr="__fork_preview";function hr(){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(mr);return typeof r=="string"&&r.length>0?r:null}function Tt(e){if(typeof window>"u")return false;try{if(window.sessionStorage.getItem(`__fork_preview_session__${e}`))return !0}catch{}return kr()!==null}function yr(){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(mr);let r=t.toString(),n=r?`#${r}`:"";try{window.history.replaceState(null,"",window.location.pathname+window.location.search+n);}catch{}}var Se=null;function kr(){if(Se)return Se;let e=hr();return e?(Se=e,yr(),Se):null}async function It(e,t){Oe(e);let r=we();if(r)return Se=null,r;let n=Se??hr();if(Se=null,!n)return null;yr();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 c=await o.json().catch(()=>({}));return console.warn(`[fork-preview] activate failed (${o.status}): ${c.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 Pt(s),s}catch(o){return console.warn("[fork-preview] activate threw",o),null}}function Sn(){return we()}function xn(){return null}function lt(){return Bt.useSyncExternalStore(Mt,Sn,xn)}function K(){let e=we();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 ct(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[c,p]of Object.entries(i.modules)){let g=p.moduleUrl??p.bundleUrl??null,f=p.legacyModuleUrl??p.legacyBundleUrl??null;s[c]={forkId:p.forkId,moduleUrl:g,legacyModuleUrl:f,bundleUrl:p.bundleUrl??g,legacyBundleUrl:p.legacyBundleUrl??f,cssUrls:p.cssUrls??[],integrity:p.integrity,metadata:p.metadata,buildId:p.buildId,updatedAt:p.updatedAt};}return {containerId:i.containerId,slots:i.slots,modules:s,generatedAt:i.generatedAt,etag:o.headers.get("ETag")??void 0}}var Fn="fork:manifest:v1";function Lt(e,t,r){return `${Fn}:${e}:${t}:${r}`}function Rn(e,t,r){if(typeof window>"u")return null;try{let n=window.localStorage.getItem(Lt(e,t,r));return n?JSON.parse(n):null}catch{return null}}function _n(e,t,r,n){if(!(typeof window>"u"))try{window.localStorage.setItem(Lt(e,t,r),JSON.stringify(n));}catch{}}function Cn(e,t,r){if(!(typeof window>"u"))try{window.localStorage.removeItem(Lt(e,t,r));}catch{}}function En(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,c]of r){let p=t.slots[s];if(!p||p.forkId!==c.forkId||p.buildId!==c.buildId)return true}let o=Object.entries(e.modules),i=Object.entries(t.modules);if(o.length!==i.length)return true;for(let[s,c]of o){let p=t.modules[s];if(!p||p.forkId!==c.forkId||p.buildId!==c.buildId)return true}return false}var vr=Bt.createContext(null);function je(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function Pn(e,t){let r={};for(let[n,o]of Object.entries(t.boundaries||{}))r[n]={...o,moduleUrl:je(e,o.moduleUrl),cssUrls:Array.isArray(o.cssUrls)?o.cssUrls.map(i=>je(e,i)):[]};return r}function br(e,t,r,n){let o={};for(let[i,s]of Object.entries(t.slots)){let c=s.bundleUrl??s.legacyBundleUrl;c&&(o[i]={id:s.forkId,userId:r,prompt:"",status:"complete",slotId:i,appId:n,bundleUrl:je(e,c),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:je(e,i),cssUrls:(o.cssUrls??[]).map(s=>je(e,s)),integrity:o.integrity,metadata:o.metadata,createdAt:o.updatedAt});}return r}function Mn(e){let{apiKey:t,baseUrl:r,children:n,appId:o,shared:i}=e,s="userId"in e?e.userId:void 0,c="authUrl"in e?e.authUrl:void 0,[p]=Bt.useState(()=>(Oe(t),Tt(t))),[g,f]=Bt.useState({}),[S,P]=Bt.useState(s?{userId:s,userHash:void 0}:null),[_,R]=Bt.useState(!!s||p),[h,y]=Bt.useState({}),[I,C]=Bt.useState(!o),[N,M]=Bt.useState(0),[L,x]=Bt.useState(null),k=Bt.useRef(new Map),d=Bt.useRef(new Map),[v,E]=Bt.useState(0),A=Bt.useRef(new Set),u=Bt.useRef(new Map),l=Bt.useRef(void 0);Ct(),Bt.useEffect(()=>{return It(t,r).then(()=>{}),()=>{}},[]);let b=lt();i&&l.current!==i&&(Et(i),l.current=i),Bt.useEffect(()=>{c&&(p||(R(false),fetch(c,{credentials:"include"}).then(T=>{if(!T.ok)throw new Error(`Auth endpoint returned ${T.status}`);return T.json()}).then(T=>{if(!T.userId||typeof T.userId!="string")throw new Error("authUrl response must include userId");P({userId:T.userId,userHash:T.userHash});}).catch(T=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",T.message);}).finally(()=>{R(true);})));},[c,p]),Bt.useEffect(()=>{!c&&s&&(P({userId:s,userHash:void 0}),R(true));},[s,c]);let j=S?.userId??"",Y=S?.userHash,D=b?"":j,W=b?void 0:Y,ee=!!o,z=Bt.useCallback(async()=>{if(!ee){x(null),y({}),C(true),M(F=>F+1);return}if(!_){C(false);return}if(!b&&!D||!o){x(null),y({}),C(true),M(F=>F+1);return}if(C(false),!b){try{let F=await ct({baseUrl:r,apiKey:t,appId:o,userId:D,userHash:W});F&&(x(F.containerId),f(br(r,F,D,o)),y(wr(r,F)));}catch(F){console.error("[ForkProvider] Failed to fetch fork manifest:",F.message),x(null),f({}),y({});}finally{M(F=>F+1),C(true);}return}if(x(b.container_id??null),b.container_id){try{let F=await ct({baseUrl:r,apiKey:t,appId:o,userId:D,containerId:b.container_id,extraHeaders:K()});F&&(f(br(r,F,D,o)),y(wr(r,F)));}catch(F){console.error("[ForkProvider] Failed to fetch preview container manifest:",F.message),f({}),y({});}finally{M(F=>F+1),C(true);}return}let T=new URLSearchParams({appId:o,userId:D});W&&T.set("userHash",W);try{let F=await fetch(`${r}/api/v1/boundaries/manifest?${T.toString()}`,{headers:{Authorization:`Bearer ${t}`,...K()}});if(!F.ok)throw new Error(`${F.status}`);let O=await F.json();y(Pn(r,O));}catch(F){console.error("[ForkProvider] Failed to fetch module override manifest:",F.message),y({});}finally{M(F=>F+1),C(true);}},[t,o,r,_,ee,W,D,b?.preview_session_id,b?.fork_id,b?.container_id]);Bt.useEffect(()=>{if(!D||o&&(!b||b.container_id))return;let T=new URLSearchParams({userId:D});W&&T.set("userHash",W),fetch(`${r}/api/v1/forks/active?${T.toString()}`,{headers:{Authorization:`Bearer ${t}`,...K()}}).then(F=>{if(!F.ok)throw new Error(`${F.status}`);return F.json()}).then(F=>{F&&typeof F=="object"&&f(F);}).catch(()=>{});},[t,o,D,W,r,b?.preview_session_id,b?.fork_id]),Bt.useEffect(()=>{z();},[z]);let se=Bt.useCallback((T,F)=>{f(O=>({...O,[T]:F}));},[]),ie=Bt.useCallback(T=>{f(F=>{let O={...F};return delete O[T],O});},[]),fe=Bt.useCallback(T=>{A.current.add(T);},[]),te=Bt.useCallback(T=>A.current.has(T)?(A.current.delete(T),true):false,[]),vt=Bt.useCallback((T,F)=>{u.current.set(T,F);},[]),qe=Bt.useCallback((T,F)=>u.current.get(T)!==F?false:(u.current.delete(T),true),[]),Me=Bt.useCallback(T=>{if(!o)return;let F=JSON.stringify(T);k.current.get(T.id)===F||d.current.get(T.id)?.signature===F||(d.current.set(T.id,{boundary:T,signature:F}),E(re=>re+1));},[o]);Bt.useEffect(()=>{if(!o||d.current.size===0)return;let T=setTimeout(()=>{let F=Array.from(d.current.values());F.length!==0&&fetch(`${r}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:o,boundaries:F.map(O=>O.boundary)})}).then(O=>{if(!O.ok)throw new Error(`${O.status}`)}).then(()=>{for(let O of F)d.current.get(O.boundary.id)?.signature===O.signature&&(d.current.delete(O.boundary.id),k.current.set(O.boundary.id,O.signature));}).catch(O=>{console.error("[ForkProvider] Failed to register module boundaries:",O.message);});},50);return ()=>{clearTimeout(T);}},[t,o,r,v]);let ce=Bt.useCallback(T=>h[T],[h]),Z=Bt.useCallback(async()=>{if(!D)throw new Error("Reset requires a resolved user identity.");let T=new URLSearchParams({userId:D});W&&T.set("userHash",W);let F={Authorization:`Bearer ${t}`,...K()};o&&(F["X-Fork-App-Id"]=o);let O=await fetch(`${r}/api/v1/forks/all?${T.toString()}`,{method:"DELETE",headers:F});if(!O.ok){let ne=await O.json().catch(()=>({}));throw new Error(ne.error||`API error: ${O.status}`)}let re=await O.json().catch(()=>({}));f({}),y({}),C(true),M(ne=>ne+1),A.current.clear(),u.current.clear();try{for(let ne=sessionStorage.length-1;ne>=0;ne-=1){let Te=sessionStorage.key(ne);Te&&Te.startsWith("__fork_animated_")&&sessionStorage.removeItem(Te);}}catch{}return re},[t,o,r,W,D]);return yn.jsx(vr.Provider,{value:{apiKey:t,userId:D,userHash:W,baseUrl:r,appId:o,forks:g,moduleOverridesEnabled:ee,moduleManifestReady:I,moduleManifestVersion:N,currentContainerId:L,previewSession:b,setSlotFork:se,clearSlotFork:ie,skipAnimationForSlot:fe,shouldSkipAnimation:te,queueBoundaryAnimation:vt,consumeBoundaryAnimation:qe,registerBoundary:Me,getBoundaryOverride:ce,refreshModuleManifest:z,resetAllForks:Z},children:n})}function Q(){let e=Bt.useContext(vr);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function dt(e){return Q().forks[e]}var De=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 Ot(e,t){let r;try{r=Bt.Children.only(e);}catch{let o=Bt.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 xr=new Set;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 Bn(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 c=r[s];c.rect.top>=n.rect.top&&c.rect.left>=n.rect.left&&c.rect.right<=n.rect.right&&c.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function On(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 c=r[s];c.rect.top>=n.rect.top&&c.rect.left>=n.rect.left&&c.rect.right<=n.rect.right&&c.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function _r(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 Rr(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 f=0;f<e.length;f++){let{rect:S,borderRadius:P}=e[f],_=S.left-.5,R=S.top-.5,h=S.width+1,y=S.height+1,I=Math.min(P+.5,h/2,y/2),C=_r(_,R,h,y,I),N=`__fork-glow-${f}`,M=document.createElementNS(t,"filter");M.setAttribute("id",N),M.setAttribute("x","-100%"),M.setAttribute("y","-100%"),M.setAttribute("width","300%"),M.setAttribute("height","300%");let L=document.createElementNS(t,"feGaussianBlur");L.setAttribute("in","SourceGraphic"),L.setAttribute("stdDeviation","8"),M.appendChild(L),o.appendChild(M);let x=`__fork-mask-${f}`,k=document.createElementNS(t,"mask");k.setAttribute("id",x),k.setAttribute("maskUnits","userSpaceOnUse"),k.setAttribute("x",String(_-200)),k.setAttribute("y",String(R-200)),k.setAttribute("width",String(h+400)),k.setAttribute("height",String(y+400));let d=document.createElementNS(t,"rect");d.setAttribute("x",String(_-200)),d.setAttribute("y",String(R-200)),d.setAttribute("width",String(h+400)),d.setAttribute("height",String(y+400)),d.setAttribute("fill","white"),k.appendChild(d);let v=document.createElementNS(t,"path");v.setAttribute("d",C),v.setAttribute("fill","black"),k.appendChild(v),o.appendChild(k);let E=document.createElementNS(t,"g");E.setAttribute("mask",`url(#${x})`),E.setAttribute("opacity","0");let A=document.createElementNS(t,"g");A.setAttribute("filter",`url(#${N})`);let u=document.createElementNS(t,"path");u.setAttribute("d",C),u.setAttribute("fill","none"),u.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),u.setAttribute("stroke-width","6"),u.setAttribute("stroke-linecap","round"),A.appendChild(u),E.appendChild(A),n.appendChild(E);let l=document.createElementNS(t,"path");l.setAttribute("d",C),l.setAttribute("fill","none"),l.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),l.setAttribute("stroke-width","2"),l.setAttribute("stroke-linecap","round"),l.setAttribute("opacity","0"),n.appendChild(l),i.push(u,l),u.__group=E;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let f=0;f<i.length;f+=2){let S=i[f],P=i[f+1],_=S.__group,R=P.getTotalLength(),h=S.getTotalLength();if(R<=0)continue;let y=R*.35;P.setAttribute("stroke-dasharray",`${y} ${R-y}`),P.setAttribute("stroke-dashoffset","0"),s.push(P.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*R,opacity:.92,offset:.06},{strokeDashoffset:-2*R,opacity:.92,offset:.92},{strokeDashoffset:-2.25*R,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let I=h*.35;S.setAttribute("stroke-dasharray",`${I} ${h-I}`),S.setAttribute("stroke-dashoffset","0"),s.push(S.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*h,offset:.06},{strokeDashoffset:-2*h,offset:.92},{strokeDashoffset:-2.25*h,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 c=false,p=()=>{if(c)return;c=true,clearTimeout(g);for(let S of s)try{S.cancel();}catch{}let f=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});f.onfinish=()=>r.remove(),window.removeEventListener("click",p);},g=setTimeout(p,14500);return setTimeout(()=>{c||window.addEventListener("click",p);},500),p}function Un(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:c,borderRadius:p}of e){let g=c.left,f=c.top,S=c.width,P=c.height,_=Math.min(p,S/2,P/2),R=_r(g,f,S,P,_),h=document.createElementNS(t,"path");h.setAttribute("d",R),h.setAttribute("fill","none"),h.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),h.setAttribute("stroke-width","1.5"),h.setAttribute("stroke-dasharray","8 4"),h.setAttribute("stroke-linecap","round"),h.setAttribute("filter","url(#__fork-removed-shadow)"),h.setAttribute("opacity","0"),n.appendChild(h),h.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 Hn(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 jn=Bt__namespace.default.memo(function({component:t,containerRef:r,wrapperStyle:n,hostProps:o}){return yn.jsx("div",{ref:r,style:n,children:yn.jsx(t,{...o})})},(e,t)=>e.component===t.component&&Hn(e.hostProps,t.hostProps)),Nt=class extends Bt__namespace.default.Component{constructor(t){super(t),this.state={hasError:false};}static getDerivedStateFromError(){return {hasError:true}}componentDidCatch(t){console.error(`[Fork:${this.props.slotId}] fork render failed`,t);}componentDidUpdate(t){t.resetKey!==this.props.resetKey&&this.state.hasError&&this.setState({hasError:false});}render(){return this.state.hasError?this.props.fallback:this.props.children}};function Cr({slotId:e,children:t,githubRepo:r,shared:n,events:o}){Ot(t,e);let i=dt(e),{baseUrl:s,apiKey:c,appId:p,shouldSkipAnimation:g}=Q(),[f,S]=Bt.useState(null),P=Bt.useRef(null),_=Bt.useRef(null),R=Bt.useRef(null),h=Bt.useRef(false),y=Bt.useRef(null),I=Bt.useRef(null),C=!!(n||o),N=Bt.useRef(null);C&&!N.current&&(N.current=new De(e));let M=Bt.useRef(o);if(M.current=o,Bt.useEffect(()=>{if(C)return ()=>{N.current?.destroy(),N.current=null;}},[C,e]),C&&N.current&&n)for(let[v,E]of Object.entries(n))N.current.set(v,E);Bt.useEffect(()=>{if(!C)return;N.current||(N.current=new De(e));let v=N.current,E=Object.keys(M.current||{}).map(A=>v.on(A,(...u)=>M.current?.[A]?.(...u)));return ()=>E.forEach(A=>A())},[C,e]),Bt.useEffect(()=>{if(xr.has(e))return;xr.add(e);let v={id:e,appId:p,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 ${c}`,"Content-Type":"application/json"},body:JSON.stringify(v)}).catch(()=>{});},[e,s,c,r,p]);let L=i?.id||null;Bt.useEffect(()=>{if(i?.bundleUrl,P.current,_.current,!i?.bundleUrl||!L){return}let v=`${s}${i.bundleUrl.replace("bundle.js","component.js")}`,E=`__fork_animated_${e}`,A=sessionStorage.getItem(E),u=g(e),l=!u&&A!==L;if(u&&L&&sessionStorage.setItem(E,L),l&&_.current){let W=Fr(_.current);R.current=W,h.current=true,`${e}${W.length}`;}window.__FORK_REACT__=Bt__namespace.default,window.__FORK_REACT_DOM__=hn__namespace,window.__FORK_REACT_JSX__=yn__namespace;let b=Date.now(),j=`${s}${i.bundleUrl.replace("bundle.js","component.css")}?t=${b}`,Y=document.createElement("link");Y.rel="stylesheet",Y.href=j,Y.dataset.forkSlot=e,document.head.appendChild(Y);let D=document.createElement("script");return D.src=v+"?t="+b,D.onload=()=>{let W=window.__FORK_EXPORT__;if(W?.default){if(_.current&&R.current&&h.current){let ee=_.current.getBoundingClientRect(),z=_.current.cloneNode(true);z.style.position="fixed",z.style.top=`${ee.top}px`,z.style.left=`${ee.left}px`,z.style.width=`${ee.width}px`,z.style.height=`${ee.height}px`,z.style.flex="none",z.style.minHeight="auto",z.style.zIndex="9998",z.style.pointerEvents="none",z.style.overflow="hidden";let se=getComputedStyle(_.current).backgroundColor;z.style.backgroundColor=se&&se!=="rgba(0, 0, 0, 0)"&&se!=="transparent"?se:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(z);let ie=_.current.querySelectorAll("*"),fe=z.querySelectorAll("*");for(let te=0;te<ie.length;te++)ie[te].scrollTop!==0&&(fe[te].scrollTop=ie[te].scrollTop),ie[te].scrollLeft!==0&&(fe[te].scrollLeft=ie[te].scrollLeft);y.current=z;}S(()=>W.default),P.current=L;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},D.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(D),()=>{D.remove(),Y.remove(),I.current&&(clearTimeout(I.current),I.current=null),y.current&&(y.current.remove(),y.current=null);}},[L,s,e]),Bt.useEffect(()=>{if(!h.current||!f||!_.current){`${e}${h.current}`,_.current;return}let v=R.current;if(!v){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!_.current)return;let E=Fr(_.current),A=Bn(v,E),u=On(v,E),l=y.current;if(`${e}${A.length}${u.length}`,u.length>0&&l){let b=Un(u);I.current=setTimeout(()=>{I.current=null;let j=400;l.animate([{opacity:1},{opacity:0}],{duration:j,fill:"forwards"}),b.animate([{opacity:1},{opacity:0}],{duration:j,fill:"forwards"}),setTimeout(()=>{l.remove(),b.remove(),y.current=null,A.length>0&&(Rr(A));},j);},3500);}else l&&(l.remove(),y.current=null),A.length>0&&(Rr(A));R.current=null,h.current=false,L&&(sessionStorage.setItem(`__fork_animated_${e}`,L),`${e}`);});});},[f]);let x={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!i||i.status!=="complete"||!i.bundleUrl)return yn.jsx("div",{ref:_,style:x,children:t});if(!f)return yn.jsx("div",{ref:_,style:x,children:t});let d=t?.props??{};return yn.jsx(Nt,{slotId:e,resetKey:L,fallback:yn.jsx("div",{ref:_,style:x,children:t}),children:yn.jsx(jn,{component:f,containerRef:_,wrapperStyle:x,hostProps:d})})}var Ar=new Set;function Wn(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 $r(e,t=new Set){return Bt.Children.forEach(e,r=>{if(!Bt.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&&$r(n.children,t);}),t}function Kn({slotId:e,props:t,children:r,allowedFetches:n,githubRepo:o,callbacks:i,mode:s="iframe",shared:c,events:p}){if(Ot(r,e),s==="direct")return yn.jsx(Cr,{slotId:e,githubRepo:o,shared:c,events:p,children:r});let g=dt(e),{baseUrl:f,apiKey:S,appId:P}=Q(),_=Bt.useRef(null),R=Bt.useRef(false),h=Bt.useRef(null),y=Bt.useRef(i);y.current=i;let I=Bt.useRef(t);I.current=t;let C=Bt.useRef(n);C.current=n,Bt.useEffect(()=>{if(typeof process<"u")return;let x=$r(r),k=new Set(i?Object.keys(i):[]),d=[...x].filter(v=>!k.has(v));d.length>0&&console.error(`[ForkSlot:${e}] Missing bridged callbacks! The following callback props are used by children but not passed to ForkSlot's \`callbacks\` prop:
2
- `+d.map(v=>` - ${v}`).join(`
3
- `)+"\n\nThe forked component will not be able to call these. Add them to the `callbacks` prop of <ForkSlot>.");},[e,r,i]),Bt.useEffect(()=>{Ar.has(e)||(Ar.add(e),fetch(`${f}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${S}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:P,label:e,propsShape:t?Wn(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:o,callbackNames:i?Object.keys(i):[],mode:s||"iframe"})}).catch(()=>{}));},[e,f,S,o,P]);let N=Bt.useCallback(x=>{let k=_.current;if(k?.contentWindow&&R.current){let d=y.current?Object.keys(y.current):[];k.contentWindow.postMessage({type:"slot:props",props:x,callbackNames:d},"*"),h.current=null;}else h.current=x;},[]),M=Bt.useCallback((x,k)=>{let d=C.current;return !d||d.length===0?false:d.some(v=>{let[E,A]=v.split(" "),u=k.split("?")[0];return x.toUpperCase()===E.toUpperCase()&&u.startsWith(A)})},[]);if(Bt.useEffect(()=>{if(!g?.bundleUrl)return;let x=async k=>{if(k.source===_.current?.contentWindow){if(k.data?.type==="slot:ready")R.current=true,_.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:C.current||[]},"*"),C.current,h.current?N(h.current):N(I.current||{});else if(k.data?.type==="slot:event"){let d=k.data.event;d?.navigate&&(window.location.hash=d.navigate);}else if(k.data?.type==="slot:clipboard-write")navigator.clipboard.writeText(k.data.text).catch(d=>{console.warn(`[ForkSlot:${e}] clipboard write failed:`,d.message);});else if(k.data?.type==="slot:callback"){let{name:d,args:v}=k.data,E=y.current?.[d];E?(E(...v||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${d}`);}else if(k.data?.type==="slot:fetch"){let{id:d,method:v,url:E,body:A}=k.data,u=_.current?.contentWindow;if(!u)return;let l=v||"GET";if(!M(l,E)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${d}: ${l} ${E} \u2014 not in allowedFetches`),u.postMessage({type:"slot:fetch-response",id:d,error:`Fetch not allowed: ${l} ${E}`},"*");return}try{let b={method:l};A&&l!=="GET"&&(b.headers={"Content-Type":"application/json"},b.body=JSON.stringify(A));let j=await fetch(E,b),Y=await j.json();`${e}${d}${j.status}`,u.postMessage({type:"slot:fetch-response",id:d,data:Y,status:j.status},"*");}catch(b){console.error(`[ForkSlot:${e}] fetch #${d} failed:`,b.message),u.postMessage({type:"slot:fetch-response",id:d,error:b.message},"*");}}}};return window.addEventListener("message",x),()=>{window.removeEventListener("message",x),R.current=false;}},[g?.bundleUrl,e,N,M]),Bt.useEffect(()=>{g?.bundleUrl&&R.current&&N(t||{});},[t,g?.bundleUrl,N]),!g||g.status!=="complete"||!g.bundleUrl)return `${e}${g?.status||"none"}${g?.bundleUrl||"none"}`,yn.jsx(yn.Fragment,{children:r});`${e}${g.bundleUrl}`;let L=`${f}${g.bundleUrl.replace("/bundle.js","/host")}`;return yn.jsx("iframe",{ref:_,src:L,sandbox:"allow-scripts allow-same-origin allow-forms allow-clipboard-write",title:`Forked ${e}`,style:{width:"100%",border:"none",flex:1,minHeight:0}})}function ft({style:e={width:20,height:20},...t}){return yn.jsxs("svg",{viewBox:"320 95 270 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:e,...t,children:[yn.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"}),yn.jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M387.096 174.735v188"}),yn.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"}),yn.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"}),yn.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"})]})}function Ht({onClick:e}){let[t,r]=Bt.useState(false),[n,o]=Bt.useState(false),i=t?48:40;return yn.jsx("button",{onClick:e,onMouseEnter:()=>r(true),onMouseLeave:()=>{r(false),o(false);},onMouseDown:()=>o(true),onMouseUp:()=>o(false),style:{position:"fixed",bottom:24,right:24,zIndex:40,width:i,height:i,borderRadius:"50%",backgroundColor:t?"rgba(255, 255, 255, 1)":"rgba(255, 255, 255, 0.3)",border:t?"1px solid rgba(156, 163, 175, 1)":"1px solid rgba(156, 163, 175, 0.3)",display:"flex",alignItems:"center",justifyContent:"center",color:t?"#1c4587":"rgba(28, 69, 135, 0.5)",boxShadow:t?"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:n?"scale(0.95)":"scale(1)",transition:"all 300ms",cursor:"pointer",padding:0,margin:0,outline:"none",boxSizing:"border-box"},title:"Fork this app",children:yn.jsx(ft,{style:{width:24,height:24}})})}var to={status:lucideReact.Loader2,agent_message:lucideReact.MessageSquare,tool_use:lucideReact.Wrench,build_start:lucideReact.Package,build_complete:lucideReact.Check,build_error:lucideReact.AlertCircle,complete:lucideReact.Sparkles,error:lucideReact.AlertCircle},ro={status:"#60a5fa",agent_message:"#a0a0a0",tool_use:"#fbbf24",build_start:"#c084fc",build_complete:"#6b7280",build_error:"#f87171",complete:"#6b7280",error:"#f87171"},no={read:lucideReact.FileSearch,write:lucideReact.Pencil,search:lucideReact.FileSearch,shell:lucideReact.Terminal,build:lucideReact.Package},oo={read:"#60a5fa",write:"#fbbf24",search:"#60a5fa",shell:"#a78bfa",build:"#c084fc"};function Dt(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 Or({events:e}){let t=Bt.useRef(null);return Bt.useEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight);},[e]),yn.jsxs(yn.Fragment,{children:[yn.jsx("style",{children:`
1
+ 'use strict';var Ut=require('react'),bn=require('react-dom'),wn=require('react/jsx-runtime'),vn=require('react/jsx-dev-runtime'),lucideReact=require('lucide-react');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var Ut__namespace=/*#__PURE__*/_interopNamespace(Ut);var bn__namespace=/*#__PURE__*/_interopNamespace(bn);var wn__namespace=/*#__PURE__*/_interopNamespace(wn);var vn__namespace=/*#__PURE__*/_interopNamespace(vn);var we="__FORK_SHARED__";function At(){var t,r,n,o;let e=globalThis;return e[we]||(e[we]={}),(t=e[we]).react||(t.react=Ut__namespace),(r=e[we])["react-dom"]||(r["react-dom"]=bn__namespace),(n=e[we])["react/jsx-runtime"]||(n["react/jsx-runtime"]=wn__namespace),(o=e[we])["react/jsx-dev-runtime"]||(o["react/jsx-dev-runtime"]=vn__namespace),e[we]}function $t(e){return Object.assign(At(),e)}var Sn="__fork_preview_session__";function at(e){return `${Sn}${e}`}var U={apiKey:null,session:null},Pt=new Set;function lt(){for(let e of Pt)try{e();}catch(t){console.error("[fork-preview] subscriber threw",t);}}function yr(e){let t=Date.parse(e.expires_at);return Number.isFinite(t)?t<=Date.now():true}function xn(e){if(typeof window>"u")return null;try{let t=window.sessionStorage.getItem(at(e));if(!t)return null;let r=JSON.parse(t);return !r||typeof r!="object"||typeof r.preview_session_id!="string"?null:yr(r)?(window.sessionStorage.removeItem(at(e)),null):r}catch{return null}}function It(e,t){if(!(typeof window>"u"))try{t?window.sessionStorage.setItem(at(e),JSON.stringify(t)):window.sessionStorage.removeItem(at(e));}catch{}}function $e(e){U.apiKey!==e&&(U.apiKey=e,U.session=xn(e),lt());}function ge(){return U.session?yr(U.session)?(ct(null),null):U.session:null}function ct(e){U.session=e,U.apiKey&&It(U.apiKey,e),lt();}function Be(e){U.session&&U.session.fork_id!==e&&(U.session={...U.session,fork_id:e},U.apiKey&&It(U.apiKey,U.session),lt());}function ve(e,t){U.session&&(U.session.container_id===e&&U.session.container_name===t||(U.session={...U.session,container_id:e,container_name:t??U.session.container_name??"Fork",fork_id:null},U.apiKey&&It(U.apiKey,U.session),lt()));}function Tt(e){return Pt.add(e),()=>{Pt.delete(e);}}var kr="__fork_preview";function br(){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(kr);return typeof r=="string"&&r.length>0?r:null}function Lt(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 vr()!==null}function wr(){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(kr);let r=t.toString(),n=r?`#${r}`:"";try{window.history.replaceState(null,"",window.location.pathname+window.location.search+n);}catch{}}var Se=null,Mt=null,Ue=null;function vr(){if(Se)return Se;let e=br();return e?(Se=e,wr(),Se):null}async function Nt(e,t){$e(e);let r=ge();if(r)return Se=null,r;let n=Se??br();if(Se=null,!n)return null;wr();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 c=await o.json().catch(()=>({}));return console.warn(`[fork-preview] activate failed (${o.status}): ${c.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 ct(s),s}catch(o){return console.warn("[fork-preview] activate threw",o),null}}async function Ht(e,t,r){$e(e);let n=ge();if(n)return n;if(!r.appId||!r.userId||!r.userHash)return null;let o=[e,t,r.appId,r.userId].join(`
2
+ `);return Ue&&Mt===o||(Mt=o,Ue=(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 p=await i.json().catch(()=>({}));return console.warn(`[fork-preview] auto admin activate failed (${i.status}): ${p.error??"unknown"}`),null}let s=await i.json(),c={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 ct(c),c}catch(i){return console.warn("[fork-preview] auto admin activate threw",i),null}finally{Mt=null,Ue=null;}})()),Ue}function _n(){return ge()}function Rn(){return null}function dt(){return Ut.useSyncExternalStore(Tt,_n,Rn)}function K(){let e=ge();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 ut(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[c,p]of Object.entries(i.modules)){let g=p.moduleUrl??p.bundleUrl??null,f=p.legacyModuleUrl??p.legacyBundleUrl??null;s[c]={forkId:p.forkId,moduleUrl:g,legacyModuleUrl:f,bundleUrl:p.bundleUrl??g,legacyBundleUrl:p.legacyBundleUrl??f,cssUrls:p.cssUrls??[],integrity:p.integrity,metadata:p.metadata,buildId:p.buildId,updatedAt:p.updatedAt};}return {containerId:i.containerId,slots:i.slots,modules:s,generatedAt:i.generatedAt,etag:o.headers.get("ETag")??void 0}}var Cn="fork:manifest:v1";function Ot(e,t,r){return `${Cn}:${e}:${t}:${r}`}function En(e,t,r){if(typeof window>"u")return null;try{let n=window.localStorage.getItem(Ot(e,t,r));return n?JSON.parse(n):null}catch{return null}}function An(e,t,r,n){if(!(typeof window>"u"))try{window.localStorage.setItem(Ot(e,t,r),JSON.stringify(n));}catch{}}function $n(e,t,r){if(!(typeof window>"u"))try{window.localStorage.removeItem(Ot(e,t,r));}catch{}}function Pn(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,c]of r){let p=t.slots[s];if(!p||p.forkId!==c.forkId||p.buildId!==c.buildId)return true}let o=Object.entries(e.modules),i=Object.entries(t.modules);if(o.length!==i.length)return true;for(let[s,c]of o){let p=t.modules[s];if(!p||p.forkId!==c.forkId||p.buildId!==c.buildId)return true}return false}var Fr=Ut.createContext(null);function De(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function Mn(e,t){let r={};for(let[n,o]of Object.entries(t.boundaries||{}))r[n]={...o,moduleUrl:De(e,o.moduleUrl),cssUrls:Array.isArray(o.cssUrls)?o.cssUrls.map(i=>De(e,i)):[]};return r}function Sr(e,t,r,n){let o={};for(let[i,s]of Object.entries(t.slots)){let c=s.bundleUrl??s.legacyBundleUrl;c&&(o[i]={id:s.forkId,userId:r,prompt:"",status:"complete",slotId:i,appId:n,bundleUrl:De(e,c),createdAt:s.updatedAt,completedAt:s.updatedAt});}return o}function xr(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:De(e,i),cssUrls:(o.cssUrls??[]).map(s=>De(e,s)),integrity:o.integrity,metadata:o.metadata,createdAt:o.updatedAt});}return r}function Ln(e){let{apiKey:t,baseUrl:r,children:n,appId:o,shared:i}=e,s="userId"in e?e.userId:void 0,c="authUrl"in e?e.authUrl:void 0,[p]=Ut.useState(()=>($e(t),Lt(t))),[g,f]=Ut.useState({}),[k,I]=Ut.useState(s?{userId:s,userHash:void 0}:null),[R,_]=Ut.useState(!!s||p),[h,b]=Ut.useState({}),[M,C]=Ut.useState(!o),[N,T]=Ut.useState(0),[L,x]=Ut.useState(null),w=Ut.useRef(new Map),d=Ut.useRef(new Map),[S,E]=Ut.useState(0),A=Ut.useRef(new Set),u=Ut.useRef(new Map),l=Ut.useRef(void 0);At(),Ut.useEffect(()=>{return Nt(t,r).then(()=>{}),()=>{}},[]);let y=dt();Ut.useEffect(()=>{p||y||!o||!k?.userHash||Ht(t,r,{appId:o,userId:k.userId,userHash:k.userHash});},[t,o,k?.userHash,k?.userId,r,p,y?.preview_session_id]),i&&l.current!==i&&($t(i),l.current=i),Ut.useEffect(()=>{c&&(p||(_(false),fetch(c,{credentials:"include"}).then($=>{if(!$.ok)throw new Error(`Auth endpoint returned ${$.status}`);return $.json()}).then($=>{if(!$.userId||typeof $.userId!="string")throw new Error("authUrl response must include userId");I({userId:$.userId,userHash:typeof $.userHash=="string"?$.userHash:void 0});}).catch($=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",$.message);}).finally(()=>{_(true);})));},[c,p]),Ut.useEffect(()=>{!c&&s&&(I({userId:s,userHash:void 0}),_(true));},[s,c]);let j=k?.userId??"",Y=k?.userHash,D=y?"":j,W=y?void 0:Y,ee=!!o,z=Ut.useCallback(async()=>{if(!ee){x(null),b({}),C(true),T(F=>F+1);return}if(!R){C(false);return}if(!y&&!D||!o){x(null),b({}),C(true),T(F=>F+1);return}if(C(false),!y){try{let F=await ut({baseUrl:r,apiKey:t,appId:o,userId:D,userHash:W});F&&(x(F.containerId),f(Sr(r,F,D,o)),b(xr(r,F)));}catch(F){console.error("[ForkProvider] Failed to fetch fork manifest:",F.message),x(null),f({}),b({});}finally{T(F=>F+1),C(true);}return}if(x(y.container_id??null),y.container_id){try{let F=await ut({baseUrl:r,apiKey:t,appId:o,userId:D,containerId:y.container_id,extraHeaders:K()});F&&(f(Sr(r,F,D,o)),b(xr(r,F)));}catch(F){console.error("[ForkProvider] Failed to fetch preview container manifest:",F.message),f({}),b({});}finally{T(F=>F+1),C(true);}return}let $=new URLSearchParams({appId:o,userId:D});W&&$.set("userHash",W);try{let F=await fetch(`${r}/api/v1/boundaries/manifest?${$.toString()}`,{headers:{Authorization:`Bearer ${t}`,...K()}});if(!F.ok)throw new Error(`${F.status}`);let O=await F.json();b(Mn(r,O));}catch(F){console.error("[ForkProvider] Failed to fetch module override manifest:",F.message),b({});}finally{T(F=>F+1),C(true);}},[t,o,r,R,ee,W,D,y?.preview_session_id,y?.fork_id,y?.container_id]);Ut.useEffect(()=>{if(!D||o&&(!y||y.container_id))return;let $=new URLSearchParams({userId:D});W&&$.set("userHash",W),fetch(`${r}/api/v1/forks/active?${$.toString()}`,{headers:{Authorization:`Bearer ${t}`,...K()}}).then(F=>{if(!F.ok)throw new Error(`${F.status}`);return F.json()}).then(F=>{F&&typeof F=="object"&&f(F);}).catch(()=>{});},[t,o,D,W,r,y?.preview_session_id,y?.fork_id]),Ut.useEffect(()=>{z();},[z]);let se=Ut.useCallback(($,F)=>{f(O=>({...O,[$]:F}));},[]),ie=Ut.useCallback($=>{f(F=>{let O={...F};return delete O[$],O});},[]),fe=Ut.useCallback($=>{A.current.add($);},[]),te=Ut.useCallback($=>A.current.has($)?(A.current.delete($),true):false,[]),xt=Ut.useCallback(($,F)=>{u.current.set($,F);},[]),Xe=Ut.useCallback(($,F)=>u.current.get($)!==F?false:(u.current.delete($),true),[]),Te=Ut.useCallback($=>{if(!o)return;let F=JSON.stringify($);w.current.get($.id)===F||d.current.get($.id)?.signature===F||(d.current.set($.id,{boundary:$,signature:F}),E(re=>re+1));},[o]);Ut.useEffect(()=>{if(!o||d.current.size===0)return;let $=setTimeout(()=>{let F=Array.from(d.current.values());F.length!==0&&fetch(`${r}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:o,boundaries:F.map(O=>O.boundary)})}).then(O=>{if(!O.ok)throw new Error(`${O.status}`)}).then(()=>{for(let O of F)d.current.get(O.boundary.id)?.signature===O.signature&&(d.current.delete(O.boundary.id),w.current.set(O.boundary.id,O.signature));}).catch(O=>{console.error("[ForkProvider] Failed to register module boundaries:",O.message);});},50);return ()=>{clearTimeout($);}},[t,o,r,S]);let ce=Ut.useCallback($=>h[$],[h]),Z=Ut.useCallback(async()=>{if(!D)throw new Error("Reset requires a resolved user identity.");let $=new URLSearchParams({userId:D});W&&$.set("userHash",W);let F={Authorization:`Bearer ${t}`,...K()};o&&(F["X-Fork-App-Id"]=o);let O=await fetch(`${r}/api/v1/forks/all?${$.toString()}`,{method:"DELETE",headers:F});if(!O.ok){let ne=await O.json().catch(()=>({}));throw new Error(ne.error||`API error: ${O.status}`)}let re=await O.json().catch(()=>({}));f({}),b({}),C(true),T(ne=>ne+1),A.current.clear(),u.current.clear();try{for(let ne=sessionStorage.length-1;ne>=0;ne-=1){let Me=sessionStorage.key(ne);Me&&Me.startsWith("__fork_animated_")&&sessionStorage.removeItem(Me);}}catch{}return re},[t,o,r,W,D]);return wn.jsx(Fr.Provider,{value:{apiKey:t,userId:D,userHash:W,baseUrl:r,appId:o,forks:g,moduleOverridesEnabled:ee,moduleManifestReady:M,moduleManifestVersion:N,currentContainerId:L,previewSession:y,setSlotFork:se,clearSlotFork:ie,skipAnimationForSlot:fe,shouldSkipAnimation:te,queueBoundaryAnimation:xt,consumeBoundaryAnimation:Xe,registerBoundary:Te,getBoundaryOverride:ce,refreshModuleManifest:z,resetAllForks:Z},children:n})}function Q(){let e=Ut.useContext(Fr);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function ft(e){return Q().forks[e]}var ze=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 jt(e,t){let r;try{r=Ut.Children.only(e);}catch{let o=Ut.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 Rr=new Set;function Cr(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 Un(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 c=r[s];c.rect.top>=n.rect.top&&c.rect.left>=n.rect.left&&c.rect.right<=n.rect.right&&c.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function jn(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 c=r[s];c.rect.top>=n.rect.top&&c.rect.left>=n.rect.left&&c.rect.right<=n.rect.right&&c.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Ar(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 Er(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 f=0;f<e.length;f++){let{rect:k,borderRadius:I}=e[f],R=k.left-.5,_=k.top-.5,h=k.width+1,b=k.height+1,M=Math.min(I+.5,h/2,b/2),C=Ar(R,_,h,b,M),N=`__fork-glow-${f}`,T=document.createElementNS(t,"filter");T.setAttribute("id",N),T.setAttribute("x","-100%"),T.setAttribute("y","-100%"),T.setAttribute("width","300%"),T.setAttribute("height","300%");let L=document.createElementNS(t,"feGaussianBlur");L.setAttribute("in","SourceGraphic"),L.setAttribute("stdDeviation","8"),T.appendChild(L),o.appendChild(T);let x=`__fork-mask-${f}`,w=document.createElementNS(t,"mask");w.setAttribute("id",x),w.setAttribute("maskUnits","userSpaceOnUse"),w.setAttribute("x",String(R-200)),w.setAttribute("y",String(_-200)),w.setAttribute("width",String(h+400)),w.setAttribute("height",String(b+400));let d=document.createElementNS(t,"rect");d.setAttribute("x",String(R-200)),d.setAttribute("y",String(_-200)),d.setAttribute("width",String(h+400)),d.setAttribute("height",String(b+400)),d.setAttribute("fill","white"),w.appendChild(d);let S=document.createElementNS(t,"path");S.setAttribute("d",C),S.setAttribute("fill","black"),w.appendChild(S),o.appendChild(w);let E=document.createElementNS(t,"g");E.setAttribute("mask",`url(#${x})`),E.setAttribute("opacity","0");let A=document.createElementNS(t,"g");A.setAttribute("filter",`url(#${N})`);let u=document.createElementNS(t,"path");u.setAttribute("d",C),u.setAttribute("fill","none"),u.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),u.setAttribute("stroke-width","6"),u.setAttribute("stroke-linecap","round"),A.appendChild(u),E.appendChild(A),n.appendChild(E);let l=document.createElementNS(t,"path");l.setAttribute("d",C),l.setAttribute("fill","none"),l.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),l.setAttribute("stroke-width","2"),l.setAttribute("stroke-linecap","round"),l.setAttribute("opacity","0"),n.appendChild(l),i.push(u,l),u.__group=E;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let f=0;f<i.length;f+=2){let k=i[f],I=i[f+1],R=k.__group,_=I.getTotalLength(),h=k.getTotalLength();if(_<=0)continue;let b=_*.35;I.setAttribute("stroke-dasharray",`${b} ${_-b}`),I.setAttribute("stroke-dashoffset","0"),s.push(I.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*_,opacity:.92,offset:.06},{strokeDashoffset:-2*_,opacity:.92,offset:.92},{strokeDashoffset:-2.25*_,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let M=h*.35;k.setAttribute("stroke-dasharray",`${M} ${h-M}`),k.setAttribute("stroke-dashoffset","0"),s.push(k.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*h,offset:.06},{strokeDashoffset:-2*h,offset:.92},{strokeDashoffset:-2.25*h,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(R.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 c=false,p=()=>{if(c)return;c=true,clearTimeout(g);for(let k of s)try{k.cancel();}catch{}let f=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});f.onfinish=()=>r.remove(),window.removeEventListener("click",p);},g=setTimeout(p,14500);return setTimeout(()=>{c||window.addEventListener("click",p);},500),p}function Dn(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:c,borderRadius:p}of e){let g=c.left,f=c.top,k=c.width,I=c.height,R=Math.min(p,k/2,I/2),_=Ar(g,f,k,I,R),h=document.createElementNS(t,"path");h.setAttribute("d",_),h.setAttribute("fill","none"),h.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),h.setAttribute("stroke-width","1.5"),h.setAttribute("stroke-dasharray","8 4"),h.setAttribute("stroke-linecap","round"),h.setAttribute("filter","url(#__fork-removed-shadow)"),h.setAttribute("opacity","0"),n.appendChild(h),h.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 zn(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 Wn=Ut__namespace.default.memo(function({component:t,containerRef:r,wrapperStyle:n,hostProps:o}){return wn.jsx("div",{ref:r,style:n,children:wn.jsx(t,{...o})})},(e,t)=>e.component===t.component&&zn(e.hostProps,t.hostProps)),Bt=class extends Ut__namespace.default.Component{constructor(t){super(t),this.state={hasError:false};}static getDerivedStateFromError(){return {hasError:true}}componentDidCatch(t){console.error(`[Fork:${this.props.slotId}] fork render failed`,t);}componentDidUpdate(t){t.resetKey!==this.props.resetKey&&this.state.hasError&&this.setState({hasError:false});}render(){return this.state.hasError?this.props.fallback:this.props.children}};function $r({slotId:e,children:t,githubRepo:r,shared:n,events:o}){jt(t,e);let i=ft(e),{baseUrl:s,apiKey:c,appId:p,shouldSkipAnimation:g}=Q(),[f,k]=Ut.useState(null),I=Ut.useRef(null),R=Ut.useRef(null),_=Ut.useRef(null),h=Ut.useRef(false),b=Ut.useRef(null),M=Ut.useRef(null),C=!!(n||o),N=Ut.useRef(null);C&&!N.current&&(N.current=new ze(e));let T=Ut.useRef(o);if(T.current=o,Ut.useEffect(()=>{if(C)return ()=>{N.current?.destroy(),N.current=null;}},[C,e]),C&&N.current&&n)for(let[S,E]of Object.entries(n))N.current.set(S,E);Ut.useEffect(()=>{if(!C)return;N.current||(N.current=new ze(e));let S=N.current,E=Object.keys(T.current||{}).map(A=>S.on(A,(...u)=>T.current?.[A]?.(...u)));return ()=>E.forEach(A=>A())},[C,e]),Ut.useEffect(()=>{if(Rr.has(e))return;Rr.add(e);let S={id:e,appId:p,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 ${c}`,"Content-Type":"application/json"},body:JSON.stringify(S)}).catch(()=>{});},[e,s,c,r,p]);let L=i?.id||null;Ut.useEffect(()=>{if(i?.bundleUrl,I.current,R.current,!i?.bundleUrl||!L){return}let S=`${s}${i.bundleUrl.replace("bundle.js","component.js")}`,E=`__fork_animated_${e}`,A=sessionStorage.getItem(E),u=g(e),l=!u&&A!==L;if(u&&L&&sessionStorage.setItem(E,L),l&&R.current){let W=Cr(R.current);_.current=W,h.current=true,`${e}${W.length}`;}window.__FORK_REACT__=Ut__namespace.default,window.__FORK_REACT_DOM__=bn__namespace,window.__FORK_REACT_JSX__=wn__namespace;let y=Date.now(),j=`${s}${i.bundleUrl.replace("bundle.js","component.css")}?t=${y}`,Y=document.createElement("link");Y.rel="stylesheet",Y.href=j,Y.dataset.forkSlot=e,document.head.appendChild(Y);let D=document.createElement("script");return D.src=S+"?t="+y,D.onload=()=>{let W=window.__FORK_EXPORT__;if(W?.default){if(R.current&&_.current&&h.current){let ee=R.current.getBoundingClientRect(),z=R.current.cloneNode(true);z.style.position="fixed",z.style.top=`${ee.top}px`,z.style.left=`${ee.left}px`,z.style.width=`${ee.width}px`,z.style.height=`${ee.height}px`,z.style.flex="none",z.style.minHeight="auto",z.style.zIndex="9998",z.style.pointerEvents="none",z.style.overflow="hidden";let se=getComputedStyle(R.current).backgroundColor;z.style.backgroundColor=se&&se!=="rgba(0, 0, 0, 0)"&&se!=="transparent"?se:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(z);let ie=R.current.querySelectorAll("*"),fe=z.querySelectorAll("*");for(let te=0;te<ie.length;te++)ie[te].scrollTop!==0&&(fe[te].scrollTop=ie[te].scrollTop),ie[te].scrollLeft!==0&&(fe[te].scrollLeft=ie[te].scrollLeft);b.current=z;}k(()=>W.default),I.current=L;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},D.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(D),()=>{D.remove(),Y.remove(),M.current&&(clearTimeout(M.current),M.current=null),b.current&&(b.current.remove(),b.current=null);}},[L,s,e]),Ut.useEffect(()=>{if(!h.current||!f||!R.current){`${e}${h.current}`,R.current;return}let S=_.current;if(!S){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!R.current)return;let E=Cr(R.current),A=Un(S,E),u=jn(S,E),l=b.current;if(`${e}${A.length}${u.length}`,u.length>0&&l){let y=Dn(u);M.current=setTimeout(()=>{M.current=null;let j=400;l.animate([{opacity:1},{opacity:0}],{duration:j,fill:"forwards"}),y.animate([{opacity:1},{opacity:0}],{duration:j,fill:"forwards"}),setTimeout(()=>{l.remove(),y.remove(),b.current=null,A.length>0&&(Er(A));},j);},3500);}else l&&(l.remove(),b.current=null),A.length>0&&(Er(A));_.current=null,h.current=false,L&&(sessionStorage.setItem(`__fork_animated_${e}`,L),`${e}`);});});},[f]);let x={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!i||i.status!=="complete"||!i.bundleUrl)return wn.jsx("div",{ref:R,style:x,children:t});if(!f)return wn.jsx("div",{ref:R,style:x,children:t});let d=t?.props??{};return wn.jsx(Bt,{slotId:e,resetKey:L,fallback:wn.jsx("div",{ref:R,style:x,children:t}),children:wn.jsx(Wn,{component:f,containerRef:R,wrapperStyle:x,hostProps:d})})}var Ir=new Set;function Jn(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 Tr(e,t=new Set){return Ut.Children.forEach(e,r=>{if(!Ut.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&&Tr(n.children,t);}),t}function qn({slotId:e,props:t,children:r,allowedFetches:n,githubRepo:o,callbacks:i,mode:s="iframe",shared:c,events:p}){if(jt(r,e),s==="direct")return wn.jsx($r,{slotId:e,githubRepo:o,shared:c,events:p,children:r});let g=ft(e),{baseUrl:f,apiKey:k,appId:I}=Q(),R=Ut.useRef(null),_=Ut.useRef(false),h=Ut.useRef(null),b=Ut.useRef(i);b.current=i;let M=Ut.useRef(t);M.current=t;let C=Ut.useRef(n);C.current=n,Ut.useEffect(()=>{if(typeof process<"u")return;let x=Tr(r),w=new Set(i?Object.keys(i):[]),d=[...x].filter(S=>!w.has(S));d.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
+ `+d.map(S=>` - ${S}`).join(`
4
+ `)+"\n\nThe forked component will not be able to call these. Add them to the `callbacks` prop of <ForkSlot>.");},[e,r,i]),Ut.useEffect(()=>{Ir.has(e)||(Ir.add(e),fetch(`${f}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${k}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:I,label:e,propsShape:t?Jn(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:o,callbackNames:i?Object.keys(i):[],mode:s||"iframe"})}).catch(()=>{}));},[e,f,k,o,I]);let N=Ut.useCallback(x=>{let w=R.current;if(w?.contentWindow&&_.current){let d=b.current?Object.keys(b.current):[];w.contentWindow.postMessage({type:"slot:props",props:x,callbackNames:d},"*"),h.current=null;}else h.current=x;},[]),T=Ut.useCallback((x,w)=>{let d=C.current;return !d||d.length===0?false:d.some(S=>{let[E,A]=S.split(" "),u=w.split("?")[0];return x.toUpperCase()===E.toUpperCase()&&u.startsWith(A)})},[]);if(Ut.useEffect(()=>{if(!g?.bundleUrl)return;let x=async w=>{if(w.source===R.current?.contentWindow){if(w.data?.type==="slot:ready")_.current=true,R.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:C.current||[]},"*"),C.current,h.current?N(h.current):N(M.current||{});else if(w.data?.type==="slot:event"){let d=w.data.event;d?.navigate&&(window.location.hash=d.navigate);}else if(w.data?.type==="slot:clipboard-write")navigator.clipboard.writeText(w.data.text).catch(d=>{console.warn(`[ForkSlot:${e}] clipboard write failed:`,d.message);});else if(w.data?.type==="slot:callback"){let{name:d,args:S}=w.data,E=b.current?.[d];E?(E(...S||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${d}`);}else if(w.data?.type==="slot:fetch"){let{id:d,method:S,url:E,body:A}=w.data,u=R.current?.contentWindow;if(!u)return;let l=S||"GET";if(!T(l,E)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${d}: ${l} ${E} \u2014 not in allowedFetches`),u.postMessage({type:"slot:fetch-response",id:d,error:`Fetch not allowed: ${l} ${E}`},"*");return}try{let y={method:l};A&&l!=="GET"&&(y.headers={"Content-Type":"application/json"},y.body=JSON.stringify(A));let j=await fetch(E,y),Y=await j.json();`${e}${d}${j.status}`,u.postMessage({type:"slot:fetch-response",id:d,data:Y,status:j.status},"*");}catch(y){console.error(`[ForkSlot:${e}] fetch #${d} failed:`,y.message),u.postMessage({type:"slot:fetch-response",id:d,error:y.message},"*");}}}};return window.addEventListener("message",x),()=>{window.removeEventListener("message",x),_.current=false;}},[g?.bundleUrl,e,N,T]),Ut.useEffect(()=>{g?.bundleUrl&&_.current&&N(t||{});},[t,g?.bundleUrl,N]),!g||g.status!=="complete"||!g.bundleUrl)return `${e}${g?.status||"none"}${g?.bundleUrl||"none"}`,wn.jsx(wn.Fragment,{children:r});`${e}${g.bundleUrl}`;let L=`${f}${g.bundleUrl.replace("/bundle.js","/host")}`;return wn.jsx("iframe",{ref:R,src:L,sandbox:"allow-scripts allow-same-origin allow-forms allow-clipboard-write",title:`Forked ${e}`,style:{width:"100%",border:"none",flex:1,minHeight:0}})}function gt({style:e={width:20,height:20},...t}){return wn.jsxs("svg",{viewBox:"320 95 270 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:e,...t,children:[wn.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"}),wn.jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M387.096 174.735v188"}),wn.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"}),wn.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"}),wn.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"})]})}function zt({onClick:e}){let[t,r]=Ut.useState(false),[n,o]=Ut.useState(false),i=t?48:40;return wn.jsx("button",{onClick:e,onMouseEnter:()=>r(true),onMouseLeave:()=>{r(false),o(false);},onMouseDown:()=>o(true),onMouseUp:()=>o(false),style:{position:"fixed",bottom:24,right:24,zIndex:40,width:i,height:i,borderRadius:"50%",backgroundColor:t?"rgba(255, 255, 255, 1)":"rgba(255, 255, 255, 0.3)",border:t?"1px solid rgba(156, 163, 175, 1)":"1px solid rgba(156, 163, 175, 0.3)",display:"flex",alignItems:"center",justifyContent:"center",color:t?"#1c4587":"rgba(28, 69, 135, 0.5)",boxShadow:t?"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:n?"scale(0.95)":"scale(1)",transition:"all 300ms",cursor:"pointer",padding:0,margin:0,outline:"none",boxSizing:"border-box"},title:"Fork this app",children:wn.jsx(gt,{style:{width:24,height:24}})})}var oo={status:lucideReact.Loader2,agent_message:lucideReact.MessageSquare,tool_use:lucideReact.Wrench,build_start:lucideReact.Package,build_complete:lucideReact.Check,build_error:lucideReact.AlertCircle,complete:lucideReact.Sparkles,error:lucideReact.AlertCircle},so={status:"#60a5fa",agent_message:"#a0a0a0",tool_use:"#fbbf24",build_start:"#c084fc",build_complete:"#6b7280",build_error:"#f87171",complete:"#6b7280",error:"#f87171"},io={read:lucideReact.FileSearch,write:lucideReact.Pencil,search:lucideReact.FileSearch,shell:lucideReact.Terminal,build:lucideReact.Package},ao={read:"#60a5fa",write:"#fbbf24",search:"#60a5fa",shell:"#a78bfa",build:"#c084fc"};function Kt(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 jr({events:e}){let t=Ut.useRef(null);return Ut.useEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight);},[e]),wn.jsxs(wn.Fragment,{children:[wn.jsx("style",{children:`
4
5
  @keyframes __fork-spin {
5
6
  from { transform: rotate(0deg); }
6
7
  to { transform: rotate(360deg); }
@@ -18,7 +19,7 @@
18
19
  .__fork-stream::-webkit-scrollbar-thumb:hover {
19
20
  background: rgba(255, 255, 255, 0.3);
20
21
  }
21
- `}),yn.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&&yn.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"#6b7280",fontSize:"11px"},children:[yn.jsx(lucideReact.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"),c=to[r.type]||lucideReact.Code,p=ro[r.type]||"#9ca3af";if(r.type==="tool_use"){let g=String(r.data.category||"");c=no[g]||lucideReact.Wrench,p=oo[g]||"#fbbf24";}return s?c=lucideReact.Loader2:!o&&r.type==="status"&&(c=lucideReact.Check,p="#4ade80"),yn.jsxs("div",{style:{display:"flex",gap:"6px",marginBottom:"6px",lineHeight:1.625},children:[yn.jsx(c,{style:{width:"12px",height:"12px",marginTop:"2px",flexShrink:0,color:p,...s?{animation:"__fork-spin 1s linear infinite"}:{}}}),yn.jsx("span",{style:{color:o&&!i?"#d1d5db":"#6b7280",wordBreak:"break-all"},children:Dt(r)})]},n)})]})]})}var jr=35,po="Working on Feature",go="Built Custom Feature",Dr=360,mt=350;function mo(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 ho(e){return e.length<=jr?e:e.slice(0,jr-3).trimEnd()+"..."}function yo({events:e}){let[t,r]=Bt.useState("Setting up environment..."),[n,o]=Bt.useState(true),i=Bt.useRef(t),s=Bt.useRef(false);return Bt.useEffect(()=>{if(!s.current){for(let p of e)if(p.type==="status"&&String(p.data.message||"").includes("Agent started")){s.current=true;break}}let c="Setting up environment...";if(s.current)for(let p=e.length-1;p>=0;p--){let g=e[p];if(g.type==="tool_use"||g.type==="build_start"||g.type==="build_complete"){c=ho(Dt(g));break}}if(c!==i.current){o(false);let p=setTimeout(()=>{r(c),i.current=c,o(true);},200);return ()=>clearTimeout(p)}},[e]),yn.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 ko({children:e}){let[t,r]=Bt.useState(null);return Bt.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?hn.createPortal(e,t):null}function ht({state:e,fork:t,events:r,error:n,slotId:o,targetId:i,targetLabel:s,historyMode:c="slot",onSubmit:p,onUndo:g,onClose:f,baseUrl:S,apiKey:P,userId:_,userHash:R,appId:h,embedded:y=false}){let[I,C]=Bt.useState(""),[N,M]=Bt.useState([]),[L,x]=Bt.useState(false),[k,d]=Bt.useState(false),[v,E]=Bt.useState(false),[A,u]=Bt.useState(false),[l,b]=Bt.useState(false),[j,Y]=Bt.useState(false),[D,W]=Bt.useState(false),[ee,z]=Bt.useState(false),[se,ie]=Bt.useState(false),[fe,te]=Bt.useState(null),[vt,qe]=Bt.useState(false),[Me,ce]=Bt.useState([]),[Z,T]=Bt.useState(null),[F,O]=Bt.useState(false),[re,ne]=Bt.useState(false),[Te,Qt]=Bt.useState(false),[rn,er]=Bt.useState(null),[q,Xe]=Bt.useState(null),[nn,tr]=Bt.useState(false),[St,Ye]=Bt.useState(false),[me,Ie]=Bt.useState(""),xt=Bt.useRef(null),[rr,he]=Bt.useState(null),[on,Le]=Bt.useState(false),[Fe,nr]=Bt.useState(null),[Ne,Ze]=Bt.useState([]),[X,Re]=Bt.useState(null),[ae,_e]=Bt.useState(false),Ce=Bt.useRef(false),Ft=Bt.useRef(null),Qe=Bt.useRef(null),{resetAllForks:sn,previewSession:G,currentContainerId:an}=Q(),ye=G?.container_id??an,et=!!(G&&on),de=Fe!==null,or=Bt.useRef(f);Bt.useEffect(()=>{or.current=f;});let Rt=Bt.useRef(null),tt=Bt.useRef(false),sr=typeof window<"u"&&"documentPictureInPicture"in window,ln=async()=>{if(!(!sr||de))try{let a=await window.documentPictureInPicture.requestWindow({width:Dr,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 m=document.adoptedStyleSheets??[];m.length>0&&(a.document.adoptedStyleSheets=[...m]);}catch{}a.addEventListener("pagehide",()=>{Rt.current=null,nr(null),tt.current||or.current(),tt.current=!1;},{once:!0}),Rt.current=a,nr(a);}catch(a){console.warn("[Fork] PiP open failed:",a);}},cn=()=>{Fe&&(tt.current=true,Fe.close());};Bt.useEffect(()=>()=>{tt.current=true,Rt.current?.close();},[]);let pe=i??o??"",ir=(s||pe).replace(/[-_]+/g," ").replace(/\b\w/g,a=>a.toUpperCase()),rt=Bt.useRef(""),ar=()=>{let a={Authorization:`Bearer ${P}`,...K()};return h&&(a["X-Fork-App-Id"]=h),!G&&_&&(a["X-Fork-User-Id"]=_),!G&&R&&(a["X-Fork-User-Hash"]=R),a},nt=y?true:k&&!v,dn=r.find(a=>{let m=a.data;return a.type==="status"&&m.summary})?.data?.summary||t?.summary||po,ke=r.find(a=>{let m=a.data;return (a.type==="status"||a.type==="complete")&&typeof m?.estimateMinutes=="number"})?.data?.estimateMinutes??t?.estimateMinutes;Bt.useEffect(()=>{if(c==="none"){x(true);return}if(!S||!P)return;if(!X){M([]),x(true);return}let a=new AbortController;return fetch(`${S}/api/v1/forks/${encodeURIComponent(X)}/messages`,{headers:ar(),signal:a.signal}).then(m=>m.ok?m.json():[]).then(m=>{if(a.signal.aborted)return;let $=[];for(let J of m){let Ee=J.forkId??X;J.role==="user"?$.push({type:"user",text:J.content,forkId:Ee}):$.push({type:"applied",text:J.content,forkId:Ee});}M($),x(true);}).catch(()=>{a.signal.aborted||x(true);}),()=>{a.abort();}},[P,h,S,c,X,G?.fork_id,G?.preview_session_id,R,_,t?.id,t?.completedAt]),Bt.useEffect(()=>{if(c==="none"||!S||!P||!F)return;if(!Z){Ze([]);return}let a=new AbortController,m=new URLSearchParams({container_id:Z});return fetch(`${S}/api/v1/forks?${m.toString()}`,{headers:ar(),signal:a.signal}).then($=>$.ok?$.json():{forks:[]}).then($=>{a.signal.aborted||Ze($.forks??[]);}).catch(()=>{}),()=>{a.abort();}},[P,h,S,c,Z,F,t?.id,t?.completedAt,G?.fork_id,G?.preview_session_id,R,_]),Bt.useEffect(()=>{e==="complete"&&z(false);},[e]);let lr=Ne.some(a=>a.status==="pending"||a.status==="running"||a.status==="building");Bt.useEffect(()=>{if(!lr||!S||!P||!Z)return;let a=new URLSearchParams({container_id:Z}),m={Authorization:`Bearer ${P}`,...K()};h&&(m["X-Fork-App-Id"]=h);let J=setInterval(async()=>{try{let Ee=await fetch(`${S}/api/v1/forks?${a.toString()}`,{headers:m});if(!Ee.ok)return;let gn=await Ee.json();Ze(gn.forks??[]);}catch{}},3e3);return ()=>clearInterval(J)},[lr,S,P,h,Z]),Bt.useEffect(()=>{if(y&&c==="none"){ce([]),T(null),O(true),Le(false);return}if(G){let a=false;return O(false),Le(false),he(null),fetch(`${S}/api/v1/preview/${encodeURIComponent(G.preview_session_id)}/containers`,{headers:{Authorization:`Bearer ${P}`,...K()}}).then(m=>{if(!m.ok)throw new Error(`${m.status}`);return m.json()}).then(m=>{a||(ce(m.containers),T(m.currentContainerId??G.container_id??null),Le(true));}).catch(m=>{a||(Le(false),he(m instanceof Error?m.message:String(m)),ye?(ce([{id:ye,name:G.container_name||"Primary container",createdAt:"",hasAccess:true,isPrimary:true}]),T(ye)):(ce([]),T(null)));}).finally(()=>{a||O(true);}),()=>{a=true;}}ye?(ce([{id:ye,name:"Primary container",createdAt:""}]),T(ye)):(ce([]),T(null)),O(true),Le(false);},[P,ye,S,y,c,G?.container_id,G?.container_name,G?.preview_session_id]);let ot=Bt.useRef(void 0);Bt.useEffect(()=>{if(F){if(ot.current===void 0){ot.current=Z;return}ot.current!==Z&&(ot.current=Z,M([]),x(false));}},[Z,F]);let st=Bt.useRef(null);Bt.useEffect(()=>{if(!re)return;let a=$=>{if(!st.current)return;let J=typeof $.composedPath=="function"?$.composedPath():[];st.current.contains($.target)||J.includes(st.current)||ne(false);},m=$=>{$.key==="Escape"&&ne(false);};return document.addEventListener("mousedown",a,true),document.addEventListener("keydown",m,true),()=>{document.removeEventListener("mousedown",a,true),document.removeEventListener("keydown",m,true);}},[re]),Bt.useEffect(()=>{re||(Ye(false),Ie(""));},[re]),Bt.useEffect(()=>{St&&(xt.current?.focus(),xt.current?.select());},[St]),Bt.useEffect(()=>{if(y)return;let a=requestAnimationFrame(()=>d(true));return ()=>cancelAnimationFrame(a)},[y]),Bt.useEffect(()=>{let a=y||de;if((a||nt)&&(e==="prompting"||e==="complete")){let m=setTimeout(()=>Ft.current?.focus(),a?100:mt+100);return ()=>clearTimeout(m)}},[nt,y,de,e]),Bt.useEffect(()=>{if(e==="complete"&&rt.current){let m=r.find($=>$.type==="complete")?.data?.summary||t?.summary||go;M($=>$[$.length-1]?.type==="applied"?$:[...$,{type:"applied",text:m}]),C(""),setTimeout(()=>Ft.current?.focus(),200);}},[e,ir,r,t?.summary]),Bt.useEffect(()=>{Qe.current&&(Qe.current.scrollTop=Qe.current.scrollHeight);},[N,e]);let cr=()=>{if(I.trim()){rt.current=I.trim();let a={};ae?(a.forceNew=true,Ce.current=true):X&&(a.forkId=X),ae||M(m=>[...m,{type:"user",text:I.trim(),forkId:X}]),p(I.trim(),pe,Z,a),C("");}};Bt.useEffect(()=>{if(Ce.current){if(e==="error"){Ce.current=false;return}t?.id&&(Re(t.id),_e(false),Ce.current=false);}},[t?.id,e]);let dr=a=>{ve(a.session.containerId,a.session.containerName),T(a.session.containerId),ce(m=>{let $=m.filter(J=>J.id!==a.container.id);return [{...a.container,isPrimary:true,hasAccess:true},...$.map(J=>({...J,isPrimary:false}))]}),Re(null),_e(false),Ce.current=false,M([]),x(false),rt.current="";},un=async a=>{if(!(!G||!et||q)){Xe(a),he(null);try{let m=await fetch(`${S}/api/v1/preview/${encodeURIComponent(G.preview_session_id)}/containers/${encodeURIComponent(a)}/primary`,{method:"POST",headers:{Authorization:`Bearer ${P}`,...K()}});if(!m.ok){let $=await m.json().catch(()=>({}));throw new Error($.error||`API error: ${m.status}`)}dr(await m.json()),ne(!1);}catch(m){he(m instanceof Error?m.message:String(m));}finally{Xe(null);}}},ur=async a=>{if(!G||!et||q)return;let m=a.trim();if(m){Xe("__new__"),he(null);try{let $=await fetch(`${S}/api/v1/preview/${encodeURIComponent(G.preview_session_id)}/containers`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${P}`,...K()},body:JSON.stringify({name:m})});if(!$.ok){let J=await $.json().catch(()=>({}));throw new Error(J.error||`API error: ${$.status}`)}dr(await $.json()),Ye(!1),Ie(""),ne(!1);}catch($){he($ instanceof Error?$.message:String($));}finally{Xe(null);}}},fn=async()=>{if(!(!g||se||!pe)){ie(true);try{let a=await g(pe);M(m=>{let $=[...m];return $.length>=2&&$[$.length-1]?.type==="applied"?$.splice(-2,2):$.length>=1&&$[$.length-1]?.type==="applied"&&$.splice(-1,1),$}),a?.removed&&M([]);}catch{}finally{ie(false);}}},fr=()=>{if(y){f();return}if(de){Fe?.close();return}E(true),d(false),setTimeout(()=>f(),mt);},pn=y||de?{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:Dr,maxWidth:"100vw",background:"#ffffff",boxShadow:nt?"-12px 0 32px -16px rgba(0, 0, 0, 0.18), -2px 0 8px -2px rgba(0, 0, 0, 0.06)":"none",borderLeft:"1px solid rgba(0, 0, 0, 0.08)",transform:nt?"translateX(0)":"translateX(100%)",transition:`transform ${mt}ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow ${mt}ms ease`,display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'},pr=Me.find(a=>a.id===Z)?.name??(F?"Fork":"Loading..."),Be=ae?[]:X?N.filter(a=>a.forkId===X||a.forkId==null):N,_t=yn.jsxs(yn.Fragment,{children:[yn.jsx("style",{children:`
22
+ `}),wn.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&&wn.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"#6b7280",fontSize:"11px"},children:[wn.jsx(lucideReact.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"),c=oo[r.type]||lucideReact.Code,p=so[r.type]||"#9ca3af";if(r.type==="tool_use"){let g=String(r.data.category||"");c=io[g]||lucideReact.Wrench,p=ao[g]||"#fbbf24";}return s?c=lucideReact.Loader2:!o&&r.type==="status"&&(c=lucideReact.Check,p="#4ade80"),wn.jsxs("div",{style:{display:"flex",gap:"6px",marginBottom:"6px",lineHeight:1.625},children:[wn.jsx(c,{style:{width:"12px",height:"12px",marginTop:"2px",flexShrink:0,color:p,...s?{animation:"__fork-spin 1s linear infinite"}:{}}}),wn.jsx("span",{style:{color:o&&!i?"#d1d5db":"#6b7280",wordBreak:"break-all"},children:Kt(r)})]},n)})]})]})}var Wr=35,ho="Working on Feature",yo="Built Custom Feature",Kr=360,yt=350;function ko(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 bo(e){return e.length<=Wr?e:e.slice(0,Wr-3).trimEnd()+"..."}function wo({events:e}){let[t,r]=Ut.useState("Setting up environment..."),[n,o]=Ut.useState(true),i=Ut.useRef(t),s=Ut.useRef(false);return Ut.useEffect(()=>{if(!s.current){for(let p of e)if(p.type==="status"&&String(p.data.message||"").includes("Agent started")){s.current=true;break}}let c="Setting up environment...";if(s.current)for(let p=e.length-1;p>=0;p--){let g=e[p];if(g.type==="tool_use"||g.type==="build_start"||g.type==="build_complete"){c=bo(Kt(g));break}}if(c!==i.current){o(false);let p=setTimeout(()=>{r(c),i.current=c,o(true);},200);return ()=>clearTimeout(p)}},[e]),wn.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 vo({children:e}){let[t,r]=Ut.useState(null);return Ut.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?bn.createPortal(e,t):null}function kt({state:e,fork:t,events:r,error:n,slotId:o,targetId:i,targetLabel:s,historyMode:c="slot",onSubmit:p,onUndo:g,onClose:f,baseUrl:k,apiKey:I,userId:R,userHash:_,appId:h,embedded:b=false}){let[M,C]=Ut.useState(""),[N,T]=Ut.useState([]),[L,x]=Ut.useState(false),[w,d]=Ut.useState(false),[S,E]=Ut.useState(false),[A,u]=Ut.useState(false),[l,y]=Ut.useState(false),[j,Y]=Ut.useState(false),[D,W]=Ut.useState(false),[ee,z]=Ut.useState(false),[se,ie]=Ut.useState(false),[fe,te]=Ut.useState(null),[xt,Xe]=Ut.useState(false),[Te,ce]=Ut.useState([]),[Z,$]=Ut.useState(null),[F,O]=Ut.useState(false),[re,ne]=Ut.useState(false),[Me,rr]=Ut.useState(false),[sn,nr]=Ut.useState(null),[V,Ye]=Ut.useState(null),[an,or]=Ut.useState(false),[Ft,Ze]=Ut.useState(false),[he,Le]=Ut.useState(""),_t=Ut.useRef(null),[sr,ye]=Ut.useState(null),[ln,Ne]=Ut.useState(false),[_e,ir]=Ut.useState(null),[He,Qe]=Ut.useState([]),[X,Re]=Ut.useState(null),[ae,Ce]=Ut.useState(false),Ee=Ut.useRef(false),Rt=Ut.useRef(null),et=Ut.useRef(null),{resetAllForks:cn,previewSession:G,currentContainerId:dn}=Q(),ke=G?.container_id??dn,tt=!!(G&&ln),de=_e!==null,ar=Ut.useRef(f);Ut.useEffect(()=>{ar.current=f;});let Ct=Ut.useRef(null),rt=Ut.useRef(false),lr=typeof window<"u"&&"documentPictureInPicture"in window,un=async()=>{if(!(!lr||de))try{let a=await window.documentPictureInPicture.requestWindow({width:Kr,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 m=document.adoptedStyleSheets??[];m.length>0&&(a.document.adoptedStyleSheets=[...m]);}catch{}a.addEventListener("pagehide",()=>{Ct.current=null,ir(null),rt.current||ar.current(),rt.current=!1;},{once:!0}),Ct.current=a,ir(a);}catch(a){console.warn("[Fork] PiP open failed:",a);}},fn=()=>{_e&&(rt.current=true,_e.close());};Ut.useEffect(()=>()=>{rt.current=true,Ct.current?.close();},[]);let pe=i??o??"",cr=(s||pe).replace(/[-_]+/g," ").replace(/\b\w/g,a=>a.toUpperCase()),nt=Ut.useRef(""),dr=()=>{let a={Authorization:`Bearer ${I}`,...K()};return h&&(a["X-Fork-App-Id"]=h),!G&&R&&(a["X-Fork-User-Id"]=R),!G&&_&&(a["X-Fork-User-Hash"]=_),a},ot=b?true:w&&!S,pn=r.find(a=>{let m=a.data;return a.type==="status"&&m.summary})?.data?.summary||t?.summary||ho,be=r.find(a=>{let m=a.data;return (a.type==="status"||a.type==="complete")&&typeof m?.estimateMinutes=="number"})?.data?.estimateMinutes??t?.estimateMinutes;Ut.useEffect(()=>{if(c==="none"){x(true);return}if(!k||!I)return;if(!X){T([]),x(true);return}let a=new AbortController;return fetch(`${k}/api/v1/forks/${encodeURIComponent(X)}/messages`,{headers:dr(),signal:a.signal}).then(m=>m.ok?m.json():[]).then(m=>{if(a.signal.aborted)return;let P=[];for(let J of m){let Ae=J.forkId??X;J.role==="user"?P.push({type:"user",text:J.content,forkId:Ae}):P.push({type:"applied",text:J.content,forkId:Ae});}T(P),x(true);}).catch(()=>{a.signal.aborted||x(true);}),()=>{a.abort();}},[I,h,k,c,X,G?.fork_id,G?.preview_session_id,_,R,t?.id,t?.completedAt]),Ut.useEffect(()=>{if(c==="none"||!k||!I||!F)return;if(!Z){Qe([]);return}let a=new AbortController,m=new URLSearchParams({container_id:Z});return fetch(`${k}/api/v1/forks?${m.toString()}`,{headers:dr(),signal:a.signal}).then(P=>P.ok?P.json():{forks:[]}).then(P=>{a.signal.aborted||Qe(P.forks??[]);}).catch(()=>{}),()=>{a.abort();}},[I,h,k,c,Z,F,t?.id,t?.completedAt,G?.fork_id,G?.preview_session_id,_,R]),Ut.useEffect(()=>{e==="complete"&&z(false);},[e]);let ur=He.some(a=>a.status==="pending"||a.status==="running"||a.status==="building");Ut.useEffect(()=>{if(!ur||!k||!I||!Z)return;let a=new URLSearchParams({container_id:Z}),m={Authorization:`Bearer ${I}`,...K()};h&&(m["X-Fork-App-Id"]=h);let J=setInterval(async()=>{try{let Ae=await fetch(`${k}/api/v1/forks?${a.toString()}`,{headers:m});if(!Ae.ok)return;let yn=await Ae.json();Qe(yn.forks??[]);}catch{}},3e3);return ()=>clearInterval(J)},[ur,k,I,h,Z]),Ut.useEffect(()=>{if(b&&c==="none"){ce([]),$(null),O(true),Ne(false);return}if(G){let a=false;return O(false),Ne(false),ye(null),fetch(`${k}/api/v1/preview/${encodeURIComponent(G.preview_session_id)}/containers`,{headers:{Authorization:`Bearer ${I}`,...K()}}).then(m=>{if(!m.ok)throw new Error(`${m.status}`);return m.json()}).then(m=>{a||(ce(m.containers),$(m.currentContainerId??G.container_id??null),Ne(true));}).catch(m=>{a||(Ne(false),ye(m instanceof Error?m.message:String(m)),ke?(ce([{id:ke,name:G.container_name||"Primary container",createdAt:"",hasAccess:true,isPrimary:true}]),$(ke)):(ce([]),$(null)));}).finally(()=>{a||O(true);}),()=>{a=true;}}ke?(ce([{id:ke,name:"Primary container",createdAt:""}]),$(ke)):(ce([]),$(null)),O(true),Ne(false);},[I,ke,k,b,c,G?.container_id,G?.container_name,G?.preview_session_id]);let st=Ut.useRef(void 0);Ut.useEffect(()=>{if(F){if(st.current===void 0){st.current=Z;return}st.current!==Z&&(st.current=Z,T([]),x(false));}},[Z,F]);let it=Ut.useRef(null);Ut.useEffect(()=>{if(!re)return;let a=P=>{if(!it.current)return;let J=typeof P.composedPath=="function"?P.composedPath():[];it.current.contains(P.target)||J.includes(it.current)||ne(false);},m=P=>{P.key==="Escape"&&ne(false);};return document.addEventListener("mousedown",a,true),document.addEventListener("keydown",m,true),()=>{document.removeEventListener("mousedown",a,true),document.removeEventListener("keydown",m,true);}},[re]),Ut.useEffect(()=>{re||(Ze(false),Le(""));},[re]),Ut.useEffect(()=>{Ft&&(_t.current?.focus(),_t.current?.select());},[Ft]),Ut.useEffect(()=>{if(b)return;let a=requestAnimationFrame(()=>d(true));return ()=>cancelAnimationFrame(a)},[b]),Ut.useEffect(()=>{let a=b||de;if((a||ot)&&(e==="prompting"||e==="complete")){let m=setTimeout(()=>Rt.current?.focus(),a?100:yt+100);return ()=>clearTimeout(m)}},[ot,b,de,e]),Ut.useEffect(()=>{if(e==="complete"&&nt.current){let m=r.find(P=>P.type==="complete")?.data?.summary||t?.summary||yo;T(P=>P[P.length-1]?.type==="applied"?P:[...P,{type:"applied",text:m}]),C(""),setTimeout(()=>Rt.current?.focus(),200);}},[e,cr,r,t?.summary]),Ut.useEffect(()=>{et.current&&(et.current.scrollTop=et.current.scrollHeight);},[N,e]);let fr=()=>{if(M.trim()){nt.current=M.trim();let a={};ae?(a.forceNew=true,Ee.current=true):X&&(a.forkId=X),ae||T(m=>[...m,{type:"user",text:M.trim(),forkId:X}]),p(M.trim(),pe,Z,a),C("");}};Ut.useEffect(()=>{if(Ee.current){if(e==="error"){Ee.current=false;return}t?.id&&(Re(t.id),Ce(false),Ee.current=false);}},[t?.id,e]);let pr=a=>{ve(a.session.containerId,a.session.containerName),$(a.session.containerId),ce(m=>{let P=m.filter(J=>J.id!==a.container.id);return [{...a.container,isPrimary:true,hasAccess:true},...P.map(J=>({...J,isPrimary:false}))]}),Re(null),Ce(false),Ee.current=false,T([]),x(false),nt.current="";},gn=async a=>{if(!(!G||!tt||V)){Ye(a),ye(null);try{let m=await fetch(`${k}/api/v1/preview/${encodeURIComponent(G.preview_session_id)}/containers/${encodeURIComponent(a)}/primary`,{method:"POST",headers:{Authorization:`Bearer ${I}`,...K()}});if(!m.ok){let P=await m.json().catch(()=>({}));throw new Error(P.error||`API error: ${m.status}`)}pr(await m.json()),ne(!1);}catch(m){ye(m instanceof Error?m.message:String(m));}finally{Ye(null);}}},gr=async a=>{if(!G||!tt||V)return;let m=a.trim();if(m){Ye("__new__"),ye(null);try{let P=await fetch(`${k}/api/v1/preview/${encodeURIComponent(G.preview_session_id)}/containers`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${I}`,...K()},body:JSON.stringify({name:m})});if(!P.ok){let J=await P.json().catch(()=>({}));throw new Error(J.error||`API error: ${P.status}`)}pr(await P.json()),Ze(!1),Le(""),ne(!1);}catch(P){ye(P instanceof Error?P.message:String(P));}finally{Ye(null);}}},mn=async()=>{if(!(!g||se||!pe)){ie(true);try{let a=await g(pe);T(m=>{let P=[...m];return P.length>=2&&P[P.length-1]?.type==="applied"?P.splice(-2,2):P.length>=1&&P[P.length-1]?.type==="applied"&&P.splice(-1,1),P}),a?.removed&&T([]);}catch{}finally{ie(false);}}},mr=()=>{if(b){f();return}if(de){_e?.close();return}E(true),d(false),setTimeout(()=>f(),yt);},hn=b||de?{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:Kr,maxWidth:"100vw",background:"#ffffff",boxShadow:ot?"-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:ot?"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'},hr=Te.find(a=>a.id===Z)?.name??(F?"Fork":"Loading..."),Oe=ae?[]:X?N.filter(a=>a.forkId===X||a.forkId==null):N,Et=wn.jsxs(wn.Fragment,{children:[wn.jsx("style",{children:`
22
23
  @keyframes __fork-pulse {
23
24
  0%, 100% { opacity: 1; }
24
25
  50% { opacity: 0.5; }
@@ -40,5 +41,5 @@
40
41
  scrollbar-width: thin;
41
42
  scrollbar-color: rgba(0, 0, 0, 0.12) transparent;
42
43
  }
43
- `}),yn.jsxs("div",{className:"__fork-panel",style:pn,children:[yn.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:[yn.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:[yn.jsx("span",{onDoubleClick:async a=>{if(a.stopPropagation(),!vt&&confirm("Kill all forks in this container?")){qe(true);try{let m=await sn();`${m?.deleted??0}`,Ze([]),Re(null),_e(!1),C("");}catch(m){console.error("[Fork] Reset failed:",m);}finally{qe(false);}}},style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:4,margin:-4,cursor:"pointer",flexShrink:0},children:yn.jsx(ft,{style:{width:16,height:16,color:"#1c4587",pointerEvents:"none"}})}),e==="running"?yn.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:dn}):Me.length===0&&!et?yn.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:"Fork"}):et?yn.jsxs("div",{ref:st,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[yn.jsxs("button",{type:"button",onClick:()=>{ne(a=>!a);},onMouseEnter:()=>Qt(true),onMouseLeave:()=>Qt(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:Te||re?"#f3f4f6":"transparent",fontSize:13,fontWeight:600,color:"#111827",fontFamily:"inherit",cursor:"pointer",maxWidth:180,minWidth:0,transition:"background-color 0.12s"},children:[yn.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:pr}),yn.jsx(lucideReact.ChevronDown,{style:{width:12,height:12,color:"#6b7280",flexShrink:0,transform:re?"rotate(180deg)":void 0,transition:"transform 0.15s"}})]}),re&&yn.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:[Me.map(a=>{let m=a.id===Z,$=rn===a.id,J=q===a.id;return yn.jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>er(a.id),onMouseLeave:()=>er(null),onClick:()=>{a.id!==Z&&un(a.id);},disabled:!!q,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:$?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:q?"default":"pointer",textAlign:"left",fontWeight:m?600:400,opacity:q&&!J?.55:1},children:[yn.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:m&&yn.jsx(lucideReact.Check,{style:{width:12,height:12}})}),yn.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:J?"Switching...":a.name})]},a.id)}),yn.jsx("div",{style:{height:1,background:"#e5e7eb",margin:"4px 0"}}),St?yn.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"4px 4px"},children:[yn.jsx("input",{ref:xt,type:"text",value:me,placeholder:"Container name",disabled:q==="__new__",onChange:a=>Ie(a.target.value),onKeyDown:a=>{a.key==="Enter"?(a.preventDefault(),ur(me)):a.key==="Escape"&&(a.preventDefault(),a.stopPropagation(),Ye(false),Ie(""));},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";}}),yn.jsx("button",{type:"button",onClick:()=>{ur(me);},disabled:!me.trim()||q==="__new__",title:"Create",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:26,height:26,border:"none",borderRadius:4,background:!me.trim()||q==="__new__"?"#e5e7eb":"#1c4587",color:!me.trim()||q==="__new__"?"#9ca3af":"#ffffff",cursor:!me.trim()||q==="__new__"?"default":"pointer",flexShrink:0},children:q==="__new__"?yn.jsx("span",{style:{width:10,height:10,border:"1.5px solid currentColor",borderTopColor:"transparent",borderRadius:"50%",animation:"__fork-spin 0.7s linear infinite"}}):yn.jsx(lucideReact.Check,{style:{width:12,height:12}})})]}):yn.jsx("button",{type:"button",role:"menuitem",onMouseEnter:()=>tr(true),onMouseLeave:()=>tr(false),onClick:()=>{q||(he(null),Ie(""),Ye(true));},disabled:!!q,style:{display:"flex",alignItems:"center",width:"100%",padding:"6px 8px",border:"none",background:nn?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:q?"default":"pointer",textAlign:"left",opacity:q&&q!=="__new__"?.55:1},children:"+ New container"}),rr&&yn.jsx("div",{style:{padding:"6px 8px",fontSize:11,lineHeight:1.35,color:"#b91c1c"},children:rr})]})]}):yn.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:pr}),e==="running"&&yn.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"}),e==="complete"&&yn.jsx("div",{style:{height:6,width:6,backgroundColor:"#1c4587",borderRadius:"50%",flexShrink:0}})]}),!y&&yn.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[sr&&yn.jsx("button",{onClick:de?cn:ln,onMouseEnter:()=>b(true),onMouseLeave:()=>b(false),title:de?"Redock to sidebar":"Pop out into window",style:{padding:6,borderRadius:6,color:l?"#4b5563":"#9ca3af",backgroundColor:l?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:de?yn.jsx(lucideReact.PictureInPicture,{style:{width:16,height:16}}):yn.jsx(lucideReact.PictureInPicture2,{style:{width:16,height:16}})}),yn.jsx("button",{onClick:fr,onMouseEnter:()=>u(true),onMouseLeave:()=>u(false),style:{padding:6,borderRadius:6,color:A?"#4b5563":"#9ca3af",backgroundColor:A?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:yn.jsx(lucideReact.X,{style:{width:16,height:16}})})]})]}),yn.jsxs("div",{ref:Qe,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[(X||ae)&&yn.jsxs("div",{style:{padding:"10px 12px 6px 12px",display:"flex",alignItems:"center",gap:8,borderBottom:"1px solid #f3f4f6"},children:[yn.jsx("button",{onClick:()=>{Re(null),_e(false),Ce.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 m=(X?Ne.find($=>$.id===X)?.targetId:null)??pe;return m?yn.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 ${m}`,children:["Forking ",yn.jsx("span",{style:{color:"#6b7280"},children:m})]}):null})()]}),!X&&!ae&&yn.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[yn.jsxs("div",{style:{padding:"12px 16px 6px 16px",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[yn.jsx("span",{style:{fontSize:12,fontWeight:600,color:"#111827"},children:"Forks"}),pe&&yn.jsx("button",{onClick:()=>{Re(null),_e(true);},title:`Start a new fork on ${pe}`,style:{padding:"4px 10px",fontSize:11,lineHeight:1.3,borderRadius:999,border:"1px dashed #d1d5db",background:"#ffffff",color:"#374151",cursor:"pointer",whiteSpace:"nowrap"},children:"+ New fork"})]}),Ne.length===0&&yn.jsx("div",{style:{padding:"24px 20px",textAlign:"center",fontSize:13,color:"#6b7280"},children:"No forks yet. Click + New fork to build something."}),Ne.length>0&&yn.jsx("div",{style:{display:"flex",flexDirection:"column"},children:Ne.map(a=>{let m=a.summary||"Untitled fork";return yn.jsxs("button",{onClick:()=>{_e(false),Re(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:$=>$.currentTarget.style.background="#fafafa",onMouseLeave:$=>$.currentTarget.style.background="#ffffff",children:[yn.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[yn.jsx("span",{style:{fontSize:13,fontWeight:500,color:"#111827",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1},children:m}),yn.jsx("span",{style:{fontSize:11,color:"#9ca3af",flexShrink:0},children:mo(a.updatedAt)})]}),yn.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:11,color:"#6b7280"},children:[yn.jsx("span",{style:{fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, "Liberation Mono", "Courier New", monospace',whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:a.targetId}),yn.jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),yn.jsxs("span",{children:[a.promptCount," prompt",a.promptCount===1?"":"s"]}),a.status==="running"||a.status==="building"?yn.jsxs(yn.Fragment,{children:[yn.jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),yn.jsx("span",{style:{color:"#2563eb"},children:"running"})]}):null]})]},a.id)})})]}),ae&&yn.jsx("div",{style:{padding:"24px 20px",textAlign:"center"},children:yn.jsx("p",{style:{fontSize:13,color:"#6b7280",marginBottom:14,lineHeight:1.625,margin:"0 0 14px 0"},children:"Describe the feature you want to build."})}),X&&Be.length>0&&yn.jsx("div",{style:{padding:"16px 16px 0 16px"},children:Be.map((a,m)=>yn.jsx("div",{style:{marginBottom:m<Be.length-1?10:0},children:a.type==="user"?yn.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexDirection:"row-reverse"},children:[yn.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:yn.jsx(lucideReact.User,{style:{width:13,height:13,color:"#6b7280"}})}),yn.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})]}):yn.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[yn.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#f0fdf4",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:yn.jsx(lucideReact.Check,{style:{width:13,height:13,color:"#9ca3af"}})}),yn.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:[yn.jsx("span",{style:{flex:1},children:a.text}),g&&m===Be.length-1&&e!=="running"&&yn.jsxs("button",{onClick:$=>{$.stopPropagation(),fn();},onMouseEnter:()=>te(m),onMouseLeave:()=>te(null),disabled:se,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:fe===m?"rgba(0,0,0,0.06)":"transparent",color:fe===m?"#6b7280":"#d1d5db",cursor:se?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:se?.4:1,flexShrink:0},children:[yn.jsx(lucideReact.Undo2,{style:{width:12,height:12}}),fe===m&&yn.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"})]})]})]})},m))}),e==="running"&&(X||ae)&&yn.jsx("div",{style:{padding:16},children:yn.jsxs("div",{onClick:()=>z(!ee),style:{backgroundColor:"#1a1a2e",borderRadius:12,overflow:"hidden",cursor:"pointer",transition:"all 0.3s cubic-bezier(0.22, 1, 0.36, 1)"},children:[yn.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px"},children:[yn.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[yn.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:yn.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),yn.jsx(yo,{events:r})]}),yn.jsx("div",{style:{color:"#6b7280",flexShrink:0,marginLeft:8,transition:"transform 0.2s ease",transform:ee?"rotate(180deg)":"rotate(0deg)"},children:yn.jsx(lucideReact.ChevronDown,{style:{width:14,height:14}})})]}),yn.jsx("div",{style:{maxHeight:ee?320:0,opacity:ee?1:0,transition:"max-height 0.35s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.25s ease",overflow:"hidden"},children:yn.jsx("div",{style:{borderTop:"1px solid rgba(255,255,255,0.08)",maxHeight:320,overflowY:"auto"},children:yn.jsx(Or,{events:r})})})]})}),e==="error"&&(X||ae)&&yn.jsxs("div",{style:{padding:"20px 16px",textAlign:"center"},children:[yn.jsx("div",{style:{width:36,height:36,backgroundColor:"#fef2f2",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 10px auto"},children:yn.jsx(lucideReact.X,{style:{width:18,height:18,color:"#ef4444"}})}),yn.jsx("p",{style:{fontSize:12,color:"#6b7280",marginBottom:10,maxWidth:260,margin:"0 auto 10px auto"},children:n}),yn.jsxs("button",{onClick:()=>{let a=t?.prompt||rt.current;a&&p(a,pe);},onMouseEnter:()=>W(true),onMouseLeave:()=>W(false),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,color:"#4f46e5",backgroundColor:D?"#e0e7ff":"#eef2ff",border:"none",cursor:"pointer",transition:"background-color 0.15s",fontFamily:"inherit"},children:[yn.jsx(lucideReact.RotateCcw,{style:{width:12,height:12}})," Try Again"]})]})]}),e!=="running"&&(X||ae)&&yn.jsx("div",{style:{padding:"8px 12px 12px 12px",borderTop:"1px solid rgba(229, 231, 235, 0.6)",flexShrink:0},children:yn.jsxs("div",{style:{display:"flex",alignItems:"flex-end",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:[yn.jsx("textarea",{ref:Ft,value:I,onChange:a=>{C(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(),cr()),a.key==="Escape"&&!y&&fr();},placeholder:Be.length>0&&!ae?"Ask for another change...":`Describe your ideal ${ir.toLowerCase()}...`,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"}}),yn.jsx("button",{onClick:cr,disabled:!I.trim(),onMouseEnter:()=>Y(true),onMouseLeave:()=>Y(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:I.trim()?1:.25,transform:j&&I.trim()?"scale(1.1)":"scale(1)",background:I.trim()?"#1c4587":"rgba(0,0,0,0.12)",border:"none",cursor:I.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:yn.jsx(lucideReact.ArrowUp,{style:{width:13,height:13}})})]})})]})]});return y?_t:de&&Fe?hn.createPortal(_t,Fe.document.body):yn.jsx(ko,{children:_t})}function Kr(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 Wt(e){let{apiKey:t,userId:r,userHash:n,baseUrl:o,appId:i,previewSession:s,refreshModuleManifest:c,queueBoundaryAnimation:p}=Q(),[g,f]=Bt.useState("idle"),[S,P]=Bt.useState(null),[_,R]=Bt.useState([]),[h,y]=Bt.useState(null),I=Bt.useRef(null),C=Bt.useCallback(()=>{f("prompting"),R([]),y(null),P(null);},[]),N=Bt.useCallback(()=>{f("idle"),I.current&&(I.current.close(),I.current=null);},[]);Bt.useEffect(()=>{s&&s.target.kind==="module"&&s.target.id===e&&f(x=>x==="idle"?"prompting":x);},[s?.preview_session_id,s?.target.id,e]);let M=Bt.useCallback(async(x,k,d)=>{try{if(!i)throw new Error("ForkProvider requires appId for module boundary prompts.");f("running"),R([]),y(null);let v;if(s){let u=d?.forkId??s.fork_id??void 0,l=await fetch(`${o}/api/v1/preview/${encodeURIComponent(s.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...K()},body:JSON.stringify({prompt:x,...e?{boundary_id:e}:{},...u&&!d?.forceNew?{fork_id:u}:{},...d?.forceNew?{force_new:!0}:{}})});if(!l.ok){let Y=await l.json().catch(()=>({}));throw new Error(Y.error||`API error: ${l.status}`)}let b=await l.json();b.container_id&&ve(b.container_id,b.container_name),Ue(b.fork_id),v=await(await fetch(`${o}/api/v1/forks/${b.fork_id}`,{headers:{Authorization:`Bearer ${t}`,...K()}})).json();}else if(d?.forkId){let u={prompt:x};r&&(u.userId=r),n&&(u.userHash=n);let l=await fetch(`${o}/api/v1/forks/${encodeURIComponent(d.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(u)});if(!l.ok){let b=await l.json().catch(()=>({}));throw new Error(b.error||`API error: ${l.status}`)}v=await l.json();}else {let u={userId:r,prompt:x,boundaryId:e,appId:i};k&&(u.containerId=k),n&&(u.userHash=n),d?.forceNew&&(u.force_new=!0);let l=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(u)});if(!l.ok){let b=await l.json().catch(()=>({}));throw new Error(b.error||`API error: ${l.status}`)}v=await l.json();}P(v);let E=new URLSearchParams({key:t});s?(E.set("previewSessionId",s.preview_session_id),E.set("previewForkId",v.id)):r&&E.set("userId",r),n&&E.set("userHash",n);let A=new EventSource(`${o}/api/v1/forks/${v.id}/events?${E.toString()}`);I.current=A,A.onmessage=u=>{try{let l=JSON.parse(u.data);if(R(b=>[...b,l]),l.type==="complete"){let b=l.data;p(e,v.id),c().catch(()=>{}).finally(()=>{let j={...v,status:"complete",moduleUrl:b.moduleUrl,cssUrls:b.cssUrls,summary:b.summary,completedAt:new Date().toISOString()};P(j),f("complete"),A.close();});}else if(l.type==="error"){let b=l.data;y(b.error||"Unknown error"),f("error"),A.close();}}catch{}},A.onerror=()=>{let u={Authorization:`Bearer ${t}`,...K()};!s&&r&&(u["X-Fork-User-Id"]=r),!s&&n&&(u["X-Fork-User-Hash"]=n),fetch(`${o}/api/v1/forks/${v.id}`,{headers:u}).then(l=>l.json()).then(l=>{P(l),l.status==="complete"?(p(e,l.id),c().catch(()=>{}),f("complete")):l.status==="error"&&(y(l.error||"Fork generation failed"),f("error"));}).catch(()=>{y("Connection lost"),f("error");}),A.close();};}catch(v){y(v.message),f("error");}},[t,i,o,e,s,p,c,n,r]),L=Bt.useCallback(async()=>{try{if(!i)throw new Error("ForkProvider requires appId for boundary undo.");let x={userId:r,boundaryId:e,appId:i};n&&(x.userHash=n);let k=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(x)});if(!k.ok){let v=await k.json().catch(()=>({}));throw new Error(v.error||`API error: ${k.status}`)}let d=await k.json();return await c().catch(()=>{}),d.removed?(P(null),f("prompting")):d.fork&&(P(d.fork),f("complete")),d}catch(x){throw y(x.message),x}},[t,i,o,e,c,n,r]);return {state:g,fork:S,events:_,error:h,open:C,close:N,startFork:M,undoFork:L}}function Gr(e){let{state:t,fork:r,events:n,error:o,open:i,close:s,startFork:c,undoFork:p}=Wt(e);return {state:t,fork:r,events:n,error:o,isOpen:t!=="idle",open:i,close:s,submit:c,undo:p}}function Kt(){let{apiKey:e,userId:t,userHash:r,baseUrl:n,previewSession:o,setSlotFork:i,clearSlotFork:s,skipAnimationForSlot:c}=Q(),[p,g]=Bt.useState("idle"),[f,S]=Bt.useState(null),[P,_]=Bt.useState([]),[R,h]=Bt.useState(null),y=Bt.useRef(null),I=Bt.useCallback(()=>{g("prompting"),_([]),h(null),S(null);},[]),C=Bt.useCallback(()=>{g("idle"),y.current&&(y.current.close(),y.current=null);},[]);Bt.useEffect(()=>{o&&o.target.kind==="slot"&&g(L=>L==="idle"?"prompting":L);},[o?.preview_session_id,o?.target.kind]);let N=Bt.useCallback(async(L,x,k,d)=>{try{g("running"),_([]),h(null);let v;if(o){let u=d?.forkId??o.fork_id??void 0,l=await fetch(`${n}/api/v1/preview/${encodeURIComponent(o.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...K()},body:JSON.stringify({prompt:L,...x?{slot_id:x}:{},...u&&!d?.forceNew?{fork_id:u}:{},...d?.forceNew?{force_new:!0}:{}})});if(!l.ok){let Y=await l.json().catch(()=>({}));throw new Error(Y.error||`API error: ${l.status}`)}let b=await l.json();b.container_id&&ve(b.container_id,b.container_name),Ue(b.fork_id),v=await(await fetch(`${n}/api/v1/forks/${b.fork_id}`,{headers:{Authorization:`Bearer ${e}`,...K()}})).json();}else if(d?.forkId){let u={prompt:L};t&&(u.userId=t),r&&(u.userHash=r);let l=await fetch(`${n}/api/v1/forks/${encodeURIComponent(d.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(u)});if(!l.ok){let b=await l.json().catch(()=>({}));throw new Error(b.error||`API error: ${l.status}`)}v=await l.json();}else {let u={userId:t,prompt:L};x&&(u.slotId=x),k&&(u.containerId=k),r&&(u.userHash=r),d?.forceNew&&(u.force_new=!0);let l=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(u)});if(!l.ok){let b=await l.json().catch(()=>({}));throw new Error(b.error||`API error: ${l.status}`)}v=await l.json();}S(v);let E=new URLSearchParams({key:e});o?(E.set("previewSessionId",o.preview_session_id),E.set("previewForkId",v.id)):t&&E.set("userId",t),r&&E.set("userHash",r);let A=new EventSource(`${n}/api/v1/forks/${v.id}/events?${E.toString()}`);y.current=A,A.onmessage=u=>{try{let l=JSON.parse(u.data);if(_(b=>[...b,l]),l.type==="complete"){let b=l.data,j={...v,status:"complete",bundleUrl:b.bundleUrl,summary:b.summary,completedAt:new Date().toISOString()};S(j),g("complete"),x&&b.bundleUrl&&i(x,j),A.close();}else if(l.type==="error"){let b=l.data;h(b.error||"Unknown error"),g("error"),A.close();}}catch{}},A.onerror=()=>{let u={Authorization:`Bearer ${e}`,...K()};!o&&t&&(u["X-Fork-User-Id"]=t),!o&&r&&(u["X-Fork-User-Hash"]=r),fetch(`${n}/api/v1/forks/${v.id}`,{headers:u}).then(l=>l.json()).then(l=>{S(l),l.status==="complete"?(g("complete"),x&&l.bundleUrl&&i(x,l)):l.status==="error"&&(h(l.error||"Fork generation failed"),g("error"));}).catch(()=>{h("Connection lost"),g("error");}),A.close();};}catch(v){h(v.message),g("error");}},[e,t,r,n,o,i]),M=Bt.useCallback(async L=>{try{let x={userId:t,slotId:L};r&&(x.userHash=r);let k=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(x)});if(!k.ok){let v=await k.json().catch(()=>({}));throw new Error(v.error||`API error: ${k.status}`)}let d=await k.json();return c(L),d.removed?(s(L),S(null),g("prompting")):d.fork&&(i(L,d.fork),S(d.fork)),d}catch(x){throw h(x.message),x}},[e,t,r,n,s,i]);return {state:p,fork:f,events:P,error:R,open:I,close:C,startFork:N,undoFork:M}}function Jr(){let{state:e,fork:t,events:r,error:n,open:o,close:i,startFork:s,undoFork:c}=Kt();return {state:e,fork:t,events:r,error:n,isOpen:e!=="idle",open:o,close:i,submit:s,undo:c}}function Gt(e){let t=Kr(e),r=Jr(),n=Gr(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:i,userId:s,userHash:c,appId:p}=Q(),g=t.type==="slot"?r:n,f=t.type==="slot"?"slot":"boundary",S=t.id,P=t.title,_=Bt.useCallback((h,y,I,C)=>t.type==="slot"?r.submit(h,y??t.id,I,C):n.submit(h,I,C),[n,r,t]),R=Bt.useCallback(h=>t.type==="slot"?r.undo(h??t.id):n.undo(),[n,r,t]);return {...g,target:t,targetId:S,targetLabel:P,historyMode:f,submit:_,undo:R,buttonProps:{onClick:g.open},panelProps:{state:g.state,fork:g.fork,events:g.events,error:g.error,...t.type==="slot"?{slotId:S,targetLabel:P,historyMode:f}:{targetId:S,targetLabel:P,historyMode:f},onSubmit:_,onUndo:R,onClose:g.close,baseUrl:o,apiKey:i,userId:s,userHash:c,appId:p}}}function Ke(e){let{embedded:t}=e,r=Gt(e);return t?yn.jsx(ht,{...r.panelProps,embedded:true}):r.isOpen?yn.jsx(ht,{...r.panelProps}):yn.jsx(Ht,{...r.buttonProps})}function xo({boundaryId:e,title:t}){return yn.jsx(Ke,{boundaryId:e,title:t})}function Vt(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 qr(e){let t=e.getBoundingClientRect(),r=e.cloneNode(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 qt(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 Xr(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 c=r[s];c.rect.top>=n.rect.top&&c.rect.left>=n.rect.left&&c.rect.right<=n.rect.right&&c.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Yr(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 c=r[s];c.rect.top>=n.rect.top&&c.rect.left>=n.rect.left&&c.rect.right<=n.rect.right&&c.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){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 Xt(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 f=0;f<e.length;f+=1){let{rect:S,borderRadius:P}=e[f],_=S.left-.5,R=S.top-.5,h=S.width+1,y=S.height+1,I=Math.min(P+.5,h/2,y/2),C=Zr(_,R,h,y,I),N=`__fork-glow-${f}`,M=document.createElementNS(t,"filter");M.setAttribute("id",N),M.setAttribute("x","-100%"),M.setAttribute("y","-100%"),M.setAttribute("width","300%"),M.setAttribute("height","300%");let L=document.createElementNS(t,"feGaussianBlur");L.setAttribute("in","SourceGraphic"),L.setAttribute("stdDeviation","8"),M.appendChild(L),o.appendChild(M);let x=`__fork-mask-${f}`,k=document.createElementNS(t,"mask");k.setAttribute("id",x),k.setAttribute("maskUnits","userSpaceOnUse"),k.setAttribute("x",String(_-200)),k.setAttribute("y",String(R-200)),k.setAttribute("width",String(h+400)),k.setAttribute("height",String(y+400));let d=document.createElementNS(t,"rect");d.setAttribute("x",String(_-200)),d.setAttribute("y",String(R-200)),d.setAttribute("width",String(h+400)),d.setAttribute("height",String(y+400)),d.setAttribute("fill","white"),k.appendChild(d);let v=document.createElementNS(t,"path");v.setAttribute("d",C),v.setAttribute("fill","black"),k.appendChild(v),o.appendChild(k);let E=document.createElementNS(t,"g");E.setAttribute("mask",`url(#${x})`),E.setAttribute("opacity","0");let A=document.createElementNS(t,"g");A.setAttribute("filter",`url(#${N})`);let u=document.createElementNS(t,"path");u.setAttribute("d",C),u.setAttribute("fill","none"),u.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),u.setAttribute("stroke-width","6"),u.setAttribute("stroke-linecap","round"),A.appendChild(u),E.appendChild(A),n.appendChild(E);let l=document.createElementNS(t,"path");l.setAttribute("d",C),l.setAttribute("fill","none"),l.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),l.setAttribute("stroke-width","2"),l.setAttribute("stroke-linecap","round"),l.setAttribute("opacity","0"),n.appendChild(l),i.push(u,l),u.__group=E;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let f=0;f<i.length;f+=2){let S=i[f],P=i[f+1],_=S.__group;if(!_)continue;let R=P.getTotalLength(),h=S.getTotalLength();if(R<=0)continue;let y=R*.35;P.setAttribute("stroke-dasharray",`${y} ${R-y}`),P.setAttribute("stroke-dashoffset","0"),s.push(P.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*R,opacity:.92,offset:.06},{strokeDashoffset:-2*R,opacity:.92,offset:.92},{strokeDashoffset:-2.25*R,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let I=h*.35;S.setAttribute("stroke-dasharray",`${I} ${h-I}`),S.setAttribute("stroke-dashoffset","0"),s.push(S.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*h,offset:.06},{strokeDashoffset:-2*h,offset:.92},{strokeDashoffset:-2.25*h,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 c=false,p=()=>{if(c)return;c=true,clearTimeout(g);for(let S of s)try{S.cancel();}catch{}let f=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});f.onfinish=()=>r.remove(),window.removeEventListener("click",p);},g=setTimeout(p,14500);return setTimeout(()=>{c||window.addEventListener("click",p);},500),p}function Qr(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:c,borderRadius:p}of e){let g=document.createElementNS(t,"path");g.setAttribute("d",Zr(c.left,c.top,c.width,c.height,p)),g.setAttribute("fill","none"),g.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),g.setAttribute("stroke-width","1.5"),g.setAttribute("stroke-dasharray","8 4"),g.setAttribute("stroke-linecap","round"),g.setAttribute("filter","url(#__fork-removed-shadow)"),g.setAttribute("opacity","0"),n.appendChild(g),g.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 Je=new Map,Ve=new Map,Yt=new Map;function _o(e){for(let t of e)Ve.set(t,(Ve.get(t)??0)+1);}function Co(e){if(!(typeof document>"u"))for(let t of e){let r=(Ve.get(t)??0)-1;if(r>0){Ve.set(t,r);continue}Ve.delete(t),Je.delete(t);let n=document.querySelector(`link[data-fork-override-href="${CSS.escape(t)}"]`);n&&n.remove();}}function Eo(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function tn(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 Ao(e){if(!e||typeof document>"u")return Promise.resolve();let t=Je.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 c=()=>{r.removeEventListener("load",c),r.removeEventListener("error",p),i();},p=()=>{r.removeEventListener("load",c),r.removeEventListener("error",p),s(new Error(`Failed to load boundary stylesheet: ${e}`));};r.addEventListener("load",c,{once:true}),r.addEventListener("error",p,{once:true});});return Je.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 Je.delete(e),o});return Je.set(e,n),n}function $o(e){let t=Yt.get(e);if(t)return t;let r=import(e).catch(n=>{throw Yt.delete(e),n});return Yt.set(e,r),r}async function Po(e,t,r){if(e)try{await Promise.all(e.cssUrls.map(i=>Ao(i)));let o=await $o(e.moduleUrl);return tn(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 tn(n,r)}function Mo(e){function t(r){let{appId:n,moduleOverridesEnabled:o,moduleManifestReady:i,moduleManifestVersion:s,registerBoundary:c,getBoundaryOverride:p,consumeBoundaryAnimation:g}=Q(),[f,S]=Bt.useState(null),[P,_]=Bt.useState(null),R=Bt.useRef(null),h=Bt.useRef(null),y=Bt.useRef(null),I=Bt.useRef(false),C=Bt.useRef(null),N=Bt.useRef(null),M=p(e.id),L=M?`override:${M.id}`:"original",x=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if(Bt.useEffect(()=>()=>{N.current&&(clearTimeout(N.current),N.current=null),C.current&&(C.current.remove(),C.current=null);},[]),Bt.useEffect(()=>{c({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[n,c,e.id,e.exportName,x]),Bt.useEffect(()=>{let k=M?.cssUrls??[];if(k.length!==0)return _o(k),()=>Co(k)},[M?.cssUrls.join("|")]),Bt.useEffect(()=>{if(o&&!i&&!f||h.current===L&&f)return;let k=false;return _(null),Po(M,e.original,e.exportName).then(d=>{if(!k){if(M?.id&&g(e.id,M.id)&&R.current){let v=Vt(R.current);if(v){let E=qt(v);E.length>0&&(y.current=E,I.current=true,N.current&&(clearTimeout(N.current),N.current=null),C.current&&C.current.remove(),C.current=qr(v));}}h.current=L,Bt.startTransition(()=>{S(()=>d);});}}).catch(d=>{k||_(Eo(d));}),()=>{k=true;}},[g,L,o,i,s,M?.id,M?.moduleUrl,M?.integrity,M?.cssUrls.join("|"),e.exportName,e.original,f]),Bt.useEffect(()=>{if(!I.current||!f||!R.current)return;let k=false;return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(k||!R.current)return;let d=y.current,v=Vt(R.current);if(y.current=null,I.current=false,!d||!v){C.current&&(C.current.remove(),C.current=null);return}let E=qt(v),A=Xr(d,E),u=Yr(d,E),l=C.current;if(u.length>0&&l){let b=Qr(u);N.current=setTimeout(()=>{N.current=null;let j=400;l.animate([{opacity:1},{opacity:0}],{duration:j,fill:"forwards"}),b.animate([{opacity:1},{opacity:0}],{duration:j,fill:"forwards"}),setTimeout(()=>{l.remove(),b.remove(),C.current===l&&(C.current=null),A.length>0&&Xt(A);},j);},3500);}else l&&(l.remove(),C.current===l&&(C.current=null)),A.length>0&&Xt(A);});}),()=>{k=true;}},[f]),P)throw P;return f?yn.jsx("div",{ref:R,style:{display:"contents"},children:yn.jsx(f,{...r})}):yn.jsx(yn.Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function Io({slotId:e,title:t,slotLabel:r}){return yn.jsx(Ke,{slotId:e,title:t,slotLabel:r})}
44
- exports.ForkBoundaryUI=xo;exports.ForkButton=Ht;exports.ForkChatInterface=Ke;exports.ForkPanel=ht;exports.ForkProvider=Mn;exports.ForkSlot=Kn;exports.ForkUI=Io;exports.clearCachedManifest=Cn;exports.forkable=Mo;exports.loadManifest=ct;exports.manifestDiffers=En;exports.readCachedManifest=Rn;exports.registerForkShared=Et;exports.useBoundaryFork=Wt;exports.useFork=Kt;exports.useForkChatPanel=Gt;exports.usePreviewSession=lt;exports.writeCachedManifest=_n;
44
+ `}),wn.jsxs("div",{className:"__fork-panel",style:hn,children:[wn.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:[wn.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:[wn.jsx("span",{onDoubleClick:async a=>{if(a.stopPropagation(),!xt&&confirm("Kill all forks in this container?")){Xe(true);try{let m=await cn();`${m?.deleted??0}`,Qe([]),Re(null),Ce(!1),C("");}catch(m){console.error("[Fork] Reset failed:",m);}finally{Xe(false);}}},style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:4,margin:-4,cursor:"pointer",flexShrink:0},children:wn.jsx(gt,{style:{width:16,height:16,color:"#1c4587",pointerEvents:"none"}})}),e==="running"?wn.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:pn}):Te.length===0&&!tt?wn.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:"Fork"}):tt?wn.jsxs("div",{ref:it,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[wn.jsxs("button",{type:"button",onClick:()=>{ne(a=>!a);},onMouseEnter:()=>rr(true),onMouseLeave:()=>rr(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:Me||re?"#f3f4f6":"transparent",fontSize:13,fontWeight:600,color:"#111827",fontFamily:"inherit",cursor:"pointer",maxWidth:180,minWidth:0,transition:"background-color 0.12s"},children:[wn.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:hr}),wn.jsx(lucideReact.ChevronDown,{style:{width:12,height:12,color:"#6b7280",flexShrink:0,transform:re?"rotate(180deg)":void 0,transition:"transform 0.15s"}})]}),re&&wn.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:[Te.map(a=>{let m=a.id===Z,P=sn===a.id,J=V===a.id;return wn.jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>nr(a.id),onMouseLeave:()=>nr(null),onClick:()=>{a.id!==Z&&gn(a.id);},disabled:!!V,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:P?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:V?"default":"pointer",textAlign:"left",fontWeight:m?600:400,opacity:V&&!J?.55:1},children:[wn.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:m&&wn.jsx(lucideReact.Check,{style:{width:12,height:12}})}),wn.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:J?"Switching...":a.name})]},a.id)}),wn.jsx("div",{style:{height:1,background:"#e5e7eb",margin:"4px 0"}}),Ft?wn.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"4px 4px"},children:[wn.jsx("input",{ref:_t,type:"text",value:he,placeholder:"Container name",disabled:V==="__new__",onChange:a=>Le(a.target.value),onKeyDown:a=>{a.key==="Enter"?(a.preventDefault(),gr(he)):a.key==="Escape"&&(a.preventDefault(),a.stopPropagation(),Ze(false),Le(""));},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";}}),wn.jsx("button",{type:"button",onClick:()=>{gr(he);},disabled:!he.trim()||V==="__new__",title:"Create",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:26,height:26,border:"none",borderRadius:4,background:!he.trim()||V==="__new__"?"#e5e7eb":"#1c4587",color:!he.trim()||V==="__new__"?"#9ca3af":"#ffffff",cursor:!he.trim()||V==="__new__"?"default":"pointer",flexShrink:0},children:V==="__new__"?wn.jsx("span",{style:{width:10,height:10,border:"1.5px solid currentColor",borderTopColor:"transparent",borderRadius:"50%",animation:"__fork-spin 0.7s linear infinite"}}):wn.jsx(lucideReact.Check,{style:{width:12,height:12}})})]}):wn.jsx("button",{type:"button",role:"menuitem",onMouseEnter:()=>or(true),onMouseLeave:()=>or(false),onClick:()=>{V||(ye(null),Le(""),Ze(true));},disabled:!!V,style:{display:"flex",alignItems:"center",width:"100%",padding:"6px 8px",border:"none",background:an?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:V?"default":"pointer",textAlign:"left",opacity:V&&V!=="__new__"?.55:1},children:"+ New container"}),sr&&wn.jsx("div",{style:{padding:"6px 8px",fontSize:11,lineHeight:1.35,color:"#b91c1c"},children:sr})]})]}):wn.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:hr}),e==="running"&&wn.jsx("span",{title:be?`Estimated ~${be} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:be?"#1c4587":"#9ca3af",backgroundColor:be?"rgba(28, 69, 135, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:be?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:be?`~${be}m`:"~ m"}),e==="complete"&&wn.jsx("div",{style:{height:6,width:6,backgroundColor:"#1c4587",borderRadius:"50%",flexShrink:0}})]}),!b&&wn.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[lr&&wn.jsx("button",{onClick:de?fn:un,onMouseEnter:()=>y(true),onMouseLeave:()=>y(false),title:de?"Redock to sidebar":"Pop out into window",style:{padding:6,borderRadius:6,color:l?"#4b5563":"#9ca3af",backgroundColor:l?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:de?wn.jsx(lucideReact.PictureInPicture,{style:{width:16,height:16}}):wn.jsx(lucideReact.PictureInPicture2,{style:{width:16,height:16}})}),wn.jsx("button",{onClick:mr,onMouseEnter:()=>u(true),onMouseLeave:()=>u(false),style:{padding:6,borderRadius:6,color:A?"#4b5563":"#9ca3af",backgroundColor:A?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:wn.jsx(lucideReact.X,{style:{width:16,height:16}})})]})]}),wn.jsxs("div",{ref:et,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[(X||ae)&&wn.jsxs("div",{style:{padding:"10px 12px 6px 12px",display:"flex",alignItems:"center",gap:8,borderBottom:"1px solid #f3f4f6"},children:[wn.jsx("button",{onClick:()=>{Re(null),Ce(false),Ee.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 m=(X?He.find(P=>P.id===X)?.targetId:null)??pe;return m?wn.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 ${m}`,children:["Forking ",wn.jsx("span",{style:{color:"#6b7280"},children:m})]}):null})()]}),!X&&!ae&&wn.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[wn.jsxs("div",{style:{padding:"12px 16px 6px 16px",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[wn.jsx("span",{style:{fontSize:12,fontWeight:600,color:"#111827"},children:"Forks"}),pe&&wn.jsx("button",{onClick:()=>{Re(null),Ce(true);},title:`Start a new fork on ${pe}`,style:{padding:"4px 10px",fontSize:11,lineHeight:1.3,borderRadius:999,border:"1px dashed #d1d5db",background:"#ffffff",color:"#374151",cursor:"pointer",whiteSpace:"nowrap"},children:"+ New fork"})]}),He.length===0&&wn.jsx("div",{style:{padding:"24px 20px",textAlign:"center",fontSize:13,color:"#6b7280"},children:"No forks yet. Click + New fork to build something."}),He.length>0&&wn.jsx("div",{style:{display:"flex",flexDirection:"column"},children:He.map(a=>{let m=a.summary||"Untitled fork";return wn.jsxs("button",{onClick:()=>{Ce(false),Re(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:P=>P.currentTarget.style.background="#fafafa",onMouseLeave:P=>P.currentTarget.style.background="#ffffff",children:[wn.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[wn.jsx("span",{style:{fontSize:13,fontWeight:500,color:"#111827",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1},children:m}),wn.jsx("span",{style:{fontSize:11,color:"#9ca3af",flexShrink:0},children:ko(a.updatedAt)})]}),wn.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:11,color:"#6b7280"},children:[wn.jsx("span",{style:{fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, "Liberation Mono", "Courier New", monospace',whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:a.targetId}),wn.jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),wn.jsxs("span",{children:[a.promptCount," prompt",a.promptCount===1?"":"s"]}),a.status==="running"||a.status==="building"?wn.jsxs(wn.Fragment,{children:[wn.jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),wn.jsx("span",{style:{color:"#2563eb"},children:"running"})]}):null]})]},a.id)})})]}),ae&&wn.jsx("div",{style:{padding:"24px 20px",textAlign:"center"},children:wn.jsx("p",{style:{fontSize:13,color:"#6b7280",marginBottom:14,lineHeight:1.625,margin:"0 0 14px 0"},children:"Describe the feature you want to build."})}),X&&Oe.length>0&&wn.jsx("div",{style:{padding:"16px 16px 0 16px"},children:Oe.map((a,m)=>wn.jsx("div",{style:{marginBottom:m<Oe.length-1?10:0},children:a.type==="user"?wn.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexDirection:"row-reverse"},children:[wn.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:wn.jsx(lucideReact.User,{style:{width:13,height:13,color:"#6b7280"}})}),wn.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})]}):wn.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[wn.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#f0fdf4",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:wn.jsx(lucideReact.Check,{style:{width:13,height:13,color:"#9ca3af"}})}),wn.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:[wn.jsx("span",{style:{flex:1},children:a.text}),g&&m===Oe.length-1&&e!=="running"&&wn.jsxs("button",{onClick:P=>{P.stopPropagation(),mn();},onMouseEnter:()=>te(m),onMouseLeave:()=>te(null),disabled:se,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:fe===m?"rgba(0,0,0,0.06)":"transparent",color:fe===m?"#6b7280":"#d1d5db",cursor:se?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:se?.4:1,flexShrink:0},children:[wn.jsx(lucideReact.Undo2,{style:{width:12,height:12}}),fe===m&&wn.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"})]})]})]})},m))}),e==="running"&&(X||ae)&&wn.jsx("div",{style:{padding:16},children:wn.jsxs("div",{onClick:()=>z(!ee),style:{backgroundColor:"#1a1a2e",borderRadius:12,overflow:"hidden",cursor:"pointer",transition:"all 0.3s cubic-bezier(0.22, 1, 0.36, 1)"},children:[wn.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px"},children:[wn.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[wn.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:wn.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),wn.jsx(wo,{events:r})]}),wn.jsx("div",{style:{color:"#6b7280",flexShrink:0,marginLeft:8,transition:"transform 0.2s ease",transform:ee?"rotate(180deg)":"rotate(0deg)"},children:wn.jsx(lucideReact.ChevronDown,{style:{width:14,height:14}})})]}),wn.jsx("div",{style:{maxHeight:ee?320:0,opacity:ee?1:0,transition:"max-height 0.35s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.25s ease",overflow:"hidden"},children:wn.jsx("div",{style:{borderTop:"1px solid rgba(255,255,255,0.08)",maxHeight:320,overflowY:"auto"},children:wn.jsx(jr,{events:r})})})]})}),e==="error"&&(X||ae)&&wn.jsxs("div",{style:{padding:"20px 16px",textAlign:"center"},children:[wn.jsx("div",{style:{width:36,height:36,backgroundColor:"#fef2f2",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 10px auto"},children:wn.jsx(lucideReact.X,{style:{width:18,height:18,color:"#ef4444"}})}),wn.jsx("p",{style:{fontSize:12,color:"#6b7280",marginBottom:10,maxWidth:260,margin:"0 auto 10px auto"},children:n}),wn.jsxs("button",{onClick:()=>{let a=t?.prompt||nt.current;a&&p(a,pe);},onMouseEnter:()=>W(true),onMouseLeave:()=>W(false),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,color:"#4f46e5",backgroundColor:D?"#e0e7ff":"#eef2ff",border:"none",cursor:"pointer",transition:"background-color 0.15s",fontFamily:"inherit"},children:[wn.jsx(lucideReact.RotateCcw,{style:{width:12,height:12}})," Try Again"]})]})]}),e!=="running"&&(X||ae)&&wn.jsx("div",{style:{padding:"8px 12px 12px 12px",borderTop:"1px solid rgba(229, 231, 235, 0.6)",flexShrink:0},children:wn.jsxs("div",{style:{display:"flex",alignItems:"flex-end",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:[wn.jsx("textarea",{ref:Rt,value:M,onChange:a=>{C(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(),fr()),a.key==="Escape"&&!b&&mr();},placeholder:Oe.length>0&&!ae?"Ask for another change...":`Describe your ideal ${cr.toLowerCase()}...`,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"}}),wn.jsx("button",{onClick:fr,disabled:!M.trim(),onMouseEnter:()=>Y(true),onMouseLeave:()=>Y(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:M.trim()?1:.25,transform:j&&M.trim()?"scale(1.1)":"scale(1)",background:M.trim()?"#1c4587":"rgba(0,0,0,0.12)",border:"none",cursor:M.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:wn.jsx(lucideReact.ArrowUp,{style:{width:13,height:13}})})]})})]})]});return b?Et:de&&_e?bn.createPortal(Et,_e.document.body):wn.jsx(vo,{children:Et})}function qr(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 Jt(e){let{apiKey:t,userId:r,userHash:n,baseUrl:o,appId:i,previewSession:s,refreshModuleManifest:c,queueBoundaryAnimation:p}=Q(),[g,f]=Ut.useState("idle"),[k,I]=Ut.useState(null),[R,_]=Ut.useState([]),[h,b]=Ut.useState(null),M=Ut.useRef(null),C=Ut.useCallback(()=>{f("prompting"),_([]),b(null),I(null);},[]),N=Ut.useCallback(()=>{f("idle"),M.current&&(M.current.close(),M.current=null);},[]);Ut.useEffect(()=>{s&&s.target.kind==="module"&&s.target.id===e&&f(x=>x==="idle"?"prompting":x);},[s?.preview_session_id,s?.target.id,e]);let T=Ut.useCallback(async(x,w,d)=>{try{if(!i)throw new Error("ForkProvider requires appId for module boundary prompts.");f("running"),_([]),b(null);let S;if(s){let u=d?.forkId??s.fork_id??void 0,l=await fetch(`${o}/api/v1/preview/${encodeURIComponent(s.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...K()},body:JSON.stringify({prompt:x,...e?{boundary_id:e}:{},...u&&!d?.forceNew?{fork_id:u}:{},...d?.forceNew?{force_new:!0}:{}})});if(!l.ok){let Y=await l.json().catch(()=>({}));throw new Error(Y.error||`API error: ${l.status}`)}let y=await l.json();y.container_id&&ve(y.container_id,y.container_name),Be(y.fork_id),S=await(await fetch(`${o}/api/v1/forks/${y.fork_id}`,{headers:{Authorization:`Bearer ${t}`,...K()}})).json();}else if(d?.forkId){let u={prompt:x};r&&(u.userId=r),n&&(u.userHash=n);let l=await fetch(`${o}/api/v1/forks/${encodeURIComponent(d.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(u)});if(!l.ok){let y=await l.json().catch(()=>({}));throw new Error(y.error||`API error: ${l.status}`)}S=await l.json();}else {let u={userId:r,prompt:x,boundaryId:e,appId:i};w&&(u.containerId=w),n&&(u.userHash=n),d?.forceNew&&(u.force_new=!0);let l=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(u)});if(!l.ok){let y=await l.json().catch(()=>({}));throw new Error(y.error||`API error: ${l.status}`)}S=await l.json();}I(S);let E=new URLSearchParams({key:t});s?(E.set("previewSessionId",s.preview_session_id),E.set("previewForkId",S.id)):r&&E.set("userId",r),n&&E.set("userHash",n);let A=new EventSource(`${o}/api/v1/forks/${S.id}/events?${E.toString()}`);M.current=A,A.onmessage=u=>{try{let l=JSON.parse(u.data);if(_(y=>[...y,l]),l.type==="complete"){let y=l.data;p(e,S.id),c().catch(()=>{}).finally(()=>{let j={...S,status:"complete",moduleUrl:y.moduleUrl,cssUrls:y.cssUrls,summary:y.summary,completedAt:new Date().toISOString()};I(j),f("complete"),A.close();});}else if(l.type==="error"){let y=l.data;b(y.error||"Unknown error"),f("error"),A.close();}}catch{}},A.onerror=()=>{let u={Authorization:`Bearer ${t}`,...K()};!s&&r&&(u["X-Fork-User-Id"]=r),!s&&n&&(u["X-Fork-User-Hash"]=n),fetch(`${o}/api/v1/forks/${S.id}`,{headers:u}).then(l=>l.json()).then(l=>{I(l),l.status==="complete"?(p(e,l.id),c().catch(()=>{}),f("complete")):l.status==="error"&&(b(l.error||"Fork generation failed"),f("error"));}).catch(()=>{b("Connection lost"),f("error");}),A.close();};}catch(S){b(S.message),f("error");}},[t,i,o,e,s,p,c,n,r]),L=Ut.useCallback(async()=>{try{if(!i)throw new Error("ForkProvider requires appId for boundary undo.");let x={userId:r,boundaryId:e,appId:i};n&&(x.userHash=n);let w=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(x)});if(!w.ok){let S=await w.json().catch(()=>({}));throw new Error(S.error||`API error: ${w.status}`)}let d=await w.json();return await c().catch(()=>{}),d.removed?(I(null),f("prompting")):d.fork&&(I(d.fork),f("complete")),d}catch(x){throw b(x.message),x}},[t,i,o,e,c,n,r]);return {state:g,fork:k,events:R,error:h,open:C,close:N,startFork:T,undoFork:L}}function Vr(e){let{state:t,fork:r,events:n,error:o,open:i,close:s,startFork:c,undoFork:p}=Jt(e);return {state:t,fork:r,events:n,error:o,isOpen:t!=="idle",open:i,close:s,submit:c,undo:p}}function qt(){let{apiKey:e,userId:t,userHash:r,baseUrl:n,previewSession:o,setSlotFork:i,clearSlotFork:s,skipAnimationForSlot:c}=Q(),[p,g]=Ut.useState("idle"),[f,k]=Ut.useState(null),[I,R]=Ut.useState([]),[_,h]=Ut.useState(null),b=Ut.useRef(null),M=Ut.useCallback(()=>{g("prompting"),R([]),h(null),k(null);},[]),C=Ut.useCallback(()=>{g("idle"),b.current&&(b.current.close(),b.current=null);},[]);Ut.useEffect(()=>{o&&o.target.kind==="slot"&&g(L=>L==="idle"?"prompting":L);},[o?.preview_session_id,o?.target.kind]);let N=Ut.useCallback(async(L,x,w,d)=>{try{g("running"),R([]),h(null);let S;if(o){let u=d?.forkId??o.fork_id??void 0,l=await fetch(`${n}/api/v1/preview/${encodeURIComponent(o.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...K()},body:JSON.stringify({prompt:L,...x?{slot_id:x}:{},...u&&!d?.forceNew?{fork_id:u}:{},...d?.forceNew?{force_new:!0}:{}})});if(!l.ok){let Y=await l.json().catch(()=>({}));throw new Error(Y.error||`API error: ${l.status}`)}let y=await l.json();y.container_id&&ve(y.container_id,y.container_name),Be(y.fork_id),S=await(await fetch(`${n}/api/v1/forks/${y.fork_id}`,{headers:{Authorization:`Bearer ${e}`,...K()}})).json();}else if(d?.forkId){let u={prompt:L};t&&(u.userId=t),r&&(u.userHash=r);let l=await fetch(`${n}/api/v1/forks/${encodeURIComponent(d.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(u)});if(!l.ok){let y=await l.json().catch(()=>({}));throw new Error(y.error||`API error: ${l.status}`)}S=await l.json();}else {let u={userId:t,prompt:L};x&&(u.slotId=x),w&&(u.containerId=w),r&&(u.userHash=r),d?.forceNew&&(u.force_new=!0);let l=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(u)});if(!l.ok){let y=await l.json().catch(()=>({}));throw new Error(y.error||`API error: ${l.status}`)}S=await l.json();}k(S);let E=new URLSearchParams({key:e});o?(E.set("previewSessionId",o.preview_session_id),E.set("previewForkId",S.id)):t&&E.set("userId",t),r&&E.set("userHash",r);let A=new EventSource(`${n}/api/v1/forks/${S.id}/events?${E.toString()}`);b.current=A,A.onmessage=u=>{try{let l=JSON.parse(u.data);if(R(y=>[...y,l]),l.type==="complete"){let y=l.data,j={...S,status:"complete",bundleUrl:y.bundleUrl,summary:y.summary,completedAt:new Date().toISOString()};k(j),g("complete"),x&&y.bundleUrl&&i(x,j),A.close();}else if(l.type==="error"){let y=l.data;h(y.error||"Unknown error"),g("error"),A.close();}}catch{}},A.onerror=()=>{let u={Authorization:`Bearer ${e}`,...K()};!o&&t&&(u["X-Fork-User-Id"]=t),!o&&r&&(u["X-Fork-User-Hash"]=r),fetch(`${n}/api/v1/forks/${S.id}`,{headers:u}).then(l=>l.json()).then(l=>{k(l),l.status==="complete"?(g("complete"),x&&l.bundleUrl&&i(x,l)):l.status==="error"&&(h(l.error||"Fork generation failed"),g("error"));}).catch(()=>{h("Connection lost"),g("error");}),A.close();};}catch(S){h(S.message),g("error");}},[e,t,r,n,o,i]),T=Ut.useCallback(async L=>{try{let x={userId:t,slotId:L};r&&(x.userHash=r);let w=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(x)});if(!w.ok){let S=await w.json().catch(()=>({}));throw new Error(S.error||`API error: ${w.status}`)}let d=await w.json();return c(L),d.removed?(s(L),k(null),g("prompting")):d.fork&&(i(L,d.fork),k(d.fork)),d}catch(x){throw h(x.message),x}},[e,t,r,n,s,i]);return {state:p,fork:f,events:I,error:_,open:M,close:C,startFork:N,undoFork:T}}function Xr(){let{state:e,fork:t,events:r,error:n,open:o,close:i,startFork:s,undoFork:c}=qt();return {state:e,fork:t,events:r,error:n,isOpen:e!=="idle",open:o,close:i,submit:s,undo:c}}function Vt(e){let t=qr(e),r=Xr(),n=Vr(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:i,userId:s,userHash:c,appId:p}=Q(),g=t.type==="slot"?r:n,f=t.type==="slot"?"slot":"boundary",k=t.id,I=t.title,R=Ut.useCallback((h,b,M,C)=>t.type==="slot"?r.submit(h,b??t.id,M,C):n.submit(h,M,C),[n,r,t]),_=Ut.useCallback(h=>t.type==="slot"?r.undo(h??t.id):n.undo(),[n,r,t]);return {...g,target:t,targetId:k,targetLabel:I,historyMode:f,submit:R,undo:_,buttonProps:{onClick:g.open},panelProps:{state:g.state,fork:g.fork,events:g.events,error:g.error,...t.type==="slot"?{slotId:k,targetLabel:I,historyMode:f}:{targetId:k,targetLabel:I,historyMode:f},onSubmit:R,onUndo:_,onClose:g.close,baseUrl:o,apiKey:i,userId:s,userHash:c,appId:p}}}function Ge(e){let{embedded:t}=e,r=Vt(e);return t?wn.jsx(kt,{...r.panelProps,embedded:true}):r.isOpen?wn.jsx(kt,{...r.panelProps}):wn.jsx(zt,{...r.buttonProps})}function Ro({boundaryId:e,title:t}){return wn.jsx(Ge,{boundaryId:e,title:t})}function Yt(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 Zr(e){let t=e.getBoundingClientRect(),r=e.cloneNode(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 Zt(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 Qr(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 c=r[s];c.rect.top>=n.rect.top&&c.rect.left>=n.rect.left&&c.rect.right<=n.rect.right&&c.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function en(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 c=r[s];c.rect.top>=n.rect.top&&c.rect.left>=n.rect.left&&c.rect.right<=n.rect.right&&c.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function tn(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 Qt(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 f=0;f<e.length;f+=1){let{rect:k,borderRadius:I}=e[f],R=k.left-.5,_=k.top-.5,h=k.width+1,b=k.height+1,M=Math.min(I+.5,h/2,b/2),C=tn(R,_,h,b,M),N=`__fork-glow-${f}`,T=document.createElementNS(t,"filter");T.setAttribute("id",N),T.setAttribute("x","-100%"),T.setAttribute("y","-100%"),T.setAttribute("width","300%"),T.setAttribute("height","300%");let L=document.createElementNS(t,"feGaussianBlur");L.setAttribute("in","SourceGraphic"),L.setAttribute("stdDeviation","8"),T.appendChild(L),o.appendChild(T);let x=`__fork-mask-${f}`,w=document.createElementNS(t,"mask");w.setAttribute("id",x),w.setAttribute("maskUnits","userSpaceOnUse"),w.setAttribute("x",String(R-200)),w.setAttribute("y",String(_-200)),w.setAttribute("width",String(h+400)),w.setAttribute("height",String(b+400));let d=document.createElementNS(t,"rect");d.setAttribute("x",String(R-200)),d.setAttribute("y",String(_-200)),d.setAttribute("width",String(h+400)),d.setAttribute("height",String(b+400)),d.setAttribute("fill","white"),w.appendChild(d);let S=document.createElementNS(t,"path");S.setAttribute("d",C),S.setAttribute("fill","black"),w.appendChild(S),o.appendChild(w);let E=document.createElementNS(t,"g");E.setAttribute("mask",`url(#${x})`),E.setAttribute("opacity","0");let A=document.createElementNS(t,"g");A.setAttribute("filter",`url(#${N})`);let u=document.createElementNS(t,"path");u.setAttribute("d",C),u.setAttribute("fill","none"),u.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),u.setAttribute("stroke-width","6"),u.setAttribute("stroke-linecap","round"),A.appendChild(u),E.appendChild(A),n.appendChild(E);let l=document.createElementNS(t,"path");l.setAttribute("d",C),l.setAttribute("fill","none"),l.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),l.setAttribute("stroke-width","2"),l.setAttribute("stroke-linecap","round"),l.setAttribute("opacity","0"),n.appendChild(l),i.push(u,l),u.__group=E;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let f=0;f<i.length;f+=2){let k=i[f],I=i[f+1],R=k.__group;if(!R)continue;let _=I.getTotalLength(),h=k.getTotalLength();if(_<=0)continue;let b=_*.35;I.setAttribute("stroke-dasharray",`${b} ${_-b}`),I.setAttribute("stroke-dashoffset","0"),s.push(I.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*_,opacity:.92,offset:.06},{strokeDashoffset:-2*_,opacity:.92,offset:.92},{strokeDashoffset:-2.25*_,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let M=h*.35;k.setAttribute("stroke-dasharray",`${M} ${h-M}`),k.setAttribute("stroke-dashoffset","0"),s.push(k.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*h,offset:.06},{strokeDashoffset:-2*h,offset:.92},{strokeDashoffset:-2.25*h,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(R.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 c=false,p=()=>{if(c)return;c=true,clearTimeout(g);for(let k of s)try{k.cancel();}catch{}let f=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});f.onfinish=()=>r.remove(),window.removeEventListener("click",p);},g=setTimeout(p,14500);return setTimeout(()=>{c||window.addEventListener("click",p);},500),p}function rn(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:c,borderRadius:p}of e){let g=document.createElementNS(t,"path");g.setAttribute("d",tn(c.left,c.top,c.width,c.height,p)),g.setAttribute("fill","none"),g.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),g.setAttribute("stroke-width","1.5"),g.setAttribute("stroke-dasharray","8 4"),g.setAttribute("stroke-linecap","round"),g.setAttribute("filter","url(#__fork-removed-shadow)"),g.setAttribute("opacity","0"),n.appendChild(g),g.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 qe=new Map,Ve=new Map,er=new Map;function Ao(e){for(let t of e)Ve.set(t,(Ve.get(t)??0)+1);}function $o(e){if(!(typeof document>"u"))for(let t of e){let r=(Ve.get(t)??0)-1;if(r>0){Ve.set(t,r);continue}Ve.delete(t),qe.delete(t);let n=document.querySelector(`link[data-fork-override-href="${CSS.escape(t)}"]`);n&&n.remove();}}function Po(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function on(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 Io(e){if(!e||typeof document>"u")return Promise.resolve();let t=qe.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 c=()=>{r.removeEventListener("load",c),r.removeEventListener("error",p),i();},p=()=>{r.removeEventListener("load",c),r.removeEventListener("error",p),s(new Error(`Failed to load boundary stylesheet: ${e}`));};r.addEventListener("load",c,{once:true}),r.addEventListener("error",p,{once:true});});return qe.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 qe.delete(e),o});return qe.set(e,n),n}function To(e){let t=er.get(e);if(t)return t;let r=import(e).catch(n=>{throw er.delete(e),n});return er.set(e,r),r}async function Mo(e,t,r){if(e)try{await Promise.all(e.cssUrls.map(i=>Io(i)));let o=await To(e.moduleUrl);return on(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 on(n,r)}function Lo(e){function t(r){let{appId:n,moduleOverridesEnabled:o,moduleManifestReady:i,moduleManifestVersion:s,registerBoundary:c,getBoundaryOverride:p,consumeBoundaryAnimation:g}=Q(),[f,k]=Ut.useState(null),[I,R]=Ut.useState(null),_=Ut.useRef(null),h=Ut.useRef(null),b=Ut.useRef(null),M=Ut.useRef(false),C=Ut.useRef(null),N=Ut.useRef(null),T=p(e.id),L=T?`override:${T.id}`:"original",x=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if(Ut.useEffect(()=>()=>{N.current&&(clearTimeout(N.current),N.current=null),C.current&&(C.current.remove(),C.current=null);},[]),Ut.useEffect(()=>{c({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[n,c,e.id,e.exportName,x]),Ut.useEffect(()=>{let w=T?.cssUrls??[];if(w.length!==0)return Ao(w),()=>$o(w)},[T?.cssUrls.join("|")]),Ut.useEffect(()=>{if(o&&!i&&!f||h.current===L&&f)return;let w=false;return R(null),Mo(T,e.original,e.exportName).then(d=>{if(!w){if(T?.id&&g(e.id,T.id)&&_.current){let S=Yt(_.current);if(S){let E=Zt(S);E.length>0&&(b.current=E,M.current=true,N.current&&(clearTimeout(N.current),N.current=null),C.current&&C.current.remove(),C.current=Zr(S));}}h.current=L,Ut.startTransition(()=>{k(()=>d);});}}).catch(d=>{w||R(Po(d));}),()=>{w=true;}},[g,L,o,i,s,T?.id,T?.moduleUrl,T?.integrity,T?.cssUrls.join("|"),e.exportName,e.original,f]),Ut.useEffect(()=>{if(!M.current||!f||!_.current)return;let w=false;return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(w||!_.current)return;let d=b.current,S=Yt(_.current);if(b.current=null,M.current=false,!d||!S){C.current&&(C.current.remove(),C.current=null);return}let E=Zt(S),A=Qr(d,E),u=en(d,E),l=C.current;if(u.length>0&&l){let y=rn(u);N.current=setTimeout(()=>{N.current=null;let j=400;l.animate([{opacity:1},{opacity:0}],{duration:j,fill:"forwards"}),y.animate([{opacity:1},{opacity:0}],{duration:j,fill:"forwards"}),setTimeout(()=>{l.remove(),y.remove(),C.current===l&&(C.current=null),A.length>0&&Qt(A);},j);},3500);}else l&&(l.remove(),C.current===l&&(C.current=null)),A.length>0&&Qt(A);});}),()=>{w=true;}},[f]),I)throw I;return f?wn.jsx("div",{ref:_,style:{display:"contents"},children:wn.jsx(f,{...r})}):wn.jsx(wn.Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function Ho({slotId:e,title:t,slotLabel:r}){return wn.jsx(Ge,{slotId:e,title:t,slotLabel:r})}
45
+ exports.ForkBoundaryUI=Ro;exports.ForkButton=zt;exports.ForkChatInterface=Ge;exports.ForkPanel=kt;exports.ForkProvider=Ln;exports.ForkSlot=qn;exports.ForkUI=Ho;exports.clearCachedManifest=$n;exports.forkable=Lo;exports.loadManifest=ut;exports.manifestDiffers=Pn;exports.readCachedManifest=En;exports.registerForkShared=$t;exports.useBoundaryFork=Jt;exports.useFork=qt;exports.useForkChatPanel=Vt;exports.usePreviewSession=dt;exports.writeCachedManifest=An;
package/dist/index.d.cts CHANGED
@@ -39,6 +39,10 @@ interface ForkProviderBase {
39
39
  * The SDK calls this on mount (same-origin, cookies sent automatically).
40
40
  * Your backend computes: userHash = HMAC-SHA256(sk_fork_key, userId).
41
41
  * This provides verified per-user fork isolation.
42
+ * If the verified user is also a Fork tenant operator (their email matches
43
+ * a fork_users row with a user_roles entry on this tenant), the SDK
44
+ * transparently enters admin mode and acts as their mapped end-user — set
45
+ * the mapping in Fork's Team Settings → End user.
42
46
  */
43
47
  type ForkProviderProps = ForkProviderBase & ({
44
48
  userId: string;
package/dist/index.d.ts CHANGED
@@ -39,6 +39,10 @@ interface ForkProviderBase {
39
39
  * The SDK calls this on mount (same-origin, cookies sent automatically).
40
40
  * Your backend computes: userHash = HMAC-SHA256(sk_fork_key, userId).
41
41
  * This provides verified per-user fork isolation.
42
+ * If the verified user is also a Fork tenant operator (their email matches
43
+ * a fork_users row with a user_roles entry on this tenant), the SDK
44
+ * transparently enters admin mode and acts as their mapped end-user — set
45
+ * the mapping in Fork's Team Settings → End user.
42
46
  */
43
47
  type ForkProviderProps = ForkProviderBase & ({
44
48
  userId: string;
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
- import*as Bt from'react';import Bt__default,{createContext,useSyncExternalStore,useState,useRef,useEffect,useCallback,startTransition,Children,useContext,isValidElement}from'react';import*as hn from'react-dom';import {createPortal}from'react-dom';import*as yn from'react/jsx-runtime';import {jsx,Fragment,jsxs}from'react/jsx-runtime';import*as kn from'react/jsx-dev-runtime';import {ChevronDown,Check,PictureInPicture,PictureInPicture2,X,User,Undo2,RotateCcw,ArrowUp,Loader2,AlertCircle,Sparkles,Package,Wrench,MessageSquare,Code,Terminal,FileSearch,Pencil}from'lucide-react';var be="__FORK_SHARED__";function Ct(){var t,r,n,o;let e=globalThis;return e[be]||(e[be]={}),(t=e[be]).react||(t.react=Bt),(r=e[be])["react-dom"]||(r["react-dom"]=hn),(n=e[be])["react/jsx-runtime"]||(n["react/jsx-runtime"]=yn),(o=e[be])["react/jsx-dev-runtime"]||(o["react/jsx-dev-runtime"]=kn),e[be]}function Et(e){return Object.assign(Ct(),e)}var bn="__fork_preview_session__";function it(e){return `${bn}${e}`}var H={apiKey:null,session:null},At=new Set;function at(){for(let e of At)try{e();}catch(t){console.error("[fork-preview] subscriber threw",t);}}function gr(e){let t=Date.parse(e.expires_at);return Number.isFinite(t)?t<=Date.now():true}function wn(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:gr(r)?(window.sessionStorage.removeItem(it(e)),null):r}catch{return null}}function $t(e,t){if(!(typeof window>"u"))try{t?window.sessionStorage.setItem(it(e),JSON.stringify(t)):window.sessionStorage.removeItem(it(e));}catch{}}function Oe(e){H.apiKey!==e&&(H.apiKey=e,H.session=wn(e),at());}function we(){return H.session?gr(H.session)?(Pt(null),null):H.session:null}function Pt(e){H.session=e,H.apiKey&&$t(H.apiKey,e),at();}function Ue(e){H.session&&H.session.fork_id!==e&&(H.session={...H.session,fork_id:e},H.apiKey&&$t(H.apiKey,H.session),at());}function ve(e,t){H.session&&(H.session.container_id===e&&H.session.container_name===t||(H.session={...H.session,container_id:e,container_name:t??H.session.container_name??"Fork",fork_id:null},H.apiKey&&$t(H.apiKey,H.session),at()));}function Mt(e){return At.add(e),()=>{At.delete(e);}}var mr="__fork_preview";function hr(){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(mr);return typeof r=="string"&&r.length>0?r:null}function Tt(e){if(typeof window>"u")return false;try{if(window.sessionStorage.getItem(`__fork_preview_session__${e}`))return !0}catch{}return kr()!==null}function yr(){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(mr);let r=t.toString(),n=r?`#${r}`:"";try{window.history.replaceState(null,"",window.location.pathname+window.location.search+n);}catch{}}var Se=null;function kr(){if(Se)return Se;let e=hr();return e?(Se=e,yr(),Se):null}async function It(e,t){Oe(e);let r=we();if(r)return Se=null,r;let n=Se??hr();if(Se=null,!n)return null;yr();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 c=await o.json().catch(()=>({}));return console.warn(`[fork-preview] activate failed (${o.status}): ${c.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 Pt(s),s}catch(o){return console.warn("[fork-preview] activate threw",o),null}}function Sn(){return we()}function xn(){return null}function lt(){return useSyncExternalStore(Mt,Sn,xn)}function K(){let e=we();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 ct(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[c,p]of Object.entries(i.modules)){let g=p.moduleUrl??p.bundleUrl??null,f=p.legacyModuleUrl??p.legacyBundleUrl??null;s[c]={forkId:p.forkId,moduleUrl:g,legacyModuleUrl:f,bundleUrl:p.bundleUrl??g,legacyBundleUrl:p.legacyBundleUrl??f,cssUrls:p.cssUrls??[],integrity:p.integrity,metadata:p.metadata,buildId:p.buildId,updatedAt:p.updatedAt};}return {containerId:i.containerId,slots:i.slots,modules:s,generatedAt:i.generatedAt,etag:o.headers.get("ETag")??void 0}}var Fn="fork:manifest:v1";function Lt(e,t,r){return `${Fn}:${e}:${t}:${r}`}function Rn(e,t,r){if(typeof window>"u")return null;try{let n=window.localStorage.getItem(Lt(e,t,r));return n?JSON.parse(n):null}catch{return null}}function _n(e,t,r,n){if(!(typeof window>"u"))try{window.localStorage.setItem(Lt(e,t,r),JSON.stringify(n));}catch{}}function Cn(e,t,r){if(!(typeof window>"u"))try{window.localStorage.removeItem(Lt(e,t,r));}catch{}}function En(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,c]of r){let p=t.slots[s];if(!p||p.forkId!==c.forkId||p.buildId!==c.buildId)return true}let o=Object.entries(e.modules),i=Object.entries(t.modules);if(o.length!==i.length)return true;for(let[s,c]of o){let p=t.modules[s];if(!p||p.forkId!==c.forkId||p.buildId!==c.buildId)return true}return false}var vr=createContext(null);function je(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function Pn(e,t){let r={};for(let[n,o]of Object.entries(t.boundaries||{}))r[n]={...o,moduleUrl:je(e,o.moduleUrl),cssUrls:Array.isArray(o.cssUrls)?o.cssUrls.map(i=>je(e,i)):[]};return r}function br(e,t,r,n){let o={};for(let[i,s]of Object.entries(t.slots)){let c=s.bundleUrl??s.legacyBundleUrl;c&&(o[i]={id:s.forkId,userId:r,prompt:"",status:"complete",slotId:i,appId:n,bundleUrl:je(e,c),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:je(e,i),cssUrls:(o.cssUrls??[]).map(s=>je(e,s)),integrity:o.integrity,metadata:o.metadata,createdAt:o.updatedAt});}return r}function Mn(e){let{apiKey:t,baseUrl:r,children:n,appId:o,shared:i}=e,s="userId"in e?e.userId:void 0,c="authUrl"in e?e.authUrl:void 0,[p]=useState(()=>(Oe(t),Tt(t))),[g,f]=useState({}),[S,P]=useState(s?{userId:s,userHash:void 0}:null),[_,R]=useState(!!s||p),[h,y]=useState({}),[I,C]=useState(!o),[N,M]=useState(0),[L,x]=useState(null),k=useRef(new Map),d=useRef(new Map),[v,E]=useState(0),A=useRef(new Set),u=useRef(new Map),l=useRef(void 0);Ct(),useEffect(()=>{return It(t,r).then(()=>{}),()=>{}},[]);let b=lt();i&&l.current!==i&&(Et(i),l.current=i),useEffect(()=>{c&&(p||(R(false),fetch(c,{credentials:"include"}).then(T=>{if(!T.ok)throw new Error(`Auth endpoint returned ${T.status}`);return T.json()}).then(T=>{if(!T.userId||typeof T.userId!="string")throw new Error("authUrl response must include userId");P({userId:T.userId,userHash:T.userHash});}).catch(T=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",T.message);}).finally(()=>{R(true);})));},[c,p]),useEffect(()=>{!c&&s&&(P({userId:s,userHash:void 0}),R(true));},[s,c]);let j=S?.userId??"",Y=S?.userHash,D=b?"":j,W=b?void 0:Y,ee=!!o,z=useCallback(async()=>{if(!ee){x(null),y({}),C(true),M(F=>F+1);return}if(!_){C(false);return}if(!b&&!D||!o){x(null),y({}),C(true),M(F=>F+1);return}if(C(false),!b){try{let F=await ct({baseUrl:r,apiKey:t,appId:o,userId:D,userHash:W});F&&(x(F.containerId),f(br(r,F,D,o)),y(wr(r,F)));}catch(F){console.error("[ForkProvider] Failed to fetch fork manifest:",F.message),x(null),f({}),y({});}finally{M(F=>F+1),C(true);}return}if(x(b.container_id??null),b.container_id){try{let F=await ct({baseUrl:r,apiKey:t,appId:o,userId:D,containerId:b.container_id,extraHeaders:K()});F&&(f(br(r,F,D,o)),y(wr(r,F)));}catch(F){console.error("[ForkProvider] Failed to fetch preview container manifest:",F.message),f({}),y({});}finally{M(F=>F+1),C(true);}return}let T=new URLSearchParams({appId:o,userId:D});W&&T.set("userHash",W);try{let F=await fetch(`${r}/api/v1/boundaries/manifest?${T.toString()}`,{headers:{Authorization:`Bearer ${t}`,...K()}});if(!F.ok)throw new Error(`${F.status}`);let O=await F.json();y(Pn(r,O));}catch(F){console.error("[ForkProvider] Failed to fetch module override manifest:",F.message),y({});}finally{M(F=>F+1),C(true);}},[t,o,r,_,ee,W,D,b?.preview_session_id,b?.fork_id,b?.container_id]);useEffect(()=>{if(!D||o&&(!b||b.container_id))return;let T=new URLSearchParams({userId:D});W&&T.set("userHash",W),fetch(`${r}/api/v1/forks/active?${T.toString()}`,{headers:{Authorization:`Bearer ${t}`,...K()}}).then(F=>{if(!F.ok)throw new Error(`${F.status}`);return F.json()}).then(F=>{F&&typeof F=="object"&&f(F);}).catch(()=>{});},[t,o,D,W,r,b?.preview_session_id,b?.fork_id]),useEffect(()=>{z();},[z]);let se=useCallback((T,F)=>{f(O=>({...O,[T]:F}));},[]),ie=useCallback(T=>{f(F=>{let O={...F};return delete O[T],O});},[]),fe=useCallback(T=>{A.current.add(T);},[]),te=useCallback(T=>A.current.has(T)?(A.current.delete(T),true):false,[]),vt=useCallback((T,F)=>{u.current.set(T,F);},[]),qe=useCallback((T,F)=>u.current.get(T)!==F?false:(u.current.delete(T),true),[]),Me=useCallback(T=>{if(!o)return;let F=JSON.stringify(T);k.current.get(T.id)===F||d.current.get(T.id)?.signature===F||(d.current.set(T.id,{boundary:T,signature:F}),E(re=>re+1));},[o]);useEffect(()=>{if(!o||d.current.size===0)return;let T=setTimeout(()=>{let F=Array.from(d.current.values());F.length!==0&&fetch(`${r}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:o,boundaries:F.map(O=>O.boundary)})}).then(O=>{if(!O.ok)throw new Error(`${O.status}`)}).then(()=>{for(let O of F)d.current.get(O.boundary.id)?.signature===O.signature&&(d.current.delete(O.boundary.id),k.current.set(O.boundary.id,O.signature));}).catch(O=>{console.error("[ForkProvider] Failed to register module boundaries:",O.message);});},50);return ()=>{clearTimeout(T);}},[t,o,r,v]);let ce=useCallback(T=>h[T],[h]),Z=useCallback(async()=>{if(!D)throw new Error("Reset requires a resolved user identity.");let T=new URLSearchParams({userId:D});W&&T.set("userHash",W);let F={Authorization:`Bearer ${t}`,...K()};o&&(F["X-Fork-App-Id"]=o);let O=await fetch(`${r}/api/v1/forks/all?${T.toString()}`,{method:"DELETE",headers:F});if(!O.ok){let ne=await O.json().catch(()=>({}));throw new Error(ne.error||`API error: ${O.status}`)}let re=await O.json().catch(()=>({}));f({}),y({}),C(true),M(ne=>ne+1),A.current.clear(),u.current.clear();try{for(let ne=sessionStorage.length-1;ne>=0;ne-=1){let Te=sessionStorage.key(ne);Te&&Te.startsWith("__fork_animated_")&&sessionStorage.removeItem(Te);}}catch{}return re},[t,o,r,W,D]);return jsx(vr.Provider,{value:{apiKey:t,userId:D,userHash:W,baseUrl:r,appId:o,forks:g,moduleOverridesEnabled:ee,moduleManifestReady:I,moduleManifestVersion:N,currentContainerId:L,previewSession:b,setSlotFork:se,clearSlotFork:ie,skipAnimationForSlot:fe,shouldSkipAnimation:te,queueBoundaryAnimation:vt,consumeBoundaryAnimation:qe,registerBoundary:Me,getBoundaryOverride:ce,refreshModuleManifest:z,resetAllForks:Z},children:n})}function Q(){let e=useContext(vr);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function dt(e){return Q().forks[e]}var De=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 Ot(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 xr=new Set;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 Bn(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 c=r[s];c.rect.top>=n.rect.top&&c.rect.left>=n.rect.left&&c.rect.right<=n.rect.right&&c.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function On(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 c=r[s];c.rect.top>=n.rect.top&&c.rect.left>=n.rect.left&&c.rect.right<=n.rect.right&&c.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function _r(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 Rr(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 f=0;f<e.length;f++){let{rect:S,borderRadius:P}=e[f],_=S.left-.5,R=S.top-.5,h=S.width+1,y=S.height+1,I=Math.min(P+.5,h/2,y/2),C=_r(_,R,h,y,I),N=`__fork-glow-${f}`,M=document.createElementNS(t,"filter");M.setAttribute("id",N),M.setAttribute("x","-100%"),M.setAttribute("y","-100%"),M.setAttribute("width","300%"),M.setAttribute("height","300%");let L=document.createElementNS(t,"feGaussianBlur");L.setAttribute("in","SourceGraphic"),L.setAttribute("stdDeviation","8"),M.appendChild(L),o.appendChild(M);let x=`__fork-mask-${f}`,k=document.createElementNS(t,"mask");k.setAttribute("id",x),k.setAttribute("maskUnits","userSpaceOnUse"),k.setAttribute("x",String(_-200)),k.setAttribute("y",String(R-200)),k.setAttribute("width",String(h+400)),k.setAttribute("height",String(y+400));let d=document.createElementNS(t,"rect");d.setAttribute("x",String(_-200)),d.setAttribute("y",String(R-200)),d.setAttribute("width",String(h+400)),d.setAttribute("height",String(y+400)),d.setAttribute("fill","white"),k.appendChild(d);let v=document.createElementNS(t,"path");v.setAttribute("d",C),v.setAttribute("fill","black"),k.appendChild(v),o.appendChild(k);let E=document.createElementNS(t,"g");E.setAttribute("mask",`url(#${x})`),E.setAttribute("opacity","0");let A=document.createElementNS(t,"g");A.setAttribute("filter",`url(#${N})`);let u=document.createElementNS(t,"path");u.setAttribute("d",C),u.setAttribute("fill","none"),u.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),u.setAttribute("stroke-width","6"),u.setAttribute("stroke-linecap","round"),A.appendChild(u),E.appendChild(A),n.appendChild(E);let l=document.createElementNS(t,"path");l.setAttribute("d",C),l.setAttribute("fill","none"),l.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),l.setAttribute("stroke-width","2"),l.setAttribute("stroke-linecap","round"),l.setAttribute("opacity","0"),n.appendChild(l),i.push(u,l),u.__group=E;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let f=0;f<i.length;f+=2){let S=i[f],P=i[f+1],_=S.__group,R=P.getTotalLength(),h=S.getTotalLength();if(R<=0)continue;let y=R*.35;P.setAttribute("stroke-dasharray",`${y} ${R-y}`),P.setAttribute("stroke-dashoffset","0"),s.push(P.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*R,opacity:.92,offset:.06},{strokeDashoffset:-2*R,opacity:.92,offset:.92},{strokeDashoffset:-2.25*R,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let I=h*.35;S.setAttribute("stroke-dasharray",`${I} ${h-I}`),S.setAttribute("stroke-dashoffset","0"),s.push(S.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*h,offset:.06},{strokeDashoffset:-2*h,offset:.92},{strokeDashoffset:-2.25*h,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 c=false,p=()=>{if(c)return;c=true,clearTimeout(g);for(let S of s)try{S.cancel();}catch{}let f=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});f.onfinish=()=>r.remove(),window.removeEventListener("click",p);},g=setTimeout(p,14500);return setTimeout(()=>{c||window.addEventListener("click",p);},500),p}function Un(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:c,borderRadius:p}of e){let g=c.left,f=c.top,S=c.width,P=c.height,_=Math.min(p,S/2,P/2),R=_r(g,f,S,P,_),h=document.createElementNS(t,"path");h.setAttribute("d",R),h.setAttribute("fill","none"),h.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),h.setAttribute("stroke-width","1.5"),h.setAttribute("stroke-dasharray","8 4"),h.setAttribute("stroke-linecap","round"),h.setAttribute("filter","url(#__fork-removed-shadow)"),h.setAttribute("opacity","0"),n.appendChild(h),h.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 Hn(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 jn=Bt__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&&Hn(e.hostProps,t.hostProps)),Nt=class extends Bt__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 Cr({slotId:e,children:t,githubRepo:r,shared:n,events:o}){Ot(t,e);let i=dt(e),{baseUrl:s,apiKey:c,appId:p,shouldSkipAnimation:g}=Q(),[f,S]=useState(null),P=useRef(null),_=useRef(null),R=useRef(null),h=useRef(false),y=useRef(null),I=useRef(null),C=!!(n||o),N=useRef(null);C&&!N.current&&(N.current=new De(e));let M=useRef(o);if(M.current=o,useEffect(()=>{if(C)return ()=>{N.current?.destroy(),N.current=null;}},[C,e]),C&&N.current&&n)for(let[v,E]of Object.entries(n))N.current.set(v,E);useEffect(()=>{if(!C)return;N.current||(N.current=new De(e));let v=N.current,E=Object.keys(M.current||{}).map(A=>v.on(A,(...u)=>M.current?.[A]?.(...u)));return ()=>E.forEach(A=>A())},[C,e]),useEffect(()=>{if(xr.has(e))return;xr.add(e);let v={id:e,appId:p,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 ${c}`,"Content-Type":"application/json"},body:JSON.stringify(v)}).catch(()=>{});},[e,s,c,r,p]);let L=i?.id||null;useEffect(()=>{if(i?.bundleUrl,P.current,_.current,!i?.bundleUrl||!L){return}let v=`${s}${i.bundleUrl.replace("bundle.js","component.js")}`,E=`__fork_animated_${e}`,A=sessionStorage.getItem(E),u=g(e),l=!u&&A!==L;if(u&&L&&sessionStorage.setItem(E,L),l&&_.current){let W=Fr(_.current);R.current=W,h.current=true,`${e}${W.length}`;}window.__FORK_REACT__=Bt__default,window.__FORK_REACT_DOM__=hn,window.__FORK_REACT_JSX__=yn;let b=Date.now(),j=`${s}${i.bundleUrl.replace("bundle.js","component.css")}?t=${b}`,Y=document.createElement("link");Y.rel="stylesheet",Y.href=j,Y.dataset.forkSlot=e,document.head.appendChild(Y);let D=document.createElement("script");return D.src=v+"?t="+b,D.onload=()=>{let W=window.__FORK_EXPORT__;if(W?.default){if(_.current&&R.current&&h.current){let ee=_.current.getBoundingClientRect(),z=_.current.cloneNode(true);z.style.position="fixed",z.style.top=`${ee.top}px`,z.style.left=`${ee.left}px`,z.style.width=`${ee.width}px`,z.style.height=`${ee.height}px`,z.style.flex="none",z.style.minHeight="auto",z.style.zIndex="9998",z.style.pointerEvents="none",z.style.overflow="hidden";let se=getComputedStyle(_.current).backgroundColor;z.style.backgroundColor=se&&se!=="rgba(0, 0, 0, 0)"&&se!=="transparent"?se:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(z);let ie=_.current.querySelectorAll("*"),fe=z.querySelectorAll("*");for(let te=0;te<ie.length;te++)ie[te].scrollTop!==0&&(fe[te].scrollTop=ie[te].scrollTop),ie[te].scrollLeft!==0&&(fe[te].scrollLeft=ie[te].scrollLeft);y.current=z;}S(()=>W.default),P.current=L;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},D.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(D),()=>{D.remove(),Y.remove(),I.current&&(clearTimeout(I.current),I.current=null),y.current&&(y.current.remove(),y.current=null);}},[L,s,e]),useEffect(()=>{if(!h.current||!f||!_.current){`${e}${h.current}`,_.current;return}let v=R.current;if(!v){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!_.current)return;let E=Fr(_.current),A=Bn(v,E),u=On(v,E),l=y.current;if(`${e}${A.length}${u.length}`,u.length>0&&l){let b=Un(u);I.current=setTimeout(()=>{I.current=null;let j=400;l.animate([{opacity:1},{opacity:0}],{duration:j,fill:"forwards"}),b.animate([{opacity:1},{opacity:0}],{duration:j,fill:"forwards"}),setTimeout(()=>{l.remove(),b.remove(),y.current=null,A.length>0&&(Rr(A));},j);},3500);}else l&&(l.remove(),y.current=null),A.length>0&&(Rr(A));R.current=null,h.current=false,L&&(sessionStorage.setItem(`__fork_animated_${e}`,L),`${e}`);});});},[f]);let x={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!i||i.status!=="complete"||!i.bundleUrl)return jsx("div",{ref:_,style:x,children:t});if(!f)return jsx("div",{ref:_,style:x,children:t});let d=t?.props??{};return jsx(Nt,{slotId:e,resetKey:L,fallback:jsx("div",{ref:_,style:x,children:t}),children:jsx(jn,{component:f,containerRef:_,wrapperStyle:x,hostProps:d})})}var Ar=new Set;function Wn(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 $r(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&&$r(n.children,t);}),t}function Kn({slotId:e,props:t,children:r,allowedFetches:n,githubRepo:o,callbacks:i,mode:s="iframe",shared:c,events:p}){if(Ot(r,e),s==="direct")return jsx(Cr,{slotId:e,githubRepo:o,shared:c,events:p,children:r});let g=dt(e),{baseUrl:f,apiKey:S,appId:P}=Q(),_=useRef(null),R=useRef(false),h=useRef(null),y=useRef(i);y.current=i;let I=useRef(t);I.current=t;let C=useRef(n);C.current=n,useEffect(()=>{if(typeof process<"u")return;let x=$r(r),k=new Set(i?Object.keys(i):[]),d=[...x].filter(v=>!k.has(v));d.length>0&&console.error(`[ForkSlot:${e}] Missing bridged callbacks! The following callback props are used by children but not passed to ForkSlot's \`callbacks\` prop:
2
- `+d.map(v=>` - ${v}`).join(`
3
- `)+"\n\nThe forked component will not be able to call these. Add them to the `callbacks` prop of <ForkSlot>.");},[e,r,i]),useEffect(()=>{Ar.has(e)||(Ar.add(e),fetch(`${f}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${S}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:P,label:e,propsShape:t?Wn(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:o,callbackNames:i?Object.keys(i):[],mode:s||"iframe"})}).catch(()=>{}));},[e,f,S,o,P]);let N=useCallback(x=>{let k=_.current;if(k?.contentWindow&&R.current){let d=y.current?Object.keys(y.current):[];k.contentWindow.postMessage({type:"slot:props",props:x,callbackNames:d},"*"),h.current=null;}else h.current=x;},[]),M=useCallback((x,k)=>{let d=C.current;return !d||d.length===0?false:d.some(v=>{let[E,A]=v.split(" "),u=k.split("?")[0];return x.toUpperCase()===E.toUpperCase()&&u.startsWith(A)})},[]);if(useEffect(()=>{if(!g?.bundleUrl)return;let x=async k=>{if(k.source===_.current?.contentWindow){if(k.data?.type==="slot:ready")R.current=true,_.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:C.current||[]},"*"),C.current,h.current?N(h.current):N(I.current||{});else if(k.data?.type==="slot:event"){let d=k.data.event;d?.navigate&&(window.location.hash=d.navigate);}else if(k.data?.type==="slot:clipboard-write")navigator.clipboard.writeText(k.data.text).catch(d=>{console.warn(`[ForkSlot:${e}] clipboard write failed:`,d.message);});else if(k.data?.type==="slot:callback"){let{name:d,args:v}=k.data,E=y.current?.[d];E?(E(...v||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${d}`);}else if(k.data?.type==="slot:fetch"){let{id:d,method:v,url:E,body:A}=k.data,u=_.current?.contentWindow;if(!u)return;let l=v||"GET";if(!M(l,E)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${d}: ${l} ${E} \u2014 not in allowedFetches`),u.postMessage({type:"slot:fetch-response",id:d,error:`Fetch not allowed: ${l} ${E}`},"*");return}try{let b={method:l};A&&l!=="GET"&&(b.headers={"Content-Type":"application/json"},b.body=JSON.stringify(A));let j=await fetch(E,b),Y=await j.json();`${e}${d}${j.status}`,u.postMessage({type:"slot:fetch-response",id:d,data:Y,status:j.status},"*");}catch(b){console.error(`[ForkSlot:${e}] fetch #${d} failed:`,b.message),u.postMessage({type:"slot:fetch-response",id:d,error:b.message},"*");}}}};return window.addEventListener("message",x),()=>{window.removeEventListener("message",x),R.current=false;}},[g?.bundleUrl,e,N,M]),useEffect(()=>{g?.bundleUrl&&R.current&&N(t||{});},[t,g?.bundleUrl,N]),!g||g.status!=="complete"||!g.bundleUrl)return `${e}${g?.status||"none"}${g?.bundleUrl||"none"}`,jsx(Fragment,{children:r});`${e}${g.bundleUrl}`;let L=`${f}${g.bundleUrl.replace("/bundle.js","/host")}`;return jsx("iframe",{ref:_,src:L,sandbox:"allow-scripts allow-same-origin allow-forms allow-clipboard-write",title:`Forked ${e}`,style:{width:"100%",border:"none",flex:1,minHeight:0}})}function ft({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"})]})}function Ht({onClick:e}){let[t,r]=useState(false),[n,o]=useState(false),i=t?48:40;return jsx("button",{onClick:e,onMouseEnter:()=>r(true),onMouseLeave:()=>{r(false),o(false);},onMouseDown:()=>o(true),onMouseUp:()=>o(false),style:{position:"fixed",bottom:24,right:24,zIndex:40,width:i,height:i,borderRadius:"50%",backgroundColor:t?"rgba(255, 255, 255, 1)":"rgba(255, 255, 255, 0.3)",border:t?"1px solid rgba(156, 163, 175, 1)":"1px solid rgba(156, 163, 175, 0.3)",display:"flex",alignItems:"center",justifyContent:"center",color:t?"#1c4587":"rgba(28, 69, 135, 0.5)",boxShadow:t?"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:n?"scale(0.95)":"scale(1)",transition:"all 300ms",cursor:"pointer",padding:0,margin:0,outline:"none",boxSizing:"border-box"},title:"Fork this app",children:jsx(ft,{style:{width:24,height:24}})})}var to={status:Loader2,agent_message:MessageSquare,tool_use:Wrench,build_start:Package,build_complete:Check,build_error:AlertCircle,complete:Sparkles,error:AlertCircle},ro={status:"#60a5fa",agent_message:"#a0a0a0",tool_use:"#fbbf24",build_start:"#c084fc",build_complete:"#6b7280",build_error:"#f87171",complete:"#6b7280",error:"#f87171"},no={read:FileSearch,write:Pencil,search:FileSearch,shell:Terminal,build:Package},oo={read:"#60a5fa",write:"#fbbf24",search:"#60a5fa",shell:"#a78bfa",build:"#c084fc"};function Dt(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 Or({events:e}){let t=useRef(null);return useEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight);},[e]),jsxs(Fragment,{children:[jsx("style",{children:`
1
+ import*as Ut from'react';import Ut__default,{createContext,useSyncExternalStore,useState,useRef,useEffect,useCallback,startTransition,Children,useContext,isValidElement}from'react';import*as bn from'react-dom';import {createPortal}from'react-dom';import*as wn from'react/jsx-runtime';import {jsx,Fragment,jsxs}from'react/jsx-runtime';import*as vn from'react/jsx-dev-runtime';import {ChevronDown,Check,PictureInPicture,PictureInPicture2,X,User,Undo2,RotateCcw,ArrowUp,Loader2,AlertCircle,Sparkles,Package,Wrench,MessageSquare,Code,Terminal,FileSearch,Pencil}from'lucide-react';var we="__FORK_SHARED__";function At(){var t,r,n,o;let e=globalThis;return e[we]||(e[we]={}),(t=e[we]).react||(t.react=Ut),(r=e[we])["react-dom"]||(r["react-dom"]=bn),(n=e[we])["react/jsx-runtime"]||(n["react/jsx-runtime"]=wn),(o=e[we])["react/jsx-dev-runtime"]||(o["react/jsx-dev-runtime"]=vn),e[we]}function $t(e){return Object.assign(At(),e)}var Sn="__fork_preview_session__";function at(e){return `${Sn}${e}`}var U={apiKey:null,session:null},Pt=new Set;function lt(){for(let e of Pt)try{e();}catch(t){console.error("[fork-preview] subscriber threw",t);}}function yr(e){let t=Date.parse(e.expires_at);return Number.isFinite(t)?t<=Date.now():true}function xn(e){if(typeof window>"u")return null;try{let t=window.sessionStorage.getItem(at(e));if(!t)return null;let r=JSON.parse(t);return !r||typeof r!="object"||typeof r.preview_session_id!="string"?null:yr(r)?(window.sessionStorage.removeItem(at(e)),null):r}catch{return null}}function It(e,t){if(!(typeof window>"u"))try{t?window.sessionStorage.setItem(at(e),JSON.stringify(t)):window.sessionStorage.removeItem(at(e));}catch{}}function $e(e){U.apiKey!==e&&(U.apiKey=e,U.session=xn(e),lt());}function ge(){return U.session?yr(U.session)?(ct(null),null):U.session:null}function ct(e){U.session=e,U.apiKey&&It(U.apiKey,e),lt();}function Be(e){U.session&&U.session.fork_id!==e&&(U.session={...U.session,fork_id:e},U.apiKey&&It(U.apiKey,U.session),lt());}function ve(e,t){U.session&&(U.session.container_id===e&&U.session.container_name===t||(U.session={...U.session,container_id:e,container_name:t??U.session.container_name??"Fork",fork_id:null},U.apiKey&&It(U.apiKey,U.session),lt()));}function Tt(e){return Pt.add(e),()=>{Pt.delete(e);}}var kr="__fork_preview";function br(){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(kr);return typeof r=="string"&&r.length>0?r:null}function Lt(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 vr()!==null}function wr(){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(kr);let r=t.toString(),n=r?`#${r}`:"";try{window.history.replaceState(null,"",window.location.pathname+window.location.search+n);}catch{}}var Se=null,Mt=null,Ue=null;function vr(){if(Se)return Se;let e=br();return e?(Se=e,wr(),Se):null}async function Nt(e,t){$e(e);let r=ge();if(r)return Se=null,r;let n=Se??br();if(Se=null,!n)return null;wr();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 c=await o.json().catch(()=>({}));return console.warn(`[fork-preview] activate failed (${o.status}): ${c.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 ct(s),s}catch(o){return console.warn("[fork-preview] activate threw",o),null}}async function Ht(e,t,r){$e(e);let n=ge();if(n)return n;if(!r.appId||!r.userId||!r.userHash)return null;let o=[e,t,r.appId,r.userId].join(`
2
+ `);return Ue&&Mt===o||(Mt=o,Ue=(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 p=await i.json().catch(()=>({}));return console.warn(`[fork-preview] auto admin activate failed (${i.status}): ${p.error??"unknown"}`),null}let s=await i.json(),c={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 ct(c),c}catch(i){return console.warn("[fork-preview] auto admin activate threw",i),null}finally{Mt=null,Ue=null;}})()),Ue}function _n(){return ge()}function Rn(){return null}function dt(){return useSyncExternalStore(Tt,_n,Rn)}function K(){let e=ge();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 ut(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[c,p]of Object.entries(i.modules)){let g=p.moduleUrl??p.bundleUrl??null,f=p.legacyModuleUrl??p.legacyBundleUrl??null;s[c]={forkId:p.forkId,moduleUrl:g,legacyModuleUrl:f,bundleUrl:p.bundleUrl??g,legacyBundleUrl:p.legacyBundleUrl??f,cssUrls:p.cssUrls??[],integrity:p.integrity,metadata:p.metadata,buildId:p.buildId,updatedAt:p.updatedAt};}return {containerId:i.containerId,slots:i.slots,modules:s,generatedAt:i.generatedAt,etag:o.headers.get("ETag")??void 0}}var Cn="fork:manifest:v1";function Ot(e,t,r){return `${Cn}:${e}:${t}:${r}`}function En(e,t,r){if(typeof window>"u")return null;try{let n=window.localStorage.getItem(Ot(e,t,r));return n?JSON.parse(n):null}catch{return null}}function An(e,t,r,n){if(!(typeof window>"u"))try{window.localStorage.setItem(Ot(e,t,r),JSON.stringify(n));}catch{}}function $n(e,t,r){if(!(typeof window>"u"))try{window.localStorage.removeItem(Ot(e,t,r));}catch{}}function Pn(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,c]of r){let p=t.slots[s];if(!p||p.forkId!==c.forkId||p.buildId!==c.buildId)return true}let o=Object.entries(e.modules),i=Object.entries(t.modules);if(o.length!==i.length)return true;for(let[s,c]of o){let p=t.modules[s];if(!p||p.forkId!==c.forkId||p.buildId!==c.buildId)return true}return false}var Fr=createContext(null);function De(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function Mn(e,t){let r={};for(let[n,o]of Object.entries(t.boundaries||{}))r[n]={...o,moduleUrl:De(e,o.moduleUrl),cssUrls:Array.isArray(o.cssUrls)?o.cssUrls.map(i=>De(e,i)):[]};return r}function Sr(e,t,r,n){let o={};for(let[i,s]of Object.entries(t.slots)){let c=s.bundleUrl??s.legacyBundleUrl;c&&(o[i]={id:s.forkId,userId:r,prompt:"",status:"complete",slotId:i,appId:n,bundleUrl:De(e,c),createdAt:s.updatedAt,completedAt:s.updatedAt});}return o}function xr(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:De(e,i),cssUrls:(o.cssUrls??[]).map(s=>De(e,s)),integrity:o.integrity,metadata:o.metadata,createdAt:o.updatedAt});}return r}function Ln(e){let{apiKey:t,baseUrl:r,children:n,appId:o,shared:i}=e,s="userId"in e?e.userId:void 0,c="authUrl"in e?e.authUrl:void 0,[p]=useState(()=>($e(t),Lt(t))),[g,f]=useState({}),[k,I]=useState(s?{userId:s,userHash:void 0}:null),[R,_]=useState(!!s||p),[h,b]=useState({}),[M,C]=useState(!o),[N,T]=useState(0),[L,x]=useState(null),w=useRef(new Map),d=useRef(new Map),[S,E]=useState(0),A=useRef(new Set),u=useRef(new Map),l=useRef(void 0);At(),useEffect(()=>{return Nt(t,r).then(()=>{}),()=>{}},[]);let y=dt();useEffect(()=>{p||y||!o||!k?.userHash||Ht(t,r,{appId:o,userId:k.userId,userHash:k.userHash});},[t,o,k?.userHash,k?.userId,r,p,y?.preview_session_id]),i&&l.current!==i&&($t(i),l.current=i),useEffect(()=>{c&&(p||(_(false),fetch(c,{credentials:"include"}).then($=>{if(!$.ok)throw new Error(`Auth endpoint returned ${$.status}`);return $.json()}).then($=>{if(!$.userId||typeof $.userId!="string")throw new Error("authUrl response must include userId");I({userId:$.userId,userHash:typeof $.userHash=="string"?$.userHash:void 0});}).catch($=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",$.message);}).finally(()=>{_(true);})));},[c,p]),useEffect(()=>{!c&&s&&(I({userId:s,userHash:void 0}),_(true));},[s,c]);let j=k?.userId??"",Y=k?.userHash,D=y?"":j,W=y?void 0:Y,ee=!!o,z=useCallback(async()=>{if(!ee){x(null),b({}),C(true),T(F=>F+1);return}if(!R){C(false);return}if(!y&&!D||!o){x(null),b({}),C(true),T(F=>F+1);return}if(C(false),!y){try{let F=await ut({baseUrl:r,apiKey:t,appId:o,userId:D,userHash:W});F&&(x(F.containerId),f(Sr(r,F,D,o)),b(xr(r,F)));}catch(F){console.error("[ForkProvider] Failed to fetch fork manifest:",F.message),x(null),f({}),b({});}finally{T(F=>F+1),C(true);}return}if(x(y.container_id??null),y.container_id){try{let F=await ut({baseUrl:r,apiKey:t,appId:o,userId:D,containerId:y.container_id,extraHeaders:K()});F&&(f(Sr(r,F,D,o)),b(xr(r,F)));}catch(F){console.error("[ForkProvider] Failed to fetch preview container manifest:",F.message),f({}),b({});}finally{T(F=>F+1),C(true);}return}let $=new URLSearchParams({appId:o,userId:D});W&&$.set("userHash",W);try{let F=await fetch(`${r}/api/v1/boundaries/manifest?${$.toString()}`,{headers:{Authorization:`Bearer ${t}`,...K()}});if(!F.ok)throw new Error(`${F.status}`);let O=await F.json();b(Mn(r,O));}catch(F){console.error("[ForkProvider] Failed to fetch module override manifest:",F.message),b({});}finally{T(F=>F+1),C(true);}},[t,o,r,R,ee,W,D,y?.preview_session_id,y?.fork_id,y?.container_id]);useEffect(()=>{if(!D||o&&(!y||y.container_id))return;let $=new URLSearchParams({userId:D});W&&$.set("userHash",W),fetch(`${r}/api/v1/forks/active?${$.toString()}`,{headers:{Authorization:`Bearer ${t}`,...K()}}).then(F=>{if(!F.ok)throw new Error(`${F.status}`);return F.json()}).then(F=>{F&&typeof F=="object"&&f(F);}).catch(()=>{});},[t,o,D,W,r,y?.preview_session_id,y?.fork_id]),useEffect(()=>{z();},[z]);let se=useCallback(($,F)=>{f(O=>({...O,[$]:F}));},[]),ie=useCallback($=>{f(F=>{let O={...F};return delete O[$],O});},[]),fe=useCallback($=>{A.current.add($);},[]),te=useCallback($=>A.current.has($)?(A.current.delete($),true):false,[]),xt=useCallback(($,F)=>{u.current.set($,F);},[]),Xe=useCallback(($,F)=>u.current.get($)!==F?false:(u.current.delete($),true),[]),Te=useCallback($=>{if(!o)return;let F=JSON.stringify($);w.current.get($.id)===F||d.current.get($.id)?.signature===F||(d.current.set($.id,{boundary:$,signature:F}),E(re=>re+1));},[o]);useEffect(()=>{if(!o||d.current.size===0)return;let $=setTimeout(()=>{let F=Array.from(d.current.values());F.length!==0&&fetch(`${r}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:o,boundaries:F.map(O=>O.boundary)})}).then(O=>{if(!O.ok)throw new Error(`${O.status}`)}).then(()=>{for(let O of F)d.current.get(O.boundary.id)?.signature===O.signature&&(d.current.delete(O.boundary.id),w.current.set(O.boundary.id,O.signature));}).catch(O=>{console.error("[ForkProvider] Failed to register module boundaries:",O.message);});},50);return ()=>{clearTimeout($);}},[t,o,r,S]);let ce=useCallback($=>h[$],[h]),Z=useCallback(async()=>{if(!D)throw new Error("Reset requires a resolved user identity.");let $=new URLSearchParams({userId:D});W&&$.set("userHash",W);let F={Authorization:`Bearer ${t}`,...K()};o&&(F["X-Fork-App-Id"]=o);let O=await fetch(`${r}/api/v1/forks/all?${$.toString()}`,{method:"DELETE",headers:F});if(!O.ok){let ne=await O.json().catch(()=>({}));throw new Error(ne.error||`API error: ${O.status}`)}let re=await O.json().catch(()=>({}));f({}),b({}),C(true),T(ne=>ne+1),A.current.clear(),u.current.clear();try{for(let ne=sessionStorage.length-1;ne>=0;ne-=1){let Me=sessionStorage.key(ne);Me&&Me.startsWith("__fork_animated_")&&sessionStorage.removeItem(Me);}}catch{}return re},[t,o,r,W,D]);return jsx(Fr.Provider,{value:{apiKey:t,userId:D,userHash:W,baseUrl:r,appId:o,forks:g,moduleOverridesEnabled:ee,moduleManifestReady:M,moduleManifestVersion:N,currentContainerId:L,previewSession:y,setSlotFork:se,clearSlotFork:ie,skipAnimationForSlot:fe,shouldSkipAnimation:te,queueBoundaryAnimation:xt,consumeBoundaryAnimation:Xe,registerBoundary:Te,getBoundaryOverride:ce,refreshModuleManifest:z,resetAllForks:Z},children:n})}function Q(){let e=useContext(Fr);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function ft(e){return Q().forks[e]}var ze=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 jt(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 Rr=new Set;function Cr(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 Un(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 c=r[s];c.rect.top>=n.rect.top&&c.rect.left>=n.rect.left&&c.rect.right<=n.rect.right&&c.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function jn(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 c=r[s];c.rect.top>=n.rect.top&&c.rect.left>=n.rect.left&&c.rect.right<=n.rect.right&&c.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Ar(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 Er(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 f=0;f<e.length;f++){let{rect:k,borderRadius:I}=e[f],R=k.left-.5,_=k.top-.5,h=k.width+1,b=k.height+1,M=Math.min(I+.5,h/2,b/2),C=Ar(R,_,h,b,M),N=`__fork-glow-${f}`,T=document.createElementNS(t,"filter");T.setAttribute("id",N),T.setAttribute("x","-100%"),T.setAttribute("y","-100%"),T.setAttribute("width","300%"),T.setAttribute("height","300%");let L=document.createElementNS(t,"feGaussianBlur");L.setAttribute("in","SourceGraphic"),L.setAttribute("stdDeviation","8"),T.appendChild(L),o.appendChild(T);let x=`__fork-mask-${f}`,w=document.createElementNS(t,"mask");w.setAttribute("id",x),w.setAttribute("maskUnits","userSpaceOnUse"),w.setAttribute("x",String(R-200)),w.setAttribute("y",String(_-200)),w.setAttribute("width",String(h+400)),w.setAttribute("height",String(b+400));let d=document.createElementNS(t,"rect");d.setAttribute("x",String(R-200)),d.setAttribute("y",String(_-200)),d.setAttribute("width",String(h+400)),d.setAttribute("height",String(b+400)),d.setAttribute("fill","white"),w.appendChild(d);let S=document.createElementNS(t,"path");S.setAttribute("d",C),S.setAttribute("fill","black"),w.appendChild(S),o.appendChild(w);let E=document.createElementNS(t,"g");E.setAttribute("mask",`url(#${x})`),E.setAttribute("opacity","0");let A=document.createElementNS(t,"g");A.setAttribute("filter",`url(#${N})`);let u=document.createElementNS(t,"path");u.setAttribute("d",C),u.setAttribute("fill","none"),u.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),u.setAttribute("stroke-width","6"),u.setAttribute("stroke-linecap","round"),A.appendChild(u),E.appendChild(A),n.appendChild(E);let l=document.createElementNS(t,"path");l.setAttribute("d",C),l.setAttribute("fill","none"),l.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),l.setAttribute("stroke-width","2"),l.setAttribute("stroke-linecap","round"),l.setAttribute("opacity","0"),n.appendChild(l),i.push(u,l),u.__group=E;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let f=0;f<i.length;f+=2){let k=i[f],I=i[f+1],R=k.__group,_=I.getTotalLength(),h=k.getTotalLength();if(_<=0)continue;let b=_*.35;I.setAttribute("stroke-dasharray",`${b} ${_-b}`),I.setAttribute("stroke-dashoffset","0"),s.push(I.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*_,opacity:.92,offset:.06},{strokeDashoffset:-2*_,opacity:.92,offset:.92},{strokeDashoffset:-2.25*_,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let M=h*.35;k.setAttribute("stroke-dasharray",`${M} ${h-M}`),k.setAttribute("stroke-dashoffset","0"),s.push(k.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*h,offset:.06},{strokeDashoffset:-2*h,offset:.92},{strokeDashoffset:-2.25*h,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(R.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 c=false,p=()=>{if(c)return;c=true,clearTimeout(g);for(let k of s)try{k.cancel();}catch{}let f=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});f.onfinish=()=>r.remove(),window.removeEventListener("click",p);},g=setTimeout(p,14500);return setTimeout(()=>{c||window.addEventListener("click",p);},500),p}function Dn(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:c,borderRadius:p}of e){let g=c.left,f=c.top,k=c.width,I=c.height,R=Math.min(p,k/2,I/2),_=Ar(g,f,k,I,R),h=document.createElementNS(t,"path");h.setAttribute("d",_),h.setAttribute("fill","none"),h.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),h.setAttribute("stroke-width","1.5"),h.setAttribute("stroke-dasharray","8 4"),h.setAttribute("stroke-linecap","round"),h.setAttribute("filter","url(#__fork-removed-shadow)"),h.setAttribute("opacity","0"),n.appendChild(h),h.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 zn(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 Wn=Ut__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&&zn(e.hostProps,t.hostProps)),Bt=class extends Ut__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 $r({slotId:e,children:t,githubRepo:r,shared:n,events:o}){jt(t,e);let i=ft(e),{baseUrl:s,apiKey:c,appId:p,shouldSkipAnimation:g}=Q(),[f,k]=useState(null),I=useRef(null),R=useRef(null),_=useRef(null),h=useRef(false),b=useRef(null),M=useRef(null),C=!!(n||o),N=useRef(null);C&&!N.current&&(N.current=new ze(e));let T=useRef(o);if(T.current=o,useEffect(()=>{if(C)return ()=>{N.current?.destroy(),N.current=null;}},[C,e]),C&&N.current&&n)for(let[S,E]of Object.entries(n))N.current.set(S,E);useEffect(()=>{if(!C)return;N.current||(N.current=new ze(e));let S=N.current,E=Object.keys(T.current||{}).map(A=>S.on(A,(...u)=>T.current?.[A]?.(...u)));return ()=>E.forEach(A=>A())},[C,e]),useEffect(()=>{if(Rr.has(e))return;Rr.add(e);let S={id:e,appId:p,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 ${c}`,"Content-Type":"application/json"},body:JSON.stringify(S)}).catch(()=>{});},[e,s,c,r,p]);let L=i?.id||null;useEffect(()=>{if(i?.bundleUrl,I.current,R.current,!i?.bundleUrl||!L){return}let S=`${s}${i.bundleUrl.replace("bundle.js","component.js")}`,E=`__fork_animated_${e}`,A=sessionStorage.getItem(E),u=g(e),l=!u&&A!==L;if(u&&L&&sessionStorage.setItem(E,L),l&&R.current){let W=Cr(R.current);_.current=W,h.current=true,`${e}${W.length}`;}window.__FORK_REACT__=Ut__default,window.__FORK_REACT_DOM__=bn,window.__FORK_REACT_JSX__=wn;let y=Date.now(),j=`${s}${i.bundleUrl.replace("bundle.js","component.css")}?t=${y}`,Y=document.createElement("link");Y.rel="stylesheet",Y.href=j,Y.dataset.forkSlot=e,document.head.appendChild(Y);let D=document.createElement("script");return D.src=S+"?t="+y,D.onload=()=>{let W=window.__FORK_EXPORT__;if(W?.default){if(R.current&&_.current&&h.current){let ee=R.current.getBoundingClientRect(),z=R.current.cloneNode(true);z.style.position="fixed",z.style.top=`${ee.top}px`,z.style.left=`${ee.left}px`,z.style.width=`${ee.width}px`,z.style.height=`${ee.height}px`,z.style.flex="none",z.style.minHeight="auto",z.style.zIndex="9998",z.style.pointerEvents="none",z.style.overflow="hidden";let se=getComputedStyle(R.current).backgroundColor;z.style.backgroundColor=se&&se!=="rgba(0, 0, 0, 0)"&&se!=="transparent"?se:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(z);let ie=R.current.querySelectorAll("*"),fe=z.querySelectorAll("*");for(let te=0;te<ie.length;te++)ie[te].scrollTop!==0&&(fe[te].scrollTop=ie[te].scrollTop),ie[te].scrollLeft!==0&&(fe[te].scrollLeft=ie[te].scrollLeft);b.current=z;}k(()=>W.default),I.current=L;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},D.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(D),()=>{D.remove(),Y.remove(),M.current&&(clearTimeout(M.current),M.current=null),b.current&&(b.current.remove(),b.current=null);}},[L,s,e]),useEffect(()=>{if(!h.current||!f||!R.current){`${e}${h.current}`,R.current;return}let S=_.current;if(!S){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!R.current)return;let E=Cr(R.current),A=Un(S,E),u=jn(S,E),l=b.current;if(`${e}${A.length}${u.length}`,u.length>0&&l){let y=Dn(u);M.current=setTimeout(()=>{M.current=null;let j=400;l.animate([{opacity:1},{opacity:0}],{duration:j,fill:"forwards"}),y.animate([{opacity:1},{opacity:0}],{duration:j,fill:"forwards"}),setTimeout(()=>{l.remove(),y.remove(),b.current=null,A.length>0&&(Er(A));},j);},3500);}else l&&(l.remove(),b.current=null),A.length>0&&(Er(A));_.current=null,h.current=false,L&&(sessionStorage.setItem(`__fork_animated_${e}`,L),`${e}`);});});},[f]);let x={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!i||i.status!=="complete"||!i.bundleUrl)return jsx("div",{ref:R,style:x,children:t});if(!f)return jsx("div",{ref:R,style:x,children:t});let d=t?.props??{};return jsx(Bt,{slotId:e,resetKey:L,fallback:jsx("div",{ref:R,style:x,children:t}),children:jsx(Wn,{component:f,containerRef:R,wrapperStyle:x,hostProps:d})})}var Ir=new Set;function Jn(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 Tr(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&&Tr(n.children,t);}),t}function qn({slotId:e,props:t,children:r,allowedFetches:n,githubRepo:o,callbacks:i,mode:s="iframe",shared:c,events:p}){if(jt(r,e),s==="direct")return jsx($r,{slotId:e,githubRepo:o,shared:c,events:p,children:r});let g=ft(e),{baseUrl:f,apiKey:k,appId:I}=Q(),R=useRef(null),_=useRef(false),h=useRef(null),b=useRef(i);b.current=i;let M=useRef(t);M.current=t;let C=useRef(n);C.current=n,useEffect(()=>{if(typeof process<"u")return;let x=Tr(r),w=new Set(i?Object.keys(i):[]),d=[...x].filter(S=>!w.has(S));d.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
+ `+d.map(S=>` - ${S}`).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(()=>{Ir.has(e)||(Ir.add(e),fetch(`${f}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${k}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:I,label:e,propsShape:t?Jn(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:o,callbackNames:i?Object.keys(i):[],mode:s||"iframe"})}).catch(()=>{}));},[e,f,k,o,I]);let N=useCallback(x=>{let w=R.current;if(w?.contentWindow&&_.current){let d=b.current?Object.keys(b.current):[];w.contentWindow.postMessage({type:"slot:props",props:x,callbackNames:d},"*"),h.current=null;}else h.current=x;},[]),T=useCallback((x,w)=>{let d=C.current;return !d||d.length===0?false:d.some(S=>{let[E,A]=S.split(" "),u=w.split("?")[0];return x.toUpperCase()===E.toUpperCase()&&u.startsWith(A)})},[]);if(useEffect(()=>{if(!g?.bundleUrl)return;let x=async w=>{if(w.source===R.current?.contentWindow){if(w.data?.type==="slot:ready")_.current=true,R.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:C.current||[]},"*"),C.current,h.current?N(h.current):N(M.current||{});else if(w.data?.type==="slot:event"){let d=w.data.event;d?.navigate&&(window.location.hash=d.navigate);}else if(w.data?.type==="slot:clipboard-write")navigator.clipboard.writeText(w.data.text).catch(d=>{console.warn(`[ForkSlot:${e}] clipboard write failed:`,d.message);});else if(w.data?.type==="slot:callback"){let{name:d,args:S}=w.data,E=b.current?.[d];E?(E(...S||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${d}`);}else if(w.data?.type==="slot:fetch"){let{id:d,method:S,url:E,body:A}=w.data,u=R.current?.contentWindow;if(!u)return;let l=S||"GET";if(!T(l,E)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${d}: ${l} ${E} \u2014 not in allowedFetches`),u.postMessage({type:"slot:fetch-response",id:d,error:`Fetch not allowed: ${l} ${E}`},"*");return}try{let y={method:l};A&&l!=="GET"&&(y.headers={"Content-Type":"application/json"},y.body=JSON.stringify(A));let j=await fetch(E,y),Y=await j.json();`${e}${d}${j.status}`,u.postMessage({type:"slot:fetch-response",id:d,data:Y,status:j.status},"*");}catch(y){console.error(`[ForkSlot:${e}] fetch #${d} failed:`,y.message),u.postMessage({type:"slot:fetch-response",id:d,error:y.message},"*");}}}};return window.addEventListener("message",x),()=>{window.removeEventListener("message",x),_.current=false;}},[g?.bundleUrl,e,N,T]),useEffect(()=>{g?.bundleUrl&&_.current&&N(t||{});},[t,g?.bundleUrl,N]),!g||g.status!=="complete"||!g.bundleUrl)return `${e}${g?.status||"none"}${g?.bundleUrl||"none"}`,jsx(Fragment,{children:r});`${e}${g.bundleUrl}`;let L=`${f}${g.bundleUrl.replace("/bundle.js","/host")}`;return jsx("iframe",{ref:R,src:L,sandbox:"allow-scripts allow-same-origin allow-forms allow-clipboard-write",title:`Forked ${e}`,style:{width:"100%",border:"none",flex:1,minHeight:0}})}function gt({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"})]})}function zt({onClick:e}){let[t,r]=useState(false),[n,o]=useState(false),i=t?48:40;return jsx("button",{onClick:e,onMouseEnter:()=>r(true),onMouseLeave:()=>{r(false),o(false);},onMouseDown:()=>o(true),onMouseUp:()=>o(false),style:{position:"fixed",bottom:24,right:24,zIndex:40,width:i,height:i,borderRadius:"50%",backgroundColor:t?"rgba(255, 255, 255, 1)":"rgba(255, 255, 255, 0.3)",border:t?"1px solid rgba(156, 163, 175, 1)":"1px solid rgba(156, 163, 175, 0.3)",display:"flex",alignItems:"center",justifyContent:"center",color:t?"#1c4587":"rgba(28, 69, 135, 0.5)",boxShadow:t?"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:n?"scale(0.95)":"scale(1)",transition:"all 300ms",cursor:"pointer",padding:0,margin:0,outline:"none",boxSizing:"border-box"},title:"Fork this app",children:jsx(gt,{style:{width:24,height:24}})})}var oo={status:Loader2,agent_message:MessageSquare,tool_use:Wrench,build_start:Package,build_complete:Check,build_error:AlertCircle,complete:Sparkles,error:AlertCircle},so={status:"#60a5fa",agent_message:"#a0a0a0",tool_use:"#fbbf24",build_start:"#c084fc",build_complete:"#6b7280",build_error:"#f87171",complete:"#6b7280",error:"#f87171"},io={read:FileSearch,write:Pencil,search:FileSearch,shell:Terminal,build:Package},ao={read:"#60a5fa",write:"#fbbf24",search:"#60a5fa",shell:"#a78bfa",build:"#c084fc"};function Kt(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 jr({events:e}){let t=useRef(null);return useEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight);},[e]),jsxs(Fragment,{children:[jsx("style",{children:`
4
5
  @keyframes __fork-spin {
5
6
  from { transform: rotate(0deg); }
6
7
  to { transform: rotate(360deg); }
@@ -18,7 +19,7 @@ import*as Bt from'react';import Bt__default,{createContext,useSyncExternalStore,
18
19
  .__fork-stream::-webkit-scrollbar-thumb:hover {
19
20
  background: rgba(255, 255, 255, 0.3);
20
21
  }
21
- `}),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"),c=to[r.type]||Code,p=ro[r.type]||"#9ca3af";if(r.type==="tool_use"){let g=String(r.data.category||"");c=no[g]||Wrench,p=oo[g]||"#fbbf24";}return s?c=Loader2:!o&&r.type==="status"&&(c=Check,p="#4ade80"),jsxs("div",{style:{display:"flex",gap:"6px",marginBottom:"6px",lineHeight:1.625},children:[jsx(c,{style:{width:"12px",height:"12px",marginTop:"2px",flexShrink:0,color:p,...s?{animation:"__fork-spin 1s linear infinite"}:{}}}),jsx("span",{style:{color:o&&!i?"#d1d5db":"#6b7280",wordBreak:"break-all"},children:Dt(r)})]},n)})]})]})}var jr=35,po="Working on Feature",go="Built Custom Feature",Dr=360,mt=350;function mo(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 ho(e){return e.length<=jr?e:e.slice(0,jr-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 p of e)if(p.type==="status"&&String(p.data.message||"").includes("Agent started")){s.current=true;break}}let c="Setting up environment...";if(s.current)for(let p=e.length-1;p>=0;p--){let g=e[p];if(g.type==="tool_use"||g.type==="build_start"||g.type==="build_complete"){c=ho(Dt(g));break}}if(c!==i.current){o(false);let p=setTimeout(()=>{r(c),i.current=c,o(true);},200);return ()=>clearTimeout(p)}},[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 ko({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 ht({state:e,fork:t,events:r,error:n,slotId:o,targetId:i,targetLabel:s,historyMode:c="slot",onSubmit:p,onUndo:g,onClose:f,baseUrl:S,apiKey:P,userId:_,userHash:R,appId:h,embedded:y=false}){let[I,C]=useState(""),[N,M]=useState([]),[L,x]=useState(false),[k,d]=useState(false),[v,E]=useState(false),[A,u]=useState(false),[l,b]=useState(false),[j,Y]=useState(false),[D,W]=useState(false),[ee,z]=useState(false),[se,ie]=useState(false),[fe,te]=useState(null),[vt,qe]=useState(false),[Me,ce]=useState([]),[Z,T]=useState(null),[F,O]=useState(false),[re,ne]=useState(false),[Te,Qt]=useState(false),[rn,er]=useState(null),[q,Xe]=useState(null),[nn,tr]=useState(false),[St,Ye]=useState(false),[me,Ie]=useState(""),xt=useRef(null),[rr,he]=useState(null),[on,Le]=useState(false),[Fe,nr]=useState(null),[Ne,Ze]=useState([]),[X$1,Re]=useState(null),[ae,_e]=useState(false),Ce=useRef(false),Ft=useRef(null),Qe=useRef(null),{resetAllForks:sn,previewSession:G,currentContainerId:an}=Q(),ye=G?.container_id??an,et=!!(G&&on),de=Fe!==null,or=useRef(f);useEffect(()=>{or.current=f;});let Rt=useRef(null),tt=useRef(false),sr=typeof window<"u"&&"documentPictureInPicture"in window,ln=async()=>{if(!(!sr||de))try{let a=await window.documentPictureInPicture.requestWindow({width:Dr,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 m=document.adoptedStyleSheets??[];m.length>0&&(a.document.adoptedStyleSheets=[...m]);}catch{}a.addEventListener("pagehide",()=>{Rt.current=null,nr(null),tt.current||or.current(),tt.current=!1;},{once:!0}),Rt.current=a,nr(a);}catch(a){console.warn("[Fork] PiP open failed:",a);}},cn=()=>{Fe&&(tt.current=true,Fe.close());};useEffect(()=>()=>{tt.current=true,Rt.current?.close();},[]);let pe=i??o??"",ir=(s||pe).replace(/[-_]+/g," ").replace(/\b\w/g,a=>a.toUpperCase()),rt=useRef(""),ar=()=>{let a={Authorization:`Bearer ${P}`,...K()};return h&&(a["X-Fork-App-Id"]=h),!G&&_&&(a["X-Fork-User-Id"]=_),!G&&R&&(a["X-Fork-User-Hash"]=R),a},nt=y?true:k&&!v,dn=r.find(a=>{let m=a.data;return a.type==="status"&&m.summary})?.data?.summary||t?.summary||po,ke=r.find(a=>{let m=a.data;return (a.type==="status"||a.type==="complete")&&typeof m?.estimateMinutes=="number"})?.data?.estimateMinutes??t?.estimateMinutes;useEffect(()=>{if(c==="none"){x(true);return}if(!S||!P)return;if(!X$1){M([]),x(true);return}let a=new AbortController;return fetch(`${S}/api/v1/forks/${encodeURIComponent(X$1)}/messages`,{headers:ar(),signal:a.signal}).then(m=>m.ok?m.json():[]).then(m=>{if(a.signal.aborted)return;let $=[];for(let J of m){let Ee=J.forkId??X$1;J.role==="user"?$.push({type:"user",text:J.content,forkId:Ee}):$.push({type:"applied",text:J.content,forkId:Ee});}M($),x(true);}).catch(()=>{a.signal.aborted||x(true);}),()=>{a.abort();}},[P,h,S,c,X$1,G?.fork_id,G?.preview_session_id,R,_,t?.id,t?.completedAt]),useEffect(()=>{if(c==="none"||!S||!P||!F)return;if(!Z){Ze([]);return}let a=new AbortController,m=new URLSearchParams({container_id:Z});return fetch(`${S}/api/v1/forks?${m.toString()}`,{headers:ar(),signal:a.signal}).then($=>$.ok?$.json():{forks:[]}).then($=>{a.signal.aborted||Ze($.forks??[]);}).catch(()=>{}),()=>{a.abort();}},[P,h,S,c,Z,F,t?.id,t?.completedAt,G?.fork_id,G?.preview_session_id,R,_]),useEffect(()=>{e==="complete"&&z(false);},[e]);let lr=Ne.some(a=>a.status==="pending"||a.status==="running"||a.status==="building");useEffect(()=>{if(!lr||!S||!P||!Z)return;let a=new URLSearchParams({container_id:Z}),m={Authorization:`Bearer ${P}`,...K()};h&&(m["X-Fork-App-Id"]=h);let J=setInterval(async()=>{try{let Ee=await fetch(`${S}/api/v1/forks?${a.toString()}`,{headers:m});if(!Ee.ok)return;let gn=await Ee.json();Ze(gn.forks??[]);}catch{}},3e3);return ()=>clearInterval(J)},[lr,S,P,h,Z]),useEffect(()=>{if(y&&c==="none"){ce([]),T(null),O(true),Le(false);return}if(G){let a=false;return O(false),Le(false),he(null),fetch(`${S}/api/v1/preview/${encodeURIComponent(G.preview_session_id)}/containers`,{headers:{Authorization:`Bearer ${P}`,...K()}}).then(m=>{if(!m.ok)throw new Error(`${m.status}`);return m.json()}).then(m=>{a||(ce(m.containers),T(m.currentContainerId??G.container_id??null),Le(true));}).catch(m=>{a||(Le(false),he(m instanceof Error?m.message:String(m)),ye?(ce([{id:ye,name:G.container_name||"Primary container",createdAt:"",hasAccess:true,isPrimary:true}]),T(ye)):(ce([]),T(null)));}).finally(()=>{a||O(true);}),()=>{a=true;}}ye?(ce([{id:ye,name:"Primary container",createdAt:""}]),T(ye)):(ce([]),T(null)),O(true),Le(false);},[P,ye,S,y,c,G?.container_id,G?.container_name,G?.preview_session_id]);let ot=useRef(void 0);useEffect(()=>{if(F){if(ot.current===void 0){ot.current=Z;return}ot.current!==Z&&(ot.current=Z,M([]),x(false));}},[Z,F]);let st=useRef(null);useEffect(()=>{if(!re)return;let a=$=>{if(!st.current)return;let J=typeof $.composedPath=="function"?$.composedPath():[];st.current.contains($.target)||J.includes(st.current)||ne(false);},m=$=>{$.key==="Escape"&&ne(false);};return document.addEventListener("mousedown",a,true),document.addEventListener("keydown",m,true),()=>{document.removeEventListener("mousedown",a,true),document.removeEventListener("keydown",m,true);}},[re]),useEffect(()=>{re||(Ye(false),Ie(""));},[re]),useEffect(()=>{St&&(xt.current?.focus(),xt.current?.select());},[St]),useEffect(()=>{if(y)return;let a=requestAnimationFrame(()=>d(true));return ()=>cancelAnimationFrame(a)},[y]),useEffect(()=>{let a=y||de;if((a||nt)&&(e==="prompting"||e==="complete")){let m=setTimeout(()=>Ft.current?.focus(),a?100:mt+100);return ()=>clearTimeout(m)}},[nt,y,de,e]),useEffect(()=>{if(e==="complete"&&rt.current){let m=r.find($=>$.type==="complete")?.data?.summary||t?.summary||go;M($=>$[$.length-1]?.type==="applied"?$:[...$,{type:"applied",text:m}]),C(""),setTimeout(()=>Ft.current?.focus(),200);}},[e,ir,r,t?.summary]),useEffect(()=>{Qe.current&&(Qe.current.scrollTop=Qe.current.scrollHeight);},[N,e]);let cr=()=>{if(I.trim()){rt.current=I.trim();let a={};ae?(a.forceNew=true,Ce.current=true):X$1&&(a.forkId=X$1),ae||M(m=>[...m,{type:"user",text:I.trim(),forkId:X$1}]),p(I.trim(),pe,Z,a),C("");}};useEffect(()=>{if(Ce.current){if(e==="error"){Ce.current=false;return}t?.id&&(Re(t.id),_e(false),Ce.current=false);}},[t?.id,e]);let dr=a=>{ve(a.session.containerId,a.session.containerName),T(a.session.containerId),ce(m=>{let $=m.filter(J=>J.id!==a.container.id);return [{...a.container,isPrimary:true,hasAccess:true},...$.map(J=>({...J,isPrimary:false}))]}),Re(null),_e(false),Ce.current=false,M([]),x(false),rt.current="";},un=async a=>{if(!(!G||!et||q)){Xe(a),he(null);try{let m=await fetch(`${S}/api/v1/preview/${encodeURIComponent(G.preview_session_id)}/containers/${encodeURIComponent(a)}/primary`,{method:"POST",headers:{Authorization:`Bearer ${P}`,...K()}});if(!m.ok){let $=await m.json().catch(()=>({}));throw new Error($.error||`API error: ${m.status}`)}dr(await m.json()),ne(!1);}catch(m){he(m instanceof Error?m.message:String(m));}finally{Xe(null);}}},ur=async a=>{if(!G||!et||q)return;let m=a.trim();if(m){Xe("__new__"),he(null);try{let $=await fetch(`${S}/api/v1/preview/${encodeURIComponent(G.preview_session_id)}/containers`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${P}`,...K()},body:JSON.stringify({name:m})});if(!$.ok){let J=await $.json().catch(()=>({}));throw new Error(J.error||`API error: ${$.status}`)}dr(await $.json()),Ye(!1),Ie(""),ne(!1);}catch($){he($ instanceof Error?$.message:String($));}finally{Xe(null);}}},fn=async()=>{if(!(!g||se||!pe)){ie(true);try{let a=await g(pe);M(m=>{let $=[...m];return $.length>=2&&$[$.length-1]?.type==="applied"?$.splice(-2,2):$.length>=1&&$[$.length-1]?.type==="applied"&&$.splice(-1,1),$}),a?.removed&&M([]);}catch{}finally{ie(false);}}},fr=()=>{if(y){f();return}if(de){Fe?.close();return}E(true),d(false),setTimeout(()=>f(),mt);},pn=y||de?{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:Dr,maxWidth:"100vw",background:"#ffffff",boxShadow:nt?"-12px 0 32px -16px rgba(0, 0, 0, 0.18), -2px 0 8px -2px rgba(0, 0, 0, 0.06)":"none",borderLeft:"1px solid rgba(0, 0, 0, 0.08)",transform:nt?"translateX(0)":"translateX(100%)",transition:`transform ${mt}ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow ${mt}ms ease`,display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'},pr=Me.find(a=>a.id===Z)?.name??(F?"Fork":"Loading..."),Be=ae?[]:X$1?N.filter(a=>a.forkId===X$1||a.forkId==null):N,_t=jsxs(Fragment,{children:[jsx("style",{children:`
22
+ `}),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"),c=oo[r.type]||Code,p=so[r.type]||"#9ca3af";if(r.type==="tool_use"){let g=String(r.data.category||"");c=io[g]||Wrench,p=ao[g]||"#fbbf24";}return s?c=Loader2:!o&&r.type==="status"&&(c=Check,p="#4ade80"),jsxs("div",{style:{display:"flex",gap:"6px",marginBottom:"6px",lineHeight:1.625},children:[jsx(c,{style:{width:"12px",height:"12px",marginTop:"2px",flexShrink:0,color:p,...s?{animation:"__fork-spin 1s linear infinite"}:{}}}),jsx("span",{style:{color:o&&!i?"#d1d5db":"#6b7280",wordBreak:"break-all"},children:Kt(r)})]},n)})]})]})}var Wr=35,ho="Working on Feature",yo="Built Custom Feature",Kr=360,yt=350;function ko(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 bo(e){return e.length<=Wr?e:e.slice(0,Wr-3).trimEnd()+"..."}function wo({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 p of e)if(p.type==="status"&&String(p.data.message||"").includes("Agent started")){s.current=true;break}}let c="Setting up environment...";if(s.current)for(let p=e.length-1;p>=0;p--){let g=e[p];if(g.type==="tool_use"||g.type==="build_start"||g.type==="build_complete"){c=bo(Kt(g));break}}if(c!==i.current){o(false);let p=setTimeout(()=>{r(c),i.current=c,o(true);},200);return ()=>clearTimeout(p)}},[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 vo({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:c="slot",onSubmit:p,onUndo:g,onClose:f,baseUrl:k,apiKey:I,userId:R,userHash:_,appId:h,embedded:b=false}){let[M,C]=useState(""),[N,T]=useState([]),[L,x]=useState(false),[w,d]=useState(false),[S,E]=useState(false),[A,u]=useState(false),[l,y]=useState(false),[j,Y]=useState(false),[D,W]=useState(false),[ee,z]=useState(false),[se,ie]=useState(false),[fe,te]=useState(null),[xt,Xe]=useState(false),[Te,ce]=useState([]),[Z,$]=useState(null),[F,O]=useState(false),[re,ne]=useState(false),[Me,rr]=useState(false),[sn,nr]=useState(null),[V,Ye]=useState(null),[an,or]=useState(false),[Ft,Ze]=useState(false),[he,Le]=useState(""),_t=useRef(null),[sr,ye]=useState(null),[ln,Ne]=useState(false),[_e,ir]=useState(null),[He,Qe]=useState([]),[X$1,Re]=useState(null),[ae,Ce]=useState(false),Ee=useRef(false),Rt=useRef(null),et=useRef(null),{resetAllForks:cn,previewSession:G,currentContainerId:dn}=Q(),ke=G?.container_id??dn,tt=!!(G&&ln),de=_e!==null,ar=useRef(f);useEffect(()=>{ar.current=f;});let Ct=useRef(null),rt=useRef(false),lr=typeof window<"u"&&"documentPictureInPicture"in window,un=async()=>{if(!(!lr||de))try{let a=await window.documentPictureInPicture.requestWindow({width:Kr,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 m=document.adoptedStyleSheets??[];m.length>0&&(a.document.adoptedStyleSheets=[...m]);}catch{}a.addEventListener("pagehide",()=>{Ct.current=null,ir(null),rt.current||ar.current(),rt.current=!1;},{once:!0}),Ct.current=a,ir(a);}catch(a){console.warn("[Fork] PiP open failed:",a);}},fn=()=>{_e&&(rt.current=true,_e.close());};useEffect(()=>()=>{rt.current=true,Ct.current?.close();},[]);let pe=i??o??"",cr=(s||pe).replace(/[-_]+/g," ").replace(/\b\w/g,a=>a.toUpperCase()),nt=useRef(""),dr=()=>{let a={Authorization:`Bearer ${I}`,...K()};return h&&(a["X-Fork-App-Id"]=h),!G&&R&&(a["X-Fork-User-Id"]=R),!G&&_&&(a["X-Fork-User-Hash"]=_),a},ot=b?true:w&&!S,pn=r.find(a=>{let m=a.data;return a.type==="status"&&m.summary})?.data?.summary||t?.summary||ho,be=r.find(a=>{let m=a.data;return (a.type==="status"||a.type==="complete")&&typeof m?.estimateMinutes=="number"})?.data?.estimateMinutes??t?.estimateMinutes;useEffect(()=>{if(c==="none"){x(true);return}if(!k||!I)return;if(!X$1){T([]),x(true);return}let a=new AbortController;return fetch(`${k}/api/v1/forks/${encodeURIComponent(X$1)}/messages`,{headers:dr(),signal:a.signal}).then(m=>m.ok?m.json():[]).then(m=>{if(a.signal.aborted)return;let P=[];for(let J of m){let Ae=J.forkId??X$1;J.role==="user"?P.push({type:"user",text:J.content,forkId:Ae}):P.push({type:"applied",text:J.content,forkId:Ae});}T(P),x(true);}).catch(()=>{a.signal.aborted||x(true);}),()=>{a.abort();}},[I,h,k,c,X$1,G?.fork_id,G?.preview_session_id,_,R,t?.id,t?.completedAt]),useEffect(()=>{if(c==="none"||!k||!I||!F)return;if(!Z){Qe([]);return}let a=new AbortController,m=new URLSearchParams({container_id:Z});return fetch(`${k}/api/v1/forks?${m.toString()}`,{headers:dr(),signal:a.signal}).then(P=>P.ok?P.json():{forks:[]}).then(P=>{a.signal.aborted||Qe(P.forks??[]);}).catch(()=>{}),()=>{a.abort();}},[I,h,k,c,Z,F,t?.id,t?.completedAt,G?.fork_id,G?.preview_session_id,_,R]),useEffect(()=>{e==="complete"&&z(false);},[e]);let ur=He.some(a=>a.status==="pending"||a.status==="running"||a.status==="building");useEffect(()=>{if(!ur||!k||!I||!Z)return;let a=new URLSearchParams({container_id:Z}),m={Authorization:`Bearer ${I}`,...K()};h&&(m["X-Fork-App-Id"]=h);let J=setInterval(async()=>{try{let Ae=await fetch(`${k}/api/v1/forks?${a.toString()}`,{headers:m});if(!Ae.ok)return;let yn=await Ae.json();Qe(yn.forks??[]);}catch{}},3e3);return ()=>clearInterval(J)},[ur,k,I,h,Z]),useEffect(()=>{if(b&&c==="none"){ce([]),$(null),O(true),Ne(false);return}if(G){let a=false;return O(false),Ne(false),ye(null),fetch(`${k}/api/v1/preview/${encodeURIComponent(G.preview_session_id)}/containers`,{headers:{Authorization:`Bearer ${I}`,...K()}}).then(m=>{if(!m.ok)throw new Error(`${m.status}`);return m.json()}).then(m=>{a||(ce(m.containers),$(m.currentContainerId??G.container_id??null),Ne(true));}).catch(m=>{a||(Ne(false),ye(m instanceof Error?m.message:String(m)),ke?(ce([{id:ke,name:G.container_name||"Primary container",createdAt:"",hasAccess:true,isPrimary:true}]),$(ke)):(ce([]),$(null)));}).finally(()=>{a||O(true);}),()=>{a=true;}}ke?(ce([{id:ke,name:"Primary container",createdAt:""}]),$(ke)):(ce([]),$(null)),O(true),Ne(false);},[I,ke,k,b,c,G?.container_id,G?.container_name,G?.preview_session_id]);let st=useRef(void 0);useEffect(()=>{if(F){if(st.current===void 0){st.current=Z;return}st.current!==Z&&(st.current=Z,T([]),x(false));}},[Z,F]);let it=useRef(null);useEffect(()=>{if(!re)return;let a=P=>{if(!it.current)return;let J=typeof P.composedPath=="function"?P.composedPath():[];it.current.contains(P.target)||J.includes(it.current)||ne(false);},m=P=>{P.key==="Escape"&&ne(false);};return document.addEventListener("mousedown",a,true),document.addEventListener("keydown",m,true),()=>{document.removeEventListener("mousedown",a,true),document.removeEventListener("keydown",m,true);}},[re]),useEffect(()=>{re||(Ze(false),Le(""));},[re]),useEffect(()=>{Ft&&(_t.current?.focus(),_t.current?.select());},[Ft]),useEffect(()=>{if(b)return;let a=requestAnimationFrame(()=>d(true));return ()=>cancelAnimationFrame(a)},[b]),useEffect(()=>{let a=b||de;if((a||ot)&&(e==="prompting"||e==="complete")){let m=setTimeout(()=>Rt.current?.focus(),a?100:yt+100);return ()=>clearTimeout(m)}},[ot,b,de,e]),useEffect(()=>{if(e==="complete"&&nt.current){let m=r.find(P=>P.type==="complete")?.data?.summary||t?.summary||yo;T(P=>P[P.length-1]?.type==="applied"?P:[...P,{type:"applied",text:m}]),C(""),setTimeout(()=>Rt.current?.focus(),200);}},[e,cr,r,t?.summary]),useEffect(()=>{et.current&&(et.current.scrollTop=et.current.scrollHeight);},[N,e]);let fr=()=>{if(M.trim()){nt.current=M.trim();let a={};ae?(a.forceNew=true,Ee.current=true):X$1&&(a.forkId=X$1),ae||T(m=>[...m,{type:"user",text:M.trim(),forkId:X$1}]),p(M.trim(),pe,Z,a),C("");}};useEffect(()=>{if(Ee.current){if(e==="error"){Ee.current=false;return}t?.id&&(Re(t.id),Ce(false),Ee.current=false);}},[t?.id,e]);let pr=a=>{ve(a.session.containerId,a.session.containerName),$(a.session.containerId),ce(m=>{let P=m.filter(J=>J.id!==a.container.id);return [{...a.container,isPrimary:true,hasAccess:true},...P.map(J=>({...J,isPrimary:false}))]}),Re(null),Ce(false),Ee.current=false,T([]),x(false),nt.current="";},gn=async a=>{if(!(!G||!tt||V)){Ye(a),ye(null);try{let m=await fetch(`${k}/api/v1/preview/${encodeURIComponent(G.preview_session_id)}/containers/${encodeURIComponent(a)}/primary`,{method:"POST",headers:{Authorization:`Bearer ${I}`,...K()}});if(!m.ok){let P=await m.json().catch(()=>({}));throw new Error(P.error||`API error: ${m.status}`)}pr(await m.json()),ne(!1);}catch(m){ye(m instanceof Error?m.message:String(m));}finally{Ye(null);}}},gr=async a=>{if(!G||!tt||V)return;let m=a.trim();if(m){Ye("__new__"),ye(null);try{let P=await fetch(`${k}/api/v1/preview/${encodeURIComponent(G.preview_session_id)}/containers`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${I}`,...K()},body:JSON.stringify({name:m})});if(!P.ok){let J=await P.json().catch(()=>({}));throw new Error(J.error||`API error: ${P.status}`)}pr(await P.json()),Ze(!1),Le(""),ne(!1);}catch(P){ye(P instanceof Error?P.message:String(P));}finally{Ye(null);}}},mn=async()=>{if(!(!g||se||!pe)){ie(true);try{let a=await g(pe);T(m=>{let P=[...m];return P.length>=2&&P[P.length-1]?.type==="applied"?P.splice(-2,2):P.length>=1&&P[P.length-1]?.type==="applied"&&P.splice(-1,1),P}),a?.removed&&T([]);}catch{}finally{ie(false);}}},mr=()=>{if(b){f();return}if(de){_e?.close();return}E(true),d(false),setTimeout(()=>f(),yt);},hn=b||de?{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:Kr,maxWidth:"100vw",background:"#ffffff",boxShadow:ot?"-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:ot?"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'},hr=Te.find(a=>a.id===Z)?.name??(F?"Fork":"Loading..."),Oe=ae?[]:X$1?N.filter(a=>a.forkId===X$1||a.forkId==null):N,Et=jsxs(Fragment,{children:[jsx("style",{children:`
22
23
  @keyframes __fork-pulse {
23
24
  0%, 100% { opacity: 1; }
24
25
  50% { opacity: 0.5; }
@@ -40,5 +41,5 @@ import*as Bt from'react';import Bt__default,{createContext,useSyncExternalStore,
40
41
  scrollbar-width: thin;
41
42
  scrollbar-color: rgba(0, 0, 0, 0.12) transparent;
42
43
  }
43
- `}),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(),!vt&&confirm("Kill all forks in this container?")){qe(true);try{let m=await sn();`${m?.deleted??0}`,Ze([]),Re(null),_e(!1),C("");}catch(m){console.error("[Fork] Reset failed:",m);}finally{qe(false);}}},style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:4,margin:-4,cursor:"pointer",flexShrink:0},children:jsx(ft,{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:dn}):Me.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:st,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[jsxs("button",{type:"button",onClick:()=>{ne(a=>!a);},onMouseEnter:()=>Qt(true),onMouseLeave:()=>Qt(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:Te||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:pr}),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:[Me.map(a=>{let m=a.id===Z,$=rn===a.id,J=q===a.id;return jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>er(a.id),onMouseLeave:()=>er(null),onClick:()=>{a.id!==Z&&un(a.id);},disabled:!!q,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:$?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:q?"default":"pointer",textAlign:"left",fontWeight:m?600:400,opacity:q&&!J?.55:1},children:[jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:m&&jsx(Check,{style:{width:12,height:12}})}),jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:J?"Switching...":a.name})]},a.id)}),jsx("div",{style:{height:1,background:"#e5e7eb",margin:"4px 0"}}),St?jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"4px 4px"},children:[jsx("input",{ref:xt,type:"text",value:me,placeholder:"Container name",disabled:q==="__new__",onChange:a=>Ie(a.target.value),onKeyDown:a=>{a.key==="Enter"?(a.preventDefault(),ur(me)):a.key==="Escape"&&(a.preventDefault(),a.stopPropagation(),Ye(false),Ie(""));},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:()=>{ur(me);},disabled:!me.trim()||q==="__new__",title:"Create",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:26,height:26,border:"none",borderRadius:4,background:!me.trim()||q==="__new__"?"#e5e7eb":"#1c4587",color:!me.trim()||q==="__new__"?"#9ca3af":"#ffffff",cursor:!me.trim()||q==="__new__"?"default":"pointer",flexShrink:0},children:q==="__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:()=>tr(true),onMouseLeave:()=>tr(false),onClick:()=>{q||(he(null),Ie(""),Ye(true));},disabled:!!q,style:{display:"flex",alignItems:"center",width:"100%",padding:"6px 8px",border:"none",background:nn?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:q?"default":"pointer",textAlign:"left",opacity:q&&q!=="__new__"?.55:1},children:"+ New container"}),rr&&jsx("div",{style:{padding:"6px 8px",fontSize:11,lineHeight:1.35,color:"#b91c1c"},children:rr})]})]}):jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:pr}),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"}),e==="complete"&&jsx("div",{style:{height:6,width:6,backgroundColor:"#1c4587",borderRadius:"50%",flexShrink:0}})]}),!y&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[sr&&jsx("button",{onClick:de?cn:ln,onMouseEnter:()=>b(true),onMouseLeave:()=>b(false),title:de?"Redock to sidebar":"Pop out into window",style:{padding:6,borderRadius:6,color:l?"#4b5563":"#9ca3af",backgroundColor:l?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:de?jsx(PictureInPicture,{style:{width:16,height:16}}):jsx(PictureInPicture2,{style:{width:16,height:16}})}),jsx("button",{onClick:fr,onMouseEnter:()=>u(true),onMouseLeave:()=>u(false),style:{padding:6,borderRadius:6,color:A?"#4b5563":"#9ca3af",backgroundColor:A?"#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:Qe,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[(X$1||ae)&&jsxs("div",{style:{padding:"10px 12px 6px 12px",display:"flex",alignItems:"center",gap:8,borderBottom:"1px solid #f3f4f6"},children:[jsx("button",{onClick:()=>{Re(null),_e(false),Ce.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 m=(X$1?Ne.find($=>$.id===X$1)?.targetId:null)??pe;return m?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 ${m}`,children:["Forking ",jsx("span",{style:{color:"#6b7280"},children:m})]}):null})()]}),!X$1&&!ae&&jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[jsxs("div",{style:{padding:"12px 16px 6px 16px",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[jsx("span",{style:{fontSize:12,fontWeight:600,color:"#111827"},children:"Forks"}),pe&&jsx("button",{onClick:()=>{Re(null),_e(true);},title:`Start a new fork on ${pe}`,style:{padding:"4px 10px",fontSize:11,lineHeight:1.3,borderRadius:999,border:"1px dashed #d1d5db",background:"#ffffff",color:"#374151",cursor:"pointer",whiteSpace:"nowrap"},children:"+ New fork"})]}),Ne.length===0&&jsx("div",{style:{padding:"24px 20px",textAlign:"center",fontSize:13,color:"#6b7280"},children:"No forks yet. Click + New fork to build something."}),Ne.length>0&&jsx("div",{style:{display:"flex",flexDirection:"column"},children:Ne.map(a=>{let m=a.summary||"Untitled fork";return jsxs("button",{onClick:()=>{_e(false),Re(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:$=>$.currentTarget.style.background="#fafafa",onMouseLeave:$=>$.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:m}),jsx("span",{style:{fontSize:11,color:"#9ca3af",flexShrink:0},children:mo(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)})})]}),ae&&jsx("div",{style:{padding:"24px 20px",textAlign:"center"},children:jsx("p",{style:{fontSize:13,color:"#6b7280",marginBottom:14,lineHeight:1.625,margin:"0 0 14px 0"},children:"Describe the feature you want to build."})}),X$1&&Be.length>0&&jsx("div",{style:{padding:"16px 16px 0 16px"},children:Be.map((a,m)=>jsx("div",{style:{marginBottom:m<Be.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})]}):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}),g&&m===Be.length-1&&e!=="running"&&jsxs("button",{onClick:$=>{$.stopPropagation(),fn();},onMouseEnter:()=>te(m),onMouseLeave:()=>te(null),disabled:se,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:fe===m?"rgba(0,0,0,0.06)":"transparent",color:fe===m?"#6b7280":"#d1d5db",cursor:se?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:se?.4:1,flexShrink:0},children:[jsx(Undo2,{style:{width:12,height:12}}),fe===m&&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"})]})]})]})},m))}),e==="running"&&(X$1||ae)&&jsx("div",{style:{padding:16},children:jsxs("div",{onClick:()=>z(!ee),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:ee?"rotate(180deg)":"rotate(0deg)"},children:jsx(ChevronDown,{style:{width:14,height:14}})})]}),jsx("div",{style:{maxHeight:ee?320:0,opacity:ee?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(Or,{events:r})})})]})}),e==="error"&&(X$1||ae)&&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&&p(a,pe);},onMouseEnter:()=>W(true),onMouseLeave:()=>W(false),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,color:"#4f46e5",backgroundColor:D?"#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"&&(X$1||ae)&&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:"flex-end",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:Ft,value:I,onChange:a=>{C(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(),cr()),a.key==="Escape"&&!y&&fr();},placeholder:Be.length>0&&!ae?"Ask for another change...":`Describe your ideal ${ir.toLowerCase()}...`,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:cr,disabled:!I.trim(),onMouseEnter:()=>Y(true),onMouseLeave:()=>Y(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:I.trim()?1:.25,transform:j&&I.trim()?"scale(1.1)":"scale(1)",background:I.trim()?"#1c4587":"rgba(0,0,0,0.12)",border:"none",cursor:I.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:jsx(ArrowUp,{style:{width:13,height:13}})})]})})]})]});return y?_t:de&&Fe?createPortal(_t,Fe.document.body):jsx(ko,{children:_t})}function Kr(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 Wt(e){let{apiKey:t,userId:r,userHash:n,baseUrl:o,appId:i,previewSession:s,refreshModuleManifest:c,queueBoundaryAnimation:p}=Q(),[g,f]=useState("idle"),[S,P]=useState(null),[_,R]=useState([]),[h,y]=useState(null),I=useRef(null),C=useCallback(()=>{f("prompting"),R([]),y(null),P(null);},[]),N=useCallback(()=>{f("idle"),I.current&&(I.current.close(),I.current=null);},[]);useEffect(()=>{s&&s.target.kind==="module"&&s.target.id===e&&f(x=>x==="idle"?"prompting":x);},[s?.preview_session_id,s?.target.id,e]);let M=useCallback(async(x,k,d)=>{try{if(!i)throw new Error("ForkProvider requires appId for module boundary prompts.");f("running"),R([]),y(null);let v;if(s){let u=d?.forkId??s.fork_id??void 0,l=await fetch(`${o}/api/v1/preview/${encodeURIComponent(s.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...K()},body:JSON.stringify({prompt:x,...e?{boundary_id:e}:{},...u&&!d?.forceNew?{fork_id:u}:{},...d?.forceNew?{force_new:!0}:{}})});if(!l.ok){let Y=await l.json().catch(()=>({}));throw new Error(Y.error||`API error: ${l.status}`)}let b=await l.json();b.container_id&&ve(b.container_id,b.container_name),Ue(b.fork_id),v=await(await fetch(`${o}/api/v1/forks/${b.fork_id}`,{headers:{Authorization:`Bearer ${t}`,...K()}})).json();}else if(d?.forkId){let u={prompt:x};r&&(u.userId=r),n&&(u.userHash=n);let l=await fetch(`${o}/api/v1/forks/${encodeURIComponent(d.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(u)});if(!l.ok){let b=await l.json().catch(()=>({}));throw new Error(b.error||`API error: ${l.status}`)}v=await l.json();}else {let u={userId:r,prompt:x,boundaryId:e,appId:i};k&&(u.containerId=k),n&&(u.userHash=n),d?.forceNew&&(u.force_new=!0);let l=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(u)});if(!l.ok){let b=await l.json().catch(()=>({}));throw new Error(b.error||`API error: ${l.status}`)}v=await l.json();}P(v);let E=new URLSearchParams({key:t});s?(E.set("previewSessionId",s.preview_session_id),E.set("previewForkId",v.id)):r&&E.set("userId",r),n&&E.set("userHash",n);let A=new EventSource(`${o}/api/v1/forks/${v.id}/events?${E.toString()}`);I.current=A,A.onmessage=u=>{try{let l=JSON.parse(u.data);if(R(b=>[...b,l]),l.type==="complete"){let b=l.data;p(e,v.id),c().catch(()=>{}).finally(()=>{let j={...v,status:"complete",moduleUrl:b.moduleUrl,cssUrls:b.cssUrls,summary:b.summary,completedAt:new Date().toISOString()};P(j),f("complete"),A.close();});}else if(l.type==="error"){let b=l.data;y(b.error||"Unknown error"),f("error"),A.close();}}catch{}},A.onerror=()=>{let u={Authorization:`Bearer ${t}`,...K()};!s&&r&&(u["X-Fork-User-Id"]=r),!s&&n&&(u["X-Fork-User-Hash"]=n),fetch(`${o}/api/v1/forks/${v.id}`,{headers:u}).then(l=>l.json()).then(l=>{P(l),l.status==="complete"?(p(e,l.id),c().catch(()=>{}),f("complete")):l.status==="error"&&(y(l.error||"Fork generation failed"),f("error"));}).catch(()=>{y("Connection lost"),f("error");}),A.close();};}catch(v){y(v.message),f("error");}},[t,i,o,e,s,p,c,n,r]),L=useCallback(async()=>{try{if(!i)throw new Error("ForkProvider requires appId for boundary undo.");let x={userId:r,boundaryId:e,appId:i};n&&(x.userHash=n);let k=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(x)});if(!k.ok){let v=await k.json().catch(()=>({}));throw new Error(v.error||`API error: ${k.status}`)}let d=await k.json();return await c().catch(()=>{}),d.removed?(P(null),f("prompting")):d.fork&&(P(d.fork),f("complete")),d}catch(x){throw y(x.message),x}},[t,i,o,e,c,n,r]);return {state:g,fork:S,events:_,error:h,open:C,close:N,startFork:M,undoFork:L}}function Gr(e){let{state:t,fork:r,events:n,error:o,open:i,close:s,startFork:c,undoFork:p}=Wt(e);return {state:t,fork:r,events:n,error:o,isOpen:t!=="idle",open:i,close:s,submit:c,undo:p}}function Kt(){let{apiKey:e,userId:t,userHash:r,baseUrl:n,previewSession:o,setSlotFork:i,clearSlotFork:s,skipAnimationForSlot:c}=Q(),[p,g]=useState("idle"),[f,S]=useState(null),[P,_]=useState([]),[R,h]=useState(null),y=useRef(null),I=useCallback(()=>{g("prompting"),_([]),h(null),S(null);},[]),C=useCallback(()=>{g("idle"),y.current&&(y.current.close(),y.current=null);},[]);useEffect(()=>{o&&o.target.kind==="slot"&&g(L=>L==="idle"?"prompting":L);},[o?.preview_session_id,o?.target.kind]);let N=useCallback(async(L,x,k,d)=>{try{g("running"),_([]),h(null);let v;if(o){let u=d?.forkId??o.fork_id??void 0,l=await fetch(`${n}/api/v1/preview/${encodeURIComponent(o.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...K()},body:JSON.stringify({prompt:L,...x?{slot_id:x}:{},...u&&!d?.forceNew?{fork_id:u}:{},...d?.forceNew?{force_new:!0}:{}})});if(!l.ok){let Y=await l.json().catch(()=>({}));throw new Error(Y.error||`API error: ${l.status}`)}let b=await l.json();b.container_id&&ve(b.container_id,b.container_name),Ue(b.fork_id),v=await(await fetch(`${n}/api/v1/forks/${b.fork_id}`,{headers:{Authorization:`Bearer ${e}`,...K()}})).json();}else if(d?.forkId){let u={prompt:L};t&&(u.userId=t),r&&(u.userHash=r);let l=await fetch(`${n}/api/v1/forks/${encodeURIComponent(d.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(u)});if(!l.ok){let b=await l.json().catch(()=>({}));throw new Error(b.error||`API error: ${l.status}`)}v=await l.json();}else {let u={userId:t,prompt:L};x&&(u.slotId=x),k&&(u.containerId=k),r&&(u.userHash=r),d?.forceNew&&(u.force_new=!0);let l=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(u)});if(!l.ok){let b=await l.json().catch(()=>({}));throw new Error(b.error||`API error: ${l.status}`)}v=await l.json();}S(v);let E=new URLSearchParams({key:e});o?(E.set("previewSessionId",o.preview_session_id),E.set("previewForkId",v.id)):t&&E.set("userId",t),r&&E.set("userHash",r);let A=new EventSource(`${n}/api/v1/forks/${v.id}/events?${E.toString()}`);y.current=A,A.onmessage=u=>{try{let l=JSON.parse(u.data);if(_(b=>[...b,l]),l.type==="complete"){let b=l.data,j={...v,status:"complete",bundleUrl:b.bundleUrl,summary:b.summary,completedAt:new Date().toISOString()};S(j),g("complete"),x&&b.bundleUrl&&i(x,j),A.close();}else if(l.type==="error"){let b=l.data;h(b.error||"Unknown error"),g("error"),A.close();}}catch{}},A.onerror=()=>{let u={Authorization:`Bearer ${e}`,...K()};!o&&t&&(u["X-Fork-User-Id"]=t),!o&&r&&(u["X-Fork-User-Hash"]=r),fetch(`${n}/api/v1/forks/${v.id}`,{headers:u}).then(l=>l.json()).then(l=>{S(l),l.status==="complete"?(g("complete"),x&&l.bundleUrl&&i(x,l)):l.status==="error"&&(h(l.error||"Fork generation failed"),g("error"));}).catch(()=>{h("Connection lost"),g("error");}),A.close();};}catch(v){h(v.message),g("error");}},[e,t,r,n,o,i]),M=useCallback(async L=>{try{let x={userId:t,slotId:L};r&&(x.userHash=r);let k=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(x)});if(!k.ok){let v=await k.json().catch(()=>({}));throw new Error(v.error||`API error: ${k.status}`)}let d=await k.json();return c(L),d.removed?(s(L),S(null),g("prompting")):d.fork&&(i(L,d.fork),S(d.fork)),d}catch(x){throw h(x.message),x}},[e,t,r,n,s,i]);return {state:p,fork:f,events:P,error:R,open:I,close:C,startFork:N,undoFork:M}}function Jr(){let{state:e,fork:t,events:r,error:n,open:o,close:i,startFork:s,undoFork:c}=Kt();return {state:e,fork:t,events:r,error:n,isOpen:e!=="idle",open:o,close:i,submit:s,undo:c}}function Gt(e){let t=Kr(e),r=Jr(),n=Gr(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:i,userId:s,userHash:c,appId:p}=Q(),g=t.type==="slot"?r:n,f=t.type==="slot"?"slot":"boundary",S=t.id,P=t.title,_=useCallback((h,y,I,C)=>t.type==="slot"?r.submit(h,y??t.id,I,C):n.submit(h,I,C),[n,r,t]),R=useCallback(h=>t.type==="slot"?r.undo(h??t.id):n.undo(),[n,r,t]);return {...g,target:t,targetId:S,targetLabel:P,historyMode:f,submit:_,undo:R,buttonProps:{onClick:g.open},panelProps:{state:g.state,fork:g.fork,events:g.events,error:g.error,...t.type==="slot"?{slotId:S,targetLabel:P,historyMode:f}:{targetId:S,targetLabel:P,historyMode:f},onSubmit:_,onUndo:R,onClose:g.close,baseUrl:o,apiKey:i,userId:s,userHash:c,appId:p}}}function Ke(e){let{embedded:t}=e,r=Gt(e);return t?jsx(ht,{...r.panelProps,embedded:true}):r.isOpen?jsx(ht,{...r.panelProps}):jsx(Ht,{...r.buttonProps})}function xo({boundaryId:e,title:t}){return jsx(Ke,{boundaryId:e,title:t})}function Vt(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 qr(e){let t=e.getBoundingClientRect(),r=e.cloneNode(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 qt(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 Xr(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 c=r[s];c.rect.top>=n.rect.top&&c.rect.left>=n.rect.left&&c.rect.right<=n.rect.right&&c.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Yr(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 c=r[s];c.rect.top>=n.rect.top&&c.rect.left>=n.rect.left&&c.rect.right<=n.rect.right&&c.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){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 Xt(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 f=0;f<e.length;f+=1){let{rect:S,borderRadius:P}=e[f],_=S.left-.5,R=S.top-.5,h=S.width+1,y=S.height+1,I=Math.min(P+.5,h/2,y/2),C=Zr(_,R,h,y,I),N=`__fork-glow-${f}`,M=document.createElementNS(t,"filter");M.setAttribute("id",N),M.setAttribute("x","-100%"),M.setAttribute("y","-100%"),M.setAttribute("width","300%"),M.setAttribute("height","300%");let L=document.createElementNS(t,"feGaussianBlur");L.setAttribute("in","SourceGraphic"),L.setAttribute("stdDeviation","8"),M.appendChild(L),o.appendChild(M);let x=`__fork-mask-${f}`,k=document.createElementNS(t,"mask");k.setAttribute("id",x),k.setAttribute("maskUnits","userSpaceOnUse"),k.setAttribute("x",String(_-200)),k.setAttribute("y",String(R-200)),k.setAttribute("width",String(h+400)),k.setAttribute("height",String(y+400));let d=document.createElementNS(t,"rect");d.setAttribute("x",String(_-200)),d.setAttribute("y",String(R-200)),d.setAttribute("width",String(h+400)),d.setAttribute("height",String(y+400)),d.setAttribute("fill","white"),k.appendChild(d);let v=document.createElementNS(t,"path");v.setAttribute("d",C),v.setAttribute("fill","black"),k.appendChild(v),o.appendChild(k);let E=document.createElementNS(t,"g");E.setAttribute("mask",`url(#${x})`),E.setAttribute("opacity","0");let A=document.createElementNS(t,"g");A.setAttribute("filter",`url(#${N})`);let u=document.createElementNS(t,"path");u.setAttribute("d",C),u.setAttribute("fill","none"),u.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),u.setAttribute("stroke-width","6"),u.setAttribute("stroke-linecap","round"),A.appendChild(u),E.appendChild(A),n.appendChild(E);let l=document.createElementNS(t,"path");l.setAttribute("d",C),l.setAttribute("fill","none"),l.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),l.setAttribute("stroke-width","2"),l.setAttribute("stroke-linecap","round"),l.setAttribute("opacity","0"),n.appendChild(l),i.push(u,l),u.__group=E;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let f=0;f<i.length;f+=2){let S=i[f],P=i[f+1],_=S.__group;if(!_)continue;let R=P.getTotalLength(),h=S.getTotalLength();if(R<=0)continue;let y=R*.35;P.setAttribute("stroke-dasharray",`${y} ${R-y}`),P.setAttribute("stroke-dashoffset","0"),s.push(P.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*R,opacity:.92,offset:.06},{strokeDashoffset:-2*R,opacity:.92,offset:.92},{strokeDashoffset:-2.25*R,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let I=h*.35;S.setAttribute("stroke-dasharray",`${I} ${h-I}`),S.setAttribute("stroke-dashoffset","0"),s.push(S.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*h,offset:.06},{strokeDashoffset:-2*h,offset:.92},{strokeDashoffset:-2.25*h,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 c=false,p=()=>{if(c)return;c=true,clearTimeout(g);for(let S of s)try{S.cancel();}catch{}let f=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});f.onfinish=()=>r.remove(),window.removeEventListener("click",p);},g=setTimeout(p,14500);return setTimeout(()=>{c||window.addEventListener("click",p);},500),p}function Qr(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:c,borderRadius:p}of e){let g=document.createElementNS(t,"path");g.setAttribute("d",Zr(c.left,c.top,c.width,c.height,p)),g.setAttribute("fill","none"),g.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),g.setAttribute("stroke-width","1.5"),g.setAttribute("stroke-dasharray","8 4"),g.setAttribute("stroke-linecap","round"),g.setAttribute("filter","url(#__fork-removed-shadow)"),g.setAttribute("opacity","0"),n.appendChild(g),g.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 Je=new Map,Ve=new Map,Yt=new Map;function _o(e){for(let t of e)Ve.set(t,(Ve.get(t)??0)+1);}function Co(e){if(!(typeof document>"u"))for(let t of e){let r=(Ve.get(t)??0)-1;if(r>0){Ve.set(t,r);continue}Ve.delete(t),Je.delete(t);let n=document.querySelector(`link[data-fork-override-href="${CSS.escape(t)}"]`);n&&n.remove();}}function Eo(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function tn(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 Ao(e){if(!e||typeof document>"u")return Promise.resolve();let t=Je.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 c=()=>{r.removeEventListener("load",c),r.removeEventListener("error",p),i();},p=()=>{r.removeEventListener("load",c),r.removeEventListener("error",p),s(new Error(`Failed to load boundary stylesheet: ${e}`));};r.addEventListener("load",c,{once:true}),r.addEventListener("error",p,{once:true});});return Je.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 Je.delete(e),o});return Je.set(e,n),n}function $o(e){let t=Yt.get(e);if(t)return t;let r=import(e).catch(n=>{throw Yt.delete(e),n});return Yt.set(e,r),r}async function Po(e,t,r){if(e)try{await Promise.all(e.cssUrls.map(i=>Ao(i)));let o=await $o(e.moduleUrl);return tn(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 tn(n,r)}function Mo(e){function t(r){let{appId:n,moduleOverridesEnabled:o,moduleManifestReady:i,moduleManifestVersion:s,registerBoundary:c,getBoundaryOverride:p,consumeBoundaryAnimation:g}=Q(),[f,S]=useState(null),[P,_]=useState(null),R=useRef(null),h=useRef(null),y=useRef(null),I=useRef(false),C=useRef(null),N=useRef(null),M=p(e.id),L=M?`override:${M.id}`:"original",x=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if(useEffect(()=>()=>{N.current&&(clearTimeout(N.current),N.current=null),C.current&&(C.current.remove(),C.current=null);},[]),useEffect(()=>{c({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[n,c,e.id,e.exportName,x]),useEffect(()=>{let k=M?.cssUrls??[];if(k.length!==0)return _o(k),()=>Co(k)},[M?.cssUrls.join("|")]),useEffect(()=>{if(o&&!i&&!f||h.current===L&&f)return;let k=false;return _(null),Po(M,e.original,e.exportName).then(d=>{if(!k){if(M?.id&&g(e.id,M.id)&&R.current){let v=Vt(R.current);if(v){let E=qt(v);E.length>0&&(y.current=E,I.current=true,N.current&&(clearTimeout(N.current),N.current=null),C.current&&C.current.remove(),C.current=qr(v));}}h.current=L,startTransition(()=>{S(()=>d);});}}).catch(d=>{k||_(Eo(d));}),()=>{k=true;}},[g,L,o,i,s,M?.id,M?.moduleUrl,M?.integrity,M?.cssUrls.join("|"),e.exportName,e.original,f]),useEffect(()=>{if(!I.current||!f||!R.current)return;let k=false;return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(k||!R.current)return;let d=y.current,v=Vt(R.current);if(y.current=null,I.current=false,!d||!v){C.current&&(C.current.remove(),C.current=null);return}let E=qt(v),A=Xr(d,E),u=Yr(d,E),l=C.current;if(u.length>0&&l){let b=Qr(u);N.current=setTimeout(()=>{N.current=null;let j=400;l.animate([{opacity:1},{opacity:0}],{duration:j,fill:"forwards"}),b.animate([{opacity:1},{opacity:0}],{duration:j,fill:"forwards"}),setTimeout(()=>{l.remove(),b.remove(),C.current===l&&(C.current=null),A.length>0&&Xt(A);},j);},3500);}else l&&(l.remove(),C.current===l&&(C.current=null)),A.length>0&&Xt(A);});}),()=>{k=true;}},[f]),P)throw P;return f?jsx("div",{ref:R,style:{display:"contents"},children:jsx(f,{...r})}):jsx(Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function Io({slotId:e,title:t,slotLabel:r}){return jsx(Ke,{slotId:e,title:t,slotLabel:r})}
44
- export{xo as ForkBoundaryUI,Ht as ForkButton,Ke as ForkChatInterface,ht as ForkPanel,Mn as ForkProvider,Kn as ForkSlot,Io as ForkUI,Cn as clearCachedManifest,Mo as forkable,ct as loadManifest,En as manifestDiffers,Rn as readCachedManifest,Et as registerForkShared,Wt as useBoundaryFork,Kt as useFork,Gt as useForkChatPanel,lt as usePreviewSession,_n as writeCachedManifest};
44
+ `}),jsxs("div",{className:"__fork-panel",style:hn,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(),!xt&&confirm("Kill all forks in this container?")){Xe(true);try{let m=await cn();`${m?.deleted??0}`,Qe([]),Re(null),Ce(!1),C("");}catch(m){console.error("[Fork] Reset failed:",m);}finally{Xe(false);}}},style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:4,margin:-4,cursor:"pointer",flexShrink:0},children:jsx(gt,{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:pn}):Te.length===0&&!tt?jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:"Fork"}):tt?jsxs("div",{ref:it,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[jsxs("button",{type:"button",onClick:()=>{ne(a=>!a);},onMouseEnter:()=>rr(true),onMouseLeave:()=>rr(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:Me||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:hr}),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:[Te.map(a=>{let m=a.id===Z,P=sn===a.id,J=V===a.id;return jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>nr(a.id),onMouseLeave:()=>nr(null),onClick:()=>{a.id!==Z&&gn(a.id);},disabled:!!V,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:P?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:V?"default":"pointer",textAlign:"left",fontWeight:m?600:400,opacity:V&&!J?.55:1},children:[jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:m&&jsx(Check,{style:{width:12,height:12}})}),jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:J?"Switching...":a.name})]},a.id)}),jsx("div",{style:{height:1,background:"#e5e7eb",margin:"4px 0"}}),Ft?jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"4px 4px"},children:[jsx("input",{ref:_t,type:"text",value:he,placeholder:"Container name",disabled:V==="__new__",onChange:a=>Le(a.target.value),onKeyDown:a=>{a.key==="Enter"?(a.preventDefault(),gr(he)):a.key==="Escape"&&(a.preventDefault(),a.stopPropagation(),Ze(false),Le(""));},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:()=>{gr(he);},disabled:!he.trim()||V==="__new__",title:"Create",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:26,height:26,border:"none",borderRadius:4,background:!he.trim()||V==="__new__"?"#e5e7eb":"#1c4587",color:!he.trim()||V==="__new__"?"#9ca3af":"#ffffff",cursor:!he.trim()||V==="__new__"?"default":"pointer",flexShrink:0},children:V==="__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:()=>or(true),onMouseLeave:()=>or(false),onClick:()=>{V||(ye(null),Le(""),Ze(true));},disabled:!!V,style:{display:"flex",alignItems:"center",width:"100%",padding:"6px 8px",border:"none",background:an?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:V?"default":"pointer",textAlign:"left",opacity:V&&V!=="__new__"?.55:1},children:"+ New container"}),sr&&jsx("div",{style:{padding:"6px 8px",fontSize:11,lineHeight:1.35,color:"#b91c1c"},children:sr})]})]}):jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:hr}),e==="running"&&jsx("span",{title:be?`Estimated ~${be} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:be?"#1c4587":"#9ca3af",backgroundColor:be?"rgba(28, 69, 135, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:be?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:be?`~${be}m`:"~ m"}),e==="complete"&&jsx("div",{style:{height:6,width:6,backgroundColor:"#1c4587",borderRadius:"50%",flexShrink:0}})]}),!b&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[lr&&jsx("button",{onClick:de?fn:un,onMouseEnter:()=>y(true),onMouseLeave:()=>y(false),title:de?"Redock to sidebar":"Pop out into window",style:{padding:6,borderRadius:6,color:l?"#4b5563":"#9ca3af",backgroundColor:l?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:de?jsx(PictureInPicture,{style:{width:16,height:16}}):jsx(PictureInPicture2,{style:{width:16,height:16}})}),jsx("button",{onClick:mr,onMouseEnter:()=>u(true),onMouseLeave:()=>u(false),style:{padding:6,borderRadius:6,color:A?"#4b5563":"#9ca3af",backgroundColor:A?"#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:et,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[(X$1||ae)&&jsxs("div",{style:{padding:"10px 12px 6px 12px",display:"flex",alignItems:"center",gap:8,borderBottom:"1px solid #f3f4f6"},children:[jsx("button",{onClick:()=>{Re(null),Ce(false),Ee.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 m=(X$1?He.find(P=>P.id===X$1)?.targetId:null)??pe;return m?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 ${m}`,children:["Forking ",jsx("span",{style:{color:"#6b7280"},children:m})]}):null})()]}),!X$1&&!ae&&jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[jsxs("div",{style:{padding:"12px 16px 6px 16px",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[jsx("span",{style:{fontSize:12,fontWeight:600,color:"#111827"},children:"Forks"}),pe&&jsx("button",{onClick:()=>{Re(null),Ce(true);},title:`Start a new fork on ${pe}`,style:{padding:"4px 10px",fontSize:11,lineHeight:1.3,borderRadius:999,border:"1px dashed #d1d5db",background:"#ffffff",color:"#374151",cursor:"pointer",whiteSpace:"nowrap"},children:"+ New fork"})]}),He.length===0&&jsx("div",{style:{padding:"24px 20px",textAlign:"center",fontSize:13,color:"#6b7280"},children:"No forks yet. Click + New fork to build something."}),He.length>0&&jsx("div",{style:{display:"flex",flexDirection:"column"},children:He.map(a=>{let m=a.summary||"Untitled fork";return jsxs("button",{onClick:()=>{Ce(false),Re(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:P=>P.currentTarget.style.background="#fafafa",onMouseLeave:P=>P.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:m}),jsx("span",{style:{fontSize:11,color:"#9ca3af",flexShrink:0},children:ko(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)})})]}),ae&&jsx("div",{style:{padding:"24px 20px",textAlign:"center"},children:jsx("p",{style:{fontSize:13,color:"#6b7280",marginBottom:14,lineHeight:1.625,margin:"0 0 14px 0"},children:"Describe the feature you want to build."})}),X$1&&Oe.length>0&&jsx("div",{style:{padding:"16px 16px 0 16px"},children:Oe.map((a,m)=>jsx("div",{style:{marginBottom:m<Oe.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})]}):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}),g&&m===Oe.length-1&&e!=="running"&&jsxs("button",{onClick:P=>{P.stopPropagation(),mn();},onMouseEnter:()=>te(m),onMouseLeave:()=>te(null),disabled:se,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:fe===m?"rgba(0,0,0,0.06)":"transparent",color:fe===m?"#6b7280":"#d1d5db",cursor:se?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:se?.4:1,flexShrink:0},children:[jsx(Undo2,{style:{width:12,height:12}}),fe===m&&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"})]})]})]})},m))}),e==="running"&&(X$1||ae)&&jsx("div",{style:{padding:16},children:jsxs("div",{onClick:()=>z(!ee),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(wo,{events:r})]}),jsx("div",{style:{color:"#6b7280",flexShrink:0,marginLeft:8,transition:"transform 0.2s ease",transform:ee?"rotate(180deg)":"rotate(0deg)"},children:jsx(ChevronDown,{style:{width:14,height:14}})})]}),jsx("div",{style:{maxHeight:ee?320:0,opacity:ee?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(jr,{events:r})})})]})}),e==="error"&&(X$1||ae)&&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||nt.current;a&&p(a,pe);},onMouseEnter:()=>W(true),onMouseLeave:()=>W(false),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,color:"#4f46e5",backgroundColor:D?"#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"&&(X$1||ae)&&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:"flex-end",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:Rt,value:M,onChange:a=>{C(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(),fr()),a.key==="Escape"&&!b&&mr();},placeholder:Oe.length>0&&!ae?"Ask for another change...":`Describe your ideal ${cr.toLowerCase()}...`,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:fr,disabled:!M.trim(),onMouseEnter:()=>Y(true),onMouseLeave:()=>Y(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:M.trim()?1:.25,transform:j&&M.trim()?"scale(1.1)":"scale(1)",background:M.trim()?"#1c4587":"rgba(0,0,0,0.12)",border:"none",cursor:M.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:jsx(ArrowUp,{style:{width:13,height:13}})})]})})]})]});return b?Et:de&&_e?createPortal(Et,_e.document.body):jsx(vo,{children:Et})}function qr(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 Jt(e){let{apiKey:t,userId:r,userHash:n,baseUrl:o,appId:i,previewSession:s,refreshModuleManifest:c,queueBoundaryAnimation:p}=Q(),[g,f]=useState("idle"),[k,I]=useState(null),[R,_]=useState([]),[h,b]=useState(null),M=useRef(null),C=useCallback(()=>{f("prompting"),_([]),b(null),I(null);},[]),N=useCallback(()=>{f("idle"),M.current&&(M.current.close(),M.current=null);},[]);useEffect(()=>{s&&s.target.kind==="module"&&s.target.id===e&&f(x=>x==="idle"?"prompting":x);},[s?.preview_session_id,s?.target.id,e]);let T=useCallback(async(x,w,d)=>{try{if(!i)throw new Error("ForkProvider requires appId for module boundary prompts.");f("running"),_([]),b(null);let S;if(s){let u=d?.forkId??s.fork_id??void 0,l=await fetch(`${o}/api/v1/preview/${encodeURIComponent(s.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...K()},body:JSON.stringify({prompt:x,...e?{boundary_id:e}:{},...u&&!d?.forceNew?{fork_id:u}:{},...d?.forceNew?{force_new:!0}:{}})});if(!l.ok){let Y=await l.json().catch(()=>({}));throw new Error(Y.error||`API error: ${l.status}`)}let y=await l.json();y.container_id&&ve(y.container_id,y.container_name),Be(y.fork_id),S=await(await fetch(`${o}/api/v1/forks/${y.fork_id}`,{headers:{Authorization:`Bearer ${t}`,...K()}})).json();}else if(d?.forkId){let u={prompt:x};r&&(u.userId=r),n&&(u.userHash=n);let l=await fetch(`${o}/api/v1/forks/${encodeURIComponent(d.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(u)});if(!l.ok){let y=await l.json().catch(()=>({}));throw new Error(y.error||`API error: ${l.status}`)}S=await l.json();}else {let u={userId:r,prompt:x,boundaryId:e,appId:i};w&&(u.containerId=w),n&&(u.userHash=n),d?.forceNew&&(u.force_new=!0);let l=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(u)});if(!l.ok){let y=await l.json().catch(()=>({}));throw new Error(y.error||`API error: ${l.status}`)}S=await l.json();}I(S);let E=new URLSearchParams({key:t});s?(E.set("previewSessionId",s.preview_session_id),E.set("previewForkId",S.id)):r&&E.set("userId",r),n&&E.set("userHash",n);let A=new EventSource(`${o}/api/v1/forks/${S.id}/events?${E.toString()}`);M.current=A,A.onmessage=u=>{try{let l=JSON.parse(u.data);if(_(y=>[...y,l]),l.type==="complete"){let y=l.data;p(e,S.id),c().catch(()=>{}).finally(()=>{let j={...S,status:"complete",moduleUrl:y.moduleUrl,cssUrls:y.cssUrls,summary:y.summary,completedAt:new Date().toISOString()};I(j),f("complete"),A.close();});}else if(l.type==="error"){let y=l.data;b(y.error||"Unknown error"),f("error"),A.close();}}catch{}},A.onerror=()=>{let u={Authorization:`Bearer ${t}`,...K()};!s&&r&&(u["X-Fork-User-Id"]=r),!s&&n&&(u["X-Fork-User-Hash"]=n),fetch(`${o}/api/v1/forks/${S.id}`,{headers:u}).then(l=>l.json()).then(l=>{I(l),l.status==="complete"?(p(e,l.id),c().catch(()=>{}),f("complete")):l.status==="error"&&(b(l.error||"Fork generation failed"),f("error"));}).catch(()=>{b("Connection lost"),f("error");}),A.close();};}catch(S){b(S.message),f("error");}},[t,i,o,e,s,p,c,n,r]),L=useCallback(async()=>{try{if(!i)throw new Error("ForkProvider requires appId for boundary undo.");let x={userId:r,boundaryId:e,appId:i};n&&(x.userHash=n);let w=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(x)});if(!w.ok){let S=await w.json().catch(()=>({}));throw new Error(S.error||`API error: ${w.status}`)}let d=await w.json();return await c().catch(()=>{}),d.removed?(I(null),f("prompting")):d.fork&&(I(d.fork),f("complete")),d}catch(x){throw b(x.message),x}},[t,i,o,e,c,n,r]);return {state:g,fork:k,events:R,error:h,open:C,close:N,startFork:T,undoFork:L}}function Vr(e){let{state:t,fork:r,events:n,error:o,open:i,close:s,startFork:c,undoFork:p}=Jt(e);return {state:t,fork:r,events:n,error:o,isOpen:t!=="idle",open:i,close:s,submit:c,undo:p}}function qt(){let{apiKey:e,userId:t,userHash:r,baseUrl:n,previewSession:o,setSlotFork:i,clearSlotFork:s,skipAnimationForSlot:c}=Q(),[p,g]=useState("idle"),[f,k]=useState(null),[I,R]=useState([]),[_,h]=useState(null),b=useRef(null),M=useCallback(()=>{g("prompting"),R([]),h(null),k(null);},[]),C=useCallback(()=>{g("idle"),b.current&&(b.current.close(),b.current=null);},[]);useEffect(()=>{o&&o.target.kind==="slot"&&g(L=>L==="idle"?"prompting":L);},[o?.preview_session_id,o?.target.kind]);let N=useCallback(async(L,x,w,d)=>{try{g("running"),R([]),h(null);let S;if(o){let u=d?.forkId??o.fork_id??void 0,l=await fetch(`${n}/api/v1/preview/${encodeURIComponent(o.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...K()},body:JSON.stringify({prompt:L,...x?{slot_id:x}:{},...u&&!d?.forceNew?{fork_id:u}:{},...d?.forceNew?{force_new:!0}:{}})});if(!l.ok){let Y=await l.json().catch(()=>({}));throw new Error(Y.error||`API error: ${l.status}`)}let y=await l.json();y.container_id&&ve(y.container_id,y.container_name),Be(y.fork_id),S=await(await fetch(`${n}/api/v1/forks/${y.fork_id}`,{headers:{Authorization:`Bearer ${e}`,...K()}})).json();}else if(d?.forkId){let u={prompt:L};t&&(u.userId=t),r&&(u.userHash=r);let l=await fetch(`${n}/api/v1/forks/${encodeURIComponent(d.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(u)});if(!l.ok){let y=await l.json().catch(()=>({}));throw new Error(y.error||`API error: ${l.status}`)}S=await l.json();}else {let u={userId:t,prompt:L};x&&(u.slotId=x),w&&(u.containerId=w),r&&(u.userHash=r),d?.forceNew&&(u.force_new=!0);let l=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(u)});if(!l.ok){let y=await l.json().catch(()=>({}));throw new Error(y.error||`API error: ${l.status}`)}S=await l.json();}k(S);let E=new URLSearchParams({key:e});o?(E.set("previewSessionId",o.preview_session_id),E.set("previewForkId",S.id)):t&&E.set("userId",t),r&&E.set("userHash",r);let A=new EventSource(`${n}/api/v1/forks/${S.id}/events?${E.toString()}`);b.current=A,A.onmessage=u=>{try{let l=JSON.parse(u.data);if(R(y=>[...y,l]),l.type==="complete"){let y=l.data,j={...S,status:"complete",bundleUrl:y.bundleUrl,summary:y.summary,completedAt:new Date().toISOString()};k(j),g("complete"),x&&y.bundleUrl&&i(x,j),A.close();}else if(l.type==="error"){let y=l.data;h(y.error||"Unknown error"),g("error"),A.close();}}catch{}},A.onerror=()=>{let u={Authorization:`Bearer ${e}`,...K()};!o&&t&&(u["X-Fork-User-Id"]=t),!o&&r&&(u["X-Fork-User-Hash"]=r),fetch(`${n}/api/v1/forks/${S.id}`,{headers:u}).then(l=>l.json()).then(l=>{k(l),l.status==="complete"?(g("complete"),x&&l.bundleUrl&&i(x,l)):l.status==="error"&&(h(l.error||"Fork generation failed"),g("error"));}).catch(()=>{h("Connection lost"),g("error");}),A.close();};}catch(S){h(S.message),g("error");}},[e,t,r,n,o,i]),T=useCallback(async L=>{try{let x={userId:t,slotId:L};r&&(x.userHash=r);let w=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(x)});if(!w.ok){let S=await w.json().catch(()=>({}));throw new Error(S.error||`API error: ${w.status}`)}let d=await w.json();return c(L),d.removed?(s(L),k(null),g("prompting")):d.fork&&(i(L,d.fork),k(d.fork)),d}catch(x){throw h(x.message),x}},[e,t,r,n,s,i]);return {state:p,fork:f,events:I,error:_,open:M,close:C,startFork:N,undoFork:T}}function Xr(){let{state:e,fork:t,events:r,error:n,open:o,close:i,startFork:s,undoFork:c}=qt();return {state:e,fork:t,events:r,error:n,isOpen:e!=="idle",open:o,close:i,submit:s,undo:c}}function Vt(e){let t=qr(e),r=Xr(),n=Vr(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:i,userId:s,userHash:c,appId:p}=Q(),g=t.type==="slot"?r:n,f=t.type==="slot"?"slot":"boundary",k=t.id,I=t.title,R=useCallback((h,b,M,C)=>t.type==="slot"?r.submit(h,b??t.id,M,C):n.submit(h,M,C),[n,r,t]),_=useCallback(h=>t.type==="slot"?r.undo(h??t.id):n.undo(),[n,r,t]);return {...g,target:t,targetId:k,targetLabel:I,historyMode:f,submit:R,undo:_,buttonProps:{onClick:g.open},panelProps:{state:g.state,fork:g.fork,events:g.events,error:g.error,...t.type==="slot"?{slotId:k,targetLabel:I,historyMode:f}:{targetId:k,targetLabel:I,historyMode:f},onSubmit:R,onUndo:_,onClose:g.close,baseUrl:o,apiKey:i,userId:s,userHash:c,appId:p}}}function Ge(e){let{embedded:t}=e,r=Vt(e);return t?jsx(kt,{...r.panelProps,embedded:true}):r.isOpen?jsx(kt,{...r.panelProps}):jsx(zt,{...r.buttonProps})}function Ro({boundaryId:e,title:t}){return jsx(Ge,{boundaryId:e,title:t})}function Yt(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 Zr(e){let t=e.getBoundingClientRect(),r=e.cloneNode(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 Zt(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 Qr(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 c=r[s];c.rect.top>=n.rect.top&&c.rect.left>=n.rect.left&&c.rect.right<=n.rect.right&&c.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function en(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 c=r[s];c.rect.top>=n.rect.top&&c.rect.left>=n.rect.left&&c.rect.right<=n.rect.right&&c.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function tn(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 Qt(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 f=0;f<e.length;f+=1){let{rect:k,borderRadius:I}=e[f],R=k.left-.5,_=k.top-.5,h=k.width+1,b=k.height+1,M=Math.min(I+.5,h/2,b/2),C=tn(R,_,h,b,M),N=`__fork-glow-${f}`,T=document.createElementNS(t,"filter");T.setAttribute("id",N),T.setAttribute("x","-100%"),T.setAttribute("y","-100%"),T.setAttribute("width","300%"),T.setAttribute("height","300%");let L=document.createElementNS(t,"feGaussianBlur");L.setAttribute("in","SourceGraphic"),L.setAttribute("stdDeviation","8"),T.appendChild(L),o.appendChild(T);let x=`__fork-mask-${f}`,w=document.createElementNS(t,"mask");w.setAttribute("id",x),w.setAttribute("maskUnits","userSpaceOnUse"),w.setAttribute("x",String(R-200)),w.setAttribute("y",String(_-200)),w.setAttribute("width",String(h+400)),w.setAttribute("height",String(b+400));let d=document.createElementNS(t,"rect");d.setAttribute("x",String(R-200)),d.setAttribute("y",String(_-200)),d.setAttribute("width",String(h+400)),d.setAttribute("height",String(b+400)),d.setAttribute("fill","white"),w.appendChild(d);let S=document.createElementNS(t,"path");S.setAttribute("d",C),S.setAttribute("fill","black"),w.appendChild(S),o.appendChild(w);let E=document.createElementNS(t,"g");E.setAttribute("mask",`url(#${x})`),E.setAttribute("opacity","0");let A=document.createElementNS(t,"g");A.setAttribute("filter",`url(#${N})`);let u=document.createElementNS(t,"path");u.setAttribute("d",C),u.setAttribute("fill","none"),u.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),u.setAttribute("stroke-width","6"),u.setAttribute("stroke-linecap","round"),A.appendChild(u),E.appendChild(A),n.appendChild(E);let l=document.createElementNS(t,"path");l.setAttribute("d",C),l.setAttribute("fill","none"),l.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),l.setAttribute("stroke-width","2"),l.setAttribute("stroke-linecap","round"),l.setAttribute("opacity","0"),n.appendChild(l),i.push(u,l),u.__group=E;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let f=0;f<i.length;f+=2){let k=i[f],I=i[f+1],R=k.__group;if(!R)continue;let _=I.getTotalLength(),h=k.getTotalLength();if(_<=0)continue;let b=_*.35;I.setAttribute("stroke-dasharray",`${b} ${_-b}`),I.setAttribute("stroke-dashoffset","0"),s.push(I.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*_,opacity:.92,offset:.06},{strokeDashoffset:-2*_,opacity:.92,offset:.92},{strokeDashoffset:-2.25*_,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let M=h*.35;k.setAttribute("stroke-dasharray",`${M} ${h-M}`),k.setAttribute("stroke-dashoffset","0"),s.push(k.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*h,offset:.06},{strokeDashoffset:-2*h,offset:.92},{strokeDashoffset:-2.25*h,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(R.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 c=false,p=()=>{if(c)return;c=true,clearTimeout(g);for(let k of s)try{k.cancel();}catch{}let f=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});f.onfinish=()=>r.remove(),window.removeEventListener("click",p);},g=setTimeout(p,14500);return setTimeout(()=>{c||window.addEventListener("click",p);},500),p}function rn(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:c,borderRadius:p}of e){let g=document.createElementNS(t,"path");g.setAttribute("d",tn(c.left,c.top,c.width,c.height,p)),g.setAttribute("fill","none"),g.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),g.setAttribute("stroke-width","1.5"),g.setAttribute("stroke-dasharray","8 4"),g.setAttribute("stroke-linecap","round"),g.setAttribute("filter","url(#__fork-removed-shadow)"),g.setAttribute("opacity","0"),n.appendChild(g),g.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 qe=new Map,Ve=new Map,er=new Map;function Ao(e){for(let t of e)Ve.set(t,(Ve.get(t)??0)+1);}function $o(e){if(!(typeof document>"u"))for(let t of e){let r=(Ve.get(t)??0)-1;if(r>0){Ve.set(t,r);continue}Ve.delete(t),qe.delete(t);let n=document.querySelector(`link[data-fork-override-href="${CSS.escape(t)}"]`);n&&n.remove();}}function Po(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function on(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 Io(e){if(!e||typeof document>"u")return Promise.resolve();let t=qe.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 c=()=>{r.removeEventListener("load",c),r.removeEventListener("error",p),i();},p=()=>{r.removeEventListener("load",c),r.removeEventListener("error",p),s(new Error(`Failed to load boundary stylesheet: ${e}`));};r.addEventListener("load",c,{once:true}),r.addEventListener("error",p,{once:true});});return qe.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 qe.delete(e),o});return qe.set(e,n),n}function To(e){let t=er.get(e);if(t)return t;let r=import(e).catch(n=>{throw er.delete(e),n});return er.set(e,r),r}async function Mo(e,t,r){if(e)try{await Promise.all(e.cssUrls.map(i=>Io(i)));let o=await To(e.moduleUrl);return on(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 on(n,r)}function Lo(e){function t(r){let{appId:n,moduleOverridesEnabled:o,moduleManifestReady:i,moduleManifestVersion:s,registerBoundary:c,getBoundaryOverride:p,consumeBoundaryAnimation:g}=Q(),[f,k]=useState(null),[I,R]=useState(null),_=useRef(null),h=useRef(null),b=useRef(null),M=useRef(false),C=useRef(null),N=useRef(null),T=p(e.id),L=T?`override:${T.id}`:"original",x=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if(useEffect(()=>()=>{N.current&&(clearTimeout(N.current),N.current=null),C.current&&(C.current.remove(),C.current=null);},[]),useEffect(()=>{c({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[n,c,e.id,e.exportName,x]),useEffect(()=>{let w=T?.cssUrls??[];if(w.length!==0)return Ao(w),()=>$o(w)},[T?.cssUrls.join("|")]),useEffect(()=>{if(o&&!i&&!f||h.current===L&&f)return;let w=false;return R(null),Mo(T,e.original,e.exportName).then(d=>{if(!w){if(T?.id&&g(e.id,T.id)&&_.current){let S=Yt(_.current);if(S){let E=Zt(S);E.length>0&&(b.current=E,M.current=true,N.current&&(clearTimeout(N.current),N.current=null),C.current&&C.current.remove(),C.current=Zr(S));}}h.current=L,startTransition(()=>{k(()=>d);});}}).catch(d=>{w||R(Po(d));}),()=>{w=true;}},[g,L,o,i,s,T?.id,T?.moduleUrl,T?.integrity,T?.cssUrls.join("|"),e.exportName,e.original,f]),useEffect(()=>{if(!M.current||!f||!_.current)return;let w=false;return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(w||!_.current)return;let d=b.current,S=Yt(_.current);if(b.current=null,M.current=false,!d||!S){C.current&&(C.current.remove(),C.current=null);return}let E=Zt(S),A=Qr(d,E),u=en(d,E),l=C.current;if(u.length>0&&l){let y=rn(u);N.current=setTimeout(()=>{N.current=null;let j=400;l.animate([{opacity:1},{opacity:0}],{duration:j,fill:"forwards"}),y.animate([{opacity:1},{opacity:0}],{duration:j,fill:"forwards"}),setTimeout(()=>{l.remove(),y.remove(),C.current===l&&(C.current=null),A.length>0&&Qt(A);},j);},3500);}else l&&(l.remove(),C.current===l&&(C.current=null)),A.length>0&&Qt(A);});}),()=>{w=true;}},[f]),I)throw I;return f?jsx("div",{ref:_,style:{display:"contents"},children:jsx(f,{...r})}):jsx(Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function Ho({slotId:e,title:t,slotLabel:r}){return jsx(Ge,{slotId:e,title:t,slotLabel:r})}
45
+ export{Ro as ForkBoundaryUI,zt as ForkButton,Ge as ForkChatInterface,kt as ForkPanel,Ln as ForkProvider,qn as ForkSlot,Ho as ForkUI,$n as clearCachedManifest,Lo as forkable,ut as loadManifest,Pn as manifestDiffers,En as readCachedManifest,$t as registerForkShared,Jt as useBoundaryFork,qt as useFork,Vt as useForkChatPanel,dt as usePreviewSession,An as writeCachedManifest};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fork-api/chat-sdk",
3
- "version": "0.1.148",
3
+ "version": "0.1.152",
4
4
  "description": "React SDK for Fork — let your users customize your UI with AI.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "homepage": "https://withfork.co",