@fork-api/chat-sdk 0.1.141 → 0.1.142

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,6 +1,6 @@
1
- 'use strict';var Rt=require('react'),Zr=require('react-dom'),Qr=require('react/jsx-runtime'),en=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 Rt__namespace=/*#__PURE__*/_interopNamespace(Rt);var Zr__namespace=/*#__PURE__*/_interopNamespace(Zr);var Qr__namespace=/*#__PURE__*/_interopNamespace(Qr);var en__namespace=/*#__PURE__*/_interopNamespace(en);var me="__FORK_SHARED__";function mt(){var t,r,n,o;let e=globalThis;return e[me]||(e[me]={}),(t=e[me]).react||(t.react=Rt__namespace),(r=e[me])["react-dom"]||(r["react-dom"]=Zr__namespace),(n=e[me])["react/jsx-runtime"]||(n["react/jsx-runtime"]=Qr__namespace),(o=e[me])["react/jsx-dev-runtime"]||(o["react/jsx-dev-runtime"]=en__namespace),e[me]}function ht(e){return Object.assign(mt(),e)}var tn="__fork_preview_session__";function Ge(e){return `${tn}${e}`}var H={apiKey:null,session:null},yt=new Set;function Ve(){for(let e of yt)try{e();}catch(t){console.error("[fork-preview] subscriber threw",t);}}function Xt(e){let t=Date.parse(e.expires_at);return Number.isFinite(t)?t<=Date.now():true}function rn(e){if(typeof window>"u")return null;try{let t=window.sessionStorage.getItem(Ge(e));if(!t)return null;let r=JSON.parse(t);return !r||typeof r!="object"||typeof r.preview_session_id!="string"?null:Xt(r)?(window.sessionStorage.removeItem(Ge(e)),null):r}catch{return null}}function kt(e,t){if(!(typeof window>"u"))try{t?window.sessionStorage.setItem(Ge(e),JSON.stringify(t)):window.sessionStorage.removeItem(Ge(e));}catch{}}function Ee(e){H.apiKey!==e&&(H.apiKey=e,H.session=rn(e),Ve());}function he(){return H.session?Xt(H.session)?(bt(null),null):H.session:null}function bt(e){H.session=e,H.apiKey&&kt(H.apiKey,e),Ve();}function Ae(e){H.session&&H.session.fork_id!==e&&(H.session={...H.session,fork_id:e},H.apiKey&&kt(H.apiKey,H.session),Ve());}function ye(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??H.session.target_user_id,fork_id:null},H.apiKey&&kt(H.apiKey,H.session),Ve()));}function wt(e){return yt.add(e),()=>{yt.delete(e);}}var Yt="__fork_preview";function Zt(){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(Yt);return typeof r=="string"&&r.length>0?r:null}function vt(e){if(typeof window>"u")return false;try{if(window.sessionStorage.getItem(`__fork_preview_session__${e}`))return !0}catch{}return er()!==null}function Qt(){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(Yt);let r=t.toString(),n=r?`#${r}`:"";try{window.history.replaceState(null,"",window.location.pathname+window.location.search+n);}catch{}}var ke=null;function er(){if(ke)return ke;let e=Zt();return e?(ke=e,Qt(),ke):null}async function St(e,t){Ee(e);let r=he();if(r)return ke=null,r;let n=ke??Zt();if(ke=null,!n)return null;Qt();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 a=await o.json().catch(()=>({}));return console.warn(`[fork-preview] activate failed (${o.status}): ${a.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,target_user_id:i.target_user_id,operator_id:i.operator_id,container_id:i.container_id??null,container_name:i.container_name??i.target_user_id,fork_id:i.fork_id??null,expires_at:i.expires_at};return bt(s),s}catch(o){return console.warn("[fork-preview] activate threw",o),null}}function on(){return he()}function sn(){return null}function Je(){return Rt.useSyncExternalStore(wt,on,sn)}function G(){let e=he();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 qe(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[a,p]of Object.entries(i.modules)){let g=p.moduleUrl??p.bundleUrl??null,d=p.legacyModuleUrl??p.legacyBundleUrl??null;s[a]={forkId:p.forkId,moduleUrl:g,legacyModuleUrl:d,bundleUrl:p.bundleUrl??g,legacyBundleUrl:p.legacyBundleUrl??d,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 an="fork:manifest:v1";function xt(e,t,r){return `${an}:${e}:${t}:${r}`}function ln(e,t,r){if(typeof window>"u")return null;try{let n=window.localStorage.getItem(xt(e,t,r));return n?JSON.parse(n):null}catch{return null}}function cn(e,t,r,n){if(!(typeof window>"u"))try{window.localStorage.setItem(xt(e,t,r),JSON.stringify(n));}catch{}}function dn(e,t,r){if(!(typeof window>"u"))try{window.localStorage.removeItem(xt(e,t,r));}catch{}}function un(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,a]of r){let p=t.slots[s];if(!p||p.forkId!==a.forkId||p.buildId!==a.buildId)return true}let o=Object.entries(e.modules),i=Object.entries(t.modules);if(o.length!==i.length)return true;for(let[s,a]of o){let p=t.modules[s];if(!p||p.forkId!==a.forkId||p.buildId!==a.buildId)return true}return false}var nr=Rt.createContext(null);function Ce(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function gn(e,t){let r={};for(let[n,o]of Object.entries(t.boundaries||{}))r[n]={...o,moduleUrl:Ce(e,o.moduleUrl),cssUrls:Array.isArray(o.cssUrls)?o.cssUrls.map(i=>Ce(e,i)):[]};return r}function tr(e,t,r,n){let o={};for(let[i,s]of Object.entries(t.slots)){let a=s.bundleUrl??s.legacyBundleUrl;a&&(o[i]={id:s.forkId,userId:r,prompt:"",status:"complete",slotId:i,appId:n,bundleUrl:Ce(e,a),createdAt:s.updatedAt,completedAt:s.updatedAt});}return o}function rr(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:Ce(e,i),cssUrls:(o.cssUrls??[]).map(s=>Ce(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,a="authUrl"in e?e.authUrl:void 0,[p]=Rt.useState(()=>(Ee(t),vt(t))),[g,d]=Rt.useState({}),[S,P]=Rt.useState(s?{userId:s,userHash:void 0}:null),[R,x]=Rt.useState(!!s||p),[h,y]=Rt.useState({}),[T,A]=Rt.useState(!o),[M,E]=Rt.useState(0),[I,v]=Rt.useState(null),b=Rt.useRef(new Map),l=Rt.useRef(new Map),[$,F]=Rt.useState(0),u=Rt.useRef(new Set),f=Rt.useRef(new Map),m=Rt.useRef(void 0);mt(),Rt.useEffect(()=>{return St(t,r).then(()=>{}),()=>{}},[]);let L=Je();i&&m.current!==i&&(ht(i),m.current=i),Rt.useEffect(()=>{a&&(p||(x(false),fetch(a,{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");P({userId:_.userId,userHash:_.userHash});}).catch(_=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",_.message);}).finally(()=>{x(true);})));},[a,p]),Rt.useEffect(()=>{!a&&s&&(P({userId:s,userHash:void 0}),x(true));},[s,a]);let W=S?.userId??"",ee=S?.userHash,N=L?L.target_user_id:W,z=L?void 0:ee,Y=!!o,D=Rt.useCallback(async()=>{if(!Y){v(null),y({}),A(true),E(w=>w+1);return}if(!R){A(false);return}if(!N||!o){v(null),y({}),A(true),E(w=>w+1);return}if(A(false),!L){try{let w=await qe({baseUrl:r,apiKey:t,appId:o,userId:N,userHash:z});w&&(v(w.containerId),d(tr(r,w,N,o)),y(rr(r,w)));}catch(w){console.error("[ForkProvider] Failed to fetch fork manifest:",w.message),v(null),d({}),y({});}finally{E(w=>w+1),A(true);}return}if(v(L.container_id??null),L.container_id){try{let w=await qe({baseUrl:r,apiKey:t,appId:o,userId:N,containerId:L.container_id,extraHeaders:G()});w&&(d(tr(r,w,N,o)),y(rr(r,w)));}catch(w){console.error("[ForkProvider] Failed to fetch preview container manifest:",w.message),d({}),y({});}finally{E(w=>w+1),A(true);}return}let _=new URLSearchParams({appId:o,userId:N});z&&_.set("userHash",z);try{let w=await fetch(`${r}/api/v1/boundaries/manifest?${_.toString()}`,{headers:{Authorization:`Bearer ${t}`,...G()}});if(!w.ok)throw new Error(`${w.status}`);let U=await w.json();y(gn(r,U));}catch(w){console.error("[ForkProvider] Failed to fetch module override manifest:",w.message),y({});}finally{E(w=>w+1),A(true);}},[t,o,r,R,Y,z,N,L?.preview_session_id,L?.fork_id,L?.container_id]);Rt.useEffect(()=>{if(!N||o&&(!L||L.container_id))return;let _=new URLSearchParams({userId:N});z&&_.set("userHash",z),fetch(`${r}/api/v1/forks/active?${_.toString()}`,{headers:{Authorization:`Bearer ${t}`,...G()}}).then(w=>{if(!w.ok)throw new Error(`${w.status}`);return w.json()}).then(w=>{w&&typeof w=="object"&&d(w);}).catch(()=>{});},[t,o,N,z,r,L?.preview_session_id,L?.fork_id]),Rt.useEffect(()=>{D();},[D]);let te=Rt.useCallback((_,w)=>{d(U=>({...U,[_]:w}));},[]),ne=Rt.useCallback(_=>{d(w=>{let U={...w};return delete U[_],U});},[]),ue=Rt.useCallback(_=>{u.current.add(_);},[]),Z=Rt.useCallback(_=>u.current.has(_)?(u.current.delete(_),true):false,[]),ct=Rt.useCallback((_,w)=>{f.current.set(_,w);},[]),Le=Rt.useCallback((_,w)=>f.current.get(_)!==w?false:(f.current.delete(_),true),[]),Re=Rt.useCallback(_=>{if(!o)return;let w=JSON.stringify(_);b.current.get(_.id)===w||l.current.get(_.id)?.signature===w||(l.current.set(_.id,{boundary:_,signature:w}),F(K=>K+1));},[o]);Rt.useEffect(()=>{if(!o||l.current.size===0)return;let _=setTimeout(()=>{let w=Array.from(l.current.values());w.length!==0&&fetch(`${r}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:o,boundaries:w.map(U=>U.boundary)})}).then(U=>{if(!U.ok)throw new Error(`${U.status}`)}).then(()=>{for(let U of w)l.current.get(U.boundary.id)?.signature===U.signature&&(l.current.delete(U.boundary.id),b.current.set(U.boundary.id,U.signature));}).catch(U=>{console.error("[ForkProvider] Failed to register module boundaries:",U.message);});},50);return ()=>{clearTimeout(_);}},[t,o,r,$]);let ie=Rt.useCallback(_=>h[_],[h]),q=Rt.useCallback(async()=>{if(!N)throw new Error("Reset requires a resolved user identity.");let _=new URLSearchParams({userId:N});z&&_.set("userHash",z);let w=await fetch(`${r}/api/v1/forks/all?${_.toString()}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`,...G()}});if(!w.ok){let K=await w.json().catch(()=>({}));throw new Error(K.error||`API error: ${w.status}`)}let U=await w.json().catch(()=>({}));d({}),y({}),A(true),E(K=>K+1),u.current.clear(),f.current.clear();try{for(let K=sessionStorage.length-1;K>=0;K-=1){let ae=sessionStorage.key(K);ae&&ae.startsWith("__fork_animated_")&&sessionStorage.removeItem(ae);}}catch{}return U},[t,r,z,N]);return Qr.jsx(nr.Provider,{value:{apiKey:t,userId:N,userHash:z,baseUrl:r,appId:o,forks:g,moduleOverridesEnabled:Y,moduleManifestReady:T,moduleManifestVersion:M,currentContainerId:I,previewSession:L,setSlotFork:te,clearSlotFork:ne,skipAnimationForSlot:ue,shouldSkipAnimation:Z,queueBoundaryAnimation:ct,consumeBoundaryAnimation:Le,registerBoundary:Re,getBoundaryOverride:ie,refreshModuleManifest:D,resetAllForks:q},children:n})}function J(){let e=Rt.useContext(nr);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function Xe(e){return J().forks[e]}var Pe=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 _t(e,t){let r;try{r=Rt.Children.only(e);}catch{let o=Rt.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 sr=new Set;function ir(e){let t=[],r=e.querySelectorAll("*");for(let n of r){if(!(n instanceof HTMLElement))continue;let o=n.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(n.tagName))continue;let i=getComputedStyle(n),s=parseFloat(i.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:s});}return t}function wn(e,t){let r=[];for(let n of t)if(!e.find(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 a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function vn(e,t){let r=[];for(let n of e)if(!t.find(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 a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function lr(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 ar(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-highlights","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");n.appendChild(o);let i=[];for(let d=0;d<e.length;d++){let{rect:S,borderRadius:P}=e[d],R=S.left-.5,x=S.top-.5,h=S.width+1,y=S.height+1,T=Math.min(P+.5,h/2,y/2),A=lr(R,x,h,y,T),M=`__fork-glow-${d}`,E=document.createElementNS(t,"filter");E.setAttribute("id",M),E.setAttribute("x","-100%"),E.setAttribute("y","-100%"),E.setAttribute("width","300%"),E.setAttribute("height","300%");let I=document.createElementNS(t,"feGaussianBlur");I.setAttribute("in","SourceGraphic"),I.setAttribute("stdDeviation","8"),E.appendChild(I),o.appendChild(E);let v=`__fork-mask-${d}`,b=document.createElementNS(t,"mask");b.setAttribute("id",v),b.setAttribute("maskUnits","userSpaceOnUse"),b.setAttribute("x",String(R-200)),b.setAttribute("y",String(x-200)),b.setAttribute("width",String(h+400)),b.setAttribute("height",String(y+400));let l=document.createElementNS(t,"rect");l.setAttribute("x",String(R-200)),l.setAttribute("y",String(x-200)),l.setAttribute("width",String(h+400)),l.setAttribute("height",String(y+400)),l.setAttribute("fill","white"),b.appendChild(l);let $=document.createElementNS(t,"path");$.setAttribute("d",A),$.setAttribute("fill","black"),b.appendChild($),o.appendChild(b);let F=document.createElementNS(t,"g");F.setAttribute("mask",`url(#${v})`),F.setAttribute("opacity","0");let u=document.createElementNS(t,"g");u.setAttribute("filter",`url(#${M})`);let f=document.createElementNS(t,"path");f.setAttribute("d",A),f.setAttribute("fill","none"),f.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),f.setAttribute("stroke-width","6"),f.setAttribute("stroke-linecap","round"),u.appendChild(f),F.appendChild(u),n.appendChild(F);let m=document.createElementNS(t,"path");m.setAttribute("d",A),m.setAttribute("fill","none"),m.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),m.setAttribute("stroke-width","2"),m.setAttribute("stroke-linecap","round"),m.setAttribute("opacity","0"),n.appendChild(m),i.push(f,m),f.__group=F;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let d=0;d<i.length;d+=2){let S=i[d],P=i[d+1],R=S.__group,x=P.getTotalLength(),h=S.getTotalLength();if(x<=0)continue;let y=x*.35;P.setAttribute("stroke-dasharray",`${y} ${x-y}`),P.setAttribute("stroke-dashoffset","0"),s.push(P.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*x,opacity:.92,offset:.06},{strokeDashoffset:-2*x,opacity:.92,offset:.92},{strokeDashoffset:-2.25*x,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let T=h*.35;S.setAttribute("stroke-dasharray",`${T} ${h-T}`),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(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 a=false,p=()=>{if(a)return;a=true,clearTimeout(g);for(let S of s)try{S.cancel();}catch{}let d=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});d.onfinish=()=>r.remove(),window.removeEventListener("click",p);},g=setTimeout(p,14500);return setTimeout(()=>{a||window.addEventListener("click",p);},500),p}function Sn(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:a,borderRadius:p}of e){let g=a.left,d=a.top,S=a.width,P=a.height,R=Math.min(p,S/2,P/2),x=lr(g,d,S,P,R),h=document.createElementNS(t,"path");h.setAttribute("d",x),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 xn(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 Fn=Rt__namespace.default.memo(function({component:t,containerRef:r,wrapperStyle:n,hostProps:o}){return Qr.jsx("div",{ref:r,style:n,children:Qr.jsx(t,{...o})})},(e,t)=>e.component===t.component&&xn(e.hostProps,t.hostProps)),Ft=class extends Rt__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}){_t(t,e);let i=Xe(e),{baseUrl:s,apiKey:a,appId:p,shouldSkipAnimation:g}=J(),[d,S]=Rt.useState(null),P=Rt.useRef(null),R=Rt.useRef(null),x=Rt.useRef(null),h=Rt.useRef(false),y=Rt.useRef(null),T=Rt.useRef(null),A=!!(n||o),M=Rt.useRef(null);A&&!M.current&&(M.current=new Pe(e));let E=Rt.useRef(o);if(E.current=o,Rt.useEffect(()=>{if(A)return ()=>{M.current?.destroy(),M.current=null;}},[A,e]),A&&M.current&&n)for(let[$,F]of Object.entries(n))M.current.set($,F);Rt.useEffect(()=>{if(!A)return;M.current||(M.current=new Pe(e));let $=M.current,F=Object.keys(E.current||{}).map(u=>$.on(u,(...f)=>E.current?.[u]?.(...f)));return ()=>F.forEach(u=>u())},[A,e]),Rt.useEffect(()=>{if(sr.has(e))return;sr.add(e);let $={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 ${a}`,"Content-Type":"application/json"},body:JSON.stringify($)}).catch(()=>{});},[e,s,a,r,p]);let I=i?.id||null;Rt.useEffect(()=>{if(i?.bundleUrl,P.current,R.current,!i?.bundleUrl||!I){return}let $=`${s}${i.bundleUrl.replace("bundle.js","component.js")}`,F=`__fork_animated_${e}`,u=sessionStorage.getItem(F),f=g(e),m=!f&&u!==I;if(f&&I&&sessionStorage.setItem(F,I),m&&R.current){let z=ir(R.current);x.current=z,h.current=true,`${e}${z.length}`;}window.__FORK_REACT__=Rt__namespace.default,window.__FORK_REACT_DOM__=Zr__namespace,window.__FORK_REACT_JSX__=Qr__namespace;let L=Date.now(),W=`${s}${i.bundleUrl.replace("bundle.js","component.css")}?t=${L}`,ee=document.createElement("link");ee.rel="stylesheet",ee.href=W,ee.dataset.forkSlot=e,document.head.appendChild(ee);let N=document.createElement("script");return N.src=$+"?t="+L,N.onload=()=>{let z=window.__FORK_EXPORT__;if(z?.default){if(R.current&&x.current&&h.current){let Y=R.current.getBoundingClientRect(),D=R.current.cloneNode(true);D.style.position="fixed",D.style.top=`${Y.top}px`,D.style.left=`${Y.left}px`,D.style.width=`${Y.width}px`,D.style.height=`${Y.height}px`,D.style.flex="none",D.style.minHeight="auto",D.style.zIndex="9998",D.style.pointerEvents="none",D.style.overflow="hidden";let te=getComputedStyle(R.current).backgroundColor;D.style.backgroundColor=te&&te!=="rgba(0, 0, 0, 0)"&&te!=="transparent"?te:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(D);let ne=R.current.querySelectorAll("*"),ue=D.querySelectorAll("*");for(let Z=0;Z<ne.length;Z++)ne[Z].scrollTop!==0&&(ue[Z].scrollTop=ne[Z].scrollTop),ne[Z].scrollLeft!==0&&(ue[Z].scrollLeft=ne[Z].scrollLeft);y.current=D;}S(()=>z.default),P.current=I;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},N.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(N),()=>{N.remove(),ee.remove(),T.current&&(clearTimeout(T.current),T.current=null),y.current&&(y.current.remove(),y.current=null);}},[I,s,e]),Rt.useEffect(()=>{if(!h.current||!d||!R.current){`${e}${h.current}`,R.current;return}let $=x.current;if(!$){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!R.current)return;let F=ir(R.current),u=wn($,F),f=vn($,F),m=y.current;if(`${e}${u.length}${f.length}`,f.length>0&&m){let L=Sn(f);T.current=setTimeout(()=>{T.current=null;let W=400;m.animate([{opacity:1},{opacity:0}],{duration:W,fill:"forwards"}),L.animate([{opacity:1},{opacity:0}],{duration:W,fill:"forwards"}),setTimeout(()=>{m.remove(),L.remove(),y.current=null,u.length>0&&(ar(u));},W);},3500);}else m&&(m.remove(),y.current=null),u.length>0&&(ar(u));x.current=null,h.current=false,I&&(sessionStorage.setItem(`__fork_animated_${e}`,I),`${e}`);});});},[d]);let v={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!i||i.status!=="complete"||!i.bundleUrl)return Qr.jsx("div",{ref:R,style:v,children:t});if(!d)return Qr.jsx("div",{ref:R,style:v,children:t});let l=t?.props??{};return Qr.jsx(Ft,{slotId:e,resetKey:I,fallback:Qr.jsx("div",{ref:R,style:v,children:t}),children:Qr.jsx(Fn,{component:d,containerRef:R,wrapperStyle:v,hostProps:l})})}var ur=new Set;function En(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 fr(e,t=new Set){return Rt.Children.forEach(e,r=>{if(!Rt.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&&fr(n.children,t);}),t}function An({slotId:e,props:t,children:r,allowedFetches:n,githubRepo:o,callbacks:i,mode:s="iframe",shared:a,events:p}){if(_t(r,e),s==="direct")return Qr.jsx(cr,{slotId:e,githubRepo:o,shared:a,events:p,children:r});let g=Xe(e),{baseUrl:d,apiKey:S,appId:P}=J(),R=Rt.useRef(null),x=Rt.useRef(false),h=Rt.useRef(null),y=Rt.useRef(i);y.current=i;let T=Rt.useRef(t);T.current=t;let A=Rt.useRef(n);A.current=n,Rt.useEffect(()=>{if(typeof process<"u")return;let v=fr(r),b=new Set(i?Object.keys(i):[]),l=[...v].filter($=>!b.has($));l.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
- `+l.map($=>` - ${$}`).join(`
3
- `)+"\n\nThe forked component will not be able to call these. Add them to the `callbacks` prop of <ForkSlot>.");},[e,r,i]),Rt.useEffect(()=>{ur.has(e)||(ur.add(e),fetch(`${d}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${S}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:P,label:e,propsShape:t?En(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:o,callbackNames:i?Object.keys(i):[],mode:s||"iframe"})}).catch(()=>{}));},[e,d,S,o,P]);let M=Rt.useCallback(v=>{let b=R.current;if(b?.contentWindow&&x.current){let l=y.current?Object.keys(y.current):[];b.contentWindow.postMessage({type:"slot:props",props:v,callbackNames:l},"*"),h.current=null;}else h.current=v;},[]),E=Rt.useCallback((v,b)=>{let l=A.current;return !l||l.length===0?false:l.some($=>{let[F,u]=$.split(" "),f=b.split("?")[0];return v.toUpperCase()===F.toUpperCase()&&f.startsWith(u)})},[]);if(Rt.useEffect(()=>{if(!g?.bundleUrl)return;let v=async b=>{if(b.source===R.current?.contentWindow){if(b.data?.type==="slot:ready")x.current=true,R.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:A.current||[]},"*"),A.current,h.current?M(h.current):M(T.current||{});else if(b.data?.type==="slot:event"){let l=b.data.event;l?.navigate&&(window.location.hash=l.navigate);}else if(b.data?.type==="slot:clipboard-write")navigator.clipboard.writeText(b.data.text).catch(l=>{console.warn(`[ForkSlot:${e}] clipboard write failed:`,l.message);});else if(b.data?.type==="slot:callback"){let{name:l,args:$}=b.data,F=y.current?.[l];F?(F(...$||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${l}`);}else if(b.data?.type==="slot:fetch"){let{id:l,method:$,url:F,body:u}=b.data,f=R.current?.contentWindow;if(!f)return;let m=$||"GET";if(!E(m,F)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${l}: ${m} ${F} \u2014 not in allowedFetches`),f.postMessage({type:"slot:fetch-response",id:l,error:`Fetch not allowed: ${m} ${F}`},"*");return}try{let L={method:m};u&&m!=="GET"&&(L.headers={"Content-Type":"application/json"},L.body=JSON.stringify(u));let W=await fetch(F,L),ee=await W.json();`${e}${l}${W.status}`,f.postMessage({type:"slot:fetch-response",id:l,data:ee,status:W.status},"*");}catch(L){console.error(`[ForkSlot:${e}] fetch #${l} failed:`,L.message),f.postMessage({type:"slot:fetch-response",id:l,error:L.message},"*");}}}};return window.addEventListener("message",v),()=>{window.removeEventListener("message",v),x.current=false;}},[g?.bundleUrl,e,M,E]),Rt.useEffect(()=>{g?.bundleUrl&&x.current&&M(t||{});},[t,g?.bundleUrl,M]),!g||g.status!=="complete"||!g.bundleUrl)return `${e}${g?.status||"none"}${g?.bundleUrl||"none"}`,Qr.jsx(Qr.Fragment,{children:r});`${e}${g.bundleUrl}`;let I=`${d}${g.bundleUrl.replace("/bundle.js","/host")}`;return Qr.jsx("iframe",{ref:R,src:I,sandbox:"allow-scripts allow-same-origin allow-forms allow-clipboard-write",title:`Forked ${e}`,style:{width:"100%",border:"none",flex:1,minHeight:0}})}function Ze({style:e={width:20,height:20},...t}){return Qr.jsxs("svg",{viewBox:"320 95 270 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:e,...t,children:[Qr.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"}),Qr.jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M387.096 174.735v188"}),Qr.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"}),Qr.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"}),Qr.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 At({onClick:e}){let[t,r]=Rt.useState(false),[n,o]=Rt.useState(false),i=t?48:40;return Qr.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:Qr.jsx(Ze,{style:{width:24,height:24}})})}var Bn={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},Hn={status:"#60a5fa",agent_message:"#a0a0a0",tool_use:"#fbbf24",build_start:"#c084fc",build_complete:"#6b7280",build_error:"#f87171",complete:"#6b7280",error:"#f87171"},Nn={read:lucideReact.FileSearch,write:lucideReact.Pencil,search:lucideReact.FileSearch,shell:lucideReact.Terminal,build:lucideReact.Package},Dn={read:"#60a5fa",write:"#fbbf24",search:"#60a5fa",shell:"#a78bfa",build:"#c084fc"};function Ct(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 wr({events:e}){let t=Rt.useRef(null);return Rt.useEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight);},[e]),Qr.jsxs(Qr.Fragment,{children:[Qr.jsx("style",{children:`
1
+ 'use strict';var $t=require('react'),nn=require('react-dom'),on=require('react/jsx-runtime'),sn=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 $t__namespace=/*#__PURE__*/_interopNamespace($t);var nn__namespace=/*#__PURE__*/_interopNamespace(nn);var on__namespace=/*#__PURE__*/_interopNamespace(on);var sn__namespace=/*#__PURE__*/_interopNamespace(sn);var ye="__FORK_SHARED__";function wt(){var t,r,n,o;let e=globalThis;return e[ye]||(e[ye]={}),(t=e[ye]).react||(t.react=$t__namespace),(r=e[ye])["react-dom"]||(r["react-dom"]=nn__namespace),(n=e[ye])["react/jsx-runtime"]||(n["react/jsx-runtime"]=on__namespace),(o=e[ye])["react/jsx-dev-runtime"]||(o["react/jsx-dev-runtime"]=sn__namespace),e[ye]}function vt(e){return Object.assign(wt(),e)}var an="__fork_preview_session__";function qe(e){return `${an}${e}`}var H={apiKey:null,session:null},St=new Set;function Xe(){for(let e of St)try{e();}catch(t){console.error("[fork-preview] subscriber threw",t);}}function nr(e){let t=Date.parse(e.expires_at);return Number.isFinite(t)?t<=Date.now():true}function ln(e){if(typeof window>"u")return null;try{let t=window.sessionStorage.getItem(qe(e));if(!t)return null;let r=JSON.parse(t);return !r||typeof r!="object"||typeof r.preview_session_id!="string"?null:nr(r)?(window.sessionStorage.removeItem(qe(e)),null):r}catch{return null}}function xt(e,t){if(!(typeof window>"u"))try{t?window.sessionStorage.setItem(qe(e),JSON.stringify(t)):window.sessionStorage.removeItem(qe(e));}catch{}}function Ae(e){H.apiKey!==e&&(H.apiKey=e,H.session=ln(e),Xe());}function be(){return H.session?nr(H.session)?(Ft(null),null):H.session:null}function Ft(e){H.session=e,H.apiKey&&xt(H.apiKey,e),Xe();}function $e(e){H.session&&H.session.fork_id!==e&&(H.session={...H.session,fork_id:e},H.apiKey&&xt(H.apiKey,H.session),Xe());}function ke(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??H.session.target_user_id,fork_id:null},H.apiKey&&xt(H.apiKey,H.session),Xe()));}function _t(e){return St.add(e),()=>{St.delete(e);}}var or="__fork_preview";function sr(){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(or);return typeof r=="string"&&r.length>0?r:null}function Rt(e){if(typeof window>"u")return false;try{if(window.sessionStorage.getItem(`__fork_preview_session__${e}`))return !0}catch{}return ar()!==null}function ir(){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(or);let r=t.toString(),n=r?`#${r}`:"";try{window.history.replaceState(null,"",window.location.pathname+window.location.search+n);}catch{}}var we=null;function ar(){if(we)return we;let e=sr();return e?(we=e,ir(),we):null}async function Et(e,t){Ae(e);let r=be();if(r)return we=null,r;let n=we??sr();if(we=null,!n)return null;ir();try{let o=await fetch(`${t}/api/v1/preview/activate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({token:n})});if(!o.ok){let l=await o.json().catch(()=>({}));return console.warn(`[fork-preview] activate failed (${o.status}): ${l.error??"unknown"}`),null}let i=await o.json(),s={preview_session_id:i.preview_session_id,tenant_id:i.tenant_id,app_id:i.app_id,target:i.target,target_user_id:i.target_user_id,operator_id:i.operator_id,container_id:i.container_id??null,container_name:i.container_name??i.target_user_id,fork_id:i.fork_id??null,expires_at:i.expires_at};return Ft(s),s}catch(o){return console.warn("[fork-preview] activate threw",o),null}}function dn(){return be()}function un(){return null}function Ye(){return $t.useSyncExternalStore(_t,dn,un)}function V(){let e=be();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 Ze(e){let t=new URLSearchParams({app:e.appId,user:e.userId});e.containerId&&t.set("containerId",e.containerId);let r=`${e.baseUrl}/api/v1/manifest?${t.toString()}`,n={Authorization:`Bearer ${e.apiKey}`,"X-Fork-App-Id":e.appId,"X-Fork-User-Id":e.userId,...e.extraHeaders??{}};e.userHash&&(n["X-Fork-User-Hash"]=e.userHash),e.previous?.etag&&(n["If-None-Match"]=e.previous.etag);let o=await fetch(r,{headers:n,signal:e.signal});if(o.status===304)return null;if(!o.ok)throw new Error(`manifest ${o.status} ${o.statusText}`);let i=await o.json(),s={};for(let[l,p]of Object.entries(i.modules)){let g=p.moduleUrl??p.bundleUrl??null,d=p.legacyModuleUrl??p.legacyBundleUrl??null;s[l]={forkId:p.forkId,moduleUrl:g,legacyModuleUrl:d,bundleUrl:p.bundleUrl??g,legacyBundleUrl:p.legacyBundleUrl??d,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 Ct(e,t,r){return `${fn}:${e}:${t}:${r}`}function pn(e,t,r){if(typeof window>"u")return null;try{let n=window.localStorage.getItem(Ct(e,t,r));return n?JSON.parse(n):null}catch{return null}}function gn(e,t,r,n){if(!(typeof window>"u"))try{window.localStorage.setItem(Ct(e,t,r),JSON.stringify(n));}catch{}}function mn(e,t,r){if(!(typeof window>"u"))try{window.localStorage.removeItem(Ct(e,t,r));}catch{}}function hn(e,t){if(!e||!t)return e!==t;if(e.containerId!==t.containerId)return true;let r=Object.entries(e.slots),n=Object.entries(t.slots);if(r.length!==n.length)return true;for(let[s,l]of r){let p=t.slots[s];if(!p||p.forkId!==l.forkId||p.buildId!==l.buildId)return true}let o=Object.entries(e.modules),i=Object.entries(t.modules);if(o.length!==i.length)return true;for(let[s,l]of o){let p=t.modules[s];if(!p||p.forkId!==l.forkId||p.buildId!==l.buildId)return true}return false}var dr=$t.createContext(null);function Te(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function kn(e,t){let r={};for(let[n,o]of Object.entries(t.boundaries||{}))r[n]={...o,moduleUrl:Te(e,o.moduleUrl),cssUrls:Array.isArray(o.cssUrls)?o.cssUrls.map(i=>Te(e,i)):[]};return r}function lr(e,t,r,n){let o={};for(let[i,s]of Object.entries(t.slots)){let l=s.bundleUrl??s.legacyBundleUrl;l&&(o[i]={id:s.forkId,userId:r,prompt:"",status:"complete",slotId:i,appId:n,bundleUrl:Te(e,l),createdAt:s.updatedAt,completedAt:s.updatedAt});}return o}function cr(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:Te(e,i),cssUrls:(o.cssUrls??[]).map(s=>Te(e,s)),integrity:o.integrity,metadata:o.metadata,createdAt:o.updatedAt});}return r}function wn(e){let{apiKey:t,baseUrl:r,children:n,appId:o,shared:i}=e,s="userId"in e?e.userId:void 0,l="authUrl"in e?e.authUrl:void 0,[p]=$t.useState(()=>(Ae(t),Rt(t))),[g,d]=$t.useState({}),[S,P]=$t.useState(s?{userId:s,userHash:void 0}:null),[_,x]=$t.useState(!!s||p),[h,y]=$t.useState({}),[T,A]=$t.useState(!o),[M,C]=$t.useState(0),[I,v]=$t.useState(null),b=$t.useRef(new Map),c=$t.useRef(new Map),[$,F]=$t.useState(0),u=$t.useRef(new Set),f=$t.useRef(new Map),m=$t.useRef(void 0);wt(),$t.useEffect(()=>{return Et(t,r).then(()=>{}),()=>{}},[]);let L=Ye();i&&m.current!==i&&(vt(i),m.current=i),$t.useEffect(()=>{l&&(p||(x(false),fetch(l,{credentials:"include"}).then(R=>{if(!R.ok)throw new Error(`Auth endpoint returned ${R.status}`);return R.json()}).then(R=>{if(!R.userId||typeof R.userId!="string")throw new Error("authUrl response must include userId");P({userId:R.userId,userHash:R.userHash});}).catch(R=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",R.message);}).finally(()=>{x(true);})));},[l,p]),$t.useEffect(()=>{!l&&s&&(P({userId:s,userHash:void 0}),x(true));},[s,l]);let K=S?.userId??"",te=S?.userHash,N=L?L.target_user_id:K,z=L?void 0:te,Q=!!o,D=$t.useCallback(async()=>{if(!Q){v(null),y({}),A(true),C(k=>k+1);return}if(!_){A(false);return}if(!N||!o){v(null),y({}),A(true),C(k=>k+1);return}if(A(false),!L){try{let k=await Ze({baseUrl:r,apiKey:t,appId:o,userId:N,userHash:z});k&&(v(k.containerId),d(lr(r,k,N,o)),y(cr(r,k)));}catch(k){console.error("[ForkProvider] Failed to fetch fork manifest:",k.message),v(null),d({}),y({});}finally{C(k=>k+1),A(true);}return}if(v(L.container_id??null),L.container_id){try{let k=await Ze({baseUrl:r,apiKey:t,appId:o,userId:N,containerId:L.container_id,extraHeaders:V()});k&&(d(lr(r,k,N,o)),y(cr(r,k)));}catch(k){console.error("[ForkProvider] Failed to fetch preview container manifest:",k.message),d({}),y({});}finally{C(k=>k+1),A(true);}return}let R=new URLSearchParams({appId:o,userId:N});z&&R.set("userHash",z);try{let k=await fetch(`${r}/api/v1/boundaries/manifest?${R.toString()}`,{headers:{Authorization:`Bearer ${t}`,...V()}});if(!k.ok)throw new Error(`${k.status}`);let U=await k.json();y(kn(r,U));}catch(k){console.error("[ForkProvider] Failed to fetch module override manifest:",k.message),y({});}finally{C(k=>k+1),A(true);}},[t,o,r,_,Q,z,N,L?.preview_session_id,L?.fork_id,L?.container_id]);$t.useEffect(()=>{if(!N||o&&(!L||L.container_id))return;let R=new URLSearchParams({userId:N});z&&R.set("userHash",z),fetch(`${r}/api/v1/forks/active?${R.toString()}`,{headers:{Authorization:`Bearer ${t}`,...V()}}).then(k=>{if(!k.ok)throw new Error(`${k.status}`);return k.json()}).then(k=>{k&&typeof k=="object"&&d(k);}).catch(()=>{});},[t,o,N,z,r,L?.preview_session_id,L?.fork_id]),$t.useEffect(()=>{D();},[D]);let re=$t.useCallback((R,k)=>{d(U=>({...U,[R]:k}));},[]),oe=$t.useCallback(R=>{d(k=>{let U={...k};return delete U[R],U});},[]),ue=$t.useCallback(R=>{u.current.add(R);},[]),ee=$t.useCallback(R=>u.current.has(R)?(u.current.delete(R),true):false,[]),ft=$t.useCallback((R,k)=>{f.current.set(R,k);},[]),Be=$t.useCallback((R,k)=>f.current.get(R)!==k?false:(f.current.delete(R),true),[]),Re=$t.useCallback(R=>{if(!o)return;let k=JSON.stringify(R);b.current.get(R.id)===k||c.current.get(R.id)?.signature===k||(c.current.set(R.id,{boundary:R,signature:k}),F(W=>W+1));},[o]);$t.useEffect(()=>{if(!o||c.current.size===0)return;let R=setTimeout(()=>{let k=Array.from(c.current.values());k.length!==0&&fetch(`${r}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:o,boundaries:k.map(U=>U.boundary)})}).then(U=>{if(!U.ok)throw new Error(`${U.status}`)}).then(()=>{for(let U of k)c.current.get(U.boundary.id)?.signature===U.signature&&(c.current.delete(U.boundary.id),b.current.set(U.boundary.id,U.signature));}).catch(U=>{console.error("[ForkProvider] Failed to register module boundaries:",U.message);});},50);return ()=>{clearTimeout(R);}},[t,o,r,$]);let ie=$t.useCallback(R=>h[R],[h]),Z=$t.useCallback(async()=>{if(!N)throw new Error("Reset requires a resolved user identity.");let R=new URLSearchParams({userId:N});z&&R.set("userHash",z);let k=await fetch(`${r}/api/v1/forks/all?${R.toString()}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`,...V()}});if(!k.ok){let W=await k.json().catch(()=>({}));throw new Error(W.error||`API error: ${k.status}`)}let U=await k.json().catch(()=>({}));d({}),y({}),A(true),C(W=>W+1),u.current.clear(),f.current.clear();try{for(let W=sessionStorage.length-1;W>=0;W-=1){let ae=sessionStorage.key(W);ae&&ae.startsWith("__fork_animated_")&&sessionStorage.removeItem(ae);}}catch{}return U},[t,r,z,N]);return on.jsx(dr.Provider,{value:{apiKey:t,userId:N,userHash:z,baseUrl:r,appId:o,forks:g,moduleOverridesEnabled:Q,moduleManifestReady:T,moduleManifestVersion:M,currentContainerId:I,previewSession:L,setSlotFork:re,clearSlotFork:oe,skipAnimationForSlot:ue,shouldSkipAnimation:ee,queueBoundaryAnimation:ft,consumeBoundaryAnimation:Be,registerBoundary:Re,getBoundaryOverride:ie,refreshModuleManifest:D,resetAllForks:Z},children:n})}function X(){let e=$t.useContext(dr);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function Qe(e){return X().forks[e]}var Me=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 Pt(e,t){let r;try{r=$t.Children.only(e);}catch{let o=$t.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 fr=new Set;function pr(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 _n(e,t){let r=[];for(let n of t)if(!e.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)&&!r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom)){for(let s=r.length-1;s>=0;s--){let l=r[s];l.rect.top>=n.rect.top&&l.rect.left>=n.rect.left&&l.rect.right<=n.rect.right&&l.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Rn(e,t){let r=[];for(let n of e)if(!t.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)&&!r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom)){for(let s=r.length-1;s>=0;s--){let l=r[s];l.rect.top>=n.rect.top&&l.rect.left>=n.rect.left&&l.rect.right<=n.rect.right&&l.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function mr(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 gr(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 d=0;d<e.length;d++){let{rect:S,borderRadius:P}=e[d],_=S.left-.5,x=S.top-.5,h=S.width+1,y=S.height+1,T=Math.min(P+.5,h/2,y/2),A=mr(_,x,h,y,T),M=`__fork-glow-${d}`,C=document.createElementNS(t,"filter");C.setAttribute("id",M),C.setAttribute("x","-100%"),C.setAttribute("y","-100%"),C.setAttribute("width","300%"),C.setAttribute("height","300%");let I=document.createElementNS(t,"feGaussianBlur");I.setAttribute("in","SourceGraphic"),I.setAttribute("stdDeviation","8"),C.appendChild(I),o.appendChild(C);let v=`__fork-mask-${d}`,b=document.createElementNS(t,"mask");b.setAttribute("id",v),b.setAttribute("maskUnits","userSpaceOnUse"),b.setAttribute("x",String(_-200)),b.setAttribute("y",String(x-200)),b.setAttribute("width",String(h+400)),b.setAttribute("height",String(y+400));let c=document.createElementNS(t,"rect");c.setAttribute("x",String(_-200)),c.setAttribute("y",String(x-200)),c.setAttribute("width",String(h+400)),c.setAttribute("height",String(y+400)),c.setAttribute("fill","white"),b.appendChild(c);let $=document.createElementNS(t,"path");$.setAttribute("d",A),$.setAttribute("fill","black"),b.appendChild($),o.appendChild(b);let F=document.createElementNS(t,"g");F.setAttribute("mask",`url(#${v})`),F.setAttribute("opacity","0");let u=document.createElementNS(t,"g");u.setAttribute("filter",`url(#${M})`);let f=document.createElementNS(t,"path");f.setAttribute("d",A),f.setAttribute("fill","none"),f.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),f.setAttribute("stroke-width","6"),f.setAttribute("stroke-linecap","round"),u.appendChild(f),F.appendChild(u),n.appendChild(F);let m=document.createElementNS(t,"path");m.setAttribute("d",A),m.setAttribute("fill","none"),m.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),m.setAttribute("stroke-width","2"),m.setAttribute("stroke-linecap","round"),m.setAttribute("opacity","0"),n.appendChild(m),i.push(f,m),f.__group=F;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let d=0;d<i.length;d+=2){let S=i[d],P=i[d+1],_=S.__group,x=P.getTotalLength(),h=S.getTotalLength();if(x<=0)continue;let y=x*.35;P.setAttribute("stroke-dasharray",`${y} ${x-y}`),P.setAttribute("stroke-dashoffset","0"),s.push(P.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*x,opacity:.92,offset:.06},{strokeDashoffset:-2*x,opacity:.92,offset:.92},{strokeDashoffset:-2.25*x,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let T=h*.35;S.setAttribute("stroke-dasharray",`${T} ${h-T}`),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 l=false,p=()=>{if(l)return;l=true,clearTimeout(g);for(let S of s)try{S.cancel();}catch{}let d=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});d.onfinish=()=>r.remove(),window.removeEventListener("click",p);},g=setTimeout(p,14500);return setTimeout(()=>{l||window.addEventListener("click",p);},500),p}function En(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-removed","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs"),i=document.createElementNS(t,"filter");i.setAttribute("id","__fork-removed-shadow"),i.setAttribute("x","-10%"),i.setAttribute("y","-10%"),i.setAttribute("width","120%"),i.setAttribute("height","120%");let s=document.createElementNS(t,"feDropShadow");s.setAttribute("dx","0"),s.setAttribute("dy","1"),s.setAttribute("stdDeviation","2"),s.setAttribute("flood-color","rgba(0,0,0,0.15)"),i.appendChild(s),o.appendChild(i),n.appendChild(o);for(let{rect:l,borderRadius:p}of e){let g=l.left,d=l.top,S=l.width,P=l.height,_=Math.min(p,S/2,P/2),x=mr(g,d,S,P,_),h=document.createElementNS(t,"path");h.setAttribute("d",x),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 Cn(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 An=$t__namespace.default.memo(function({component:t,containerRef:r,wrapperStyle:n,hostProps:o}){return on.jsx("div",{ref:r,style:n,children:on.jsx(t,{...o})})},(e,t)=>e.component===t.component&&Cn(e.hostProps,t.hostProps)),At=class extends $t__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 hr({slotId:e,children:t,githubRepo:r,shared:n,events:o}){Pt(t,e);let i=Qe(e),{baseUrl:s,apiKey:l,appId:p,shouldSkipAnimation:g}=X(),[d,S]=$t.useState(null),P=$t.useRef(null),_=$t.useRef(null),x=$t.useRef(null),h=$t.useRef(false),y=$t.useRef(null),T=$t.useRef(null),A=!!(n||o),M=$t.useRef(null);A&&!M.current&&(M.current=new Me(e));let C=$t.useRef(o);if(C.current=o,$t.useEffect(()=>{if(A)return ()=>{M.current?.destroy(),M.current=null;}},[A,e]),A&&M.current&&n)for(let[$,F]of Object.entries(n))M.current.set($,F);$t.useEffect(()=>{if(!A)return;M.current||(M.current=new Me(e));let $=M.current,F=Object.keys(C.current||{}).map(u=>$.on(u,(...f)=>C.current?.[u]?.(...f)));return ()=>F.forEach(u=>u())},[A,e]),$t.useEffect(()=>{if(fr.has(e))return;fr.add(e);let $={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 ${l}`,"Content-Type":"application/json"},body:JSON.stringify($)}).catch(()=>{});},[e,s,l,r,p]);let I=i?.id||null;$t.useEffect(()=>{if(i?.bundleUrl,P.current,_.current,!i?.bundleUrl||!I){return}let $=`${s}${i.bundleUrl.replace("bundle.js","component.js")}`,F=`__fork_animated_${e}`,u=sessionStorage.getItem(F),f=g(e),m=!f&&u!==I;if(f&&I&&sessionStorage.setItem(F,I),m&&_.current){let z=pr(_.current);x.current=z,h.current=true,`${e}${z.length}`;}window.__FORK_REACT__=$t__namespace.default,window.__FORK_REACT_DOM__=nn__namespace,window.__FORK_REACT_JSX__=on__namespace;let L=Date.now(),K=`${s}${i.bundleUrl.replace("bundle.js","component.css")}?t=${L}`,te=document.createElement("link");te.rel="stylesheet",te.href=K,te.dataset.forkSlot=e,document.head.appendChild(te);let N=document.createElement("script");return N.src=$+"?t="+L,N.onload=()=>{let z=window.__FORK_EXPORT__;if(z?.default){if(_.current&&x.current&&h.current){let Q=_.current.getBoundingClientRect(),D=_.current.cloneNode(true);D.style.position="fixed",D.style.top=`${Q.top}px`,D.style.left=`${Q.left}px`,D.style.width=`${Q.width}px`,D.style.height=`${Q.height}px`,D.style.flex="none",D.style.minHeight="auto",D.style.zIndex="9998",D.style.pointerEvents="none",D.style.overflow="hidden";let re=getComputedStyle(_.current).backgroundColor;D.style.backgroundColor=re&&re!=="rgba(0, 0, 0, 0)"&&re!=="transparent"?re:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(D);let oe=_.current.querySelectorAll("*"),ue=D.querySelectorAll("*");for(let ee=0;ee<oe.length;ee++)oe[ee].scrollTop!==0&&(ue[ee].scrollTop=oe[ee].scrollTop),oe[ee].scrollLeft!==0&&(ue[ee].scrollLeft=oe[ee].scrollLeft);y.current=D;}S(()=>z.default),P.current=I;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},N.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(N),()=>{N.remove(),te.remove(),T.current&&(clearTimeout(T.current),T.current=null),y.current&&(y.current.remove(),y.current=null);}},[I,s,e]),$t.useEffect(()=>{if(!h.current||!d||!_.current){`${e}${h.current}`,_.current;return}let $=x.current;if(!$){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!_.current)return;let F=pr(_.current),u=_n($,F),f=Rn($,F),m=y.current;if(`${e}${u.length}${f.length}`,f.length>0&&m){let L=En(f);T.current=setTimeout(()=>{T.current=null;let K=400;m.animate([{opacity:1},{opacity:0}],{duration:K,fill:"forwards"}),L.animate([{opacity:1},{opacity:0}],{duration:K,fill:"forwards"}),setTimeout(()=>{m.remove(),L.remove(),y.current=null,u.length>0&&(gr(u));},K);},3500);}else m&&(m.remove(),y.current=null),u.length>0&&(gr(u));x.current=null,h.current=false,I&&(sessionStorage.setItem(`__fork_animated_${e}`,I),`${e}`);});});},[d]);let v={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!i||i.status!=="complete"||!i.bundleUrl)return on.jsx("div",{ref:_,style:v,children:t});if(!d)return on.jsx("div",{ref:_,style:v,children:t});let c=t?.props??{};return on.jsx(At,{slotId:e,resetKey:I,fallback:on.jsx("div",{ref:_,style:v,children:t}),children:on.jsx(An,{component:d,containerRef:_,wrapperStyle:v,hostProps:c})})}var br=new Set;function Tn(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 kr(e,t=new Set){return $t.Children.forEach(e,r=>{if(!$t.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&&kr(n.children,t);}),t}function Mn({slotId:e,props:t,children:r,allowedFetches:n,githubRepo:o,callbacks:i,mode:s="iframe",shared:l,events:p}){if(Pt(r,e),s==="direct")return on.jsx(hr,{slotId:e,githubRepo:o,shared:l,events:p,children:r});let g=Qe(e),{baseUrl:d,apiKey:S,appId:P}=X(),_=$t.useRef(null),x=$t.useRef(false),h=$t.useRef(null),y=$t.useRef(i);y.current=i;let T=$t.useRef(t);T.current=t;let A=$t.useRef(n);A.current=n,$t.useEffect(()=>{if(typeof process<"u")return;let v=kr(r),b=new Set(i?Object.keys(i):[]),c=[...v].filter($=>!b.has($));c.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
+ `+c.map($=>` - ${$}`).join(`
3
+ `)+"\n\nThe forked component will not be able to call these. Add them to the `callbacks` prop of <ForkSlot>.");},[e,r,i]),$t.useEffect(()=>{br.has(e)||(br.add(e),fetch(`${d}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${S}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:P,label:e,propsShape:t?Tn(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:o,callbackNames:i?Object.keys(i):[],mode:s||"iframe"})}).catch(()=>{}));},[e,d,S,o,P]);let M=$t.useCallback(v=>{let b=_.current;if(b?.contentWindow&&x.current){let c=y.current?Object.keys(y.current):[];b.contentWindow.postMessage({type:"slot:props",props:v,callbackNames:c},"*"),h.current=null;}else h.current=v;},[]),C=$t.useCallback((v,b)=>{let c=A.current;return !c||c.length===0?false:c.some($=>{let[F,u]=$.split(" "),f=b.split("?")[0];return v.toUpperCase()===F.toUpperCase()&&f.startsWith(u)})},[]);if($t.useEffect(()=>{if(!g?.bundleUrl)return;let v=async b=>{if(b.source===_.current?.contentWindow){if(b.data?.type==="slot:ready")x.current=true,_.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:A.current||[]},"*"),A.current,h.current?M(h.current):M(T.current||{});else if(b.data?.type==="slot:event"){let c=b.data.event;c?.navigate&&(window.location.hash=c.navigate);}else if(b.data?.type==="slot:clipboard-write")navigator.clipboard.writeText(b.data.text).catch(c=>{console.warn(`[ForkSlot:${e}] clipboard write failed:`,c.message);});else if(b.data?.type==="slot:callback"){let{name:c,args:$}=b.data,F=y.current?.[c];F?(F(...$||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${c}`);}else if(b.data?.type==="slot:fetch"){let{id:c,method:$,url:F,body:u}=b.data,f=_.current?.contentWindow;if(!f)return;let m=$||"GET";if(!C(m,F)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${c}: ${m} ${F} \u2014 not in allowedFetches`),f.postMessage({type:"slot:fetch-response",id:c,error:`Fetch not allowed: ${m} ${F}`},"*");return}try{let L={method:m};u&&m!=="GET"&&(L.headers={"Content-Type":"application/json"},L.body=JSON.stringify(u));let K=await fetch(F,L),te=await K.json();`${e}${c}${K.status}`,f.postMessage({type:"slot:fetch-response",id:c,data:te,status:K.status},"*");}catch(L){console.error(`[ForkSlot:${e}] fetch #${c} failed:`,L.message),f.postMessage({type:"slot:fetch-response",id:c,error:L.message},"*");}}}};return window.addEventListener("message",v),()=>{window.removeEventListener("message",v),x.current=false;}},[g?.bundleUrl,e,M,C]),$t.useEffect(()=>{g?.bundleUrl&&x.current&&M(t||{});},[t,g?.bundleUrl,M]),!g||g.status!=="complete"||!g.bundleUrl)return `${e}${g?.status||"none"}${g?.bundleUrl||"none"}`,on.jsx(on.Fragment,{children:r});`${e}${g.bundleUrl}`;let I=`${d}${g.bundleUrl.replace("/bundle.js","/host")}`;return on.jsx("iframe",{ref:_,src:I,sandbox:"allow-scripts allow-same-origin allow-forms allow-clipboard-write",title:`Forked ${e}`,style:{width:"100%",border:"none",flex:1,minHeight:0}})}function tt({style:e={width:20,height:20},...t}){return on.jsxs("svg",{viewBox:"320 95 270 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:e,...t,children:[on.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"}),on.jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M387.096 174.735v188"}),on.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"}),on.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"}),on.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 Mt({onClick:e}){let[t,r]=$t.useState(false),[n,o]=$t.useState(false),i=t?48:40;return on.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:on.jsx(tt,{style:{width:24,height:24}})})}var zn={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},Wn={status:"#60a5fa",agent_message:"#a0a0a0",tool_use:"#fbbf24",build_start:"#c084fc",build_complete:"#6b7280",build_error:"#f87171",complete:"#6b7280",error:"#f87171"},Kn={read:lucideReact.FileSearch,write:lucideReact.Pencil,search:lucideReact.FileSearch,shell:lucideReact.Terminal,build:lucideReact.Package},Gn={read:"#60a5fa",write:"#fbbf24",search:"#60a5fa",shell:"#a78bfa",build:"#c084fc"};function Lt(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 Er({events:e}){let t=$t.useRef(null);return $t.useEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight);},[e]),on.jsxs(on.Fragment,{children:[on.jsx("style",{children:`
4
4
  @keyframes __fork-spin {
5
5
  from { transform: rotate(0deg); }
6
6
  to { transform: rotate(360deg); }
@@ -18,7 +18,7 @@
18
18
  .__fork-stream::-webkit-scrollbar-thumb:hover {
19
19
  background: rgba(255, 255, 255, 0.3);
20
20
  }
21
- `}),Qr.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&&Qr.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"#6b7280",fontSize:"11px"},children:[Qr.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"),a=Bn[r.type]||lucideReact.Code,p=Hn[r.type]||"#9ca3af";if(r.type==="tool_use"){let g=String(r.data.category||"");a=Nn[g]||lucideReact.Wrench,p=Dn[g]||"#fbbf24";}return s?a=lucideReact.Loader2:!o&&r.type==="status"&&(a=lucideReact.Check,p="#4ade80"),Qr.jsxs("div",{style:{display:"flex",gap:"6px",marginBottom:"6px",lineHeight:1.625},children:[Qr.jsx(a,{style:{width:"12px",height:"12px",marginTop:"2px",flexShrink:0,color:p,...s?{animation:"__fork-spin 1s linear infinite"}:{}}}),Qr.jsx("span",{style:{color:o&&!i?"#d1d5db":"#6b7280",wordBreak:"break-all"},children:Ct(r)})]},n)})]})]})}var Fr=35,qn="Working on Feature",Xn="Built Custom Feature",Rr=360,tt=350;function Yn(e){return e.length<=Fr?e:e.slice(0,Fr-3).trimEnd()+"..."}function Zn({events:e}){let[t,r]=Rt.useState("Setting up environment..."),[n,o]=Rt.useState(true),i=Rt.useRef(t),s=Rt.useRef(false);return Rt.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 a="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"){a=Yn(Ct(g));break}}if(a!==i.current){o(false);let p=setTimeout(()=>{r(a),i.current=a,o(true);},200);return ()=>clearTimeout(p)}},[e]),Qr.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 Qn({children:e}){let[t,r]=Rt.useState(null);return Rt.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?Zr.createPortal(e,t):null}function rt({state:e,fork:t,events:r,error:n,slotId:o,targetId:i,targetLabel:s,historyMode:a="slot",onSubmit:p,onUndo:g,onClose:d,baseUrl:S,apiKey:P,userId:R,userHash:x,appId:h,embedded:y=false}){let[T,A]=Rt.useState(""),[M,E]=Rt.useState([]),[I,v]=Rt.useState(false),[b,l]=Rt.useState(false),[$,F]=Rt.useState(false),[u,f]=Rt.useState(false),[m,L]=Rt.useState(false),[W,ee]=Rt.useState(false),[N,z]=Rt.useState(false),[Y,D]=Rt.useState(false),[te,ne]=Rt.useState(false),[ue,Z]=Rt.useState(null),[ct,Le]=Rt.useState(false),[Re,ie]=Rt.useState([]),[q,_]=Rt.useState(null),[w,U]=Rt.useState(false),[K,ae]=Rt.useState(false),[Br,Nt]=Rt.useState(false),[Hr,Dt]=Rt.useState(null),[re,Oe]=Rt.useState(null),[Nr,jt]=Rt.useState(false),[zt,we]=Rt.useState(null),[Dr,_e]=Rt.useState(false),[ve,Wt]=Rt.useState(null),dt=Rt.useRef(null),Ue=Rt.useRef(null),{resetAllForks:jr,previewSession:V,currentContainerId:zr}=J(),pe=V?.container_id??zr,Be=!!(V&&Dr),le=ve!==null,Kt=Rt.useRef(d);Rt.useEffect(()=>{Kt.current=d;});let ut=Rt.useRef(null),He=Rt.useRef(false),Gt=typeof window<"u"&&"documentPictureInPicture"in window,Wr=async()=>{if(!(!Gt||le))try{let c=await window.documentPictureInPicture.requestWindow({width:Rr,height:640});c.document.body.style.margin="0",c.document.body.style.padding="0",c.document.body.style.height="100vh",c.document.body.style.overflow="hidden",c.document.body.style.background="#ffffff";try{let k=document.adoptedStyleSheets??[];k.length>0&&(c.document.adoptedStyleSheets=[...k]);}catch{}c.addEventListener("pagehide",()=>{ut.current=null,Wt(null),He.current||Kt.current(),He.current=!1;},{once:!0}),ut.current=c,Wt(c);}catch(c){console.warn("[Fork] PiP open failed:",c);}},Kr=()=>{ve&&(He.current=true,ve.close());};Rt.useEffect(()=>()=>{He.current=true,ut.current?.close();},[]);let ce=i??o??"",Ne=(s||ce).replace(/[-_]+/g," ").replace(/\b\w/g,c=>c.toUpperCase()),De=Rt.useRef(""),je=y?true:b&&!$,Gr=r.find(c=>{let k=c.data;return c.type==="status"&&k.summary})?.data?.summary||t?.summary||qn,ge=r.find(c=>{let k=c.data;return (c.type==="status"||c.type==="complete")&&typeof k?.estimateMinutes=="number"})?.data?.estimateMinutes??t?.estimateMinutes;Rt.useEffect(()=>{if(a==="none"){v(true);return}if(!S||!P||!R||!ce||I||!w)return;if(V&&!q){E([]),v(true);return}let c=new AbortController,k=new URLSearchParams({userId:R});if(x&&k.set("userHash",x),q&&k.set("containerId",q),a==="slot")k.set("slotId",ce);else if(a==="boundary"){if(!h){v(true);return}k.set("boundaryId",ce),k.set("appId",h);}let O={Authorization:`Bearer ${P}`,...G()};return h&&(O["X-Fork-App-Id"]=h),fetch(`${S}/api/v1/forks/history?${k.toString()}`,{headers:O,signal:c.signal}).then(X=>X.ok?X.json():[]).then(X=>{if(c.signal.aborted)return;let Ke=[];for(let gt of X)gt.role==="user"?Ke.push({type:"user",text:gt.content}):Ke.push({type:"applied",text:gt.content});E(Ke),v(true);}).catch(()=>{c.signal.aborted||v(true);}),()=>{c.abort();}},[P,h,S,I,a,ce,x,R,q,w,V?.preview_session_id]),Rt.useEffect(()=>{e==="complete"&&D(false);},[e]),Rt.useEffect(()=>{if(y&&a==="none"){ie([]),_(null),U(true),_e(false);return}if(V){let c=false;return U(false),_e(false),we(null),fetch(`${S}/api/v1/preview/${encodeURIComponent(V.preview_session_id)}/containers`,{headers:{Authorization:`Bearer ${P}`,...G()}}).then(k=>{if(!k.ok)throw new Error(`${k.status}`);return k.json()}).then(k=>{c||(ie(k.containers),_(k.currentContainerId??V.container_id??null),_e(true));}).catch(k=>{c||(_e(false),we(k instanceof Error?k.message:String(k)),pe?(ie([{id:pe,name:V.container_name||"Primary container",createdAt:"",hasAccess:true,isPrimary:true}]),_(pe)):(ie([]),_(null)));}).finally(()=>{c||U(true);}),()=>{c=true;}}pe?(ie([{id:pe,name:"Primary container",createdAt:""}]),_(pe)):(ie([]),_(null)),U(true),_e(false);},[P,pe,S,y,a,V?.container_id,V?.container_name,V?.preview_session_id]);let ze=Rt.useRef(void 0);Rt.useEffect(()=>{if(w){if(ze.current===void 0){ze.current=q;return}ze.current!==q&&(ze.current=q,E([]),v(false));}},[q,w]);let We=Rt.useRef(null);Rt.useEffect(()=>{if(!K)return;let c=O=>{if(!We.current)return;let X=typeof O.composedPath=="function"?O.composedPath():[];We.current.contains(O.target)||X.includes(We.current)||ae(false);},k=O=>{O.key==="Escape"&&ae(false);};return document.addEventListener("mousedown",c,true),document.addEventListener("keydown",k,true),()=>{document.removeEventListener("mousedown",c,true),document.removeEventListener("keydown",k,true);}},[K]),Rt.useEffect(()=>{if(y)return;let c=requestAnimationFrame(()=>l(true));return ()=>cancelAnimationFrame(c)},[y]),Rt.useEffect(()=>{let c=y||le;if((c||je)&&(e==="prompting"||e==="complete")){let k=setTimeout(()=>dt.current?.focus(),c?100:tt+100);return ()=>clearTimeout(k)}},[je,y,le,e]),Rt.useEffect(()=>{if(e==="complete"&&De.current){let k=r.find(O=>O.type==="complete")?.data?.summary||t?.summary||Xn;E(O=>O[O.length-1]?.type==="applied"?O:[...O,{type:"applied",text:k}]),A(""),setTimeout(()=>dt.current?.focus(),200);}},[e,Ne,r,t?.summary]),Rt.useEffect(()=>{Ue.current&&(Ue.current.scrollTop=Ue.current.scrollHeight);},[M,e]);let Vt=()=>{T.trim()&&(De.current=T.trim(),E(c=>[...c,{type:"user",text:T.trim()}]),p(T.trim(),ce,q),A(""));},Jt=c=>{ye(c.session.containerId,c.session.containerName),_(c.session.containerId),ie(k=>{let O=k.filter(X=>X.id!==c.container.id);return [{...c.container,isPrimary:true,hasAccess:true},...O.map(X=>({...X,isPrimary:false}))]}),E([]),v(false),De.current="";},Vr=async c=>{if(!(!V||!Be||re)){Oe(c),we(null);try{let k=await fetch(`${S}/api/v1/preview/${encodeURIComponent(V.preview_session_id)}/containers/${encodeURIComponent(c)}/primary`,{method:"POST",headers:{Authorization:`Bearer ${P}`,...G()}});if(!k.ok){let O=await k.json().catch(()=>({}));throw new Error(O.error||`API error: ${k.status}`)}Jt(await k.json()),ae(!1);}catch(k){we(k instanceof Error?k.message:String(k));}finally{Oe(null);}}},Jr=async()=>{if(!V||!Be||re)return;let c=window.prompt("Container name","New container");if(!(!c||!c.trim())){Oe("__new__"),we(null);try{let k=await fetch(`${S}/api/v1/preview/${encodeURIComponent(V.preview_session_id)}/containers`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${P}`,...G()},body:JSON.stringify({name:c.trim()})});if(!k.ok){let O=await k.json().catch(()=>({}));throw new Error(O.error||`API error: ${k.status}`)}Jt(await k.json()),ae(!1);}catch(k){we(k instanceof Error?k.message:String(k));}finally{Oe(null);}}},qr=async()=>{if(!(!g||te||!ce)){ne(true);try{let c=await g(ce);E(k=>{let O=[...k];return O.length>=2&&O[O.length-1]?.type==="applied"?O.splice(-2,2):O.length>=1&&O[O.length-1]?.type==="applied"&&O.splice(-1,1),O}),c?.removed&&E([]);}catch{}finally{ne(false);}}},ft=()=>{if(y){d();return}if(le){ve?.close();return}F(true),l(false),setTimeout(()=>d(),tt);},Xr=y||le?{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:Rr,maxWidth:"100vw",background:"#ffffff",boxShadow:je?"-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:je?"translateX(0)":"translateX(100%)",transition:`transform ${tt}ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow ${tt}ms ease`,display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'},qt=Re.find(c=>c.id===q)?.name??(w?`Fork ${Ne}`:"Loading..."),pt=Qr.jsxs(Qr.Fragment,{children:[Qr.jsx("style",{children:`
21
+ `}),on.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&&on.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"#6b7280",fontSize:"11px"},children:[on.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"),l=zn[r.type]||lucideReact.Code,p=Wn[r.type]||"#9ca3af";if(r.type==="tool_use"){let g=String(r.data.category||"");l=Kn[g]||lucideReact.Wrench,p=Gn[g]||"#fbbf24";}return s?l=lucideReact.Loader2:!o&&r.type==="status"&&(l=lucideReact.Check,p="#4ade80"),on.jsxs("div",{style:{display:"flex",gap:"6px",marginBottom:"6px",lineHeight:1.625},children:[on.jsx(l,{style:{width:"12px",height:"12px",marginTop:"2px",flexShrink:0,color:p,...s?{animation:"__fork-spin 1s linear infinite"}:{}}}),on.jsx("span",{style:{color:o&&!i?"#d1d5db":"#6b7280",wordBreak:"break-all"},children:Lt(r)})]},n)})]})]})}var $r=35,eo="Working on Feature",to="Built Custom Feature",Pr=360,ot=350;function ro(e){return e.length<=$r?e:e.slice(0,$r-3).trimEnd()+"..."}function no({events:e}){let[t,r]=$t.useState("Setting up environment..."),[n,o]=$t.useState(true),i=$t.useRef(t),s=$t.useRef(false);return $t.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 l="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"){l=ro(Lt(g));break}}if(l!==i.current){o(false);let p=setTimeout(()=>{r(l),i.current=l,o(true);},200);return ()=>clearTimeout(p)}},[e]),on.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 oo({children:e}){let[t,r]=$t.useState(null);return $t.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?nn.createPortal(e,t):null}function st({state:e,fork:t,events:r,error:n,slotId:o,targetId:i,targetLabel:s,historyMode:l="slot",onSubmit:p,onUndo:g,onClose:d,baseUrl:S,apiKey:P,userId:_,userHash:x,appId:h,embedded:y=false}){let[T,A]=$t.useState(""),[M,C]=$t.useState([]),[I,v]=$t.useState(false),[b,c]=$t.useState(false),[$,F]=$t.useState(false),[u,f]=$t.useState(false),[m,L]=$t.useState(false),[K,te]=$t.useState(false),[N,z]=$t.useState(false),[Q,D]=$t.useState(false),[re,oe]=$t.useState(false),[ue,ee]=$t.useState(null),[ft,Be]=$t.useState(false),[Re,ie]=$t.useState([]),[Z,R]=$t.useState(null),[k,U]=$t.useState(false),[W,ae]=$t.useState(false),[Wr,Gt]=$t.useState(false),[Kr,Vt]=$t.useState(null),[G,Ue]=$t.useState(null),[Gr,Jt]=$t.useState(false),[pt,He]=$t.useState(false),[pe,Ee]=$t.useState(""),gt=$t.useRef(null),[qt,ge]=$t.useState(null),[Vr,Ce]=$t.useState(false),[Se,Xt]=$t.useState(null),mt=$t.useRef(null),Ne=$t.useRef(null),{resetAllForks:Jr,previewSession:q,currentContainerId:qr}=X(),me=q?.container_id??qr,De=!!(q&&Vr),le=Se!==null,Yt=$t.useRef(d);$t.useEffect(()=>{Yt.current=d;});let ht=$t.useRef(null),je=$t.useRef(false),Zt=typeof window<"u"&&"documentPictureInPicture"in window,Xr=async()=>{if(!(!Zt||le))try{let a=await window.documentPictureInPicture.requestWindow({width:Pr,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 w=document.adoptedStyleSheets??[];w.length>0&&(a.document.adoptedStyleSheets=[...w]);}catch{}a.addEventListener("pagehide",()=>{ht.current=null,Xt(null),je.current||Yt.current(),je.current=!1;},{once:!0}),ht.current=a,Xt(a);}catch(a){console.warn("[Fork] PiP open failed:",a);}},Yr=()=>{Se&&(je.current=true,Se.close());};$t.useEffect(()=>()=>{je.current=true,ht.current?.close();},[]);let ce=i??o??"",ze=(s||ce).replace(/[-_]+/g," ").replace(/\b\w/g,a=>a.toUpperCase()),We=$t.useRef(""),Ke=y?true:b&&!$,Zr=r.find(a=>{let w=a.data;return a.type==="status"&&w.summary})?.data?.summary||t?.summary||eo,he=r.find(a=>{let w=a.data;return (a.type==="status"||a.type==="complete")&&typeof w?.estimateMinutes=="number"})?.data?.estimateMinutes??t?.estimateMinutes;$t.useEffect(()=>{if(l==="none"){v(true);return}if(!S||!P||!_||!ce||I||!k)return;if(q&&!Z){C([]),v(true);return}let a=new AbortController,w=new URLSearchParams({userId:_});if(x&&w.set("userHash",x),Z&&w.set("containerId",Z),l==="slot")w.set("slotId",ce);else if(l==="boundary"){if(!h){v(true);return}w.set("boundaryId",ce),w.set("appId",h);}let O={Authorization:`Bearer ${P}`,...V()};return h&&(O["X-Fork-App-Id"]=h),fetch(`${S}/api/v1/forks/history?${w.toString()}`,{headers:O,signal:a.signal}).then(J=>J.ok?J.json():[]).then(J=>{if(a.signal.aborted)return;let Je=[];for(let kt of J)kt.role==="user"?Je.push({type:"user",text:kt.content}):Je.push({type:"applied",text:kt.content});C(Je),v(true);}).catch(()=>{a.signal.aborted||v(true);}),()=>{a.abort();}},[P,h,S,I,l,ce,x,_,Z,k,q?.preview_session_id]),$t.useEffect(()=>{e==="complete"&&D(false);},[e]),$t.useEffect(()=>{if(y&&l==="none"){ie([]),R(null),U(true),Ce(false);return}if(q){let a=false;return U(false),Ce(false),ge(null),fetch(`${S}/api/v1/preview/${encodeURIComponent(q.preview_session_id)}/containers`,{headers:{Authorization:`Bearer ${P}`,...V()}}).then(w=>{if(!w.ok)throw new Error(`${w.status}`);return w.json()}).then(w=>{a||(ie(w.containers),R(w.currentContainerId??q.container_id??null),Ce(true));}).catch(w=>{a||(Ce(false),ge(w instanceof Error?w.message:String(w)),me?(ie([{id:me,name:q.container_name||"Primary container",createdAt:"",hasAccess:true,isPrimary:true}]),R(me)):(ie([]),R(null)));}).finally(()=>{a||U(true);}),()=>{a=true;}}me?(ie([{id:me,name:"Primary container",createdAt:""}]),R(me)):(ie([]),R(null)),U(true),Ce(false);},[P,me,S,y,l,q?.container_id,q?.container_name,q?.preview_session_id]);let Ge=$t.useRef(void 0);$t.useEffect(()=>{if(k){if(Ge.current===void 0){Ge.current=Z;return}Ge.current!==Z&&(Ge.current=Z,C([]),v(false));}},[Z,k]);let Ve=$t.useRef(null);$t.useEffect(()=>{if(!W)return;let a=O=>{if(!Ve.current)return;let J=typeof O.composedPath=="function"?O.composedPath():[];Ve.current.contains(O.target)||J.includes(Ve.current)||ae(false);},w=O=>{O.key==="Escape"&&ae(false);};return document.addEventListener("mousedown",a,true),document.addEventListener("keydown",w,true),()=>{document.removeEventListener("mousedown",a,true),document.removeEventListener("keydown",w,true);}},[W]),$t.useEffect(()=>{W||(He(false),Ee(""));},[W]),$t.useEffect(()=>{pt&&(gt.current?.focus(),gt.current?.select());},[pt]),$t.useEffect(()=>{if(y)return;let a=requestAnimationFrame(()=>c(true));return ()=>cancelAnimationFrame(a)},[y]),$t.useEffect(()=>{let a=y||le;if((a||Ke)&&(e==="prompting"||e==="complete")){let w=setTimeout(()=>mt.current?.focus(),a?100:ot+100);return ()=>clearTimeout(w)}},[Ke,y,le,e]),$t.useEffect(()=>{if(e==="complete"&&We.current){let w=r.find(O=>O.type==="complete")?.data?.summary||t?.summary||to;C(O=>O[O.length-1]?.type==="applied"?O:[...O,{type:"applied",text:w}]),A(""),setTimeout(()=>mt.current?.focus(),200);}},[e,ze,r,t?.summary]),$t.useEffect(()=>{Ne.current&&(Ne.current.scrollTop=Ne.current.scrollHeight);},[M,e]);let Qt=()=>{T.trim()&&(We.current=T.trim(),C(a=>[...a,{type:"user",text:T.trim()}]),p(T.trim(),ce,Z),A(""));},er=a=>{ke(a.session.containerId,a.session.containerName),R(a.session.containerId),ie(w=>{let O=w.filter(J=>J.id!==a.container.id);return [{...a.container,isPrimary:true,hasAccess:true},...O.map(J=>({...J,isPrimary:false}))]}),C([]),v(false),We.current="";},Qr=async a=>{if(!(!q||!De||G)){Ue(a),ge(null);try{let w=await fetch(`${S}/api/v1/preview/${encodeURIComponent(q.preview_session_id)}/containers/${encodeURIComponent(a)}/primary`,{method:"POST",headers:{Authorization:`Bearer ${P}`,...V()}});if(!w.ok){let O=await w.json().catch(()=>({}));throw new Error(O.error||`API error: ${w.status}`)}er(await w.json()),ae(!1);}catch(w){ge(w instanceof Error?w.message:String(w));}finally{Ue(null);}}},tr=async a=>{if(!q||!De||G)return;let w=a.trim();if(w){Ue("__new__"),ge(null);try{let O=await fetch(`${S}/api/v1/preview/${encodeURIComponent(q.preview_session_id)}/containers`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${P}`,...V()},body:JSON.stringify({name:w})});if(!O.ok){let J=await O.json().catch(()=>({}));throw new Error(J.error||`API error: ${O.status}`)}er(await O.json()),He(!1),Ee(""),ae(!1);}catch(O){ge(O instanceof Error?O.message:String(O));}finally{Ue(null);}}},en=async()=>{if(!(!g||re||!ce)){oe(true);try{let a=await g(ce);C(w=>{let O=[...w];return O.length>=2&&O[O.length-1]?.type==="applied"?O.splice(-2,2):O.length>=1&&O[O.length-1]?.type==="applied"&&O.splice(-1,1),O}),a?.removed&&C([]);}catch{}finally{oe(false);}}},yt=()=>{if(y){d();return}if(le){Se?.close();return}F(true),c(false),setTimeout(()=>d(),ot);},tn=y||le?{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:Pr,maxWidth:"100vw",background:"#ffffff",boxShadow:Ke?"-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:Ke?"translateX(0)":"translateX(100%)",transition:`transform ${ot}ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow ${ot}ms ease`,display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'},rr=Re.find(a=>a.id===Z)?.name??(k?`Fork ${ze}`:"Loading..."),bt=on.jsxs(on.Fragment,{children:[on.jsx("style",{children:`
22
22
  @keyframes __fork-pulse {
23
23
  0%, 100% { opacity: 1; }
24
24
  50% { opacity: 0.5; }
@@ -40,5 +40,5 @@
40
40
  scrollbar-width: thin;
41
41
  scrollbar-color: rgba(0, 0, 0, 0.12) transparent;
42
42
  }
43
- `}),Qr.jsxs("div",{className:"__fork-panel",style:Xr,children:[Qr.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:[Qr.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:[Qr.jsx(Ze,{style:{width:16,height:16,color:"#1c4587",cursor:"pointer",flexShrink:0},onDoubleClick:async c=>{if(c.stopPropagation(),!ct&&confirm("Reset all forks? This will remove all forked components.")){Le(true);try{let k=await jr();`${k?.deleted??0}`,E([]),A(""),D(!1),ft();}catch(k){console.error("[Fork] Reset failed:",k);}finally{Le(false);}}}}),e==="running"?Qr.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:Gr}):Re.length===0&&!Be?Qr.jsxs("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:["Fork ",Ne]}):Be?Qr.jsxs("div",{ref:We,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[Qr.jsxs("button",{type:"button",onClick:()=>{ae(c=>!c);},onMouseEnter:()=>Nt(true),onMouseLeave:()=>Nt(false),"aria-haspopup":"menu","aria-expanded":K,style:{display:"inline-flex",alignItems:"center",gap:4,padding:"3px 6px",border:"1px solid transparent",borderRadius:6,background:Br||K?"#f3f4f6":"transparent",fontSize:13,fontWeight:600,color:"#111827",fontFamily:"inherit",cursor:"pointer",maxWidth:180,minWidth:0,transition:"background-color 0.12s"},children:[Qr.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:qt}),Qr.jsx(lucideReact.ChevronDown,{style:{width:12,height:12,color:"#6b7280",flexShrink:0,transform:K?"rotate(180deg)":void 0,transition:"transform 0.15s"}})]}),K&&Qr.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:[Re.map(c=>{let k=c.id===q,O=Hr===c.id,X=re===c.id;return Qr.jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>Dt(c.id),onMouseLeave:()=>Dt(null),onClick:()=>{c.id!==q&&Vr(c.id);},disabled:!!re,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:O?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:re?"default":"pointer",textAlign:"left",fontWeight:k?600:400,opacity:re&&!X?.55:1},children:[Qr.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:k&&Qr.jsx(lucideReact.Check,{style:{width:12,height:12}})}),Qr.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:X?"Switching...":c.name})]},c.id)}),Qr.jsx("div",{style:{height:1,background:"#e5e7eb",margin:"4px 0"}}),Qr.jsx("button",{type:"button",role:"menuitem",onMouseEnter:()=>jt(true),onMouseLeave:()=>jt(false),onClick:()=>{Jr();},disabled:!!re,style:{display:"flex",alignItems:"center",width:"100%",padding:"6px 8px",border:"none",background:Nr?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:re?"default":"pointer",textAlign:"left",opacity:re&&re!=="__new__"?.55:1},children:re==="__new__"?"Creating...":"+ New container"}),zt&&Qr.jsx("div",{style:{padding:"6px 8px",fontSize:11,lineHeight:1.35,color:"#b91c1c"},children:zt})]})]}):Qr.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:qt}),e==="running"&&Qr.jsx("span",{title:ge?`Estimated ~${ge} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:ge?"#1c4587":"#9ca3af",backgroundColor:ge?"rgba(28, 69, 135, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:ge?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:ge?`~${ge}m`:"~ m"}),e==="complete"&&Qr.jsx("div",{style:{height:6,width:6,backgroundColor:"#1c4587",borderRadius:"50%",flexShrink:0}})]}),!y&&Qr.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[Gt&&Qr.jsx("button",{onClick:le?Kr:Wr,onMouseEnter:()=>L(true),onMouseLeave:()=>L(false),title:le?"Redock to sidebar":"Pop out into window",style:{padding:6,borderRadius:6,color:m?"#4b5563":"#9ca3af",backgroundColor:m?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:le?Qr.jsx(lucideReact.PictureInPicture,{style:{width:16,height:16}}):Qr.jsx(lucideReact.PictureInPicture2,{style:{width:16,height:16}})}),Qr.jsx("button",{onClick:ft,onMouseEnter:()=>f(true),onMouseLeave:()=>f(false),style:{padding:6,borderRadius:6,color:u?"#4b5563":"#9ca3af",backgroundColor:u?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:Qr.jsx(lucideReact.X,{style:{width:16,height:16}})})]})]}),Qr.jsxs("div",{ref:Ue,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[e==="prompting"&&M.length===0&&Qr.jsx("div",{style:{padding:"24px 20px",textAlign:"center"},children:Qr.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."})}),M.length>0&&Qr.jsx("div",{style:{padding:"16px 16px 0 16px"},children:M.map((c,k)=>Qr.jsx("div",{style:{marginBottom:k<M.length-1?10:0},children:c.type==="user"?Qr.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexDirection:"row-reverse"},children:[Qr.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:Qr.jsx(lucideReact.User,{style:{width:13,height:13,color:"#6b7280"}})}),Qr.jsx("div",{style:{backgroundColor:"#f3f4f6",borderRadius:"12px 4px 12px 12px",padding:"8px 12px",fontSize:13,color:"#374151",lineHeight:1.5,maxWidth:"75%"},children:c.text})]}):Qr.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[Qr.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#f0fdf4",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:Qr.jsx(lucideReact.Check,{style:{width:13,height:13,color:"#9ca3af"}})}),Qr.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:[Qr.jsx("span",{style:{flex:1},children:c.text}),g&&k===M.length-1&&e!=="running"&&Qr.jsxs("button",{onClick:O=>{O.stopPropagation(),qr();},onMouseEnter:()=>Z(k),onMouseLeave:()=>Z(null),disabled:te,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:ue===k?"rgba(0,0,0,0.06)":"transparent",color:ue===k?"#6b7280":"#d1d5db",cursor:te?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:te?.4:1,flexShrink:0},children:[Qr.jsx(lucideReact.Undo2,{style:{width:12,height:12}}),ue===k&&Qr.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"})]})]})]})},k))}),e==="running"&&Qr.jsx("div",{style:{padding:16},children:Qr.jsxs("div",{onClick:()=>D(!Y),style:{backgroundColor:"#1a1a2e",borderRadius:12,overflow:"hidden",cursor:"pointer",transition:"all 0.3s cubic-bezier(0.22, 1, 0.36, 1)"},children:[Qr.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px"},children:[Qr.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[Qr.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:Qr.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),Qr.jsx(Zn,{events:r})]}),Qr.jsx("div",{style:{color:"#6b7280",flexShrink:0,marginLeft:8,transition:"transform 0.2s ease",transform:Y?"rotate(180deg)":"rotate(0deg)"},children:Qr.jsx(lucideReact.ChevronDown,{style:{width:14,height:14}})})]}),Qr.jsx("div",{style:{maxHeight:Y?320:0,opacity:Y?1:0,transition:"max-height 0.35s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.25s ease",overflow:"hidden"},children:Qr.jsx("div",{style:{borderTop:"1px solid rgba(255,255,255,0.08)",maxHeight:320,overflowY:"auto"},children:Qr.jsx(wr,{events:r})})})]})}),e==="error"&&Qr.jsxs("div",{style:{padding:"20px 16px",textAlign:"center"},children:[Qr.jsx("div",{style:{width:36,height:36,backgroundColor:"#fef2f2",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 10px auto"},children:Qr.jsx(lucideReact.X,{style:{width:18,height:18,color:"#ef4444"}})}),Qr.jsx("p",{style:{fontSize:12,color:"#6b7280",marginBottom:10,maxWidth:260,margin:"0 auto 10px auto"},children:n}),Qr.jsxs("button",{onClick:()=>{let c=t?.prompt||De.current;c&&p(c,ce);},onMouseEnter:()=>z(true),onMouseLeave:()=>z(false),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,color:"#4f46e5",backgroundColor:N?"#e0e7ff":"#eef2ff",border:"none",cursor:"pointer",transition:"background-color 0.15s",fontFamily:"inherit"},children:[Qr.jsx(lucideReact.RotateCcw,{style:{width:12,height:12}})," Try Again"]})]})]}),e!=="running"&&Qr.jsx("div",{style:{padding:"8px 12px 12px 12px",borderTop:"1px solid rgba(229, 231, 235, 0.6)",flexShrink:0},children:Qr.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:[Qr.jsx("textarea",{ref:dt,value:T,onChange:c=>{A(c.target.value),c.target.style.height="auto",c.target.style.height=Math.min(c.target.scrollHeight,160)+"px";},onKeyDown:c=>{c.key==="Enter"&&!c.shiftKey&&(c.preventDefault(),Vt()),c.key==="Escape"&&!y&&ft();},placeholder:M.length>0?"Ask for another change...":`Describe your ideal ${Ne.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"}}),Qr.jsx("button",{onClick:Vt,disabled:!T.trim(),onMouseEnter:()=>ee(true),onMouseLeave:()=>ee(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:T.trim()?1:.25,transform:W&&T.trim()?"scale(1.1)":"scale(1)",background:T.trim()?"#1c4587":"rgba(0,0,0,0.12)",border:"none",cursor:T.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:Qr.jsx(lucideReact.ArrowUp,{style:{width:13,height:13}})})]})})]})]});return y?pt:le&&ve?Zr.createPortal(pt,ve.document.body):Qr.jsx(Qn,{children:pt})}function Er(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 Pt(e){let{apiKey:t,userId:r,userHash:n,baseUrl:o,appId:i,previewSession:s,refreshModuleManifest:a,queueBoundaryAnimation:p}=J(),[g,d]=Rt.useState("idle"),[S,P]=Rt.useState(null),[R,x]=Rt.useState([]),[h,y]=Rt.useState(null),T=Rt.useRef(null),A=Rt.useCallback(()=>{d("prompting"),x([]),y(null),P(null);},[]),M=Rt.useCallback(()=>{d("idle"),T.current&&(T.current.close(),T.current=null);},[]);Rt.useEffect(()=>{s&&s.target.kind==="module"&&s.target.id===e&&d(v=>v==="idle"?"prompting":v);},[s?.preview_session_id,s?.target.id,e]);let E=Rt.useCallback(async(v,b)=>{try{if(!i)throw new Error("ForkProvider requires appId for module boundary prompts.");d("running"),x([]),y(null);let l;if(s){let u=await fetch(`${o}/api/v1/preview/${encodeURIComponent(s.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...G()},body:JSON.stringify({prompt:v,...s.fork_id?{fork_id:s.fork_id}:{}})});if(!u.ok){let L=await u.json().catch(()=>({}));throw new Error(L.error||`API error: ${u.status}`)}let f=await u.json();f.container_id&&ye(f.container_id,f.container_name),Ae(f.fork_id),l=await(await fetch(`${o}/api/v1/forks/${f.fork_id}`,{headers:{Authorization:`Bearer ${t}`,...G()}})).json();}else {let u={userId:r,prompt:v,boundaryId:e,appId:i};b&&(u.containerId=b),n&&(u.userHash=n);let f=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(u)});if(!f.ok){let m=await f.json().catch(()=>({}));throw new Error(m.error||`API error: ${f.status}`)}l=await f.json();}P(l);let $=new URLSearchParams({key:t});n&&($.set("userId",r),$.set("userHash",n));let F=new EventSource(`${o}/api/v1/forks/${l.id}/events?${$.toString()}`);T.current=F,F.onmessage=u=>{try{let f=JSON.parse(u.data);if(x(m=>[...m,f]),f.type==="complete"){let m=f.data;p(e,l.id),a().catch(()=>{}).finally(()=>{let L={...l,status:"complete",moduleUrl:m.moduleUrl,cssUrls:m.cssUrls,summary:m.summary,completedAt:new Date().toISOString()};P(L),d("complete"),F.close();});}else if(f.type==="error"){let m=f.data;y(m.error||"Unknown error"),d("error"),F.close();}}catch{}},F.onerror=()=>{fetch(`${o}/api/v1/forks/${l.id}`,{headers:{Authorization:`Bearer ${t}`}}).then(u=>u.json()).then(u=>{P(u),u.status==="complete"?(p(e,u.id),a().catch(()=>{}),d("complete")):u.status==="error"&&(y(u.error||"Fork generation failed"),d("error"));}).catch(()=>{y("Connection lost"),d("error");}),F.close();};}catch(l){y(l.message),d("error");}},[t,i,o,e,s,p,a,n,r]),I=Rt.useCallback(async()=>{try{if(!i)throw new Error("ForkProvider requires appId for boundary undo.");let v={userId:r,boundaryId:e,appId:i};n&&(v.userHash=n);let b=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(v)});if(!b.ok){let $=await b.json().catch(()=>({}));throw new Error($.error||`API error: ${b.status}`)}let l=await b.json();return await a().catch(()=>{}),l.removed?(P(null),d("prompting")):l.fork&&(P(l.fork),d("complete")),l}catch(v){throw y(v.message),v}},[t,i,o,e,a,n,r]);return {state:g,fork:S,events:R,error:h,open:A,close:M,startFork:E,undoFork:I}}function Ar(e){let{state:t,fork:r,events:n,error:o,open:i,close:s,startFork:a,undoFork:p}=Pt(e);return {state:t,fork:r,events:n,error:o,isOpen:t!=="idle",open:i,close:s,submit:a,undo:p}}function Tt(){let{apiKey:e,userId:t,userHash:r,baseUrl:n,previewSession:o,setSlotFork:i,clearSlotFork:s,skipAnimationForSlot:a}=J(),[p,g]=Rt.useState("idle"),[d,S]=Rt.useState(null),[P,R]=Rt.useState([]),[x,h]=Rt.useState(null),y=Rt.useRef(null),T=Rt.useCallback(()=>{g("prompting"),R([]),h(null),S(null);},[]),A=Rt.useCallback(()=>{g("idle"),y.current&&(y.current.close(),y.current=null);},[]);Rt.useEffect(()=>{o&&o.target.kind==="slot"&&g(I=>I==="idle"?"prompting":I);},[o?.preview_session_id,o?.target.kind]);let M=Rt.useCallback(async(I,v,b)=>{try{g("running"),R([]),h(null);let l;if(o){let u=await fetch(`${n}/api/v1/preview/${encodeURIComponent(o.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...G()},body:JSON.stringify({prompt:I,...o.fork_id?{fork_id:o.fork_id}:{}})});if(!u.ok){let L=await u.json().catch(()=>({}));throw new Error(L.error||`API error: ${u.status}`)}let f=await u.json();f.container_id&&ye(f.container_id,f.container_name),Ae(f.fork_id),l=await(await fetch(`${n}/api/v1/forks/${f.fork_id}`,{headers:{Authorization:`Bearer ${e}`,...G()}})).json();}else {let u={userId:t,prompt:I};v&&(u.slotId=v),b&&(u.containerId=b),r&&(u.userHash=r);let f=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(u)});if(!f.ok){let m=await f.json().catch(()=>({}));throw new Error(m.error||`API error: ${f.status}`)}l=await f.json();}S(l);let $=new URLSearchParams({key:e});r&&($.set("userId",t),$.set("userHash",r));let F=new EventSource(`${n}/api/v1/forks/${l.id}/events?${$.toString()}`);y.current=F,F.onmessage=u=>{try{let f=JSON.parse(u.data);if(R(m=>[...m,f]),f.type==="complete"){let m=f.data,L={...l,status:"complete",bundleUrl:m.bundleUrl,summary:m.summary,completedAt:new Date().toISOString()};S(L),g("complete"),v&&m.bundleUrl&&i(v,L),F.close();}else if(f.type==="error"){let m=f.data;h(m.error||"Unknown error"),g("error"),F.close();}}catch{}},F.onerror=()=>{fetch(`${n}/api/v1/forks/${l.id}`,{headers:{Authorization:`Bearer ${e}`}}).then(u=>u.json()).then(u=>{S(u),u.status==="complete"?(g("complete"),v&&u.bundleUrl&&i(v,u)):u.status==="error"&&(h(u.error||"Fork generation failed"),g("error"));}).catch(()=>{h("Connection lost"),g("error");}),F.close();};}catch(l){h(l.message),g("error");}},[e,t,r,n,o,i]),E=Rt.useCallback(async I=>{try{let v={userId:t,slotId:I};r&&(v.userHash=r);let b=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(v)});if(!b.ok){let $=await b.json().catch(()=>({}));throw new Error($.error||`API error: ${b.status}`)}let l=await b.json();return a(I),l.removed?(s(I),S(null),g("prompting")):l.fork&&(i(I,l.fork),S(l.fork)),l}catch(v){throw h(v.message),v}},[e,t,r,n,s,i]);return {state:p,fork:d,events:P,error:x,open:T,close:A,startFork:M,undoFork:E}}function $r(){let{state:e,fork:t,events:r,error:n,open:o,close:i,startFork:s,undoFork:a}=Tt();return {state:e,fork:t,events:r,error:n,isOpen:e!=="idle",open:o,close:i,submit:s,undo:a}}function Mt(e){let t=Er(e),r=$r(),n=Ar(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:i,userId:s,userHash:a,appId:p}=J(),g=t.type==="slot"?r:n,d=t.type==="slot"?"slot":"boundary",S=t.id,P=t.title,R=Rt.useCallback((h,y,T)=>t.type==="slot"?r.submit(h,y??t.id,T):n.submit(h,T),[n,r,t]),x=Rt.useCallback(h=>t.type==="slot"?r.undo(h??t.id):n.undo(),[n,r,t]);return {...g,target:t,targetId:S,targetLabel:P,historyMode:d,submit:R,undo:x,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:d}:{targetId:S,targetLabel:P,historyMode:d},onSubmit:R,onUndo:x,onClose:g.close,baseUrl:o,apiKey:i,userId:s,userHash:a,appId:p}}}function Ie(e){let{embedded:t}=e,r=Mt(e);return t?Qr.jsx(rt,{...r.panelProps,embedded:true}):r.isOpen?Qr.jsx(rt,{...r.panelProps}):Qr.jsx(At,{...r.buttonProps})}function so({boundaryId:e,title:t}){return Qr.jsx(Ie,{boundaryId:e,title:t})}function Lt(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 Pr(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 Ot(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 Tr(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 a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Mr(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 a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Ir(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 Ut(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 d=0;d<e.length;d+=1){let{rect:S,borderRadius:P}=e[d],R=S.left-.5,x=S.top-.5,h=S.width+1,y=S.height+1,T=Math.min(P+.5,h/2,y/2),A=Ir(R,x,h,y,T),M=`__fork-glow-${d}`,E=document.createElementNS(t,"filter");E.setAttribute("id",M),E.setAttribute("x","-100%"),E.setAttribute("y","-100%"),E.setAttribute("width","300%"),E.setAttribute("height","300%");let I=document.createElementNS(t,"feGaussianBlur");I.setAttribute("in","SourceGraphic"),I.setAttribute("stdDeviation","8"),E.appendChild(I),o.appendChild(E);let v=`__fork-mask-${d}`,b=document.createElementNS(t,"mask");b.setAttribute("id",v),b.setAttribute("maskUnits","userSpaceOnUse"),b.setAttribute("x",String(R-200)),b.setAttribute("y",String(x-200)),b.setAttribute("width",String(h+400)),b.setAttribute("height",String(y+400));let l=document.createElementNS(t,"rect");l.setAttribute("x",String(R-200)),l.setAttribute("y",String(x-200)),l.setAttribute("width",String(h+400)),l.setAttribute("height",String(y+400)),l.setAttribute("fill","white"),b.appendChild(l);let $=document.createElementNS(t,"path");$.setAttribute("d",A),$.setAttribute("fill","black"),b.appendChild($),o.appendChild(b);let F=document.createElementNS(t,"g");F.setAttribute("mask",`url(#${v})`),F.setAttribute("opacity","0");let u=document.createElementNS(t,"g");u.setAttribute("filter",`url(#${M})`);let f=document.createElementNS(t,"path");f.setAttribute("d",A),f.setAttribute("fill","none"),f.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),f.setAttribute("stroke-width","6"),f.setAttribute("stroke-linecap","round"),u.appendChild(f),F.appendChild(u),n.appendChild(F);let m=document.createElementNS(t,"path");m.setAttribute("d",A),m.setAttribute("fill","none"),m.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),m.setAttribute("stroke-width","2"),m.setAttribute("stroke-linecap","round"),m.setAttribute("opacity","0"),n.appendChild(m),i.push(f,m),f.__group=F;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let d=0;d<i.length;d+=2){let S=i[d],P=i[d+1],R=S.__group;if(!R)continue;let x=P.getTotalLength(),h=S.getTotalLength();if(x<=0)continue;let y=x*.35;P.setAttribute("stroke-dasharray",`${y} ${x-y}`),P.setAttribute("stroke-dashoffset","0"),s.push(P.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*x,opacity:.92,offset:.06},{strokeDashoffset:-2*x,opacity:.92,offset:.92},{strokeDashoffset:-2.25*x,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let T=h*.35;S.setAttribute("stroke-dasharray",`${T} ${h-T}`),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(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 a=false,p=()=>{if(a)return;a=true,clearTimeout(g);for(let S of s)try{S.cancel();}catch{}let d=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});d.onfinish=()=>r.remove(),window.removeEventListener("click",p);},g=setTimeout(p,14500);return setTimeout(()=>{a||window.addEventListener("click",p);},500),p}function Lr(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:a,borderRadius:p}of e){let g=document.createElementNS(t,"path");g.setAttribute("d",Ir(a.left,a.top,a.width,a.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 lt=new Map,Bt=new Map;function lo(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function Ur(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 co(e){if(!e||typeof document>"u")return Promise.resolve();let t=lt.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 a=()=>{r.removeEventListener("load",a),r.removeEventListener("error",p),i();},p=()=>{r.removeEventListener("load",a),r.removeEventListener("error",p),s(new Error(`Failed to load boundary stylesheet: ${e}`));};r.addEventListener("load",a,{once:true}),r.addEventListener("error",p,{once:true});});return lt.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 lt.delete(e),o});return lt.set(e,n),n}function uo(e){let t=Bt.get(e);if(t)return t;let r=import(e).catch(n=>{throw Bt.delete(e),n});return Bt.set(e,r),r}async function fo(e,t,r){if(e)try{await Promise.all(e.cssUrls.map(i=>co(i)));let o=await uo(e.moduleUrl);return Ur(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 Ur(n,r)}function po(e){function t(r){let{appId:n,moduleOverridesEnabled:o,moduleManifestReady:i,moduleManifestVersion:s,registerBoundary:a,getBoundaryOverride:p,consumeBoundaryAnimation:g}=J(),[d,S]=Rt.useState(null),[P,R]=Rt.useState(null),x=Rt.useRef(null),h=Rt.useRef(null),y=Rt.useRef(null),T=Rt.useRef(false),A=Rt.useRef(null),M=Rt.useRef(null),E=p(e.id),I=E?`override:${E.id}`:"original",v=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if(Rt.useEffect(()=>()=>{M.current&&(clearTimeout(M.current),M.current=null),A.current&&(A.current.remove(),A.current=null);},[]),Rt.useEffect(()=>{a({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[n,a,e.id,e.exportName,v]),Rt.useEffect(()=>{if(o&&!i&&!d||h.current===I&&d)return;let b=false;return R(null),fo(E,e.original,e.exportName).then(l=>{if(!b){if(E?.id&&g(e.id,E.id)&&x.current){let $=Lt(x.current);if($){let F=Ot($);F.length>0&&(y.current=F,T.current=true,M.current&&(clearTimeout(M.current),M.current=null),A.current&&A.current.remove(),A.current=Pr($));}}h.current=I,Rt.startTransition(()=>{S(()=>l);});}}).catch(l=>{b||R(lo(l));}),()=>{b=true;}},[g,I,o,i,s,E?.id,E?.moduleUrl,E?.integrity,E?.cssUrls.join("|"),e.exportName,e.original,d]),Rt.useEffect(()=>{if(!T.current||!d||!x.current)return;let b=false;return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(b||!x.current)return;let l=y.current,$=Lt(x.current);if(y.current=null,T.current=false,!l||!$){A.current&&(A.current.remove(),A.current=null);return}let F=Ot($),u=Tr(l,F),f=Mr(l,F),m=A.current;if(f.length>0&&m){let L=Lr(f);M.current=setTimeout(()=>{M.current=null;let W=400;m.animate([{opacity:1},{opacity:0}],{duration:W,fill:"forwards"}),L.animate([{opacity:1},{opacity:0}],{duration:W,fill:"forwards"}),setTimeout(()=>{m.remove(),L.remove(),A.current===m&&(A.current=null),u.length>0&&Ut(u);},W);},3500);}else m&&(m.remove(),A.current===m&&(A.current=null)),u.length>0&&Ut(u);});}),()=>{b=true;}},[d]),P)throw P;return d?Qr.jsx("div",{ref:x,style:{display:"contents"},children:Qr.jsx(d,{...r})}):Qr.jsx(Qr.Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function mo({slotId:e,title:t,slotLabel:r}){return Qr.jsx(Ie,{slotId:e,title:t,slotLabel:r})}
44
- exports.ForkBoundaryUI=so;exports.ForkButton=At;exports.ForkChatInterface=Ie;exports.ForkPanel=rt;exports.ForkProvider=mn;exports.ForkSlot=An;exports.ForkUI=mo;exports.clearCachedManifest=dn;exports.forkable=po;exports.loadManifest=qe;exports.manifestDiffers=un;exports.readCachedManifest=ln;exports.registerForkShared=ht;exports.useBoundaryFork=Pt;exports.useFork=Tt;exports.useForkChatPanel=Mt;exports.usePreviewSession=Je;exports.writeCachedManifest=cn;
43
+ `}),on.jsxs("div",{className:"__fork-panel",style:tn,children:[on.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:[on.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:[on.jsx(tt,{style:{width:16,height:16,color:"#1c4587",cursor:"pointer",flexShrink:0},onDoubleClick:async a=>{if(a.stopPropagation(),!ft&&confirm("Reset all forks? This will remove all forked components.")){Be(true);try{let w=await Jr();`${w?.deleted??0}`,C([]),A(""),D(!1),yt();}catch(w){console.error("[Fork] Reset failed:",w);}finally{Be(false);}}}}),e==="running"?on.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:Zr}):Re.length===0&&!De?on.jsxs("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:["Fork ",ze]}):De?on.jsxs("div",{ref:Ve,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[on.jsxs("button",{type:"button",onClick:()=>{ae(a=>!a);},onMouseEnter:()=>Gt(true),onMouseLeave:()=>Gt(false),"aria-haspopup":"menu","aria-expanded":W,style:{display:"inline-flex",alignItems:"center",gap:4,padding:"3px 6px",border:"1px solid transparent",borderRadius:6,background:Wr||W?"#f3f4f6":"transparent",fontSize:13,fontWeight:600,color:"#111827",fontFamily:"inherit",cursor:"pointer",maxWidth:180,minWidth:0,transition:"background-color 0.12s"},children:[on.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:rr}),on.jsx(lucideReact.ChevronDown,{style:{width:12,height:12,color:"#6b7280",flexShrink:0,transform:W?"rotate(180deg)":void 0,transition:"transform 0.15s"}})]}),W&&on.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:[Re.map(a=>{let w=a.id===Z,O=Kr===a.id,J=G===a.id;return on.jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>Vt(a.id),onMouseLeave:()=>Vt(null),onClick:()=>{a.id!==Z&&Qr(a.id);},disabled:!!G,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:O?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:G?"default":"pointer",textAlign:"left",fontWeight:w?600:400,opacity:G&&!J?.55:1},children:[on.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:w&&on.jsx(lucideReact.Check,{style:{width:12,height:12}})}),on.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:J?"Switching...":a.name})]},a.id)}),on.jsx("div",{style:{height:1,background:"#e5e7eb",margin:"4px 0"}}),pt?on.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"4px 4px"},children:[on.jsx("input",{ref:gt,type:"text",value:pe,placeholder:"Container name",disabled:G==="__new__",onChange:a=>Ee(a.target.value),onKeyDown:a=>{a.key==="Enter"?(a.preventDefault(),tr(pe)):a.key==="Escape"&&(a.preventDefault(),a.stopPropagation(),He(false),Ee(""));},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";}}),on.jsx("button",{type:"button",onClick:()=>{tr(pe);},disabled:!pe.trim()||G==="__new__",title:"Create",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:26,height:26,border:"none",borderRadius:4,background:!pe.trim()||G==="__new__"?"#e5e7eb":"#1c4587",color:!pe.trim()||G==="__new__"?"#9ca3af":"#ffffff",cursor:!pe.trim()||G==="__new__"?"default":"pointer",flexShrink:0},children:G==="__new__"?on.jsx("span",{style:{width:10,height:10,border:"1.5px solid currentColor",borderTopColor:"transparent",borderRadius:"50%",animation:"__fork-spin 0.7s linear infinite"}}):on.jsx(lucideReact.Check,{style:{width:12,height:12}})})]}):on.jsx("button",{type:"button",role:"menuitem",onMouseEnter:()=>Jt(true),onMouseLeave:()=>Jt(false),onClick:()=>{G||(ge(null),Ee(""),He(true));},disabled:!!G,style:{display:"flex",alignItems:"center",width:"100%",padding:"6px 8px",border:"none",background:Gr?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:G?"default":"pointer",textAlign:"left",opacity:G&&G!=="__new__"?.55:1},children:"+ New container"}),qt&&on.jsx("div",{style:{padding:"6px 8px",fontSize:11,lineHeight:1.35,color:"#b91c1c"},children:qt})]})]}):on.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:rr}),e==="running"&&on.jsx("span",{title:he?`Estimated ~${he} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:he?"#1c4587":"#9ca3af",backgroundColor:he?"rgba(28, 69, 135, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:he?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:he?`~${he}m`:"~ m"}),e==="complete"&&on.jsx("div",{style:{height:6,width:6,backgroundColor:"#1c4587",borderRadius:"50%",flexShrink:0}})]}),!y&&on.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[Zt&&on.jsx("button",{onClick:le?Yr:Xr,onMouseEnter:()=>L(true),onMouseLeave:()=>L(false),title:le?"Redock to sidebar":"Pop out into window",style:{padding:6,borderRadius:6,color:m?"#4b5563":"#9ca3af",backgroundColor:m?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:le?on.jsx(lucideReact.PictureInPicture,{style:{width:16,height:16}}):on.jsx(lucideReact.PictureInPicture2,{style:{width:16,height:16}})}),on.jsx("button",{onClick:yt,onMouseEnter:()=>f(true),onMouseLeave:()=>f(false),style:{padding:6,borderRadius:6,color:u?"#4b5563":"#9ca3af",backgroundColor:u?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:on.jsx(lucideReact.X,{style:{width:16,height:16}})})]})]}),on.jsxs("div",{ref:Ne,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[e==="prompting"&&M.length===0&&on.jsx("div",{style:{padding:"24px 20px",textAlign:"center"},children:on.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."})}),M.length>0&&on.jsx("div",{style:{padding:"16px 16px 0 16px"},children:M.map((a,w)=>on.jsx("div",{style:{marginBottom:w<M.length-1?10:0},children:a.type==="user"?on.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexDirection:"row-reverse"},children:[on.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:on.jsx(lucideReact.User,{style:{width:13,height:13,color:"#6b7280"}})}),on.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})]}):on.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[on.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#f0fdf4",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:on.jsx(lucideReact.Check,{style:{width:13,height:13,color:"#9ca3af"}})}),on.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:[on.jsx("span",{style:{flex:1},children:a.text}),g&&w===M.length-1&&e!=="running"&&on.jsxs("button",{onClick:O=>{O.stopPropagation(),en();},onMouseEnter:()=>ee(w),onMouseLeave:()=>ee(null),disabled:re,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:ue===w?"rgba(0,0,0,0.06)":"transparent",color:ue===w?"#6b7280":"#d1d5db",cursor:re?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:re?.4:1,flexShrink:0},children:[on.jsx(lucideReact.Undo2,{style:{width:12,height:12}}),ue===w&&on.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"})]})]})]})},w))}),e==="running"&&on.jsx("div",{style:{padding:16},children:on.jsxs("div",{onClick:()=>D(!Q),style:{backgroundColor:"#1a1a2e",borderRadius:12,overflow:"hidden",cursor:"pointer",transition:"all 0.3s cubic-bezier(0.22, 1, 0.36, 1)"},children:[on.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px"},children:[on.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[on.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:on.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),on.jsx(no,{events:r})]}),on.jsx("div",{style:{color:"#6b7280",flexShrink:0,marginLeft:8,transition:"transform 0.2s ease",transform:Q?"rotate(180deg)":"rotate(0deg)"},children:on.jsx(lucideReact.ChevronDown,{style:{width:14,height:14}})})]}),on.jsx("div",{style:{maxHeight:Q?320:0,opacity:Q?1:0,transition:"max-height 0.35s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.25s ease",overflow:"hidden"},children:on.jsx("div",{style:{borderTop:"1px solid rgba(255,255,255,0.08)",maxHeight:320,overflowY:"auto"},children:on.jsx(Er,{events:r})})})]})}),e==="error"&&on.jsxs("div",{style:{padding:"20px 16px",textAlign:"center"},children:[on.jsx("div",{style:{width:36,height:36,backgroundColor:"#fef2f2",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 10px auto"},children:on.jsx(lucideReact.X,{style:{width:18,height:18,color:"#ef4444"}})}),on.jsx("p",{style:{fontSize:12,color:"#6b7280",marginBottom:10,maxWidth:260,margin:"0 auto 10px auto"},children:n}),on.jsxs("button",{onClick:()=>{let a=t?.prompt||We.current;a&&p(a,ce);},onMouseEnter:()=>z(true),onMouseLeave:()=>z(false),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,color:"#4f46e5",backgroundColor:N?"#e0e7ff":"#eef2ff",border:"none",cursor:"pointer",transition:"background-color 0.15s",fontFamily:"inherit"},children:[on.jsx(lucideReact.RotateCcw,{style:{width:12,height:12}})," Try Again"]})]})]}),e!=="running"&&on.jsx("div",{style:{padding:"8px 12px 12px 12px",borderTop:"1px solid rgba(229, 231, 235, 0.6)",flexShrink:0},children:on.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:[on.jsx("textarea",{ref:mt,value:T,onChange:a=>{A(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(),Qt()),a.key==="Escape"&&!y&&yt();},placeholder:M.length>0?"Ask for another change...":`Describe your ideal ${ze.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"}}),on.jsx("button",{onClick:Qt,disabled:!T.trim(),onMouseEnter:()=>te(true),onMouseLeave:()=>te(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:T.trim()?1:.25,transform:K&&T.trim()?"scale(1.1)":"scale(1)",background:T.trim()?"#1c4587":"rgba(0,0,0,0.12)",border:"none",cursor:T.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:on.jsx(lucideReact.ArrowUp,{style:{width:13,height:13}})})]})})]})]});return y?bt:le&&Se?nn.createPortal(bt,Se.document.body):on.jsx(oo,{children:bt})}function Mr(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 Bt(e){let{apiKey:t,userId:r,userHash:n,baseUrl:o,appId:i,previewSession:s,refreshModuleManifest:l,queueBoundaryAnimation:p}=X(),[g,d]=$t.useState("idle"),[S,P]=$t.useState(null),[_,x]=$t.useState([]),[h,y]=$t.useState(null),T=$t.useRef(null),A=$t.useCallback(()=>{d("prompting"),x([]),y(null),P(null);},[]),M=$t.useCallback(()=>{d("idle"),T.current&&(T.current.close(),T.current=null);},[]);$t.useEffect(()=>{s&&s.target.kind==="module"&&s.target.id===e&&d(v=>v==="idle"?"prompting":v);},[s?.preview_session_id,s?.target.id,e]);let C=$t.useCallback(async(v,b)=>{try{if(!i)throw new Error("ForkProvider requires appId for module boundary prompts.");d("running"),x([]),y(null);let c;if(s){let u=await fetch(`${o}/api/v1/preview/${encodeURIComponent(s.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...V()},body:JSON.stringify({prompt:v,...s.fork_id?{fork_id:s.fork_id}:{}})});if(!u.ok){let L=await u.json().catch(()=>({}));throw new Error(L.error||`API error: ${u.status}`)}let f=await u.json();f.container_id&&ke(f.container_id,f.container_name),$e(f.fork_id),c=await(await fetch(`${o}/api/v1/forks/${f.fork_id}`,{headers:{Authorization:`Bearer ${t}`,...V()}})).json();}else {let u={userId:r,prompt:v,boundaryId:e,appId:i};b&&(u.containerId=b),n&&(u.userHash=n);let f=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(u)});if(!f.ok){let m=await f.json().catch(()=>({}));throw new Error(m.error||`API error: ${f.status}`)}c=await f.json();}P(c);let $=new URLSearchParams({key:t});n&&($.set("userId",r),$.set("userHash",n));let F=new EventSource(`${o}/api/v1/forks/${c.id}/events?${$.toString()}`);T.current=F,F.onmessage=u=>{try{let f=JSON.parse(u.data);if(x(m=>[...m,f]),f.type==="complete"){let m=f.data;p(e,c.id),l().catch(()=>{}).finally(()=>{let L={...c,status:"complete",moduleUrl:m.moduleUrl,cssUrls:m.cssUrls,summary:m.summary,completedAt:new Date().toISOString()};P(L),d("complete"),F.close();});}else if(f.type==="error"){let m=f.data;y(m.error||"Unknown error"),d("error"),F.close();}}catch{}},F.onerror=()=>{fetch(`${o}/api/v1/forks/${c.id}`,{headers:{Authorization:`Bearer ${t}`}}).then(u=>u.json()).then(u=>{P(u),u.status==="complete"?(p(e,u.id),l().catch(()=>{}),d("complete")):u.status==="error"&&(y(u.error||"Fork generation failed"),d("error"));}).catch(()=>{y("Connection lost"),d("error");}),F.close();};}catch(c){y(c.message),d("error");}},[t,i,o,e,s,p,l,n,r]),I=$t.useCallback(async()=>{try{if(!i)throw new Error("ForkProvider requires appId for boundary undo.");let v={userId:r,boundaryId:e,appId:i};n&&(v.userHash=n);let b=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(v)});if(!b.ok){let $=await b.json().catch(()=>({}));throw new Error($.error||`API error: ${b.status}`)}let c=await b.json();return await l().catch(()=>{}),c.removed?(P(null),d("prompting")):c.fork&&(P(c.fork),d("complete")),c}catch(v){throw y(v.message),v}},[t,i,o,e,l,n,r]);return {state:g,fork:S,events:_,error:h,open:A,close:M,startFork:C,undoFork:I}}function Ir(e){let{state:t,fork:r,events:n,error:o,open:i,close:s,startFork:l,undoFork:p}=Bt(e);return {state:t,fork:r,events:n,error:o,isOpen:t!=="idle",open:i,close:s,submit:l,undo:p}}function Ut(){let{apiKey:e,userId:t,userHash:r,baseUrl:n,previewSession:o,setSlotFork:i,clearSlotFork:s,skipAnimationForSlot:l}=X(),[p,g]=$t.useState("idle"),[d,S]=$t.useState(null),[P,_]=$t.useState([]),[x,h]=$t.useState(null),y=$t.useRef(null),T=$t.useCallback(()=>{g("prompting"),_([]),h(null),S(null);},[]),A=$t.useCallback(()=>{g("idle"),y.current&&(y.current.close(),y.current=null);},[]);$t.useEffect(()=>{o&&o.target.kind==="slot"&&g(I=>I==="idle"?"prompting":I);},[o?.preview_session_id,o?.target.kind]);let M=$t.useCallback(async(I,v,b)=>{try{g("running"),_([]),h(null);let c;if(o){let u=await fetch(`${n}/api/v1/preview/${encodeURIComponent(o.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...V()},body:JSON.stringify({prompt:I,...o.fork_id?{fork_id:o.fork_id}:{}})});if(!u.ok){let L=await u.json().catch(()=>({}));throw new Error(L.error||`API error: ${u.status}`)}let f=await u.json();f.container_id&&ke(f.container_id,f.container_name),$e(f.fork_id),c=await(await fetch(`${n}/api/v1/forks/${f.fork_id}`,{headers:{Authorization:`Bearer ${e}`,...V()}})).json();}else {let u={userId:t,prompt:I};v&&(u.slotId=v),b&&(u.containerId=b),r&&(u.userHash=r);let f=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(u)});if(!f.ok){let m=await f.json().catch(()=>({}));throw new Error(m.error||`API error: ${f.status}`)}c=await f.json();}S(c);let $=new URLSearchParams({key:e});r&&($.set("userId",t),$.set("userHash",r));let F=new EventSource(`${n}/api/v1/forks/${c.id}/events?${$.toString()}`);y.current=F,F.onmessage=u=>{try{let f=JSON.parse(u.data);if(_(m=>[...m,f]),f.type==="complete"){let m=f.data,L={...c,status:"complete",bundleUrl:m.bundleUrl,summary:m.summary,completedAt:new Date().toISOString()};S(L),g("complete"),v&&m.bundleUrl&&i(v,L),F.close();}else if(f.type==="error"){let m=f.data;h(m.error||"Unknown error"),g("error"),F.close();}}catch{}},F.onerror=()=>{fetch(`${n}/api/v1/forks/${c.id}`,{headers:{Authorization:`Bearer ${e}`}}).then(u=>u.json()).then(u=>{S(u),u.status==="complete"?(g("complete"),v&&u.bundleUrl&&i(v,u)):u.status==="error"&&(h(u.error||"Fork generation failed"),g("error"));}).catch(()=>{h("Connection lost"),g("error");}),F.close();};}catch(c){h(c.message),g("error");}},[e,t,r,n,o,i]),C=$t.useCallback(async I=>{try{let v={userId:t,slotId:I};r&&(v.userHash=r);let b=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(v)});if(!b.ok){let $=await b.json().catch(()=>({}));throw new Error($.error||`API error: ${b.status}`)}let c=await b.json();return l(I),c.removed?(s(I),S(null),g("prompting")):c.fork&&(i(I,c.fork),S(c.fork)),c}catch(v){throw h(v.message),v}},[e,t,r,n,s,i]);return {state:p,fork:d,events:P,error:x,open:T,close:A,startFork:M,undoFork:C}}function Lr(){let{state:e,fork:t,events:r,error:n,open:o,close:i,startFork:s,undoFork:l}=Ut();return {state:e,fork:t,events:r,error:n,isOpen:e!=="idle",open:o,close:i,submit:s,undo:l}}function Ht(e){let t=Mr(e),r=Lr(),n=Ir(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:i,userId:s,userHash:l,appId:p}=X(),g=t.type==="slot"?r:n,d=t.type==="slot"?"slot":"boundary",S=t.id,P=t.title,_=$t.useCallback((h,y,T)=>t.type==="slot"?r.submit(h,y??t.id,T):n.submit(h,T),[n,r,t]),x=$t.useCallback(h=>t.type==="slot"?r.undo(h??t.id):n.undo(),[n,r,t]);return {...g,target:t,targetId:S,targetLabel:P,historyMode:d,submit:_,undo:x,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:d}:{targetId:S,targetLabel:P,historyMode:d},onSubmit:_,onUndo:x,onClose:g.close,baseUrl:o,apiKey:i,userId:s,userHash:l,appId:p}}}function Oe(e){let{embedded:t}=e,r=Ht(e);return t?on.jsx(st,{...r.panelProps,embedded:true}):r.isOpen?on.jsx(st,{...r.panelProps}):on.jsx(Mt,{...r.buttonProps})}function uo({boundaryId:e,title:t}){return on.jsx(Oe,{boundaryId:e,title:t})}function Dt(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 Br(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 jt(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 Ur(e,t){let r=[];for(let n of t)if(!(e.find(s=>s.tag===n.tag&&s.className===n.className&&Math.abs(s.rect.top-n.rect.top)<20&&Math.abs(s.rect.left-n.rect.left)<20)||r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom))){for(let s=r.length-1;s>=0;s-=1){let l=r[s];l.rect.top>=n.rect.top&&l.rect.left>=n.rect.left&&l.rect.right<=n.rect.right&&l.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Hr(e,t){let r=[];for(let n of e)if(!(t.find(s=>s.tag===n.tag&&s.className===n.className&&Math.abs(s.rect.top-n.rect.top)<20&&Math.abs(s.rect.left-n.rect.left)<20)||r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom))){for(let s=r.length-1;s>=0;s-=1){let l=r[s];l.rect.top>=n.rect.top&&l.rect.left>=n.rect.left&&l.rect.right<=n.rect.right&&l.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Nr(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 zt(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 d=0;d<e.length;d+=1){let{rect:S,borderRadius:P}=e[d],_=S.left-.5,x=S.top-.5,h=S.width+1,y=S.height+1,T=Math.min(P+.5,h/2,y/2),A=Nr(_,x,h,y,T),M=`__fork-glow-${d}`,C=document.createElementNS(t,"filter");C.setAttribute("id",M),C.setAttribute("x","-100%"),C.setAttribute("y","-100%"),C.setAttribute("width","300%"),C.setAttribute("height","300%");let I=document.createElementNS(t,"feGaussianBlur");I.setAttribute("in","SourceGraphic"),I.setAttribute("stdDeviation","8"),C.appendChild(I),o.appendChild(C);let v=`__fork-mask-${d}`,b=document.createElementNS(t,"mask");b.setAttribute("id",v),b.setAttribute("maskUnits","userSpaceOnUse"),b.setAttribute("x",String(_-200)),b.setAttribute("y",String(x-200)),b.setAttribute("width",String(h+400)),b.setAttribute("height",String(y+400));let c=document.createElementNS(t,"rect");c.setAttribute("x",String(_-200)),c.setAttribute("y",String(x-200)),c.setAttribute("width",String(h+400)),c.setAttribute("height",String(y+400)),c.setAttribute("fill","white"),b.appendChild(c);let $=document.createElementNS(t,"path");$.setAttribute("d",A),$.setAttribute("fill","black"),b.appendChild($),o.appendChild(b);let F=document.createElementNS(t,"g");F.setAttribute("mask",`url(#${v})`),F.setAttribute("opacity","0");let u=document.createElementNS(t,"g");u.setAttribute("filter",`url(#${M})`);let f=document.createElementNS(t,"path");f.setAttribute("d",A),f.setAttribute("fill","none"),f.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),f.setAttribute("stroke-width","6"),f.setAttribute("stroke-linecap","round"),u.appendChild(f),F.appendChild(u),n.appendChild(F);let m=document.createElementNS(t,"path");m.setAttribute("d",A),m.setAttribute("fill","none"),m.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),m.setAttribute("stroke-width","2"),m.setAttribute("stroke-linecap","round"),m.setAttribute("opacity","0"),n.appendChild(m),i.push(f,m),f.__group=F;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let d=0;d<i.length;d+=2){let S=i[d],P=i[d+1],_=S.__group;if(!_)continue;let x=P.getTotalLength(),h=S.getTotalLength();if(x<=0)continue;let y=x*.35;P.setAttribute("stroke-dasharray",`${y} ${x-y}`),P.setAttribute("stroke-dashoffset","0"),s.push(P.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*x,opacity:.92,offset:.06},{strokeDashoffset:-2*x,opacity:.92,offset:.92},{strokeDashoffset:-2.25*x,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let T=h*.35;S.setAttribute("stroke-dasharray",`${T} ${h-T}`),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 l=false,p=()=>{if(l)return;l=true,clearTimeout(g);for(let S of s)try{S.cancel();}catch{}let d=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});d.onfinish=()=>r.remove(),window.removeEventListener("click",p);},g=setTimeout(p,14500);return setTimeout(()=>{l||window.addEventListener("click",p);},500),p}function Dr(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-removed","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs"),i=document.createElementNS(t,"filter");i.setAttribute("id","__fork-removed-shadow"),i.setAttribute("x","-10%"),i.setAttribute("y","-10%"),i.setAttribute("width","120%"),i.setAttribute("height","120%");let s=document.createElementNS(t,"feDropShadow");s.setAttribute("dx","0"),s.setAttribute("dy","1"),s.setAttribute("stdDeviation","2"),s.setAttribute("flood-color","rgba(0,0,0,0.15)"),i.appendChild(s),o.appendChild(i),n.appendChild(o);for(let{rect:l,borderRadius:p}of e){let g=document.createElementNS(t,"path");g.setAttribute("d",Nr(l.left,l.top,l.width,l.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 ut=new Map,Wt=new Map;function go(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function zr(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 mo(e){if(!e||typeof document>"u")return Promise.resolve();let t=ut.get(e);if(t)return t;let r=document.querySelector(`link[data-fork-override-href="${e}"]`);if(r instanceof HTMLLinkElement){let o=r.sheet?Promise.resolve():new Promise((i,s)=>{let l=()=>{r.removeEventListener("load",l),r.removeEventListener("error",p),i();},p=()=>{r.removeEventListener("load",l),r.removeEventListener("error",p),s(new Error(`Failed to load boundary stylesheet: ${e}`));};r.addEventListener("load",l,{once:true}),r.addEventListener("error",p,{once:true});});return ut.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 ut.delete(e),o});return ut.set(e,n),n}function ho(e){let t=Wt.get(e);if(t)return t;let r=import(e).catch(n=>{throw Wt.delete(e),n});return Wt.set(e,r),r}async function yo(e,t,r){if(e)try{await Promise.all(e.cssUrls.map(i=>mo(i)));let o=await ho(e.moduleUrl);return zr(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 zr(n,r)}function bo(e){function t(r){let{appId:n,moduleOverridesEnabled:o,moduleManifestReady:i,moduleManifestVersion:s,registerBoundary:l,getBoundaryOverride:p,consumeBoundaryAnimation:g}=X(),[d,S]=$t.useState(null),[P,_]=$t.useState(null),x=$t.useRef(null),h=$t.useRef(null),y=$t.useRef(null),T=$t.useRef(false),A=$t.useRef(null),M=$t.useRef(null),C=p(e.id),I=C?`override:${C.id}`:"original",v=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if($t.useEffect(()=>()=>{M.current&&(clearTimeout(M.current),M.current=null),A.current&&(A.current.remove(),A.current=null);},[]),$t.useEffect(()=>{l({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[n,l,e.id,e.exportName,v]),$t.useEffect(()=>{if(o&&!i&&!d||h.current===I&&d)return;let b=false;return _(null),yo(C,e.original,e.exportName).then(c=>{if(!b){if(C?.id&&g(e.id,C.id)&&x.current){let $=Dt(x.current);if($){let F=jt($);F.length>0&&(y.current=F,T.current=true,M.current&&(clearTimeout(M.current),M.current=null),A.current&&A.current.remove(),A.current=Br($));}}h.current=I,$t.startTransition(()=>{S(()=>c);});}}).catch(c=>{b||_(go(c));}),()=>{b=true;}},[g,I,o,i,s,C?.id,C?.moduleUrl,C?.integrity,C?.cssUrls.join("|"),e.exportName,e.original,d]),$t.useEffect(()=>{if(!T.current||!d||!x.current)return;let b=false;return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(b||!x.current)return;let c=y.current,$=Dt(x.current);if(y.current=null,T.current=false,!c||!$){A.current&&(A.current.remove(),A.current=null);return}let F=jt($),u=Ur(c,F),f=Hr(c,F),m=A.current;if(f.length>0&&m){let L=Dr(f);M.current=setTimeout(()=>{M.current=null;let K=400;m.animate([{opacity:1},{opacity:0}],{duration:K,fill:"forwards"}),L.animate([{opacity:1},{opacity:0}],{duration:K,fill:"forwards"}),setTimeout(()=>{m.remove(),L.remove(),A.current===m&&(A.current=null),u.length>0&&zt(u);},K);},3500);}else m&&(m.remove(),A.current===m&&(A.current=null)),u.length>0&&zt(u);});}),()=>{b=true;}},[d]),P)throw P;return d?on.jsx("div",{ref:x,style:{display:"contents"},children:on.jsx(d,{...r})}):on.jsx(on.Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function wo({slotId:e,title:t,slotLabel:r}){return on.jsx(Oe,{slotId:e,title:t,slotLabel:r})}
44
+ exports.ForkBoundaryUI=uo;exports.ForkButton=Mt;exports.ForkChatInterface=Oe;exports.ForkPanel=st;exports.ForkProvider=wn;exports.ForkSlot=Mn;exports.ForkUI=wo;exports.clearCachedManifest=mn;exports.forkable=bo;exports.loadManifest=Ze;exports.manifestDiffers=hn;exports.readCachedManifest=pn;exports.registerForkShared=vt;exports.useBoundaryFork=Bt;exports.useFork=Ut;exports.useForkChatPanel=Ht;exports.usePreviewSession=Ye;exports.writeCachedManifest=gn;
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import*as Rt from'react';import Rt__default,{createContext,useSyncExternalStore,useState,useRef,useEffect,useCallback,startTransition,Children,useContext,isValidElement}from'react';import*as Zr from'react-dom';import {createPortal}from'react-dom';import*as Qr from'react/jsx-runtime';import {jsx,Fragment,jsxs}from'react/jsx-runtime';import*as en 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 me="__FORK_SHARED__";function mt(){var t,r,n,o;let e=globalThis;return e[me]||(e[me]={}),(t=e[me]).react||(t.react=Rt),(r=e[me])["react-dom"]||(r["react-dom"]=Zr),(n=e[me])["react/jsx-runtime"]||(n["react/jsx-runtime"]=Qr),(o=e[me])["react/jsx-dev-runtime"]||(o["react/jsx-dev-runtime"]=en),e[me]}function ht(e){return Object.assign(mt(),e)}var tn="__fork_preview_session__";function Ge(e){return `${tn}${e}`}var H={apiKey:null,session:null},yt=new Set;function Ve(){for(let e of yt)try{e();}catch(t){console.error("[fork-preview] subscriber threw",t);}}function Xt(e){let t=Date.parse(e.expires_at);return Number.isFinite(t)?t<=Date.now():true}function rn(e){if(typeof window>"u")return null;try{let t=window.sessionStorage.getItem(Ge(e));if(!t)return null;let r=JSON.parse(t);return !r||typeof r!="object"||typeof r.preview_session_id!="string"?null:Xt(r)?(window.sessionStorage.removeItem(Ge(e)),null):r}catch{return null}}function kt(e,t){if(!(typeof window>"u"))try{t?window.sessionStorage.setItem(Ge(e),JSON.stringify(t)):window.sessionStorage.removeItem(Ge(e));}catch{}}function Ee(e){H.apiKey!==e&&(H.apiKey=e,H.session=rn(e),Ve());}function he(){return H.session?Xt(H.session)?(bt(null),null):H.session:null}function bt(e){H.session=e,H.apiKey&&kt(H.apiKey,e),Ve();}function Ae(e){H.session&&H.session.fork_id!==e&&(H.session={...H.session,fork_id:e},H.apiKey&&kt(H.apiKey,H.session),Ve());}function ye(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??H.session.target_user_id,fork_id:null},H.apiKey&&kt(H.apiKey,H.session),Ve()));}function wt(e){return yt.add(e),()=>{yt.delete(e);}}var Yt="__fork_preview";function Zt(){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(Yt);return typeof r=="string"&&r.length>0?r:null}function vt(e){if(typeof window>"u")return false;try{if(window.sessionStorage.getItem(`__fork_preview_session__${e}`))return !0}catch{}return er()!==null}function Qt(){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(Yt);let r=t.toString(),n=r?`#${r}`:"";try{window.history.replaceState(null,"",window.location.pathname+window.location.search+n);}catch{}}var ke=null;function er(){if(ke)return ke;let e=Zt();return e?(ke=e,Qt(),ke):null}async function St(e,t){Ee(e);let r=he();if(r)return ke=null,r;let n=ke??Zt();if(ke=null,!n)return null;Qt();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 a=await o.json().catch(()=>({}));return console.warn(`[fork-preview] activate failed (${o.status}): ${a.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,target_user_id:i.target_user_id,operator_id:i.operator_id,container_id:i.container_id??null,container_name:i.container_name??i.target_user_id,fork_id:i.fork_id??null,expires_at:i.expires_at};return bt(s),s}catch(o){return console.warn("[fork-preview] activate threw",o),null}}function on(){return he()}function sn(){return null}function Je(){return useSyncExternalStore(wt,on,sn)}function G(){let e=he();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 qe(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[a,p]of Object.entries(i.modules)){let g=p.moduleUrl??p.bundleUrl??null,d=p.legacyModuleUrl??p.legacyBundleUrl??null;s[a]={forkId:p.forkId,moduleUrl:g,legacyModuleUrl:d,bundleUrl:p.bundleUrl??g,legacyBundleUrl:p.legacyBundleUrl??d,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 an="fork:manifest:v1";function xt(e,t,r){return `${an}:${e}:${t}:${r}`}function ln(e,t,r){if(typeof window>"u")return null;try{let n=window.localStorage.getItem(xt(e,t,r));return n?JSON.parse(n):null}catch{return null}}function cn(e,t,r,n){if(!(typeof window>"u"))try{window.localStorage.setItem(xt(e,t,r),JSON.stringify(n));}catch{}}function dn(e,t,r){if(!(typeof window>"u"))try{window.localStorage.removeItem(xt(e,t,r));}catch{}}function un(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,a]of r){let p=t.slots[s];if(!p||p.forkId!==a.forkId||p.buildId!==a.buildId)return true}let o=Object.entries(e.modules),i=Object.entries(t.modules);if(o.length!==i.length)return true;for(let[s,a]of o){let p=t.modules[s];if(!p||p.forkId!==a.forkId||p.buildId!==a.buildId)return true}return false}var nr=createContext(null);function Ce(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function gn(e,t){let r={};for(let[n,o]of Object.entries(t.boundaries||{}))r[n]={...o,moduleUrl:Ce(e,o.moduleUrl),cssUrls:Array.isArray(o.cssUrls)?o.cssUrls.map(i=>Ce(e,i)):[]};return r}function tr(e,t,r,n){let o={};for(let[i,s]of Object.entries(t.slots)){let a=s.bundleUrl??s.legacyBundleUrl;a&&(o[i]={id:s.forkId,userId:r,prompt:"",status:"complete",slotId:i,appId:n,bundleUrl:Ce(e,a),createdAt:s.updatedAt,completedAt:s.updatedAt});}return o}function rr(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:Ce(e,i),cssUrls:(o.cssUrls??[]).map(s=>Ce(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,a="authUrl"in e?e.authUrl:void 0,[p]=useState(()=>(Ee(t),vt(t))),[g,d]=useState({}),[S,P]=useState(s?{userId:s,userHash:void 0}:null),[R,x]=useState(!!s||p),[h,y]=useState({}),[T,A]=useState(!o),[M,E]=useState(0),[I,v]=useState(null),b=useRef(new Map),l=useRef(new Map),[$,F]=useState(0),u=useRef(new Set),f=useRef(new Map),m=useRef(void 0);mt(),useEffect(()=>{return St(t,r).then(()=>{}),()=>{}},[]);let L=Je();i&&m.current!==i&&(ht(i),m.current=i),useEffect(()=>{a&&(p||(x(false),fetch(a,{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");P({userId:_.userId,userHash:_.userHash});}).catch(_=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",_.message);}).finally(()=>{x(true);})));},[a,p]),useEffect(()=>{!a&&s&&(P({userId:s,userHash:void 0}),x(true));},[s,a]);let W=S?.userId??"",ee=S?.userHash,N=L?L.target_user_id:W,z=L?void 0:ee,Y=!!o,D=useCallback(async()=>{if(!Y){v(null),y({}),A(true),E(w=>w+1);return}if(!R){A(false);return}if(!N||!o){v(null),y({}),A(true),E(w=>w+1);return}if(A(false),!L){try{let w=await qe({baseUrl:r,apiKey:t,appId:o,userId:N,userHash:z});w&&(v(w.containerId),d(tr(r,w,N,o)),y(rr(r,w)));}catch(w){console.error("[ForkProvider] Failed to fetch fork manifest:",w.message),v(null),d({}),y({});}finally{E(w=>w+1),A(true);}return}if(v(L.container_id??null),L.container_id){try{let w=await qe({baseUrl:r,apiKey:t,appId:o,userId:N,containerId:L.container_id,extraHeaders:G()});w&&(d(tr(r,w,N,o)),y(rr(r,w)));}catch(w){console.error("[ForkProvider] Failed to fetch preview container manifest:",w.message),d({}),y({});}finally{E(w=>w+1),A(true);}return}let _=new URLSearchParams({appId:o,userId:N});z&&_.set("userHash",z);try{let w=await fetch(`${r}/api/v1/boundaries/manifest?${_.toString()}`,{headers:{Authorization:`Bearer ${t}`,...G()}});if(!w.ok)throw new Error(`${w.status}`);let U=await w.json();y(gn(r,U));}catch(w){console.error("[ForkProvider] Failed to fetch module override manifest:",w.message),y({});}finally{E(w=>w+1),A(true);}},[t,o,r,R,Y,z,N,L?.preview_session_id,L?.fork_id,L?.container_id]);useEffect(()=>{if(!N||o&&(!L||L.container_id))return;let _=new URLSearchParams({userId:N});z&&_.set("userHash",z),fetch(`${r}/api/v1/forks/active?${_.toString()}`,{headers:{Authorization:`Bearer ${t}`,...G()}}).then(w=>{if(!w.ok)throw new Error(`${w.status}`);return w.json()}).then(w=>{w&&typeof w=="object"&&d(w);}).catch(()=>{});},[t,o,N,z,r,L?.preview_session_id,L?.fork_id]),useEffect(()=>{D();},[D]);let te=useCallback((_,w)=>{d(U=>({...U,[_]:w}));},[]),ne=useCallback(_=>{d(w=>{let U={...w};return delete U[_],U});},[]),ue=useCallback(_=>{u.current.add(_);},[]),Z=useCallback(_=>u.current.has(_)?(u.current.delete(_),true):false,[]),ct=useCallback((_,w)=>{f.current.set(_,w);},[]),Le=useCallback((_,w)=>f.current.get(_)!==w?false:(f.current.delete(_),true),[]),Re=useCallback(_=>{if(!o)return;let w=JSON.stringify(_);b.current.get(_.id)===w||l.current.get(_.id)?.signature===w||(l.current.set(_.id,{boundary:_,signature:w}),F(K=>K+1));},[o]);useEffect(()=>{if(!o||l.current.size===0)return;let _=setTimeout(()=>{let w=Array.from(l.current.values());w.length!==0&&fetch(`${r}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:o,boundaries:w.map(U=>U.boundary)})}).then(U=>{if(!U.ok)throw new Error(`${U.status}`)}).then(()=>{for(let U of w)l.current.get(U.boundary.id)?.signature===U.signature&&(l.current.delete(U.boundary.id),b.current.set(U.boundary.id,U.signature));}).catch(U=>{console.error("[ForkProvider] Failed to register module boundaries:",U.message);});},50);return ()=>{clearTimeout(_);}},[t,o,r,$]);let ie=useCallback(_=>h[_],[h]),q=useCallback(async()=>{if(!N)throw new Error("Reset requires a resolved user identity.");let _=new URLSearchParams({userId:N});z&&_.set("userHash",z);let w=await fetch(`${r}/api/v1/forks/all?${_.toString()}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`,...G()}});if(!w.ok){let K=await w.json().catch(()=>({}));throw new Error(K.error||`API error: ${w.status}`)}let U=await w.json().catch(()=>({}));d({}),y({}),A(true),E(K=>K+1),u.current.clear(),f.current.clear();try{for(let K=sessionStorage.length-1;K>=0;K-=1){let ae=sessionStorage.key(K);ae&&ae.startsWith("__fork_animated_")&&sessionStorage.removeItem(ae);}}catch{}return U},[t,r,z,N]);return jsx(nr.Provider,{value:{apiKey:t,userId:N,userHash:z,baseUrl:r,appId:o,forks:g,moduleOverridesEnabled:Y,moduleManifestReady:T,moduleManifestVersion:M,currentContainerId:I,previewSession:L,setSlotFork:te,clearSlotFork:ne,skipAnimationForSlot:ue,shouldSkipAnimation:Z,queueBoundaryAnimation:ct,consumeBoundaryAnimation:Le,registerBoundary:Re,getBoundaryOverride:ie,refreshModuleManifest:D,resetAllForks:q},children:n})}function J(){let e=useContext(nr);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function Xe(e){return J().forks[e]}var Pe=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 _t(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 sr=new Set;function ir(e){let t=[],r=e.querySelectorAll("*");for(let n of r){if(!(n instanceof HTMLElement))continue;let o=n.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(n.tagName))continue;let i=getComputedStyle(n),s=parseFloat(i.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:s});}return t}function wn(e,t){let r=[];for(let n of t)if(!e.find(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 a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function vn(e,t){let r=[];for(let n of e)if(!t.find(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 a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function lr(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 ar(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-highlights","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");n.appendChild(o);let i=[];for(let d=0;d<e.length;d++){let{rect:S,borderRadius:P}=e[d],R=S.left-.5,x=S.top-.5,h=S.width+1,y=S.height+1,T=Math.min(P+.5,h/2,y/2),A=lr(R,x,h,y,T),M=`__fork-glow-${d}`,E=document.createElementNS(t,"filter");E.setAttribute("id",M),E.setAttribute("x","-100%"),E.setAttribute("y","-100%"),E.setAttribute("width","300%"),E.setAttribute("height","300%");let I=document.createElementNS(t,"feGaussianBlur");I.setAttribute("in","SourceGraphic"),I.setAttribute("stdDeviation","8"),E.appendChild(I),o.appendChild(E);let v=`__fork-mask-${d}`,b=document.createElementNS(t,"mask");b.setAttribute("id",v),b.setAttribute("maskUnits","userSpaceOnUse"),b.setAttribute("x",String(R-200)),b.setAttribute("y",String(x-200)),b.setAttribute("width",String(h+400)),b.setAttribute("height",String(y+400));let l=document.createElementNS(t,"rect");l.setAttribute("x",String(R-200)),l.setAttribute("y",String(x-200)),l.setAttribute("width",String(h+400)),l.setAttribute("height",String(y+400)),l.setAttribute("fill","white"),b.appendChild(l);let $=document.createElementNS(t,"path");$.setAttribute("d",A),$.setAttribute("fill","black"),b.appendChild($),o.appendChild(b);let F=document.createElementNS(t,"g");F.setAttribute("mask",`url(#${v})`),F.setAttribute("opacity","0");let u=document.createElementNS(t,"g");u.setAttribute("filter",`url(#${M})`);let f=document.createElementNS(t,"path");f.setAttribute("d",A),f.setAttribute("fill","none"),f.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),f.setAttribute("stroke-width","6"),f.setAttribute("stroke-linecap","round"),u.appendChild(f),F.appendChild(u),n.appendChild(F);let m=document.createElementNS(t,"path");m.setAttribute("d",A),m.setAttribute("fill","none"),m.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),m.setAttribute("stroke-width","2"),m.setAttribute("stroke-linecap","round"),m.setAttribute("opacity","0"),n.appendChild(m),i.push(f,m),f.__group=F;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let d=0;d<i.length;d+=2){let S=i[d],P=i[d+1],R=S.__group,x=P.getTotalLength(),h=S.getTotalLength();if(x<=0)continue;let y=x*.35;P.setAttribute("stroke-dasharray",`${y} ${x-y}`),P.setAttribute("stroke-dashoffset","0"),s.push(P.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*x,opacity:.92,offset:.06},{strokeDashoffset:-2*x,opacity:.92,offset:.92},{strokeDashoffset:-2.25*x,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let T=h*.35;S.setAttribute("stroke-dasharray",`${T} ${h-T}`),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(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 a=false,p=()=>{if(a)return;a=true,clearTimeout(g);for(let S of s)try{S.cancel();}catch{}let d=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});d.onfinish=()=>r.remove(),window.removeEventListener("click",p);},g=setTimeout(p,14500);return setTimeout(()=>{a||window.addEventListener("click",p);},500),p}function Sn(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:a,borderRadius:p}of e){let g=a.left,d=a.top,S=a.width,P=a.height,R=Math.min(p,S/2,P/2),x=lr(g,d,S,P,R),h=document.createElementNS(t,"path");h.setAttribute("d",x),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 xn(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 Fn=Rt__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&&xn(e.hostProps,t.hostProps)),Ft=class extends Rt__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}){_t(t,e);let i=Xe(e),{baseUrl:s,apiKey:a,appId:p,shouldSkipAnimation:g}=J(),[d,S]=useState(null),P=useRef(null),R=useRef(null),x=useRef(null),h=useRef(false),y=useRef(null),T=useRef(null),A=!!(n||o),M=useRef(null);A&&!M.current&&(M.current=new Pe(e));let E=useRef(o);if(E.current=o,useEffect(()=>{if(A)return ()=>{M.current?.destroy(),M.current=null;}},[A,e]),A&&M.current&&n)for(let[$,F]of Object.entries(n))M.current.set($,F);useEffect(()=>{if(!A)return;M.current||(M.current=new Pe(e));let $=M.current,F=Object.keys(E.current||{}).map(u=>$.on(u,(...f)=>E.current?.[u]?.(...f)));return ()=>F.forEach(u=>u())},[A,e]),useEffect(()=>{if(sr.has(e))return;sr.add(e);let $={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 ${a}`,"Content-Type":"application/json"},body:JSON.stringify($)}).catch(()=>{});},[e,s,a,r,p]);let I=i?.id||null;useEffect(()=>{if(i?.bundleUrl,P.current,R.current,!i?.bundleUrl||!I){return}let $=`${s}${i.bundleUrl.replace("bundle.js","component.js")}`,F=`__fork_animated_${e}`,u=sessionStorage.getItem(F),f=g(e),m=!f&&u!==I;if(f&&I&&sessionStorage.setItem(F,I),m&&R.current){let z=ir(R.current);x.current=z,h.current=true,`${e}${z.length}`;}window.__FORK_REACT__=Rt__default,window.__FORK_REACT_DOM__=Zr,window.__FORK_REACT_JSX__=Qr;let L=Date.now(),W=`${s}${i.bundleUrl.replace("bundle.js","component.css")}?t=${L}`,ee=document.createElement("link");ee.rel="stylesheet",ee.href=W,ee.dataset.forkSlot=e,document.head.appendChild(ee);let N=document.createElement("script");return N.src=$+"?t="+L,N.onload=()=>{let z=window.__FORK_EXPORT__;if(z?.default){if(R.current&&x.current&&h.current){let Y=R.current.getBoundingClientRect(),D=R.current.cloneNode(true);D.style.position="fixed",D.style.top=`${Y.top}px`,D.style.left=`${Y.left}px`,D.style.width=`${Y.width}px`,D.style.height=`${Y.height}px`,D.style.flex="none",D.style.minHeight="auto",D.style.zIndex="9998",D.style.pointerEvents="none",D.style.overflow="hidden";let te=getComputedStyle(R.current).backgroundColor;D.style.backgroundColor=te&&te!=="rgba(0, 0, 0, 0)"&&te!=="transparent"?te:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(D);let ne=R.current.querySelectorAll("*"),ue=D.querySelectorAll("*");for(let Z=0;Z<ne.length;Z++)ne[Z].scrollTop!==0&&(ue[Z].scrollTop=ne[Z].scrollTop),ne[Z].scrollLeft!==0&&(ue[Z].scrollLeft=ne[Z].scrollLeft);y.current=D;}S(()=>z.default),P.current=I;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},N.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(N),()=>{N.remove(),ee.remove(),T.current&&(clearTimeout(T.current),T.current=null),y.current&&(y.current.remove(),y.current=null);}},[I,s,e]),useEffect(()=>{if(!h.current||!d||!R.current){`${e}${h.current}`,R.current;return}let $=x.current;if(!$){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!R.current)return;let F=ir(R.current),u=wn($,F),f=vn($,F),m=y.current;if(`${e}${u.length}${f.length}`,f.length>0&&m){let L=Sn(f);T.current=setTimeout(()=>{T.current=null;let W=400;m.animate([{opacity:1},{opacity:0}],{duration:W,fill:"forwards"}),L.animate([{opacity:1},{opacity:0}],{duration:W,fill:"forwards"}),setTimeout(()=>{m.remove(),L.remove(),y.current=null,u.length>0&&(ar(u));},W);},3500);}else m&&(m.remove(),y.current=null),u.length>0&&(ar(u));x.current=null,h.current=false,I&&(sessionStorage.setItem(`__fork_animated_${e}`,I),`${e}`);});});},[d]);let v={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!i||i.status!=="complete"||!i.bundleUrl)return jsx("div",{ref:R,style:v,children:t});if(!d)return jsx("div",{ref:R,style:v,children:t});let l=t?.props??{};return jsx(Ft,{slotId:e,resetKey:I,fallback:jsx("div",{ref:R,style:v,children:t}),children:jsx(Fn,{component:d,containerRef:R,wrapperStyle:v,hostProps:l})})}var ur=new Set;function En(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 fr(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&&fr(n.children,t);}),t}function An({slotId:e,props:t,children:r,allowedFetches:n,githubRepo:o,callbacks:i,mode:s="iframe",shared:a,events:p}){if(_t(r,e),s==="direct")return jsx(cr,{slotId:e,githubRepo:o,shared:a,events:p,children:r});let g=Xe(e),{baseUrl:d,apiKey:S,appId:P}=J(),R=useRef(null),x=useRef(false),h=useRef(null),y=useRef(i);y.current=i;let T=useRef(t);T.current=t;let A=useRef(n);A.current=n,useEffect(()=>{if(typeof process<"u")return;let v=fr(r),b=new Set(i?Object.keys(i):[]),l=[...v].filter($=>!b.has($));l.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
- `+l.map($=>` - ${$}`).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(()=>{ur.has(e)||(ur.add(e),fetch(`${d}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${S}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:P,label:e,propsShape:t?En(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:o,callbackNames:i?Object.keys(i):[],mode:s||"iframe"})}).catch(()=>{}));},[e,d,S,o,P]);let M=useCallback(v=>{let b=R.current;if(b?.contentWindow&&x.current){let l=y.current?Object.keys(y.current):[];b.contentWindow.postMessage({type:"slot:props",props:v,callbackNames:l},"*"),h.current=null;}else h.current=v;},[]),E=useCallback((v,b)=>{let l=A.current;return !l||l.length===0?false:l.some($=>{let[F,u]=$.split(" "),f=b.split("?")[0];return v.toUpperCase()===F.toUpperCase()&&f.startsWith(u)})},[]);if(useEffect(()=>{if(!g?.bundleUrl)return;let v=async b=>{if(b.source===R.current?.contentWindow){if(b.data?.type==="slot:ready")x.current=true,R.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:A.current||[]},"*"),A.current,h.current?M(h.current):M(T.current||{});else if(b.data?.type==="slot:event"){let l=b.data.event;l?.navigate&&(window.location.hash=l.navigate);}else if(b.data?.type==="slot:clipboard-write")navigator.clipboard.writeText(b.data.text).catch(l=>{console.warn(`[ForkSlot:${e}] clipboard write failed:`,l.message);});else if(b.data?.type==="slot:callback"){let{name:l,args:$}=b.data,F=y.current?.[l];F?(F(...$||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${l}`);}else if(b.data?.type==="slot:fetch"){let{id:l,method:$,url:F,body:u}=b.data,f=R.current?.contentWindow;if(!f)return;let m=$||"GET";if(!E(m,F)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${l}: ${m} ${F} \u2014 not in allowedFetches`),f.postMessage({type:"slot:fetch-response",id:l,error:`Fetch not allowed: ${m} ${F}`},"*");return}try{let L={method:m};u&&m!=="GET"&&(L.headers={"Content-Type":"application/json"},L.body=JSON.stringify(u));let W=await fetch(F,L),ee=await W.json();`${e}${l}${W.status}`,f.postMessage({type:"slot:fetch-response",id:l,data:ee,status:W.status},"*");}catch(L){console.error(`[ForkSlot:${e}] fetch #${l} failed:`,L.message),f.postMessage({type:"slot:fetch-response",id:l,error:L.message},"*");}}}};return window.addEventListener("message",v),()=>{window.removeEventListener("message",v),x.current=false;}},[g?.bundleUrl,e,M,E]),useEffect(()=>{g?.bundleUrl&&x.current&&M(t||{});},[t,g?.bundleUrl,M]),!g||g.status!=="complete"||!g.bundleUrl)return `${e}${g?.status||"none"}${g?.bundleUrl||"none"}`,jsx(Fragment,{children:r});`${e}${g.bundleUrl}`;let I=`${d}${g.bundleUrl.replace("/bundle.js","/host")}`;return jsx("iframe",{ref:R,src:I,sandbox:"allow-scripts allow-same-origin allow-forms allow-clipboard-write",title:`Forked ${e}`,style:{width:"100%",border:"none",flex:1,minHeight:0}})}function Ze({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 At({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(Ze,{style:{width:24,height:24}})})}var Bn={status:Loader2,agent_message:MessageSquare,tool_use:Wrench,build_start:Package,build_complete:Check,build_error:AlertCircle,complete:Sparkles,error:AlertCircle},Hn={status:"#60a5fa",agent_message:"#a0a0a0",tool_use:"#fbbf24",build_start:"#c084fc",build_complete:"#6b7280",build_error:"#f87171",complete:"#6b7280",error:"#f87171"},Nn={read:FileSearch,write:Pencil,search:FileSearch,shell:Terminal,build:Package},Dn={read:"#60a5fa",write:"#fbbf24",search:"#60a5fa",shell:"#a78bfa",build:"#c084fc"};function Ct(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 wr({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 $t from'react';import $t__default,{createContext,useSyncExternalStore,useState,useRef,useEffect,useCallback,startTransition,Children,useContext,isValidElement}from'react';import*as nn from'react-dom';import {createPortal}from'react-dom';import*as on from'react/jsx-runtime';import {jsx,Fragment,jsxs}from'react/jsx-runtime';import*as sn from'react/jsx-dev-runtime';import {ChevronDown,Check,PictureInPicture,PictureInPicture2,X as X$1,User,Undo2,RotateCcw,ArrowUp,Loader2,AlertCircle,Sparkles,Package,Wrench,MessageSquare,Code,Terminal,FileSearch,Pencil}from'lucide-react';var ye="__FORK_SHARED__";function wt(){var t,r,n,o;let e=globalThis;return e[ye]||(e[ye]={}),(t=e[ye]).react||(t.react=$t),(r=e[ye])["react-dom"]||(r["react-dom"]=nn),(n=e[ye])["react/jsx-runtime"]||(n["react/jsx-runtime"]=on),(o=e[ye])["react/jsx-dev-runtime"]||(o["react/jsx-dev-runtime"]=sn),e[ye]}function vt(e){return Object.assign(wt(),e)}var an="__fork_preview_session__";function qe(e){return `${an}${e}`}var H={apiKey:null,session:null},St=new Set;function Xe(){for(let e of St)try{e();}catch(t){console.error("[fork-preview] subscriber threw",t);}}function nr(e){let t=Date.parse(e.expires_at);return Number.isFinite(t)?t<=Date.now():true}function ln(e){if(typeof window>"u")return null;try{let t=window.sessionStorage.getItem(qe(e));if(!t)return null;let r=JSON.parse(t);return !r||typeof r!="object"||typeof r.preview_session_id!="string"?null:nr(r)?(window.sessionStorage.removeItem(qe(e)),null):r}catch{return null}}function xt(e,t){if(!(typeof window>"u"))try{t?window.sessionStorage.setItem(qe(e),JSON.stringify(t)):window.sessionStorage.removeItem(qe(e));}catch{}}function Ae(e){H.apiKey!==e&&(H.apiKey=e,H.session=ln(e),Xe());}function be(){return H.session?nr(H.session)?(Ft(null),null):H.session:null}function Ft(e){H.session=e,H.apiKey&&xt(H.apiKey,e),Xe();}function $e(e){H.session&&H.session.fork_id!==e&&(H.session={...H.session,fork_id:e},H.apiKey&&xt(H.apiKey,H.session),Xe());}function ke(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??H.session.target_user_id,fork_id:null},H.apiKey&&xt(H.apiKey,H.session),Xe()));}function _t(e){return St.add(e),()=>{St.delete(e);}}var or="__fork_preview";function sr(){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(or);return typeof r=="string"&&r.length>0?r:null}function Rt(e){if(typeof window>"u")return false;try{if(window.sessionStorage.getItem(`__fork_preview_session__${e}`))return !0}catch{}return ar()!==null}function ir(){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(or);let r=t.toString(),n=r?`#${r}`:"";try{window.history.replaceState(null,"",window.location.pathname+window.location.search+n);}catch{}}var we=null;function ar(){if(we)return we;let e=sr();return e?(we=e,ir(),we):null}async function Et(e,t){Ae(e);let r=be();if(r)return we=null,r;let n=we??sr();if(we=null,!n)return null;ir();try{let o=await fetch(`${t}/api/v1/preview/activate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({token:n})});if(!o.ok){let l=await o.json().catch(()=>({}));return console.warn(`[fork-preview] activate failed (${o.status}): ${l.error??"unknown"}`),null}let i=await o.json(),s={preview_session_id:i.preview_session_id,tenant_id:i.tenant_id,app_id:i.app_id,target:i.target,target_user_id:i.target_user_id,operator_id:i.operator_id,container_id:i.container_id??null,container_name:i.container_name??i.target_user_id,fork_id:i.fork_id??null,expires_at:i.expires_at};return Ft(s),s}catch(o){return console.warn("[fork-preview] activate threw",o),null}}function dn(){return be()}function un(){return null}function Ye(){return useSyncExternalStore(_t,dn,un)}function V(){let e=be();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 Ze(e){let t=new URLSearchParams({app:e.appId,user:e.userId});e.containerId&&t.set("containerId",e.containerId);let r=`${e.baseUrl}/api/v1/manifest?${t.toString()}`,n={Authorization:`Bearer ${e.apiKey}`,"X-Fork-App-Id":e.appId,"X-Fork-User-Id":e.userId,...e.extraHeaders??{}};e.userHash&&(n["X-Fork-User-Hash"]=e.userHash),e.previous?.etag&&(n["If-None-Match"]=e.previous.etag);let o=await fetch(r,{headers:n,signal:e.signal});if(o.status===304)return null;if(!o.ok)throw new Error(`manifest ${o.status} ${o.statusText}`);let i=await o.json(),s={};for(let[l,p]of Object.entries(i.modules)){let g=p.moduleUrl??p.bundleUrl??null,d=p.legacyModuleUrl??p.legacyBundleUrl??null;s[l]={forkId:p.forkId,moduleUrl:g,legacyModuleUrl:d,bundleUrl:p.bundleUrl??g,legacyBundleUrl:p.legacyBundleUrl??d,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 Ct(e,t,r){return `${fn}:${e}:${t}:${r}`}function pn(e,t,r){if(typeof window>"u")return null;try{let n=window.localStorage.getItem(Ct(e,t,r));return n?JSON.parse(n):null}catch{return null}}function gn(e,t,r,n){if(!(typeof window>"u"))try{window.localStorage.setItem(Ct(e,t,r),JSON.stringify(n));}catch{}}function mn(e,t,r){if(!(typeof window>"u"))try{window.localStorage.removeItem(Ct(e,t,r));}catch{}}function hn(e,t){if(!e||!t)return e!==t;if(e.containerId!==t.containerId)return true;let r=Object.entries(e.slots),n=Object.entries(t.slots);if(r.length!==n.length)return true;for(let[s,l]of r){let p=t.slots[s];if(!p||p.forkId!==l.forkId||p.buildId!==l.buildId)return true}let o=Object.entries(e.modules),i=Object.entries(t.modules);if(o.length!==i.length)return true;for(let[s,l]of o){let p=t.modules[s];if(!p||p.forkId!==l.forkId||p.buildId!==l.buildId)return true}return false}var dr=createContext(null);function Te(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function kn(e,t){let r={};for(let[n,o]of Object.entries(t.boundaries||{}))r[n]={...o,moduleUrl:Te(e,o.moduleUrl),cssUrls:Array.isArray(o.cssUrls)?o.cssUrls.map(i=>Te(e,i)):[]};return r}function lr(e,t,r,n){let o={};for(let[i,s]of Object.entries(t.slots)){let l=s.bundleUrl??s.legacyBundleUrl;l&&(o[i]={id:s.forkId,userId:r,prompt:"",status:"complete",slotId:i,appId:n,bundleUrl:Te(e,l),createdAt:s.updatedAt,completedAt:s.updatedAt});}return o}function cr(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:Te(e,i),cssUrls:(o.cssUrls??[]).map(s=>Te(e,s)),integrity:o.integrity,metadata:o.metadata,createdAt:o.updatedAt});}return r}function wn(e){let{apiKey:t,baseUrl:r,children:n,appId:o,shared:i}=e,s="userId"in e?e.userId:void 0,l="authUrl"in e?e.authUrl:void 0,[p]=useState(()=>(Ae(t),Rt(t))),[g,d]=useState({}),[S,P]=useState(s?{userId:s,userHash:void 0}:null),[_,x]=useState(!!s||p),[h,y]=useState({}),[T,A]=useState(!o),[M,C]=useState(0),[I,v]=useState(null),b=useRef(new Map),c=useRef(new Map),[$,F]=useState(0),u=useRef(new Set),f=useRef(new Map),m=useRef(void 0);wt(),useEffect(()=>{return Et(t,r).then(()=>{}),()=>{}},[]);let L=Ye();i&&m.current!==i&&(vt(i),m.current=i),useEffect(()=>{l&&(p||(x(false),fetch(l,{credentials:"include"}).then(R=>{if(!R.ok)throw new Error(`Auth endpoint returned ${R.status}`);return R.json()}).then(R=>{if(!R.userId||typeof R.userId!="string")throw new Error("authUrl response must include userId");P({userId:R.userId,userHash:R.userHash});}).catch(R=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",R.message);}).finally(()=>{x(true);})));},[l,p]),useEffect(()=>{!l&&s&&(P({userId:s,userHash:void 0}),x(true));},[s,l]);let K=S?.userId??"",te=S?.userHash,N=L?L.target_user_id:K,z=L?void 0:te,Q=!!o,D=useCallback(async()=>{if(!Q){v(null),y({}),A(true),C(k=>k+1);return}if(!_){A(false);return}if(!N||!o){v(null),y({}),A(true),C(k=>k+1);return}if(A(false),!L){try{let k=await Ze({baseUrl:r,apiKey:t,appId:o,userId:N,userHash:z});k&&(v(k.containerId),d(lr(r,k,N,o)),y(cr(r,k)));}catch(k){console.error("[ForkProvider] Failed to fetch fork manifest:",k.message),v(null),d({}),y({});}finally{C(k=>k+1),A(true);}return}if(v(L.container_id??null),L.container_id){try{let k=await Ze({baseUrl:r,apiKey:t,appId:o,userId:N,containerId:L.container_id,extraHeaders:V()});k&&(d(lr(r,k,N,o)),y(cr(r,k)));}catch(k){console.error("[ForkProvider] Failed to fetch preview container manifest:",k.message),d({}),y({});}finally{C(k=>k+1),A(true);}return}let R=new URLSearchParams({appId:o,userId:N});z&&R.set("userHash",z);try{let k=await fetch(`${r}/api/v1/boundaries/manifest?${R.toString()}`,{headers:{Authorization:`Bearer ${t}`,...V()}});if(!k.ok)throw new Error(`${k.status}`);let U=await k.json();y(kn(r,U));}catch(k){console.error("[ForkProvider] Failed to fetch module override manifest:",k.message),y({});}finally{C(k=>k+1),A(true);}},[t,o,r,_,Q,z,N,L?.preview_session_id,L?.fork_id,L?.container_id]);useEffect(()=>{if(!N||o&&(!L||L.container_id))return;let R=new URLSearchParams({userId:N});z&&R.set("userHash",z),fetch(`${r}/api/v1/forks/active?${R.toString()}`,{headers:{Authorization:`Bearer ${t}`,...V()}}).then(k=>{if(!k.ok)throw new Error(`${k.status}`);return k.json()}).then(k=>{k&&typeof k=="object"&&d(k);}).catch(()=>{});},[t,o,N,z,r,L?.preview_session_id,L?.fork_id]),useEffect(()=>{D();},[D]);let re=useCallback((R,k)=>{d(U=>({...U,[R]:k}));},[]),oe=useCallback(R=>{d(k=>{let U={...k};return delete U[R],U});},[]),ue=useCallback(R=>{u.current.add(R);},[]),ee=useCallback(R=>u.current.has(R)?(u.current.delete(R),true):false,[]),ft=useCallback((R,k)=>{f.current.set(R,k);},[]),Be=useCallback((R,k)=>f.current.get(R)!==k?false:(f.current.delete(R),true),[]),Re=useCallback(R=>{if(!o)return;let k=JSON.stringify(R);b.current.get(R.id)===k||c.current.get(R.id)?.signature===k||(c.current.set(R.id,{boundary:R,signature:k}),F(W=>W+1));},[o]);useEffect(()=>{if(!o||c.current.size===0)return;let R=setTimeout(()=>{let k=Array.from(c.current.values());k.length!==0&&fetch(`${r}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:o,boundaries:k.map(U=>U.boundary)})}).then(U=>{if(!U.ok)throw new Error(`${U.status}`)}).then(()=>{for(let U of k)c.current.get(U.boundary.id)?.signature===U.signature&&(c.current.delete(U.boundary.id),b.current.set(U.boundary.id,U.signature));}).catch(U=>{console.error("[ForkProvider] Failed to register module boundaries:",U.message);});},50);return ()=>{clearTimeout(R);}},[t,o,r,$]);let ie=useCallback(R=>h[R],[h]),Z=useCallback(async()=>{if(!N)throw new Error("Reset requires a resolved user identity.");let R=new URLSearchParams({userId:N});z&&R.set("userHash",z);let k=await fetch(`${r}/api/v1/forks/all?${R.toString()}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`,...V()}});if(!k.ok){let W=await k.json().catch(()=>({}));throw new Error(W.error||`API error: ${k.status}`)}let U=await k.json().catch(()=>({}));d({}),y({}),A(true),C(W=>W+1),u.current.clear(),f.current.clear();try{for(let W=sessionStorage.length-1;W>=0;W-=1){let ae=sessionStorage.key(W);ae&&ae.startsWith("__fork_animated_")&&sessionStorage.removeItem(ae);}}catch{}return U},[t,r,z,N]);return jsx(dr.Provider,{value:{apiKey:t,userId:N,userHash:z,baseUrl:r,appId:o,forks:g,moduleOverridesEnabled:Q,moduleManifestReady:T,moduleManifestVersion:M,currentContainerId:I,previewSession:L,setSlotFork:re,clearSlotFork:oe,skipAnimationForSlot:ue,shouldSkipAnimation:ee,queueBoundaryAnimation:ft,consumeBoundaryAnimation:Be,registerBoundary:Re,getBoundaryOverride:ie,refreshModuleManifest:D,resetAllForks:Z},children:n})}function X(){let e=useContext(dr);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function Qe(e){return X().forks[e]}var Me=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 Pt(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 fr=new Set;function pr(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 _n(e,t){let r=[];for(let n of t)if(!e.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)&&!r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom)){for(let s=r.length-1;s>=0;s--){let l=r[s];l.rect.top>=n.rect.top&&l.rect.left>=n.rect.left&&l.rect.right<=n.rect.right&&l.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Rn(e,t){let r=[];for(let n of e)if(!t.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)&&!r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom)){for(let s=r.length-1;s>=0;s--){let l=r[s];l.rect.top>=n.rect.top&&l.rect.left>=n.rect.left&&l.rect.right<=n.rect.right&&l.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function mr(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 gr(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 d=0;d<e.length;d++){let{rect:S,borderRadius:P}=e[d],_=S.left-.5,x=S.top-.5,h=S.width+1,y=S.height+1,T=Math.min(P+.5,h/2,y/2),A=mr(_,x,h,y,T),M=`__fork-glow-${d}`,C=document.createElementNS(t,"filter");C.setAttribute("id",M),C.setAttribute("x","-100%"),C.setAttribute("y","-100%"),C.setAttribute("width","300%"),C.setAttribute("height","300%");let I=document.createElementNS(t,"feGaussianBlur");I.setAttribute("in","SourceGraphic"),I.setAttribute("stdDeviation","8"),C.appendChild(I),o.appendChild(C);let v=`__fork-mask-${d}`,b=document.createElementNS(t,"mask");b.setAttribute("id",v),b.setAttribute("maskUnits","userSpaceOnUse"),b.setAttribute("x",String(_-200)),b.setAttribute("y",String(x-200)),b.setAttribute("width",String(h+400)),b.setAttribute("height",String(y+400));let c=document.createElementNS(t,"rect");c.setAttribute("x",String(_-200)),c.setAttribute("y",String(x-200)),c.setAttribute("width",String(h+400)),c.setAttribute("height",String(y+400)),c.setAttribute("fill","white"),b.appendChild(c);let $=document.createElementNS(t,"path");$.setAttribute("d",A),$.setAttribute("fill","black"),b.appendChild($),o.appendChild(b);let F=document.createElementNS(t,"g");F.setAttribute("mask",`url(#${v})`),F.setAttribute("opacity","0");let u=document.createElementNS(t,"g");u.setAttribute("filter",`url(#${M})`);let f=document.createElementNS(t,"path");f.setAttribute("d",A),f.setAttribute("fill","none"),f.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),f.setAttribute("stroke-width","6"),f.setAttribute("stroke-linecap","round"),u.appendChild(f),F.appendChild(u),n.appendChild(F);let m=document.createElementNS(t,"path");m.setAttribute("d",A),m.setAttribute("fill","none"),m.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),m.setAttribute("stroke-width","2"),m.setAttribute("stroke-linecap","round"),m.setAttribute("opacity","0"),n.appendChild(m),i.push(f,m),f.__group=F;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let d=0;d<i.length;d+=2){let S=i[d],P=i[d+1],_=S.__group,x=P.getTotalLength(),h=S.getTotalLength();if(x<=0)continue;let y=x*.35;P.setAttribute("stroke-dasharray",`${y} ${x-y}`),P.setAttribute("stroke-dashoffset","0"),s.push(P.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*x,opacity:.92,offset:.06},{strokeDashoffset:-2*x,opacity:.92,offset:.92},{strokeDashoffset:-2.25*x,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let T=h*.35;S.setAttribute("stroke-dasharray",`${T} ${h-T}`),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 l=false,p=()=>{if(l)return;l=true,clearTimeout(g);for(let S of s)try{S.cancel();}catch{}let d=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});d.onfinish=()=>r.remove(),window.removeEventListener("click",p);},g=setTimeout(p,14500);return setTimeout(()=>{l||window.addEventListener("click",p);},500),p}function En(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-removed","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs"),i=document.createElementNS(t,"filter");i.setAttribute("id","__fork-removed-shadow"),i.setAttribute("x","-10%"),i.setAttribute("y","-10%"),i.setAttribute("width","120%"),i.setAttribute("height","120%");let s=document.createElementNS(t,"feDropShadow");s.setAttribute("dx","0"),s.setAttribute("dy","1"),s.setAttribute("stdDeviation","2"),s.setAttribute("flood-color","rgba(0,0,0,0.15)"),i.appendChild(s),o.appendChild(i),n.appendChild(o);for(let{rect:l,borderRadius:p}of e){let g=l.left,d=l.top,S=l.width,P=l.height,_=Math.min(p,S/2,P/2),x=mr(g,d,S,P,_),h=document.createElementNS(t,"path");h.setAttribute("d",x),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 Cn(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 An=$t__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&&Cn(e.hostProps,t.hostProps)),At=class extends $t__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 hr({slotId:e,children:t,githubRepo:r,shared:n,events:o}){Pt(t,e);let i=Qe(e),{baseUrl:s,apiKey:l,appId:p,shouldSkipAnimation:g}=X(),[d,S]=useState(null),P=useRef(null),_=useRef(null),x=useRef(null),h=useRef(false),y=useRef(null),T=useRef(null),A=!!(n||o),M=useRef(null);A&&!M.current&&(M.current=new Me(e));let C=useRef(o);if(C.current=o,useEffect(()=>{if(A)return ()=>{M.current?.destroy(),M.current=null;}},[A,e]),A&&M.current&&n)for(let[$,F]of Object.entries(n))M.current.set($,F);useEffect(()=>{if(!A)return;M.current||(M.current=new Me(e));let $=M.current,F=Object.keys(C.current||{}).map(u=>$.on(u,(...f)=>C.current?.[u]?.(...f)));return ()=>F.forEach(u=>u())},[A,e]),useEffect(()=>{if(fr.has(e))return;fr.add(e);let $={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 ${l}`,"Content-Type":"application/json"},body:JSON.stringify($)}).catch(()=>{});},[e,s,l,r,p]);let I=i?.id||null;useEffect(()=>{if(i?.bundleUrl,P.current,_.current,!i?.bundleUrl||!I){return}let $=`${s}${i.bundleUrl.replace("bundle.js","component.js")}`,F=`__fork_animated_${e}`,u=sessionStorage.getItem(F),f=g(e),m=!f&&u!==I;if(f&&I&&sessionStorage.setItem(F,I),m&&_.current){let z=pr(_.current);x.current=z,h.current=true,`${e}${z.length}`;}window.__FORK_REACT__=$t__default,window.__FORK_REACT_DOM__=nn,window.__FORK_REACT_JSX__=on;let L=Date.now(),K=`${s}${i.bundleUrl.replace("bundle.js","component.css")}?t=${L}`,te=document.createElement("link");te.rel="stylesheet",te.href=K,te.dataset.forkSlot=e,document.head.appendChild(te);let N=document.createElement("script");return N.src=$+"?t="+L,N.onload=()=>{let z=window.__FORK_EXPORT__;if(z?.default){if(_.current&&x.current&&h.current){let Q=_.current.getBoundingClientRect(),D=_.current.cloneNode(true);D.style.position="fixed",D.style.top=`${Q.top}px`,D.style.left=`${Q.left}px`,D.style.width=`${Q.width}px`,D.style.height=`${Q.height}px`,D.style.flex="none",D.style.minHeight="auto",D.style.zIndex="9998",D.style.pointerEvents="none",D.style.overflow="hidden";let re=getComputedStyle(_.current).backgroundColor;D.style.backgroundColor=re&&re!=="rgba(0, 0, 0, 0)"&&re!=="transparent"?re:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(D);let oe=_.current.querySelectorAll("*"),ue=D.querySelectorAll("*");for(let ee=0;ee<oe.length;ee++)oe[ee].scrollTop!==0&&(ue[ee].scrollTop=oe[ee].scrollTop),oe[ee].scrollLeft!==0&&(ue[ee].scrollLeft=oe[ee].scrollLeft);y.current=D;}S(()=>z.default),P.current=I;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},N.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(N),()=>{N.remove(),te.remove(),T.current&&(clearTimeout(T.current),T.current=null),y.current&&(y.current.remove(),y.current=null);}},[I,s,e]),useEffect(()=>{if(!h.current||!d||!_.current){`${e}${h.current}`,_.current;return}let $=x.current;if(!$){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!_.current)return;let F=pr(_.current),u=_n($,F),f=Rn($,F),m=y.current;if(`${e}${u.length}${f.length}`,f.length>0&&m){let L=En(f);T.current=setTimeout(()=>{T.current=null;let K=400;m.animate([{opacity:1},{opacity:0}],{duration:K,fill:"forwards"}),L.animate([{opacity:1},{opacity:0}],{duration:K,fill:"forwards"}),setTimeout(()=>{m.remove(),L.remove(),y.current=null,u.length>0&&(gr(u));},K);},3500);}else m&&(m.remove(),y.current=null),u.length>0&&(gr(u));x.current=null,h.current=false,I&&(sessionStorage.setItem(`__fork_animated_${e}`,I),`${e}`);});});},[d]);let v={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!i||i.status!=="complete"||!i.bundleUrl)return jsx("div",{ref:_,style:v,children:t});if(!d)return jsx("div",{ref:_,style:v,children:t});let c=t?.props??{};return jsx(At,{slotId:e,resetKey:I,fallback:jsx("div",{ref:_,style:v,children:t}),children:jsx(An,{component:d,containerRef:_,wrapperStyle:v,hostProps:c})})}var br=new Set;function Tn(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 kr(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&&kr(n.children,t);}),t}function Mn({slotId:e,props:t,children:r,allowedFetches:n,githubRepo:o,callbacks:i,mode:s="iframe",shared:l,events:p}){if(Pt(r,e),s==="direct")return jsx(hr,{slotId:e,githubRepo:o,shared:l,events:p,children:r});let g=Qe(e),{baseUrl:d,apiKey:S,appId:P}=X(),_=useRef(null),x=useRef(false),h=useRef(null),y=useRef(i);y.current=i;let T=useRef(t);T.current=t;let A=useRef(n);A.current=n,useEffect(()=>{if(typeof process<"u")return;let v=kr(r),b=new Set(i?Object.keys(i):[]),c=[...v].filter($=>!b.has($));c.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
+ `+c.map($=>` - ${$}`).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(()=>{br.has(e)||(br.add(e),fetch(`${d}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${S}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:P,label:e,propsShape:t?Tn(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:o,callbackNames:i?Object.keys(i):[],mode:s||"iframe"})}).catch(()=>{}));},[e,d,S,o,P]);let M=useCallback(v=>{let b=_.current;if(b?.contentWindow&&x.current){let c=y.current?Object.keys(y.current):[];b.contentWindow.postMessage({type:"slot:props",props:v,callbackNames:c},"*"),h.current=null;}else h.current=v;},[]),C=useCallback((v,b)=>{let c=A.current;return !c||c.length===0?false:c.some($=>{let[F,u]=$.split(" "),f=b.split("?")[0];return v.toUpperCase()===F.toUpperCase()&&f.startsWith(u)})},[]);if(useEffect(()=>{if(!g?.bundleUrl)return;let v=async b=>{if(b.source===_.current?.contentWindow){if(b.data?.type==="slot:ready")x.current=true,_.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:A.current||[]},"*"),A.current,h.current?M(h.current):M(T.current||{});else if(b.data?.type==="slot:event"){let c=b.data.event;c?.navigate&&(window.location.hash=c.navigate);}else if(b.data?.type==="slot:clipboard-write")navigator.clipboard.writeText(b.data.text).catch(c=>{console.warn(`[ForkSlot:${e}] clipboard write failed:`,c.message);});else if(b.data?.type==="slot:callback"){let{name:c,args:$}=b.data,F=y.current?.[c];F?(F(...$||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${c}`);}else if(b.data?.type==="slot:fetch"){let{id:c,method:$,url:F,body:u}=b.data,f=_.current?.contentWindow;if(!f)return;let m=$||"GET";if(!C(m,F)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${c}: ${m} ${F} \u2014 not in allowedFetches`),f.postMessage({type:"slot:fetch-response",id:c,error:`Fetch not allowed: ${m} ${F}`},"*");return}try{let L={method:m};u&&m!=="GET"&&(L.headers={"Content-Type":"application/json"},L.body=JSON.stringify(u));let K=await fetch(F,L),te=await K.json();`${e}${c}${K.status}`,f.postMessage({type:"slot:fetch-response",id:c,data:te,status:K.status},"*");}catch(L){console.error(`[ForkSlot:${e}] fetch #${c} failed:`,L.message),f.postMessage({type:"slot:fetch-response",id:c,error:L.message},"*");}}}};return window.addEventListener("message",v),()=>{window.removeEventListener("message",v),x.current=false;}},[g?.bundleUrl,e,M,C]),useEffect(()=>{g?.bundleUrl&&x.current&&M(t||{});},[t,g?.bundleUrl,M]),!g||g.status!=="complete"||!g.bundleUrl)return `${e}${g?.status||"none"}${g?.bundleUrl||"none"}`,jsx(Fragment,{children:r});`${e}${g.bundleUrl}`;let I=`${d}${g.bundleUrl.replace("/bundle.js","/host")}`;return jsx("iframe",{ref:_,src:I,sandbox:"allow-scripts allow-same-origin allow-forms allow-clipboard-write",title:`Forked ${e}`,style:{width:"100%",border:"none",flex:1,minHeight:0}})}function tt({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 Mt({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(tt,{style:{width:24,height:24}})})}var zn={status:Loader2,agent_message:MessageSquare,tool_use:Wrench,build_start:Package,build_complete:Check,build_error:AlertCircle,complete:Sparkles,error:AlertCircle},Wn={status:"#60a5fa",agent_message:"#a0a0a0",tool_use:"#fbbf24",build_start:"#c084fc",build_complete:"#6b7280",build_error:"#f87171",complete:"#6b7280",error:"#f87171"},Kn={read:FileSearch,write:Pencil,search:FileSearch,shell:Terminal,build:Package},Gn={read:"#60a5fa",write:"#fbbf24",search:"#60a5fa",shell:"#a78bfa",build:"#c084fc"};function Lt(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 Er({events:e}){let t=useRef(null);return useEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight);},[e]),jsxs(Fragment,{children:[jsx("style",{children:`
4
4
  @keyframes __fork-spin {
5
5
  from { transform: rotate(0deg); }
6
6
  to { transform: rotate(360deg); }
@@ -18,7 +18,7 @@ import*as Rt from'react';import Rt__default,{createContext,useSyncExternalStore,
18
18
  .__fork-stream::-webkit-scrollbar-thumb:hover {
19
19
  background: rgba(255, 255, 255, 0.3);
20
20
  }
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"),a=Bn[r.type]||Code,p=Hn[r.type]||"#9ca3af";if(r.type==="tool_use"){let g=String(r.data.category||"");a=Nn[g]||Wrench,p=Dn[g]||"#fbbf24";}return s?a=Loader2:!o&&r.type==="status"&&(a=Check,p="#4ade80"),jsxs("div",{style:{display:"flex",gap:"6px",marginBottom:"6px",lineHeight:1.625},children:[jsx(a,{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:Ct(r)})]},n)})]})]})}var Fr=35,qn="Working on Feature",Xn="Built Custom Feature",Rr=360,tt=350;function Yn(e){return e.length<=Fr?e:e.slice(0,Fr-3).trimEnd()+"..."}function Zn({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 a="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"){a=Yn(Ct(g));break}}if(a!==i.current){o(false);let p=setTimeout(()=>{r(a),i.current=a,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 Qn({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 rt({state:e,fork:t,events:r,error:n,slotId:o,targetId:i,targetLabel:s,historyMode:a="slot",onSubmit:p,onUndo:g,onClose:d,baseUrl:S,apiKey:P,userId:R,userHash:x,appId:h,embedded:y=false}){let[T,A]=useState(""),[M,E]=useState([]),[I,v]=useState(false),[b,l]=useState(false),[$,F]=useState(false),[u,f]=useState(false),[m,L]=useState(false),[W,ee]=useState(false),[N,z]=useState(false),[Y,D]=useState(false),[te,ne]=useState(false),[ue,Z]=useState(null),[ct,Le]=useState(false),[Re,ie]=useState([]),[q,_]=useState(null),[w,U]=useState(false),[K,ae]=useState(false),[Br,Nt]=useState(false),[Hr,Dt]=useState(null),[re,Oe]=useState(null),[Nr,jt]=useState(false),[zt,we]=useState(null),[Dr,_e]=useState(false),[ve,Wt]=useState(null),dt=useRef(null),Ue=useRef(null),{resetAllForks:jr,previewSession:V,currentContainerId:zr}=J(),pe=V?.container_id??zr,Be=!!(V&&Dr),le=ve!==null,Kt=useRef(d);useEffect(()=>{Kt.current=d;});let ut=useRef(null),He=useRef(false),Gt=typeof window<"u"&&"documentPictureInPicture"in window,Wr=async()=>{if(!(!Gt||le))try{let c=await window.documentPictureInPicture.requestWindow({width:Rr,height:640});c.document.body.style.margin="0",c.document.body.style.padding="0",c.document.body.style.height="100vh",c.document.body.style.overflow="hidden",c.document.body.style.background="#ffffff";try{let k=document.adoptedStyleSheets??[];k.length>0&&(c.document.adoptedStyleSheets=[...k]);}catch{}c.addEventListener("pagehide",()=>{ut.current=null,Wt(null),He.current||Kt.current(),He.current=!1;},{once:!0}),ut.current=c,Wt(c);}catch(c){console.warn("[Fork] PiP open failed:",c);}},Kr=()=>{ve&&(He.current=true,ve.close());};useEffect(()=>()=>{He.current=true,ut.current?.close();},[]);let ce=i??o??"",Ne=(s||ce).replace(/[-_]+/g," ").replace(/\b\w/g,c=>c.toUpperCase()),De=useRef(""),je=y?true:b&&!$,Gr=r.find(c=>{let k=c.data;return c.type==="status"&&k.summary})?.data?.summary||t?.summary||qn,ge=r.find(c=>{let k=c.data;return (c.type==="status"||c.type==="complete")&&typeof k?.estimateMinutes=="number"})?.data?.estimateMinutes??t?.estimateMinutes;useEffect(()=>{if(a==="none"){v(true);return}if(!S||!P||!R||!ce||I||!w)return;if(V&&!q){E([]),v(true);return}let c=new AbortController,k=new URLSearchParams({userId:R});if(x&&k.set("userHash",x),q&&k.set("containerId",q),a==="slot")k.set("slotId",ce);else if(a==="boundary"){if(!h){v(true);return}k.set("boundaryId",ce),k.set("appId",h);}let O={Authorization:`Bearer ${P}`,...G()};return h&&(O["X-Fork-App-Id"]=h),fetch(`${S}/api/v1/forks/history?${k.toString()}`,{headers:O,signal:c.signal}).then(X=>X.ok?X.json():[]).then(X=>{if(c.signal.aborted)return;let Ke=[];for(let gt of X)gt.role==="user"?Ke.push({type:"user",text:gt.content}):Ke.push({type:"applied",text:gt.content});E(Ke),v(true);}).catch(()=>{c.signal.aborted||v(true);}),()=>{c.abort();}},[P,h,S,I,a,ce,x,R,q,w,V?.preview_session_id]),useEffect(()=>{e==="complete"&&D(false);},[e]),useEffect(()=>{if(y&&a==="none"){ie([]),_(null),U(true),_e(false);return}if(V){let c=false;return U(false),_e(false),we(null),fetch(`${S}/api/v1/preview/${encodeURIComponent(V.preview_session_id)}/containers`,{headers:{Authorization:`Bearer ${P}`,...G()}}).then(k=>{if(!k.ok)throw new Error(`${k.status}`);return k.json()}).then(k=>{c||(ie(k.containers),_(k.currentContainerId??V.container_id??null),_e(true));}).catch(k=>{c||(_e(false),we(k instanceof Error?k.message:String(k)),pe?(ie([{id:pe,name:V.container_name||"Primary container",createdAt:"",hasAccess:true,isPrimary:true}]),_(pe)):(ie([]),_(null)));}).finally(()=>{c||U(true);}),()=>{c=true;}}pe?(ie([{id:pe,name:"Primary container",createdAt:""}]),_(pe)):(ie([]),_(null)),U(true),_e(false);},[P,pe,S,y,a,V?.container_id,V?.container_name,V?.preview_session_id]);let ze=useRef(void 0);useEffect(()=>{if(w){if(ze.current===void 0){ze.current=q;return}ze.current!==q&&(ze.current=q,E([]),v(false));}},[q,w]);let We=useRef(null);useEffect(()=>{if(!K)return;let c=O=>{if(!We.current)return;let X=typeof O.composedPath=="function"?O.composedPath():[];We.current.contains(O.target)||X.includes(We.current)||ae(false);},k=O=>{O.key==="Escape"&&ae(false);};return document.addEventListener("mousedown",c,true),document.addEventListener("keydown",k,true),()=>{document.removeEventListener("mousedown",c,true),document.removeEventListener("keydown",k,true);}},[K]),useEffect(()=>{if(y)return;let c=requestAnimationFrame(()=>l(true));return ()=>cancelAnimationFrame(c)},[y]),useEffect(()=>{let c=y||le;if((c||je)&&(e==="prompting"||e==="complete")){let k=setTimeout(()=>dt.current?.focus(),c?100:tt+100);return ()=>clearTimeout(k)}},[je,y,le,e]),useEffect(()=>{if(e==="complete"&&De.current){let k=r.find(O=>O.type==="complete")?.data?.summary||t?.summary||Xn;E(O=>O[O.length-1]?.type==="applied"?O:[...O,{type:"applied",text:k}]),A(""),setTimeout(()=>dt.current?.focus(),200);}},[e,Ne,r,t?.summary]),useEffect(()=>{Ue.current&&(Ue.current.scrollTop=Ue.current.scrollHeight);},[M,e]);let Vt=()=>{T.trim()&&(De.current=T.trim(),E(c=>[...c,{type:"user",text:T.trim()}]),p(T.trim(),ce,q),A(""));},Jt=c=>{ye(c.session.containerId,c.session.containerName),_(c.session.containerId),ie(k=>{let O=k.filter(X=>X.id!==c.container.id);return [{...c.container,isPrimary:true,hasAccess:true},...O.map(X=>({...X,isPrimary:false}))]}),E([]),v(false),De.current="";},Vr=async c=>{if(!(!V||!Be||re)){Oe(c),we(null);try{let k=await fetch(`${S}/api/v1/preview/${encodeURIComponent(V.preview_session_id)}/containers/${encodeURIComponent(c)}/primary`,{method:"POST",headers:{Authorization:`Bearer ${P}`,...G()}});if(!k.ok){let O=await k.json().catch(()=>({}));throw new Error(O.error||`API error: ${k.status}`)}Jt(await k.json()),ae(!1);}catch(k){we(k instanceof Error?k.message:String(k));}finally{Oe(null);}}},Jr=async()=>{if(!V||!Be||re)return;let c=window.prompt("Container name","New container");if(!(!c||!c.trim())){Oe("__new__"),we(null);try{let k=await fetch(`${S}/api/v1/preview/${encodeURIComponent(V.preview_session_id)}/containers`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${P}`,...G()},body:JSON.stringify({name:c.trim()})});if(!k.ok){let O=await k.json().catch(()=>({}));throw new Error(O.error||`API error: ${k.status}`)}Jt(await k.json()),ae(!1);}catch(k){we(k instanceof Error?k.message:String(k));}finally{Oe(null);}}},qr=async()=>{if(!(!g||te||!ce)){ne(true);try{let c=await g(ce);E(k=>{let O=[...k];return O.length>=2&&O[O.length-1]?.type==="applied"?O.splice(-2,2):O.length>=1&&O[O.length-1]?.type==="applied"&&O.splice(-1,1),O}),c?.removed&&E([]);}catch{}finally{ne(false);}}},ft=()=>{if(y){d();return}if(le){ve?.close();return}F(true),l(false),setTimeout(()=>d(),tt);},Xr=y||le?{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:Rr,maxWidth:"100vw",background:"#ffffff",boxShadow:je?"-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:je?"translateX(0)":"translateX(100%)",transition:`transform ${tt}ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow ${tt}ms ease`,display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'},qt=Re.find(c=>c.id===q)?.name??(w?`Fork ${Ne}`:"Loading..."),pt=jsxs(Fragment,{children:[jsx("style",{children:`
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"),l=zn[r.type]||Code,p=Wn[r.type]||"#9ca3af";if(r.type==="tool_use"){let g=String(r.data.category||"");l=Kn[g]||Wrench,p=Gn[g]||"#fbbf24";}return s?l=Loader2:!o&&r.type==="status"&&(l=Check,p="#4ade80"),jsxs("div",{style:{display:"flex",gap:"6px",marginBottom:"6px",lineHeight:1.625},children:[jsx(l,{style:{width:"12px",height:"12px",marginTop:"2px",flexShrink:0,color:p,...s?{animation:"__fork-spin 1s linear infinite"}:{}}}),jsx("span",{style:{color:o&&!i?"#d1d5db":"#6b7280",wordBreak:"break-all"},children:Lt(r)})]},n)})]})]})}var $r=35,eo="Working on Feature",to="Built Custom Feature",Pr=360,ot=350;function ro(e){return e.length<=$r?e:e.slice(0,$r-3).trimEnd()+"..."}function no({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 l="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"){l=ro(Lt(g));break}}if(l!==i.current){o(false);let p=setTimeout(()=>{r(l),i.current=l,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 oo({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 st({state:e,fork:t,events:r,error:n,slotId:o,targetId:i,targetLabel:s,historyMode:l="slot",onSubmit:p,onUndo:g,onClose:d,baseUrl:S,apiKey:P,userId:_,userHash:x,appId:h,embedded:y=false}){let[T,A]=useState(""),[M,C]=useState([]),[I,v]=useState(false),[b,c]=useState(false),[$,F]=useState(false),[u,f]=useState(false),[m,L]=useState(false),[K,te]=useState(false),[N,z]=useState(false),[Q,D]=useState(false),[re,oe]=useState(false),[ue,ee]=useState(null),[ft,Be]=useState(false),[Re,ie]=useState([]),[Z,R]=useState(null),[k,U]=useState(false),[W,ae]=useState(false),[Wr,Gt]=useState(false),[Kr,Vt]=useState(null),[G,Ue]=useState(null),[Gr,Jt]=useState(false),[pt,He]=useState(false),[pe,Ee]=useState(""),gt=useRef(null),[qt,ge]=useState(null),[Vr,Ce]=useState(false),[Se,Xt]=useState(null),mt=useRef(null),Ne=useRef(null),{resetAllForks:Jr,previewSession:q,currentContainerId:qr}=X(),me=q?.container_id??qr,De=!!(q&&Vr),le=Se!==null,Yt=useRef(d);useEffect(()=>{Yt.current=d;});let ht=useRef(null),je=useRef(false),Zt=typeof window<"u"&&"documentPictureInPicture"in window,Xr=async()=>{if(!(!Zt||le))try{let a=await window.documentPictureInPicture.requestWindow({width:Pr,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 w=document.adoptedStyleSheets??[];w.length>0&&(a.document.adoptedStyleSheets=[...w]);}catch{}a.addEventListener("pagehide",()=>{ht.current=null,Xt(null),je.current||Yt.current(),je.current=!1;},{once:!0}),ht.current=a,Xt(a);}catch(a){console.warn("[Fork] PiP open failed:",a);}},Yr=()=>{Se&&(je.current=true,Se.close());};useEffect(()=>()=>{je.current=true,ht.current?.close();},[]);let ce=i??o??"",ze=(s||ce).replace(/[-_]+/g," ").replace(/\b\w/g,a=>a.toUpperCase()),We=useRef(""),Ke=y?true:b&&!$,Zr=r.find(a=>{let w=a.data;return a.type==="status"&&w.summary})?.data?.summary||t?.summary||eo,he=r.find(a=>{let w=a.data;return (a.type==="status"||a.type==="complete")&&typeof w?.estimateMinutes=="number"})?.data?.estimateMinutes??t?.estimateMinutes;useEffect(()=>{if(l==="none"){v(true);return}if(!S||!P||!_||!ce||I||!k)return;if(q&&!Z){C([]),v(true);return}let a=new AbortController,w=new URLSearchParams({userId:_});if(x&&w.set("userHash",x),Z&&w.set("containerId",Z),l==="slot")w.set("slotId",ce);else if(l==="boundary"){if(!h){v(true);return}w.set("boundaryId",ce),w.set("appId",h);}let O={Authorization:`Bearer ${P}`,...V()};return h&&(O["X-Fork-App-Id"]=h),fetch(`${S}/api/v1/forks/history?${w.toString()}`,{headers:O,signal:a.signal}).then(J=>J.ok?J.json():[]).then(J=>{if(a.signal.aborted)return;let Je=[];for(let kt of J)kt.role==="user"?Je.push({type:"user",text:kt.content}):Je.push({type:"applied",text:kt.content});C(Je),v(true);}).catch(()=>{a.signal.aborted||v(true);}),()=>{a.abort();}},[P,h,S,I,l,ce,x,_,Z,k,q?.preview_session_id]),useEffect(()=>{e==="complete"&&D(false);},[e]),useEffect(()=>{if(y&&l==="none"){ie([]),R(null),U(true),Ce(false);return}if(q){let a=false;return U(false),Ce(false),ge(null),fetch(`${S}/api/v1/preview/${encodeURIComponent(q.preview_session_id)}/containers`,{headers:{Authorization:`Bearer ${P}`,...V()}}).then(w=>{if(!w.ok)throw new Error(`${w.status}`);return w.json()}).then(w=>{a||(ie(w.containers),R(w.currentContainerId??q.container_id??null),Ce(true));}).catch(w=>{a||(Ce(false),ge(w instanceof Error?w.message:String(w)),me?(ie([{id:me,name:q.container_name||"Primary container",createdAt:"",hasAccess:true,isPrimary:true}]),R(me)):(ie([]),R(null)));}).finally(()=>{a||U(true);}),()=>{a=true;}}me?(ie([{id:me,name:"Primary container",createdAt:""}]),R(me)):(ie([]),R(null)),U(true),Ce(false);},[P,me,S,y,l,q?.container_id,q?.container_name,q?.preview_session_id]);let Ge=useRef(void 0);useEffect(()=>{if(k){if(Ge.current===void 0){Ge.current=Z;return}Ge.current!==Z&&(Ge.current=Z,C([]),v(false));}},[Z,k]);let Ve=useRef(null);useEffect(()=>{if(!W)return;let a=O=>{if(!Ve.current)return;let J=typeof O.composedPath=="function"?O.composedPath():[];Ve.current.contains(O.target)||J.includes(Ve.current)||ae(false);},w=O=>{O.key==="Escape"&&ae(false);};return document.addEventListener("mousedown",a,true),document.addEventListener("keydown",w,true),()=>{document.removeEventListener("mousedown",a,true),document.removeEventListener("keydown",w,true);}},[W]),useEffect(()=>{W||(He(false),Ee(""));},[W]),useEffect(()=>{pt&&(gt.current?.focus(),gt.current?.select());},[pt]),useEffect(()=>{if(y)return;let a=requestAnimationFrame(()=>c(true));return ()=>cancelAnimationFrame(a)},[y]),useEffect(()=>{let a=y||le;if((a||Ke)&&(e==="prompting"||e==="complete")){let w=setTimeout(()=>mt.current?.focus(),a?100:ot+100);return ()=>clearTimeout(w)}},[Ke,y,le,e]),useEffect(()=>{if(e==="complete"&&We.current){let w=r.find(O=>O.type==="complete")?.data?.summary||t?.summary||to;C(O=>O[O.length-1]?.type==="applied"?O:[...O,{type:"applied",text:w}]),A(""),setTimeout(()=>mt.current?.focus(),200);}},[e,ze,r,t?.summary]),useEffect(()=>{Ne.current&&(Ne.current.scrollTop=Ne.current.scrollHeight);},[M,e]);let Qt=()=>{T.trim()&&(We.current=T.trim(),C(a=>[...a,{type:"user",text:T.trim()}]),p(T.trim(),ce,Z),A(""));},er=a=>{ke(a.session.containerId,a.session.containerName),R(a.session.containerId),ie(w=>{let O=w.filter(J=>J.id!==a.container.id);return [{...a.container,isPrimary:true,hasAccess:true},...O.map(J=>({...J,isPrimary:false}))]}),C([]),v(false),We.current="";},Qr=async a=>{if(!(!q||!De||G)){Ue(a),ge(null);try{let w=await fetch(`${S}/api/v1/preview/${encodeURIComponent(q.preview_session_id)}/containers/${encodeURIComponent(a)}/primary`,{method:"POST",headers:{Authorization:`Bearer ${P}`,...V()}});if(!w.ok){let O=await w.json().catch(()=>({}));throw new Error(O.error||`API error: ${w.status}`)}er(await w.json()),ae(!1);}catch(w){ge(w instanceof Error?w.message:String(w));}finally{Ue(null);}}},tr=async a=>{if(!q||!De||G)return;let w=a.trim();if(w){Ue("__new__"),ge(null);try{let O=await fetch(`${S}/api/v1/preview/${encodeURIComponent(q.preview_session_id)}/containers`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${P}`,...V()},body:JSON.stringify({name:w})});if(!O.ok){let J=await O.json().catch(()=>({}));throw new Error(J.error||`API error: ${O.status}`)}er(await O.json()),He(!1),Ee(""),ae(!1);}catch(O){ge(O instanceof Error?O.message:String(O));}finally{Ue(null);}}},en=async()=>{if(!(!g||re||!ce)){oe(true);try{let a=await g(ce);C(w=>{let O=[...w];return O.length>=2&&O[O.length-1]?.type==="applied"?O.splice(-2,2):O.length>=1&&O[O.length-1]?.type==="applied"&&O.splice(-1,1),O}),a?.removed&&C([]);}catch{}finally{oe(false);}}},yt=()=>{if(y){d();return}if(le){Se?.close();return}F(true),c(false),setTimeout(()=>d(),ot);},tn=y||le?{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:Pr,maxWidth:"100vw",background:"#ffffff",boxShadow:Ke?"-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:Ke?"translateX(0)":"translateX(100%)",transition:`transform ${ot}ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow ${ot}ms ease`,display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'},rr=Re.find(a=>a.id===Z)?.name??(k?`Fork ${ze}`:"Loading..."),bt=jsxs(Fragment,{children:[jsx("style",{children:`
22
22
  @keyframes __fork-pulse {
23
23
  0%, 100% { opacity: 1; }
24
24
  50% { opacity: 0.5; }
@@ -40,5 +40,5 @@ import*as Rt from'react';import Rt__default,{createContext,useSyncExternalStore,
40
40
  scrollbar-width: thin;
41
41
  scrollbar-color: rgba(0, 0, 0, 0.12) transparent;
42
42
  }
43
- `}),jsxs("div",{className:"__fork-panel",style:Xr,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(Ze,{style:{width:16,height:16,color:"#1c4587",cursor:"pointer",flexShrink:0},onDoubleClick:async c=>{if(c.stopPropagation(),!ct&&confirm("Reset all forks? This will remove all forked components.")){Le(true);try{let k=await jr();`${k?.deleted??0}`,E([]),A(""),D(!1),ft();}catch(k){console.error("[Fork] Reset failed:",k);}finally{Le(false);}}}}),e==="running"?jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:Gr}):Re.length===0&&!Be?jsxs("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:["Fork ",Ne]}):Be?jsxs("div",{ref:We,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[jsxs("button",{type:"button",onClick:()=>{ae(c=>!c);},onMouseEnter:()=>Nt(true),onMouseLeave:()=>Nt(false),"aria-haspopup":"menu","aria-expanded":K,style:{display:"inline-flex",alignItems:"center",gap:4,padding:"3px 6px",border:"1px solid transparent",borderRadius:6,background:Br||K?"#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:qt}),jsx(ChevronDown,{style:{width:12,height:12,color:"#6b7280",flexShrink:0,transform:K?"rotate(180deg)":void 0,transition:"transform 0.15s"}})]}),K&&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:[Re.map(c=>{let k=c.id===q,O=Hr===c.id,X=re===c.id;return jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>Dt(c.id),onMouseLeave:()=>Dt(null),onClick:()=>{c.id!==q&&Vr(c.id);},disabled:!!re,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:O?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:re?"default":"pointer",textAlign:"left",fontWeight:k?600:400,opacity:re&&!X?.55:1},children:[jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:k&&jsx(Check,{style:{width:12,height:12}})}),jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:X?"Switching...":c.name})]},c.id)}),jsx("div",{style:{height:1,background:"#e5e7eb",margin:"4px 0"}}),jsx("button",{type:"button",role:"menuitem",onMouseEnter:()=>jt(true),onMouseLeave:()=>jt(false),onClick:()=>{Jr();},disabled:!!re,style:{display:"flex",alignItems:"center",width:"100%",padding:"6px 8px",border:"none",background:Nr?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:re?"default":"pointer",textAlign:"left",opacity:re&&re!=="__new__"?.55:1},children:re==="__new__"?"Creating...":"+ New container"}),zt&&jsx("div",{style:{padding:"6px 8px",fontSize:11,lineHeight:1.35,color:"#b91c1c"},children:zt})]})]}):jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:qt}),e==="running"&&jsx("span",{title:ge?`Estimated ~${ge} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:ge?"#1c4587":"#9ca3af",backgroundColor:ge?"rgba(28, 69, 135, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:ge?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:ge?`~${ge}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:[Gt&&jsx("button",{onClick:le?Kr:Wr,onMouseEnter:()=>L(true),onMouseLeave:()=>L(false),title:le?"Redock to sidebar":"Pop out into window",style:{padding:6,borderRadius:6,color:m?"#4b5563":"#9ca3af",backgroundColor:m?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:le?jsx(PictureInPicture,{style:{width:16,height:16}}):jsx(PictureInPicture2,{style:{width:16,height:16}})}),jsx("button",{onClick:ft,onMouseEnter:()=>f(true),onMouseLeave:()=>f(false),style:{padding:6,borderRadius:6,color:u?"#4b5563":"#9ca3af",backgroundColor:u?"#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:Ue,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[e==="prompting"&&M.length===0&&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."})}),M.length>0&&jsx("div",{style:{padding:"16px 16px 0 16px"},children:M.map((c,k)=>jsx("div",{style:{marginBottom:k<M.length-1?10:0},children:c.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:c.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:c.text}),g&&k===M.length-1&&e!=="running"&&jsxs("button",{onClick:O=>{O.stopPropagation(),qr();},onMouseEnter:()=>Z(k),onMouseLeave:()=>Z(null),disabled:te,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:ue===k?"rgba(0,0,0,0.06)":"transparent",color:ue===k?"#6b7280":"#d1d5db",cursor:te?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:te?.4:1,flexShrink:0},children:[jsx(Undo2,{style:{width:12,height:12}}),ue===k&&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"})]})]})]})},k))}),e==="running"&&jsx("div",{style:{padding:16},children:jsxs("div",{onClick:()=>D(!Y),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(Zn,{events:r})]}),jsx("div",{style:{color:"#6b7280",flexShrink:0,marginLeft:8,transition:"transform 0.2s ease",transform:Y?"rotate(180deg)":"rotate(0deg)"},children:jsx(ChevronDown,{style:{width:14,height:14}})})]}),jsx("div",{style:{maxHeight:Y?320:0,opacity:Y?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(wr,{events:r})})})]})}),e==="error"&&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 c=t?.prompt||De.current;c&&p(c,ce);},onMouseEnter:()=>z(true),onMouseLeave:()=>z(false),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,color:"#4f46e5",backgroundColor:N?"#e0e7ff":"#eef2ff",border:"none",cursor:"pointer",transition:"background-color 0.15s",fontFamily:"inherit"},children:[jsx(RotateCcw,{style:{width:12,height:12}})," Try Again"]})]})]}),e!=="running"&&jsx("div",{style:{padding:"8px 12px 12px 12px",borderTop:"1px solid rgba(229, 231, 235, 0.6)",flexShrink:0},children:jsxs("div",{style:{display:"flex",alignItems:"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:dt,value:T,onChange:c=>{A(c.target.value),c.target.style.height="auto",c.target.style.height=Math.min(c.target.scrollHeight,160)+"px";},onKeyDown:c=>{c.key==="Enter"&&!c.shiftKey&&(c.preventDefault(),Vt()),c.key==="Escape"&&!y&&ft();},placeholder:M.length>0?"Ask for another change...":`Describe your ideal ${Ne.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:Vt,disabled:!T.trim(),onMouseEnter:()=>ee(true),onMouseLeave:()=>ee(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:T.trim()?1:.25,transform:W&&T.trim()?"scale(1.1)":"scale(1)",background:T.trim()?"#1c4587":"rgba(0,0,0,0.12)",border:"none",cursor:T.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:jsx(ArrowUp,{style:{width:13,height:13}})})]})})]})]});return y?pt:le&&ve?createPortal(pt,ve.document.body):jsx(Qn,{children:pt})}function Er(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 Pt(e){let{apiKey:t,userId:r,userHash:n,baseUrl:o,appId:i,previewSession:s,refreshModuleManifest:a,queueBoundaryAnimation:p}=J(),[g,d]=useState("idle"),[S,P]=useState(null),[R,x]=useState([]),[h,y]=useState(null),T=useRef(null),A=useCallback(()=>{d("prompting"),x([]),y(null),P(null);},[]),M=useCallback(()=>{d("idle"),T.current&&(T.current.close(),T.current=null);},[]);useEffect(()=>{s&&s.target.kind==="module"&&s.target.id===e&&d(v=>v==="idle"?"prompting":v);},[s?.preview_session_id,s?.target.id,e]);let E=useCallback(async(v,b)=>{try{if(!i)throw new Error("ForkProvider requires appId for module boundary prompts.");d("running"),x([]),y(null);let l;if(s){let u=await fetch(`${o}/api/v1/preview/${encodeURIComponent(s.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...G()},body:JSON.stringify({prompt:v,...s.fork_id?{fork_id:s.fork_id}:{}})});if(!u.ok){let L=await u.json().catch(()=>({}));throw new Error(L.error||`API error: ${u.status}`)}let f=await u.json();f.container_id&&ye(f.container_id,f.container_name),Ae(f.fork_id),l=await(await fetch(`${o}/api/v1/forks/${f.fork_id}`,{headers:{Authorization:`Bearer ${t}`,...G()}})).json();}else {let u={userId:r,prompt:v,boundaryId:e,appId:i};b&&(u.containerId=b),n&&(u.userHash=n);let f=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(u)});if(!f.ok){let m=await f.json().catch(()=>({}));throw new Error(m.error||`API error: ${f.status}`)}l=await f.json();}P(l);let $=new URLSearchParams({key:t});n&&($.set("userId",r),$.set("userHash",n));let F=new EventSource(`${o}/api/v1/forks/${l.id}/events?${$.toString()}`);T.current=F,F.onmessage=u=>{try{let f=JSON.parse(u.data);if(x(m=>[...m,f]),f.type==="complete"){let m=f.data;p(e,l.id),a().catch(()=>{}).finally(()=>{let L={...l,status:"complete",moduleUrl:m.moduleUrl,cssUrls:m.cssUrls,summary:m.summary,completedAt:new Date().toISOString()};P(L),d("complete"),F.close();});}else if(f.type==="error"){let m=f.data;y(m.error||"Unknown error"),d("error"),F.close();}}catch{}},F.onerror=()=>{fetch(`${o}/api/v1/forks/${l.id}`,{headers:{Authorization:`Bearer ${t}`}}).then(u=>u.json()).then(u=>{P(u),u.status==="complete"?(p(e,u.id),a().catch(()=>{}),d("complete")):u.status==="error"&&(y(u.error||"Fork generation failed"),d("error"));}).catch(()=>{y("Connection lost"),d("error");}),F.close();};}catch(l){y(l.message),d("error");}},[t,i,o,e,s,p,a,n,r]),I=useCallback(async()=>{try{if(!i)throw new Error("ForkProvider requires appId for boundary undo.");let v={userId:r,boundaryId:e,appId:i};n&&(v.userHash=n);let b=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(v)});if(!b.ok){let $=await b.json().catch(()=>({}));throw new Error($.error||`API error: ${b.status}`)}let l=await b.json();return await a().catch(()=>{}),l.removed?(P(null),d("prompting")):l.fork&&(P(l.fork),d("complete")),l}catch(v){throw y(v.message),v}},[t,i,o,e,a,n,r]);return {state:g,fork:S,events:R,error:h,open:A,close:M,startFork:E,undoFork:I}}function Ar(e){let{state:t,fork:r,events:n,error:o,open:i,close:s,startFork:a,undoFork:p}=Pt(e);return {state:t,fork:r,events:n,error:o,isOpen:t!=="idle",open:i,close:s,submit:a,undo:p}}function Tt(){let{apiKey:e,userId:t,userHash:r,baseUrl:n,previewSession:o,setSlotFork:i,clearSlotFork:s,skipAnimationForSlot:a}=J(),[p,g]=useState("idle"),[d,S]=useState(null),[P,R]=useState([]),[x,h]=useState(null),y=useRef(null),T=useCallback(()=>{g("prompting"),R([]),h(null),S(null);},[]),A=useCallback(()=>{g("idle"),y.current&&(y.current.close(),y.current=null);},[]);useEffect(()=>{o&&o.target.kind==="slot"&&g(I=>I==="idle"?"prompting":I);},[o?.preview_session_id,o?.target.kind]);let M=useCallback(async(I,v,b)=>{try{g("running"),R([]),h(null);let l;if(o){let u=await fetch(`${n}/api/v1/preview/${encodeURIComponent(o.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...G()},body:JSON.stringify({prompt:I,...o.fork_id?{fork_id:o.fork_id}:{}})});if(!u.ok){let L=await u.json().catch(()=>({}));throw new Error(L.error||`API error: ${u.status}`)}let f=await u.json();f.container_id&&ye(f.container_id,f.container_name),Ae(f.fork_id),l=await(await fetch(`${n}/api/v1/forks/${f.fork_id}`,{headers:{Authorization:`Bearer ${e}`,...G()}})).json();}else {let u={userId:t,prompt:I};v&&(u.slotId=v),b&&(u.containerId=b),r&&(u.userHash=r);let f=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(u)});if(!f.ok){let m=await f.json().catch(()=>({}));throw new Error(m.error||`API error: ${f.status}`)}l=await f.json();}S(l);let $=new URLSearchParams({key:e});r&&($.set("userId",t),$.set("userHash",r));let F=new EventSource(`${n}/api/v1/forks/${l.id}/events?${$.toString()}`);y.current=F,F.onmessage=u=>{try{let f=JSON.parse(u.data);if(R(m=>[...m,f]),f.type==="complete"){let m=f.data,L={...l,status:"complete",bundleUrl:m.bundleUrl,summary:m.summary,completedAt:new Date().toISOString()};S(L),g("complete"),v&&m.bundleUrl&&i(v,L),F.close();}else if(f.type==="error"){let m=f.data;h(m.error||"Unknown error"),g("error"),F.close();}}catch{}},F.onerror=()=>{fetch(`${n}/api/v1/forks/${l.id}`,{headers:{Authorization:`Bearer ${e}`}}).then(u=>u.json()).then(u=>{S(u),u.status==="complete"?(g("complete"),v&&u.bundleUrl&&i(v,u)):u.status==="error"&&(h(u.error||"Fork generation failed"),g("error"));}).catch(()=>{h("Connection lost"),g("error");}),F.close();};}catch(l){h(l.message),g("error");}},[e,t,r,n,o,i]),E=useCallback(async I=>{try{let v={userId:t,slotId:I};r&&(v.userHash=r);let b=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(v)});if(!b.ok){let $=await b.json().catch(()=>({}));throw new Error($.error||`API error: ${b.status}`)}let l=await b.json();return a(I),l.removed?(s(I),S(null),g("prompting")):l.fork&&(i(I,l.fork),S(l.fork)),l}catch(v){throw h(v.message),v}},[e,t,r,n,s,i]);return {state:p,fork:d,events:P,error:x,open:T,close:A,startFork:M,undoFork:E}}function $r(){let{state:e,fork:t,events:r,error:n,open:o,close:i,startFork:s,undoFork:a}=Tt();return {state:e,fork:t,events:r,error:n,isOpen:e!=="idle",open:o,close:i,submit:s,undo:a}}function Mt(e){let t=Er(e),r=$r(),n=Ar(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:i,userId:s,userHash:a,appId:p}=J(),g=t.type==="slot"?r:n,d=t.type==="slot"?"slot":"boundary",S=t.id,P=t.title,R=useCallback((h,y,T)=>t.type==="slot"?r.submit(h,y??t.id,T):n.submit(h,T),[n,r,t]),x=useCallback(h=>t.type==="slot"?r.undo(h??t.id):n.undo(),[n,r,t]);return {...g,target:t,targetId:S,targetLabel:P,historyMode:d,submit:R,undo:x,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:d}:{targetId:S,targetLabel:P,historyMode:d},onSubmit:R,onUndo:x,onClose:g.close,baseUrl:o,apiKey:i,userId:s,userHash:a,appId:p}}}function Ie(e){let{embedded:t}=e,r=Mt(e);return t?jsx(rt,{...r.panelProps,embedded:true}):r.isOpen?jsx(rt,{...r.panelProps}):jsx(At,{...r.buttonProps})}function so({boundaryId:e,title:t}){return jsx(Ie,{boundaryId:e,title:t})}function Lt(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 Pr(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 Ot(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 Tr(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 a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Mr(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 a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Ir(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 Ut(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 d=0;d<e.length;d+=1){let{rect:S,borderRadius:P}=e[d],R=S.left-.5,x=S.top-.5,h=S.width+1,y=S.height+1,T=Math.min(P+.5,h/2,y/2),A=Ir(R,x,h,y,T),M=`__fork-glow-${d}`,E=document.createElementNS(t,"filter");E.setAttribute("id",M),E.setAttribute("x","-100%"),E.setAttribute("y","-100%"),E.setAttribute("width","300%"),E.setAttribute("height","300%");let I=document.createElementNS(t,"feGaussianBlur");I.setAttribute("in","SourceGraphic"),I.setAttribute("stdDeviation","8"),E.appendChild(I),o.appendChild(E);let v=`__fork-mask-${d}`,b=document.createElementNS(t,"mask");b.setAttribute("id",v),b.setAttribute("maskUnits","userSpaceOnUse"),b.setAttribute("x",String(R-200)),b.setAttribute("y",String(x-200)),b.setAttribute("width",String(h+400)),b.setAttribute("height",String(y+400));let l=document.createElementNS(t,"rect");l.setAttribute("x",String(R-200)),l.setAttribute("y",String(x-200)),l.setAttribute("width",String(h+400)),l.setAttribute("height",String(y+400)),l.setAttribute("fill","white"),b.appendChild(l);let $=document.createElementNS(t,"path");$.setAttribute("d",A),$.setAttribute("fill","black"),b.appendChild($),o.appendChild(b);let F=document.createElementNS(t,"g");F.setAttribute("mask",`url(#${v})`),F.setAttribute("opacity","0");let u=document.createElementNS(t,"g");u.setAttribute("filter",`url(#${M})`);let f=document.createElementNS(t,"path");f.setAttribute("d",A),f.setAttribute("fill","none"),f.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),f.setAttribute("stroke-width","6"),f.setAttribute("stroke-linecap","round"),u.appendChild(f),F.appendChild(u),n.appendChild(F);let m=document.createElementNS(t,"path");m.setAttribute("d",A),m.setAttribute("fill","none"),m.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),m.setAttribute("stroke-width","2"),m.setAttribute("stroke-linecap","round"),m.setAttribute("opacity","0"),n.appendChild(m),i.push(f,m),f.__group=F;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let d=0;d<i.length;d+=2){let S=i[d],P=i[d+1],R=S.__group;if(!R)continue;let x=P.getTotalLength(),h=S.getTotalLength();if(x<=0)continue;let y=x*.35;P.setAttribute("stroke-dasharray",`${y} ${x-y}`),P.setAttribute("stroke-dashoffset","0"),s.push(P.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*x,opacity:.92,offset:.06},{strokeDashoffset:-2*x,opacity:.92,offset:.92},{strokeDashoffset:-2.25*x,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let T=h*.35;S.setAttribute("stroke-dasharray",`${T} ${h-T}`),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(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 a=false,p=()=>{if(a)return;a=true,clearTimeout(g);for(let S of s)try{S.cancel();}catch{}let d=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});d.onfinish=()=>r.remove(),window.removeEventListener("click",p);},g=setTimeout(p,14500);return setTimeout(()=>{a||window.addEventListener("click",p);},500),p}function Lr(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:a,borderRadius:p}of e){let g=document.createElementNS(t,"path");g.setAttribute("d",Ir(a.left,a.top,a.width,a.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 lt=new Map,Bt=new Map;function lo(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function Ur(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 co(e){if(!e||typeof document>"u")return Promise.resolve();let t=lt.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 a=()=>{r.removeEventListener("load",a),r.removeEventListener("error",p),i();},p=()=>{r.removeEventListener("load",a),r.removeEventListener("error",p),s(new Error(`Failed to load boundary stylesheet: ${e}`));};r.addEventListener("load",a,{once:true}),r.addEventListener("error",p,{once:true});});return lt.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 lt.delete(e),o});return lt.set(e,n),n}function uo(e){let t=Bt.get(e);if(t)return t;let r=import(e).catch(n=>{throw Bt.delete(e),n});return Bt.set(e,r),r}async function fo(e,t,r){if(e)try{await Promise.all(e.cssUrls.map(i=>co(i)));let o=await uo(e.moduleUrl);return Ur(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 Ur(n,r)}function po(e){function t(r){let{appId:n,moduleOverridesEnabled:o,moduleManifestReady:i,moduleManifestVersion:s,registerBoundary:a,getBoundaryOverride:p,consumeBoundaryAnimation:g}=J(),[d,S]=useState(null),[P,R]=useState(null),x=useRef(null),h=useRef(null),y=useRef(null),T=useRef(false),A=useRef(null),M=useRef(null),E=p(e.id),I=E?`override:${E.id}`:"original",v=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if(useEffect(()=>()=>{M.current&&(clearTimeout(M.current),M.current=null),A.current&&(A.current.remove(),A.current=null);},[]),useEffect(()=>{a({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[n,a,e.id,e.exportName,v]),useEffect(()=>{if(o&&!i&&!d||h.current===I&&d)return;let b=false;return R(null),fo(E,e.original,e.exportName).then(l=>{if(!b){if(E?.id&&g(e.id,E.id)&&x.current){let $=Lt(x.current);if($){let F=Ot($);F.length>0&&(y.current=F,T.current=true,M.current&&(clearTimeout(M.current),M.current=null),A.current&&A.current.remove(),A.current=Pr($));}}h.current=I,startTransition(()=>{S(()=>l);});}}).catch(l=>{b||R(lo(l));}),()=>{b=true;}},[g,I,o,i,s,E?.id,E?.moduleUrl,E?.integrity,E?.cssUrls.join("|"),e.exportName,e.original,d]),useEffect(()=>{if(!T.current||!d||!x.current)return;let b=false;return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(b||!x.current)return;let l=y.current,$=Lt(x.current);if(y.current=null,T.current=false,!l||!$){A.current&&(A.current.remove(),A.current=null);return}let F=Ot($),u=Tr(l,F),f=Mr(l,F),m=A.current;if(f.length>0&&m){let L=Lr(f);M.current=setTimeout(()=>{M.current=null;let W=400;m.animate([{opacity:1},{opacity:0}],{duration:W,fill:"forwards"}),L.animate([{opacity:1},{opacity:0}],{duration:W,fill:"forwards"}),setTimeout(()=>{m.remove(),L.remove(),A.current===m&&(A.current=null),u.length>0&&Ut(u);},W);},3500);}else m&&(m.remove(),A.current===m&&(A.current=null)),u.length>0&&Ut(u);});}),()=>{b=true;}},[d]),P)throw P;return d?jsx("div",{ref:x,style:{display:"contents"},children:jsx(d,{...r})}):jsx(Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function mo({slotId:e,title:t,slotLabel:r}){return jsx(Ie,{slotId:e,title:t,slotLabel:r})}
44
- export{so as ForkBoundaryUI,At as ForkButton,Ie as ForkChatInterface,rt as ForkPanel,mn as ForkProvider,An as ForkSlot,mo as ForkUI,dn as clearCachedManifest,po as forkable,qe as loadManifest,un as manifestDiffers,ln as readCachedManifest,ht as registerForkShared,Pt as useBoundaryFork,Tt as useFork,Mt as useForkChatPanel,Je as usePreviewSession,cn as writeCachedManifest};
43
+ `}),jsxs("div",{className:"__fork-panel",style:tn,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(tt,{style:{width:16,height:16,color:"#1c4587",cursor:"pointer",flexShrink:0},onDoubleClick:async a=>{if(a.stopPropagation(),!ft&&confirm("Reset all forks? This will remove all forked components.")){Be(true);try{let w=await Jr();`${w?.deleted??0}`,C([]),A(""),D(!1),yt();}catch(w){console.error("[Fork] Reset failed:",w);}finally{Be(false);}}}}),e==="running"?jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:Zr}):Re.length===0&&!De?jsxs("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:["Fork ",ze]}):De?jsxs("div",{ref:Ve,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[jsxs("button",{type:"button",onClick:()=>{ae(a=>!a);},onMouseEnter:()=>Gt(true),onMouseLeave:()=>Gt(false),"aria-haspopup":"menu","aria-expanded":W,style:{display:"inline-flex",alignItems:"center",gap:4,padding:"3px 6px",border:"1px solid transparent",borderRadius:6,background:Wr||W?"#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:rr}),jsx(ChevronDown,{style:{width:12,height:12,color:"#6b7280",flexShrink:0,transform:W?"rotate(180deg)":void 0,transition:"transform 0.15s"}})]}),W&&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:[Re.map(a=>{let w=a.id===Z,O=Kr===a.id,J=G===a.id;return jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>Vt(a.id),onMouseLeave:()=>Vt(null),onClick:()=>{a.id!==Z&&Qr(a.id);},disabled:!!G,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:O?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:G?"default":"pointer",textAlign:"left",fontWeight:w?600:400,opacity:G&&!J?.55:1},children:[jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:w&&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"}}),pt?jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"4px 4px"},children:[jsx("input",{ref:gt,type:"text",value:pe,placeholder:"Container name",disabled:G==="__new__",onChange:a=>Ee(a.target.value),onKeyDown:a=>{a.key==="Enter"?(a.preventDefault(),tr(pe)):a.key==="Escape"&&(a.preventDefault(),a.stopPropagation(),He(false),Ee(""));},style:{flex:1,minWidth:0,padding:"5px 8px",border:"1px solid #d1d5db",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",background:"#ffffff",outline:"none"},onFocus:a=>{a.currentTarget.style.borderColor="#1c4587",a.currentTarget.style.boxShadow="0 0 0 2px rgba(28,69,135,0.15)";},onBlur:a=>{a.currentTarget.style.borderColor="#d1d5db",a.currentTarget.style.boxShadow="none";}}),jsx("button",{type:"button",onClick:()=>{tr(pe);},disabled:!pe.trim()||G==="__new__",title:"Create",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:26,height:26,border:"none",borderRadius:4,background:!pe.trim()||G==="__new__"?"#e5e7eb":"#1c4587",color:!pe.trim()||G==="__new__"?"#9ca3af":"#ffffff",cursor:!pe.trim()||G==="__new__"?"default":"pointer",flexShrink:0},children:G==="__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:()=>Jt(true),onMouseLeave:()=>Jt(false),onClick:()=>{G||(ge(null),Ee(""),He(true));},disabled:!!G,style:{display:"flex",alignItems:"center",width:"100%",padding:"6px 8px",border:"none",background:Gr?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:G?"default":"pointer",textAlign:"left",opacity:G&&G!=="__new__"?.55:1},children:"+ New container"}),qt&&jsx("div",{style:{padding:"6px 8px",fontSize:11,lineHeight:1.35,color:"#b91c1c"},children:qt})]})]}):jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:rr}),e==="running"&&jsx("span",{title:he?`Estimated ~${he} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:he?"#1c4587":"#9ca3af",backgroundColor:he?"rgba(28, 69, 135, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:he?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:he?`~${he}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:[Zt&&jsx("button",{onClick:le?Yr:Xr,onMouseEnter:()=>L(true),onMouseLeave:()=>L(false),title:le?"Redock to sidebar":"Pop out into window",style:{padding:6,borderRadius:6,color:m?"#4b5563":"#9ca3af",backgroundColor:m?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:le?jsx(PictureInPicture,{style:{width:16,height:16}}):jsx(PictureInPicture2,{style:{width:16,height:16}})}),jsx("button",{onClick:yt,onMouseEnter:()=>f(true),onMouseLeave:()=>f(false),style:{padding:6,borderRadius:6,color:u?"#4b5563":"#9ca3af",backgroundColor:u?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:jsx(X$1,{style:{width:16,height:16}})})]})]}),jsxs("div",{ref:Ne,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[e==="prompting"&&M.length===0&&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."})}),M.length>0&&jsx("div",{style:{padding:"16px 16px 0 16px"},children:M.map((a,w)=>jsx("div",{style:{marginBottom:w<M.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&&w===M.length-1&&e!=="running"&&jsxs("button",{onClick:O=>{O.stopPropagation(),en();},onMouseEnter:()=>ee(w),onMouseLeave:()=>ee(null),disabled:re,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:ue===w?"rgba(0,0,0,0.06)":"transparent",color:ue===w?"#6b7280":"#d1d5db",cursor:re?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:re?.4:1,flexShrink:0},children:[jsx(Undo2,{style:{width:12,height:12}}),ue===w&&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"})]})]})]})},w))}),e==="running"&&jsx("div",{style:{padding:16},children:jsxs("div",{onClick:()=>D(!Q),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(no,{events:r})]}),jsx("div",{style:{color:"#6b7280",flexShrink:0,marginLeft:8,transition:"transform 0.2s ease",transform:Q?"rotate(180deg)":"rotate(0deg)"},children:jsx(ChevronDown,{style:{width:14,height:14}})})]}),jsx("div",{style:{maxHeight:Q?320:0,opacity:Q?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(Er,{events:r})})})]})}),e==="error"&&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$1,{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||We.current;a&&p(a,ce);},onMouseEnter:()=>z(true),onMouseLeave:()=>z(false),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,color:"#4f46e5",backgroundColor:N?"#e0e7ff":"#eef2ff",border:"none",cursor:"pointer",transition:"background-color 0.15s",fontFamily:"inherit"},children:[jsx(RotateCcw,{style:{width:12,height:12}})," Try Again"]})]})]}),e!=="running"&&jsx("div",{style:{padding:"8px 12px 12px 12px",borderTop:"1px solid rgba(229, 231, 235, 0.6)",flexShrink:0},children:jsxs("div",{style:{display:"flex",alignItems:"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:mt,value:T,onChange:a=>{A(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(),Qt()),a.key==="Escape"&&!y&&yt();},placeholder:M.length>0?"Ask for another change...":`Describe your ideal ${ze.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:Qt,disabled:!T.trim(),onMouseEnter:()=>te(true),onMouseLeave:()=>te(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:T.trim()?1:.25,transform:K&&T.trim()?"scale(1.1)":"scale(1)",background:T.trim()?"#1c4587":"rgba(0,0,0,0.12)",border:"none",cursor:T.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:jsx(ArrowUp,{style:{width:13,height:13}})})]})})]})]});return y?bt:le&&Se?createPortal(bt,Se.document.body):jsx(oo,{children:bt})}function Mr(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 Bt(e){let{apiKey:t,userId:r,userHash:n,baseUrl:o,appId:i,previewSession:s,refreshModuleManifest:l,queueBoundaryAnimation:p}=X(),[g,d]=useState("idle"),[S,P]=useState(null),[_,x]=useState([]),[h,y]=useState(null),T=useRef(null),A=useCallback(()=>{d("prompting"),x([]),y(null),P(null);},[]),M=useCallback(()=>{d("idle"),T.current&&(T.current.close(),T.current=null);},[]);useEffect(()=>{s&&s.target.kind==="module"&&s.target.id===e&&d(v=>v==="idle"?"prompting":v);},[s?.preview_session_id,s?.target.id,e]);let C=useCallback(async(v,b)=>{try{if(!i)throw new Error("ForkProvider requires appId for module boundary prompts.");d("running"),x([]),y(null);let c;if(s){let u=await fetch(`${o}/api/v1/preview/${encodeURIComponent(s.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...V()},body:JSON.stringify({prompt:v,...s.fork_id?{fork_id:s.fork_id}:{}})});if(!u.ok){let L=await u.json().catch(()=>({}));throw new Error(L.error||`API error: ${u.status}`)}let f=await u.json();f.container_id&&ke(f.container_id,f.container_name),$e(f.fork_id),c=await(await fetch(`${o}/api/v1/forks/${f.fork_id}`,{headers:{Authorization:`Bearer ${t}`,...V()}})).json();}else {let u={userId:r,prompt:v,boundaryId:e,appId:i};b&&(u.containerId=b),n&&(u.userHash=n);let f=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(u)});if(!f.ok){let m=await f.json().catch(()=>({}));throw new Error(m.error||`API error: ${f.status}`)}c=await f.json();}P(c);let $=new URLSearchParams({key:t});n&&($.set("userId",r),$.set("userHash",n));let F=new EventSource(`${o}/api/v1/forks/${c.id}/events?${$.toString()}`);T.current=F,F.onmessage=u=>{try{let f=JSON.parse(u.data);if(x(m=>[...m,f]),f.type==="complete"){let m=f.data;p(e,c.id),l().catch(()=>{}).finally(()=>{let L={...c,status:"complete",moduleUrl:m.moduleUrl,cssUrls:m.cssUrls,summary:m.summary,completedAt:new Date().toISOString()};P(L),d("complete"),F.close();});}else if(f.type==="error"){let m=f.data;y(m.error||"Unknown error"),d("error"),F.close();}}catch{}},F.onerror=()=>{fetch(`${o}/api/v1/forks/${c.id}`,{headers:{Authorization:`Bearer ${t}`}}).then(u=>u.json()).then(u=>{P(u),u.status==="complete"?(p(e,u.id),l().catch(()=>{}),d("complete")):u.status==="error"&&(y(u.error||"Fork generation failed"),d("error"));}).catch(()=>{y("Connection lost"),d("error");}),F.close();};}catch(c){y(c.message),d("error");}},[t,i,o,e,s,p,l,n,r]),I=useCallback(async()=>{try{if(!i)throw new Error("ForkProvider requires appId for boundary undo.");let v={userId:r,boundaryId:e,appId:i};n&&(v.userHash=n);let b=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(v)});if(!b.ok){let $=await b.json().catch(()=>({}));throw new Error($.error||`API error: ${b.status}`)}let c=await b.json();return await l().catch(()=>{}),c.removed?(P(null),d("prompting")):c.fork&&(P(c.fork),d("complete")),c}catch(v){throw y(v.message),v}},[t,i,o,e,l,n,r]);return {state:g,fork:S,events:_,error:h,open:A,close:M,startFork:C,undoFork:I}}function Ir(e){let{state:t,fork:r,events:n,error:o,open:i,close:s,startFork:l,undoFork:p}=Bt(e);return {state:t,fork:r,events:n,error:o,isOpen:t!=="idle",open:i,close:s,submit:l,undo:p}}function Ut(){let{apiKey:e,userId:t,userHash:r,baseUrl:n,previewSession:o,setSlotFork:i,clearSlotFork:s,skipAnimationForSlot:l}=X(),[p,g]=useState("idle"),[d,S]=useState(null),[P,_]=useState([]),[x,h]=useState(null),y=useRef(null),T=useCallback(()=>{g("prompting"),_([]),h(null),S(null);},[]),A=useCallback(()=>{g("idle"),y.current&&(y.current.close(),y.current=null);},[]);useEffect(()=>{o&&o.target.kind==="slot"&&g(I=>I==="idle"?"prompting":I);},[o?.preview_session_id,o?.target.kind]);let M=useCallback(async(I,v,b)=>{try{g("running"),_([]),h(null);let c;if(o){let u=await fetch(`${n}/api/v1/preview/${encodeURIComponent(o.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...V()},body:JSON.stringify({prompt:I,...o.fork_id?{fork_id:o.fork_id}:{}})});if(!u.ok){let L=await u.json().catch(()=>({}));throw new Error(L.error||`API error: ${u.status}`)}let f=await u.json();f.container_id&&ke(f.container_id,f.container_name),$e(f.fork_id),c=await(await fetch(`${n}/api/v1/forks/${f.fork_id}`,{headers:{Authorization:`Bearer ${e}`,...V()}})).json();}else {let u={userId:t,prompt:I};v&&(u.slotId=v),b&&(u.containerId=b),r&&(u.userHash=r);let f=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(u)});if(!f.ok){let m=await f.json().catch(()=>({}));throw new Error(m.error||`API error: ${f.status}`)}c=await f.json();}S(c);let $=new URLSearchParams({key:e});r&&($.set("userId",t),$.set("userHash",r));let F=new EventSource(`${n}/api/v1/forks/${c.id}/events?${$.toString()}`);y.current=F,F.onmessage=u=>{try{let f=JSON.parse(u.data);if(_(m=>[...m,f]),f.type==="complete"){let m=f.data,L={...c,status:"complete",bundleUrl:m.bundleUrl,summary:m.summary,completedAt:new Date().toISOString()};S(L),g("complete"),v&&m.bundleUrl&&i(v,L),F.close();}else if(f.type==="error"){let m=f.data;h(m.error||"Unknown error"),g("error"),F.close();}}catch{}},F.onerror=()=>{fetch(`${n}/api/v1/forks/${c.id}`,{headers:{Authorization:`Bearer ${e}`}}).then(u=>u.json()).then(u=>{S(u),u.status==="complete"?(g("complete"),v&&u.bundleUrl&&i(v,u)):u.status==="error"&&(h(u.error||"Fork generation failed"),g("error"));}).catch(()=>{h("Connection lost"),g("error");}),F.close();};}catch(c){h(c.message),g("error");}},[e,t,r,n,o,i]),C=useCallback(async I=>{try{let v={userId:t,slotId:I};r&&(v.userHash=r);let b=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(v)});if(!b.ok){let $=await b.json().catch(()=>({}));throw new Error($.error||`API error: ${b.status}`)}let c=await b.json();return l(I),c.removed?(s(I),S(null),g("prompting")):c.fork&&(i(I,c.fork),S(c.fork)),c}catch(v){throw h(v.message),v}},[e,t,r,n,s,i]);return {state:p,fork:d,events:P,error:x,open:T,close:A,startFork:M,undoFork:C}}function Lr(){let{state:e,fork:t,events:r,error:n,open:o,close:i,startFork:s,undoFork:l}=Ut();return {state:e,fork:t,events:r,error:n,isOpen:e!=="idle",open:o,close:i,submit:s,undo:l}}function Ht(e){let t=Mr(e),r=Lr(),n=Ir(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:i,userId:s,userHash:l,appId:p}=X(),g=t.type==="slot"?r:n,d=t.type==="slot"?"slot":"boundary",S=t.id,P=t.title,_=useCallback((h,y,T)=>t.type==="slot"?r.submit(h,y??t.id,T):n.submit(h,T),[n,r,t]),x=useCallback(h=>t.type==="slot"?r.undo(h??t.id):n.undo(),[n,r,t]);return {...g,target:t,targetId:S,targetLabel:P,historyMode:d,submit:_,undo:x,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:d}:{targetId:S,targetLabel:P,historyMode:d},onSubmit:_,onUndo:x,onClose:g.close,baseUrl:o,apiKey:i,userId:s,userHash:l,appId:p}}}function Oe(e){let{embedded:t}=e,r=Ht(e);return t?jsx(st,{...r.panelProps,embedded:true}):r.isOpen?jsx(st,{...r.panelProps}):jsx(Mt,{...r.buttonProps})}function uo({boundaryId:e,title:t}){return jsx(Oe,{boundaryId:e,title:t})}function Dt(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 Br(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 jt(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 Ur(e,t){let r=[];for(let n of t)if(!(e.find(s=>s.tag===n.tag&&s.className===n.className&&Math.abs(s.rect.top-n.rect.top)<20&&Math.abs(s.rect.left-n.rect.left)<20)||r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom))){for(let s=r.length-1;s>=0;s-=1){let l=r[s];l.rect.top>=n.rect.top&&l.rect.left>=n.rect.left&&l.rect.right<=n.rect.right&&l.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Hr(e,t){let r=[];for(let n of e)if(!(t.find(s=>s.tag===n.tag&&s.className===n.className&&Math.abs(s.rect.top-n.rect.top)<20&&Math.abs(s.rect.left-n.rect.left)<20)||r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom))){for(let s=r.length-1;s>=0;s-=1){let l=r[s];l.rect.top>=n.rect.top&&l.rect.left>=n.rect.left&&l.rect.right<=n.rect.right&&l.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Nr(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 zt(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 d=0;d<e.length;d+=1){let{rect:S,borderRadius:P}=e[d],_=S.left-.5,x=S.top-.5,h=S.width+1,y=S.height+1,T=Math.min(P+.5,h/2,y/2),A=Nr(_,x,h,y,T),M=`__fork-glow-${d}`,C=document.createElementNS(t,"filter");C.setAttribute("id",M),C.setAttribute("x","-100%"),C.setAttribute("y","-100%"),C.setAttribute("width","300%"),C.setAttribute("height","300%");let I=document.createElementNS(t,"feGaussianBlur");I.setAttribute("in","SourceGraphic"),I.setAttribute("stdDeviation","8"),C.appendChild(I),o.appendChild(C);let v=`__fork-mask-${d}`,b=document.createElementNS(t,"mask");b.setAttribute("id",v),b.setAttribute("maskUnits","userSpaceOnUse"),b.setAttribute("x",String(_-200)),b.setAttribute("y",String(x-200)),b.setAttribute("width",String(h+400)),b.setAttribute("height",String(y+400));let c=document.createElementNS(t,"rect");c.setAttribute("x",String(_-200)),c.setAttribute("y",String(x-200)),c.setAttribute("width",String(h+400)),c.setAttribute("height",String(y+400)),c.setAttribute("fill","white"),b.appendChild(c);let $=document.createElementNS(t,"path");$.setAttribute("d",A),$.setAttribute("fill","black"),b.appendChild($),o.appendChild(b);let F=document.createElementNS(t,"g");F.setAttribute("mask",`url(#${v})`),F.setAttribute("opacity","0");let u=document.createElementNS(t,"g");u.setAttribute("filter",`url(#${M})`);let f=document.createElementNS(t,"path");f.setAttribute("d",A),f.setAttribute("fill","none"),f.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),f.setAttribute("stroke-width","6"),f.setAttribute("stroke-linecap","round"),u.appendChild(f),F.appendChild(u),n.appendChild(F);let m=document.createElementNS(t,"path");m.setAttribute("d",A),m.setAttribute("fill","none"),m.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),m.setAttribute("stroke-width","2"),m.setAttribute("stroke-linecap","round"),m.setAttribute("opacity","0"),n.appendChild(m),i.push(f,m),f.__group=F;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let d=0;d<i.length;d+=2){let S=i[d],P=i[d+1],_=S.__group;if(!_)continue;let x=P.getTotalLength(),h=S.getTotalLength();if(x<=0)continue;let y=x*.35;P.setAttribute("stroke-dasharray",`${y} ${x-y}`),P.setAttribute("stroke-dashoffset","0"),s.push(P.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*x,opacity:.92,offset:.06},{strokeDashoffset:-2*x,opacity:.92,offset:.92},{strokeDashoffset:-2.25*x,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let T=h*.35;S.setAttribute("stroke-dasharray",`${T} ${h-T}`),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 l=false,p=()=>{if(l)return;l=true,clearTimeout(g);for(let S of s)try{S.cancel();}catch{}let d=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});d.onfinish=()=>r.remove(),window.removeEventListener("click",p);},g=setTimeout(p,14500);return setTimeout(()=>{l||window.addEventListener("click",p);},500),p}function Dr(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-removed","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs"),i=document.createElementNS(t,"filter");i.setAttribute("id","__fork-removed-shadow"),i.setAttribute("x","-10%"),i.setAttribute("y","-10%"),i.setAttribute("width","120%"),i.setAttribute("height","120%");let s=document.createElementNS(t,"feDropShadow");s.setAttribute("dx","0"),s.setAttribute("dy","1"),s.setAttribute("stdDeviation","2"),s.setAttribute("flood-color","rgba(0,0,0,0.15)"),i.appendChild(s),o.appendChild(i),n.appendChild(o);for(let{rect:l,borderRadius:p}of e){let g=document.createElementNS(t,"path");g.setAttribute("d",Nr(l.left,l.top,l.width,l.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 ut=new Map,Wt=new Map;function go(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function zr(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 mo(e){if(!e||typeof document>"u")return Promise.resolve();let t=ut.get(e);if(t)return t;let r=document.querySelector(`link[data-fork-override-href="${e}"]`);if(r instanceof HTMLLinkElement){let o=r.sheet?Promise.resolve():new Promise((i,s)=>{let l=()=>{r.removeEventListener("load",l),r.removeEventListener("error",p),i();},p=()=>{r.removeEventListener("load",l),r.removeEventListener("error",p),s(new Error(`Failed to load boundary stylesheet: ${e}`));};r.addEventListener("load",l,{once:true}),r.addEventListener("error",p,{once:true});});return ut.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 ut.delete(e),o});return ut.set(e,n),n}function ho(e){let t=Wt.get(e);if(t)return t;let r=import(e).catch(n=>{throw Wt.delete(e),n});return Wt.set(e,r),r}async function yo(e,t,r){if(e)try{await Promise.all(e.cssUrls.map(i=>mo(i)));let o=await ho(e.moduleUrl);return zr(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 zr(n,r)}function bo(e){function t(r){let{appId:n,moduleOverridesEnabled:o,moduleManifestReady:i,moduleManifestVersion:s,registerBoundary:l,getBoundaryOverride:p,consumeBoundaryAnimation:g}=X(),[d,S]=useState(null),[P,_]=useState(null),x=useRef(null),h=useRef(null),y=useRef(null),T=useRef(false),A=useRef(null),M=useRef(null),C=p(e.id),I=C?`override:${C.id}`:"original",v=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if(useEffect(()=>()=>{M.current&&(clearTimeout(M.current),M.current=null),A.current&&(A.current.remove(),A.current=null);},[]),useEffect(()=>{l({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[n,l,e.id,e.exportName,v]),useEffect(()=>{if(o&&!i&&!d||h.current===I&&d)return;let b=false;return _(null),yo(C,e.original,e.exportName).then(c=>{if(!b){if(C?.id&&g(e.id,C.id)&&x.current){let $=Dt(x.current);if($){let F=jt($);F.length>0&&(y.current=F,T.current=true,M.current&&(clearTimeout(M.current),M.current=null),A.current&&A.current.remove(),A.current=Br($));}}h.current=I,startTransition(()=>{S(()=>c);});}}).catch(c=>{b||_(go(c));}),()=>{b=true;}},[g,I,o,i,s,C?.id,C?.moduleUrl,C?.integrity,C?.cssUrls.join("|"),e.exportName,e.original,d]),useEffect(()=>{if(!T.current||!d||!x.current)return;let b=false;return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(b||!x.current)return;let c=y.current,$=Dt(x.current);if(y.current=null,T.current=false,!c||!$){A.current&&(A.current.remove(),A.current=null);return}let F=jt($),u=Ur(c,F),f=Hr(c,F),m=A.current;if(f.length>0&&m){let L=Dr(f);M.current=setTimeout(()=>{M.current=null;let K=400;m.animate([{opacity:1},{opacity:0}],{duration:K,fill:"forwards"}),L.animate([{opacity:1},{opacity:0}],{duration:K,fill:"forwards"}),setTimeout(()=>{m.remove(),L.remove(),A.current===m&&(A.current=null),u.length>0&&zt(u);},K);},3500);}else m&&(m.remove(),A.current===m&&(A.current=null)),u.length>0&&zt(u);});}),()=>{b=true;}},[d]),P)throw P;return d?jsx("div",{ref:x,style:{display:"contents"},children:jsx(d,{...r})}):jsx(Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function wo({slotId:e,title:t,slotLabel:r}){return jsx(Oe,{slotId:e,title:t,slotLabel:r})}
44
+ export{uo as ForkBoundaryUI,Mt as ForkButton,Oe as ForkChatInterface,st as ForkPanel,wn as ForkProvider,Mn as ForkSlot,wo as ForkUI,mn as clearCachedManifest,bo as forkable,Ze as loadManifest,hn as manifestDiffers,pn as readCachedManifest,vt as registerForkShared,Bt as useBoundaryFork,Ut as useFork,Ht as useForkChatPanel,Ye as usePreviewSession,gn as writeCachedManifest};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fork-api/chat-sdk",
3
- "version": "0.1.141",
3
+ "version": "0.1.142",
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",