@fork-api/chat-sdk 0.1.129 → 0.1.131

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 He=require('react'),Ht=require('react-dom'),Ot=require('react/jsx-runtime'),Ut=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 He__namespace=/*#__PURE__*/_interopNamespace(He);var Ht__namespace=/*#__PURE__*/_interopNamespace(Ht);var Ot__namespace=/*#__PURE__*/_interopNamespace(Ot);var Ut__namespace=/*#__PURE__*/_interopNamespace(Ut);var re="__FORK_SHARED__";function Le(){var t,r,o,n;let e=globalThis;return e[re]||(e[re]={}),(t=e[re]).react||(t.react=He__namespace),(r=e[re])["react-dom"]||(r["react-dom"]=Ht__namespace),(o=e[re])["react/jsx-runtime"]||(o["react/jsx-runtime"]=Ot__namespace),(n=e[re])["react/jsx-dev-runtime"]||(n["react/jsx-dev-runtime"]=Ut__namespace),e[re]}function Be(e){return Object.assign(Le(),e)}var et=He.createContext(null);function Qe(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function jt(e,t){let r={};for(let[o,n]of Object.entries(t.boundaries||{}))r[o]={...n,moduleUrl:Qe(e,n.moduleUrl),cssUrls:Array.isArray(n.cssUrls)?n.cssUrls.map(i=>Qe(e,i)):[]};return r}function zt(e){let{apiKey:t,baseUrl:r,children:o,appId:n,shared:i}=e,s="userId"in e?e.userId:void 0,a="authUrl"in e?e.authUrl:void 0,[b,d]=He.useState({}),[m,S]=He.useState(s?{userId:s,userHash:void 0}:null),[P,w]=He.useState(!!s),[h,l]=He.useState({}),[$,T]=He.useState(!n),[R,C]=He.useState(0),F=He.useRef(new Map),y=He.useRef(new Map),[E,c]=He.useState(0),u=He.useRef(new Set),x=He.useRef(new Map),k=He.useRef(void 0);Le(),i&&k.current!==i&&(Be(i),k.current=i),He.useEffect(()=>{a&&(w(false),fetch(a,{credentials:"include"}).then(v=>{if(!v.ok)throw new Error(`Auth endpoint returned ${v.status}`);return v.json()}).then(v=>{if(!v.userId||typeof v.userId!="string")throw new Error("authUrl response must include userId");S({userId:v.userId,userHash:v.userHash});}).catch(v=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",v.message);}).finally(()=>{w(true);}));},[a]),He.useEffect(()=>{!a&&s&&(S({userId:s,userHash:void 0}),w(true));},[s,a]);let f=m?.userId??"",g=m?.userHash,p=!!n,B=He.useCallback(async()=>{if(!p){l({}),T(true),C(_=>_+1);return}if(!P){T(false);return}if(!f||!n){l({}),T(true),C(_=>_+1);return}let v=new URLSearchParams({appId:n,userId:f});g&&v.set("userHash",g),T(false);try{let _=await fetch(`${r}/api/v1/boundaries/manifest?${v.toString()}`,{headers:{Authorization:`Bearer ${t}`}});if(!_.ok)throw new Error(`${_.status}`);let N=await _.json();l(jt(r,N));}catch(_){console.error("[ForkProvider] Failed to fetch module override manifest:",_.message),l({});}finally{C(_=>_+1),T(true);}},[t,n,r,P,p,g,f]);He.useEffect(()=>{if(!f)return;let v=new URLSearchParams({userId:f});g&&v.set("userHash",g),fetch(`${r}/api/v1/forks/active?${v.toString()}`,{headers:{Authorization:`Bearer ${t}`}}).then(_=>{if(!_.ok)throw new Error(`${_.status}`);return _.json()}).then(_=>{_&&typeof _=="object"&&d(_);}).catch(()=>{});},[t,f,g,r]),He.useEffect(()=>{B();},[B]);let U=He.useCallback((v,_)=>{d(N=>({...N,[v]:_}));},[]),K=He.useCallback(v=>{d(_=>{let N={..._};return delete N[v],N});},[]),V=He.useCallback(v=>{u.current.add(v);},[]),G=He.useCallback(v=>u.current.has(v)?(u.current.delete(v),true):false,[]),Y=He.useCallback((v,_)=>{x.current.set(v,_);},[]),O=He.useCallback((v,_)=>x.current.get(v)!==_?false:(x.current.delete(v),true),[]),q=He.useCallback(v=>{if(!n)return;let _=JSON.stringify(v);F.current.get(v.id)===_||y.current.get(v.id)?.signature===_||(y.current.set(v.id,{boundary:v,signature:_}),c(z=>z+1));},[n]);He.useEffect(()=>{if(!n||y.current.size===0)return;let v=setTimeout(()=>{let _=Array.from(y.current.values());_.length!==0&&fetch(`${r}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:n,boundaries:_.map(N=>N.boundary)})}).then(N=>{if(!N.ok)throw new Error(`${N.status}`)}).then(()=>{for(let N of _)y.current.get(N.boundary.id)?.signature===N.signature&&(y.current.delete(N.boundary.id),F.current.set(N.boundary.id,N.signature));}).catch(N=>{console.error("[ForkProvider] Failed to register module boundaries:",N.message);});},50);return ()=>{clearTimeout(v);}},[t,n,r,E]);let W=He.useCallback(v=>h[v],[h]),ee=He.useCallback(async()=>{if(!g)throw new Error("Reset requires verified user identity (provide authUrl / userHash).");let v=new URLSearchParams({userId:f,userHash:g}),_=await fetch(`${r}/api/v1/forks/all?${v.toString()}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}});if(!_.ok){let z=await _.json().catch(()=>({}));throw new Error(z.error||`API error: ${_.status}`)}let N=await _.json().catch(()=>({}));d({}),l({}),T(true),C(z=>z+1),u.current.clear(),x.current.clear();try{for(let z=sessionStorage.length-1;z>=0;z-=1){let Z=sessionStorage.key(z);Z&&Z.startsWith("__fork_animated_")&&sessionStorage.removeItem(Z);}}catch{}return N},[t,r,g,f]);return Ot.jsx(et.Provider,{value:{apiKey:t,userId:f,userHash:g,baseUrl:r,appId:n,forks:b,moduleOverridesEnabled:p,moduleManifestReady:$,moduleManifestVersion:R,setSlotFork:U,clearSlotFork:K,skipAnimationForSlot:V,shouldSkipAnimation:G,queueBoundaryAnimation:Y,consumeBoundaryAnimation:O,registerBoundary:q,getBoundaryOverride:W,refreshModuleManifest:B,resetAllForks:ee},children:o})}function I(){let e=He.useContext(et);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function ke(e){return I().forks[e]}var fe=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 o=this.values.get(t);if(Object.is(o,r))return;if(o!==void 0&&r!==null&&o!==null&&typeof o=="object"&&typeof r=="object")try{if(JSON.stringify(o)===JSON.stringify(r))return}catch{}this.values.set(t,r),this.snapshots.set(t,r);let n=this.listeners.get(t);n&&n.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(o=>this.subscribe(t,o),()=>this.getSnapshot(t)):(console.warn("[ForkBridge] React.useSyncExternalStore not available, returning static value"),this.values.get(t))}emit(t,...r){let o=this.eventHandlers.get(t);o&&o.forEach(n=>n(...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 Oe(e,t){let r;try{r=He.Children.only(e);}catch{let n=He.Children.count(e);throw new Error(`<ForkSlot slotId="${t}"> must wrap exactly one React component, got ${n} children. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`)}let o=r.type;if(typeof o=="string")throw new Error(`<ForkSlot slotId="${t}"> child must be a React component (function or class), not an HTML element <${o}>. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`);if(typeof o=="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 rt=new Set;function ot(e){let t=[],r=e.querySelectorAll("*");for(let o of r){if(!(o instanceof HTMLElement))continue;let n=o.getBoundingClientRect();if(n.width<10||n.height<10||["SCRIPT","STYLE","META","LINK"].includes(o.tagName))continue;let i=getComputedStyle(o),s=parseFloat(i.borderTopLeftRadius)||0;t.push({tag:o.tagName,className:o.className||"",text:(o.textContent||"").slice(0,50).trim(),rect:n,borderRadius:s});}return t}function qt(e,t){let r=[];for(let o of t)if(!e.find(i=>i.tag===o.tag&&i.className===o.className&&Math.abs(i.rect.top-o.rect.top)<20&&Math.abs(i.rect.left-o.rect.left)<20)&&!r.some(s=>o.rect.top>=s.rect.top&&o.rect.left>=s.rect.left&&o.rect.right<=s.rect.right&&o.rect.bottom<=s.rect.bottom)){for(let s=r.length-1;s>=0;s--){let a=r[s];a.rect.top>=o.rect.top&&a.rect.left>=o.rect.left&&a.rect.right<=o.rect.right&&a.rect.bottom<=o.rect.bottom&&r.splice(s,1);}r.push({rect:o.rect,borderRadius:o.borderRadius});}return r}function Jt(e,t){let r=[];for(let o of e)if(!t.find(i=>i.tag===o.tag&&i.className===o.className&&Math.abs(i.rect.top-o.rect.top)<20&&Math.abs(i.rect.left-o.rect.left)<20)&&!r.some(s=>o.rect.top>=s.rect.top&&o.rect.left>=s.rect.left&&o.rect.right<=s.rect.right&&o.rect.bottom<=s.rect.bottom)){for(let s=r.length-1;s>=0;s--){let a=r[s];a.rect.top>=o.rect.top&&a.rect.left>=o.rect.left&&a.rect.right<=o.rect.right&&a.rect.bottom<=o.rect.bottom&&r.splice(s,1);}r.push({rect:o.rect,borderRadius:o.borderRadius});}return r}function st(e,t,r,o,n){return n=Math.max(0,Math.min(n,r/2,o/2)),n===0?`M ${e} ${t} L ${e+r} ${t} L ${e+r} ${t+o} L ${e} ${t+o} Z`:[`M ${e+n} ${t}`,`L ${e+r-n} ${t}`,`A ${n} ${n} 0 0 1 ${e+r} ${t+n}`,`L ${e+r} ${t+o-n}`,`A ${n} ${n} 0 0 1 ${e+r-n} ${t+o}`,`L ${e+n} ${t+o}`,`A ${n} ${n} 0 0 1 ${e} ${t+o-n}`,`L ${e} ${t+n}`,`A ${n} ${n} 0 0 1 ${e+n} ${t}`,"Z"].join(" ")}function nt(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 o=document.createElementNS(t,"svg");o.setAttribute("width","100%"),o.setAttribute("height","100%"),o.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let n=document.createElementNS(t,"defs");o.appendChild(n);let i=[];for(let m=0;m<e.length;m++){let{rect:S,borderRadius:P}=e[m],w=S.left-.5,h=S.top-.5,l=S.width+1,$=S.height+1,T=Math.min(P+.5,l/2,$/2),R=st(w,h,l,$,T),C=`__fork-glow-${m}`,F=document.createElementNS(t,"filter");F.setAttribute("id",C),F.setAttribute("x","-100%"),F.setAttribute("y","-100%"),F.setAttribute("width","300%"),F.setAttribute("height","300%");let y=document.createElementNS(t,"feGaussianBlur");y.setAttribute("in","SourceGraphic"),y.setAttribute("stdDeviation","8"),F.appendChild(y),n.appendChild(F);let E=`__fork-mask-${m}`,c=document.createElementNS(t,"mask");c.setAttribute("id",E),c.setAttribute("maskUnits","userSpaceOnUse"),c.setAttribute("x",String(w-200)),c.setAttribute("y",String(h-200)),c.setAttribute("width",String(l+400)),c.setAttribute("height",String($+400));let u=document.createElementNS(t,"rect");u.setAttribute("x",String(w-200)),u.setAttribute("y",String(h-200)),u.setAttribute("width",String(l+400)),u.setAttribute("height",String($+400)),u.setAttribute("fill","white"),c.appendChild(u);let x=document.createElementNS(t,"path");x.setAttribute("d",R),x.setAttribute("fill","black"),c.appendChild(x),n.appendChild(c);let k=document.createElementNS(t,"g");k.setAttribute("mask",`url(#${E})`),k.setAttribute("opacity","0");let f=document.createElementNS(t,"g");f.setAttribute("filter",`url(#${C})`);let g=document.createElementNS(t,"path");g.setAttribute("d",R),g.setAttribute("fill","none"),g.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),g.setAttribute("stroke-width","6"),g.setAttribute("stroke-linecap","round"),f.appendChild(g),k.appendChild(f),o.appendChild(k);let p=document.createElementNS(t,"path");p.setAttribute("d",R),p.setAttribute("fill","none"),p.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),p.setAttribute("stroke-width","2"),p.setAttribute("stroke-linecap","round"),p.setAttribute("opacity","0"),o.appendChild(p),i.push(g,p),g.__group=k;}r.appendChild(o),document.body.appendChild(r);let s=[];for(let m=0;m<i.length;m+=2){let S=i[m],P=i[m+1],w=S.__group,h=P.getTotalLength(),l=S.getTotalLength();if(h<=0)continue;let $=h*.35;P.setAttribute("stroke-dasharray",`${$} ${h-$}`),P.setAttribute("stroke-dashoffset","0"),s.push(P.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*h,opacity:.92,offset:.06},{strokeDashoffset:-2*h,opacity:.92,offset:.92},{strokeDashoffset:-2.25*h,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let T=l*.35;S.setAttribute("stroke-dasharray",`${T} ${l-T}`),S.setAttribute("stroke-dashoffset","0"),s.push(S.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*l,offset:.06},{strokeDashoffset:-2*l,offset:.92},{strokeDashoffset:-2.25*l,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(w.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,b=()=>{if(a)return;a=true,clearTimeout(d);for(let S of s)try{S.cancel();}catch{}let m=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});m.onfinish=()=>r.remove(),window.removeEventListener("click",b);},d=setTimeout(b,14500);return setTimeout(()=>{a||window.addEventListener("click",b);},500),b}function Yt(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 o=document.createElementNS(t,"svg");o.setAttribute("width","100%"),o.setAttribute("height","100%"),o.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let n=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),n.appendChild(i),o.appendChild(n);for(let{rect:a,borderRadius:b}of e){let d=a.left,m=a.top,S=a.width,P=a.height,w=Math.min(b,S/2,P/2),h=st(d,m,S,P,w),l=document.createElementNS(t,"path");l.setAttribute("d",h),l.setAttribute("fill","none"),l.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),l.setAttribute("stroke-width","1.5"),l.setAttribute("stroke-dasharray","8 4"),l.setAttribute("stroke-linecap","round"),l.setAttribute("filter","url(#__fork-removed-shadow)"),l.setAttribute("opacity","0"),o.appendChild(l),l.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(o),document.body.appendChild(r),r}function Xt(e,t){if(e===t)return true;let r=Object.keys(e);if(r.length!==Object.keys(t).length)return false;for(let o of r)if(!Object.is(e[o],t[o]))return false;return true}var Zt=He__namespace.default.memo(function({component:t,containerRef:r,wrapperStyle:o,hostProps:n}){return Ot.jsx("div",{ref:r,style:o,children:Ot.jsx(t,{...n})})},(e,t)=>e.component===t.component&&Xt(e.hostProps,t.hostProps)),Ne=class extends He__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 it({slotId:e,children:t,githubRepo:r,shared:o,events:n}){Oe(t,e);let i=ke(e),{baseUrl:s,apiKey:a,appId:b,shouldSkipAnimation:d}=I(),[m,S]=He.useState(null),P=He.useRef(null),w=He.useRef(null),h=He.useRef(null),l=He.useRef(false),$=He.useRef(null),T=He.useRef(null),R=!!(o||n),C=He.useRef(null);R&&!C.current&&(C.current=new fe(e));let F=He.useRef(n);if(F.current=n,He.useEffect(()=>{if(R)return ()=>{C.current?.destroy(),C.current=null;}},[R,e]),R&&C.current&&o)for(let[x,k]of Object.entries(o))C.current.set(x,k);He.useEffect(()=>{if(!R)return;C.current||(C.current=new fe(e));let x=C.current,k=Object.keys(F.current||{}).map(f=>x.on(f,(...g)=>F.current?.[f]?.(...g)));return ()=>k.forEach(f=>f())},[R,e]),He.useEffect(()=>{if(rt.has(e))return;rt.add(e);let x={id:e,appId:b,label:e,eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:r,mode:"direct",sharedKeys:o?Object.keys(o):[],eventNames:n?Object.keys(n):[],propsShape:"",callbackNames:[]};fetch(`${s}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify(x)}).catch(()=>{});},[e,s,a,r,b]);let y=i?.id||null;He.useEffect(()=>{if(i?.bundleUrl,P.current,w.current,!i?.bundleUrl||!y){return}let x=`${s}${i.bundleUrl.replace("bundle.js","component.js")}`,k=`__fork_animated_${e}`,f=sessionStorage.getItem(k),g=d(e),p=!g&&f!==y;if(g&&y&&sessionStorage.setItem(k,y),p&&w.current){let G=ot(w.current);h.current=G,l.current=true,`${e}${G.length}`;}window.__FORK_REACT__=He__namespace.default,window.__FORK_REACT_DOM__=Ht__namespace,window.__FORK_REACT_JSX__=Ot__namespace;let B=Date.now(),U=`${s}${i.bundleUrl.replace("bundle.js","component.css")}?t=${B}`,K=document.createElement("link");K.rel="stylesheet",K.href=U,K.dataset.forkSlot=e,document.head.appendChild(K);let V=document.createElement("script");return V.src=x+"?t="+B,V.onload=()=>{let G=window.__FORK_EXPORT__;if(G?.default){if(w.current&&h.current&&l.current){let Y=w.current.getBoundingClientRect(),O=w.current.cloneNode(true);O.style.position="fixed",O.style.top=`${Y.top}px`,O.style.left=`${Y.left}px`,O.style.width=`${Y.width}px`,O.style.height=`${Y.height}px`,O.style.flex="none",O.style.minHeight="auto",O.style.zIndex="9998",O.style.pointerEvents="none",O.style.overflow="hidden";let q=getComputedStyle(w.current).backgroundColor;O.style.backgroundColor=q&&q!=="rgba(0, 0, 0, 0)"&&q!=="transparent"?q:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(O);let W=w.current.querySelectorAll("*"),ee=O.querySelectorAll("*");for(let v=0;v<W.length;v++)W[v].scrollTop!==0&&(ee[v].scrollTop=W[v].scrollTop),W[v].scrollLeft!==0&&(ee[v].scrollLeft=W[v].scrollLeft);$.current=O;}S(()=>G.default),P.current=y;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},V.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(V),()=>{V.remove(),K.remove(),T.current&&(clearTimeout(T.current),T.current=null),$.current&&($.current.remove(),$.current=null);}},[y,s,e]),He.useEffect(()=>{if(!l.current||!m||!w.current){`${e}${l.current}`,w.current;return}let x=h.current;if(!x){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!w.current)return;let k=ot(w.current),f=qt(x,k),g=Jt(x,k),p=$.current;if(`${e}${f.length}${g.length}`,g.length>0&&p){let B=Yt(g);T.current=setTimeout(()=>{T.current=null;let U=400;p.animate([{opacity:1},{opacity:0}],{duration:U,fill:"forwards"}),B.animate([{opacity:1},{opacity:0}],{duration:U,fill:"forwards"}),setTimeout(()=>{p.remove(),B.remove(),$.current=null,f.length>0&&(nt(f));},U);},3500);}else p&&(p.remove(),$.current=null),f.length>0&&(nt(f));h.current=null,l.current=false,y&&(sessionStorage.setItem(`__fork_animated_${e}`,y),`${e}`);});});},[m]);let E={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!i||i.status!=="complete"||!i.bundleUrl)return Ot.jsx("div",{ref:w,style:E,children:t});if(!m)return Ot.jsx("div",{ref:w,style:E,children:t});let u=t?.props??{};return Ot.jsx(Ne,{slotId:e,resetKey:y,fallback:Ot.jsx("div",{ref:w,style:E,children:t}),children:Ot.jsx(Zt,{component:m,containerRef:w,wrapperStyle:E,hostProps:u})})}var lt=new Set;function tr(e){return `{ ${Object.entries(e).map(([r,o])=>o==null?`${r}: unknown`:Array.isArray(o)?`${r}: ${o.length>0?typeof o[0]:"unknown"}[]`:`${r}: ${typeof o}`).join("; ")} }`}function ct(e,t=new Set){return He.Children.forEach(e,r=>{if(!He.isValidElement(r))return;let o=r.props;for(let[n,i]of Object.entries(o))typeof i=="function"&&/^on[A-Z]/.test(n)&&t.add(n);o.children&&ct(o.children,t);}),t}function rr({slotId:e,props:t,children:r,allowedFetches:o,githubRepo:n,callbacks:i,mode:s="iframe",shared:a,events:b}){if(Oe(r,e),s==="direct")return Ot.jsx(it,{slotId:e,githubRepo:n,shared:a,events:b,children:r});let d=ke(e),{baseUrl:m,apiKey:S,appId:P}=I(),w=He.useRef(null),h=He.useRef(false),l=He.useRef(null),$=He.useRef(i);$.current=i;let T=He.useRef(t);T.current=t;let R=He.useRef(o);R.current=o,He.useEffect(()=>{if(typeof process<"u")return;let E=ct(r),c=new Set(i?Object.keys(i):[]),u=[...E].filter(x=>!c.has(x));u.length>0&&console.error(`[ForkSlot:${e}] Missing bridged callbacks! The following callback props are used by children but not passed to ForkSlot's \`callbacks\` prop:
1
+ 'use strict';var He=require('react'),Ht=require('react-dom'),Ot=require('react/jsx-runtime'),Ut=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 He__namespace=/*#__PURE__*/_interopNamespace(He);var Ht__namespace=/*#__PURE__*/_interopNamespace(Ht);var Ot__namespace=/*#__PURE__*/_interopNamespace(Ot);var Ut__namespace=/*#__PURE__*/_interopNamespace(Ut);var oe="__FORK_SHARED__";function Le(){var t,r,o,n;let e=globalThis;return e[oe]||(e[oe]={}),(t=e[oe]).react||(t.react=He__namespace),(r=e[oe])["react-dom"]||(r["react-dom"]=Ht__namespace),(o=e[oe])["react/jsx-runtime"]||(o["react/jsx-runtime"]=Ot__namespace),(n=e[oe])["react/jsx-dev-runtime"]||(n["react/jsx-dev-runtime"]=Ut__namespace),e[oe]}function Be(e){return Object.assign(Le(),e)}var tt=He.createContext(null);function et(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function jt(e,t){let r={};for(let[o,n]of Object.entries(t.boundaries||{}))r[o]={...n,moduleUrl:et(e,n.moduleUrl),cssUrls:Array.isArray(n.cssUrls)?n.cssUrls.map(i=>et(e,i)):[]};return r}function zt(e){let{apiKey:t,baseUrl:r,children:o,appId:n,shared:i}=e,s="userId"in e?e.userId:void 0,a="authUrl"in e?e.authUrl:void 0,[b,d]=He.useState({}),[m,S]=He.useState(s?{userId:s,userHash:void 0}:null),[_,w]=He.useState(!!s),[h,l]=He.useState({}),[$,T]=He.useState(!n),[R,C]=He.useState(0),F=He.useRef(new Map),y=He.useRef(new Map),[E,c]=He.useState(0),u=He.useRef(new Set),x=He.useRef(new Map),k=He.useRef(void 0);Le(),i&&k.current!==i&&(Be(i),k.current=i),He.useEffect(()=>{a&&(w(false),fetch(a,{credentials:"include"}).then(v=>{if(!v.ok)throw new Error(`Auth endpoint returned ${v.status}`);return v.json()}).then(v=>{if(!v.userId||typeof v.userId!="string")throw new Error("authUrl response must include userId");S({userId:v.userId,userHash:v.userHash});}).catch(v=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",v.message);}).finally(()=>{w(true);}));},[a]),He.useEffect(()=>{!a&&s&&(S({userId:s,userHash:void 0}),w(true));},[s,a]);let f=m?.userId??"",g=m?.userHash,p=!!n,B=He.useCallback(async()=>{if(!p){l({}),T(true),C(P=>P+1);return}if(!_){T(false);return}if(!f||!n){l({}),T(true),C(P=>P+1);return}let v=new URLSearchParams({appId:n,userId:f});g&&v.set("userHash",g),T(false);try{let P=await fetch(`${r}/api/v1/boundaries/manifest?${v.toString()}`,{headers:{Authorization:`Bearer ${t}`}});if(!P.ok)throw new Error(`${P.status}`);let N=await P.json();l(jt(r,N));}catch(P){console.error("[ForkProvider] Failed to fetch module override manifest:",P.message),l({});}finally{C(P=>P+1),T(true);}},[t,n,r,_,p,g,f]);He.useEffect(()=>{if(!f)return;let v=new URLSearchParams({userId:f});g&&v.set("userHash",g),fetch(`${r}/api/v1/forks/active?${v.toString()}`,{headers:{Authorization:`Bearer ${t}`}}).then(P=>{if(!P.ok)throw new Error(`${P.status}`);return P.json()}).then(P=>{P&&typeof P=="object"&&d(P);}).catch(()=>{});},[t,f,g,r]),He.useEffect(()=>{B();},[B]);let U=He.useCallback((v,P)=>{d(N=>({...N,[v]:P}));},[]),K=He.useCallback(v=>{d(P=>{let N={...P};return delete N[v],N});},[]),V=He.useCallback(v=>{u.current.add(v);},[]),G=He.useCallback(v=>u.current.has(v)?(u.current.delete(v),true):false,[]),Y=He.useCallback((v,P)=>{x.current.set(v,P);},[]),O=He.useCallback((v,P)=>x.current.get(v)!==P?false:(x.current.delete(v),true),[]),q=He.useCallback(v=>{if(!n)return;let P=JSON.stringify(v);F.current.get(v.id)===P||y.current.get(v.id)?.signature===P||(y.current.set(v.id,{boundary:v,signature:P}),c(z=>z+1));},[n]);He.useEffect(()=>{if(!n||y.current.size===0)return;let v=setTimeout(()=>{let P=Array.from(y.current.values());P.length!==0&&fetch(`${r}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:n,boundaries:P.map(N=>N.boundary)})}).then(N=>{if(!N.ok)throw new Error(`${N.status}`)}).then(()=>{for(let N of P)y.current.get(N.boundary.id)?.signature===N.signature&&(y.current.delete(N.boundary.id),F.current.set(N.boundary.id,N.signature));}).catch(N=>{console.error("[ForkProvider] Failed to register module boundaries:",N.message);});},50);return ()=>{clearTimeout(v);}},[t,n,r,E]);let W=He.useCallback(v=>h[v],[h]),te=He.useCallback(async()=>{if(!g)throw new Error("Reset requires verified user identity (provide authUrl / userHash).");let v=new URLSearchParams({userId:f,userHash:g}),P=await fetch(`${r}/api/v1/forks/all?${v.toString()}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}});if(!P.ok){let z=await P.json().catch(()=>({}));throw new Error(z.error||`API error: ${P.status}`)}let N=await P.json().catch(()=>({}));d({}),l({}),T(true),C(z=>z+1),u.current.clear(),x.current.clear();try{for(let z=sessionStorage.length-1;z>=0;z-=1){let Z=sessionStorage.key(z);Z&&Z.startsWith("__fork_animated_")&&sessionStorage.removeItem(Z);}}catch{}return N},[t,r,g,f]);return Ot.jsx(tt.Provider,{value:{apiKey:t,userId:f,userHash:g,baseUrl:r,appId:n,forks:b,moduleOverridesEnabled:p,moduleManifestReady:$,moduleManifestVersion:R,setSlotFork:U,clearSlotFork:K,skipAnimationForSlot:V,shouldSkipAnimation:G,queueBoundaryAnimation:Y,consumeBoundaryAnimation:O,registerBoundary:q,getBoundaryOverride:W,refreshModuleManifest:B,resetAllForks:te},children:o})}function j(){let e=He.useContext(tt);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function be(e){return j().forks[e]}var ue=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 o=this.values.get(t);if(Object.is(o,r))return;if(o!==void 0&&r!==null&&o!==null&&typeof o=="object"&&typeof r=="object")try{if(JSON.stringify(o)===JSON.stringify(r))return}catch{}this.values.set(t,r),this.snapshots.set(t,r);let n=this.listeners.get(t);n&&n.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(o=>this.subscribe(t,o),()=>this.getSnapshot(t)):(console.warn("[ForkBridge] React.useSyncExternalStore not available, returning static value"),this.values.get(t))}emit(t,...r){let o=this.eventHandlers.get(t);o&&o.forEach(n=>n(...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 Oe(e,t){let r;try{r=He.Children.only(e);}catch{let n=He.Children.count(e);throw new Error(`<ForkSlot slotId="${t}"> must wrap exactly one React component, got ${n} children. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`)}let o=r.type;if(typeof o=="string")throw new Error(`<ForkSlot slotId="${t}"> child must be a React component (function or class), not an HTML element <${o}>. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`);if(typeof o=="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 ot=new Set;function nt(e){let t=[],r=e.querySelectorAll("*");for(let o of r){if(!(o instanceof HTMLElement))continue;let n=o.getBoundingClientRect();if(n.width<10||n.height<10||["SCRIPT","STYLE","META","LINK"].includes(o.tagName))continue;let i=getComputedStyle(o),s=parseFloat(i.borderTopLeftRadius)||0;t.push({tag:o.tagName,className:o.className||"",text:(o.textContent||"").slice(0,50).trim(),rect:n,borderRadius:s});}return t}function qt(e,t){let r=[];for(let o of t)if(!e.find(i=>i.tag===o.tag&&i.className===o.className&&Math.abs(i.rect.top-o.rect.top)<20&&Math.abs(i.rect.left-o.rect.left)<20)&&!r.some(s=>o.rect.top>=s.rect.top&&o.rect.left>=s.rect.left&&o.rect.right<=s.rect.right&&o.rect.bottom<=s.rect.bottom)){for(let s=r.length-1;s>=0;s--){let a=r[s];a.rect.top>=o.rect.top&&a.rect.left>=o.rect.left&&a.rect.right<=o.rect.right&&a.rect.bottom<=o.rect.bottom&&r.splice(s,1);}r.push({rect:o.rect,borderRadius:o.borderRadius});}return r}function Jt(e,t){let r=[];for(let o of e)if(!t.find(i=>i.tag===o.tag&&i.className===o.className&&Math.abs(i.rect.top-o.rect.top)<20&&Math.abs(i.rect.left-o.rect.left)<20)&&!r.some(s=>o.rect.top>=s.rect.top&&o.rect.left>=s.rect.left&&o.rect.right<=s.rect.right&&o.rect.bottom<=s.rect.bottom)){for(let s=r.length-1;s>=0;s--){let a=r[s];a.rect.top>=o.rect.top&&a.rect.left>=o.rect.left&&a.rect.right<=o.rect.right&&a.rect.bottom<=o.rect.bottom&&r.splice(s,1);}r.push({rect:o.rect,borderRadius:o.borderRadius});}return r}function it(e,t,r,o,n){return n=Math.max(0,Math.min(n,r/2,o/2)),n===0?`M ${e} ${t} L ${e+r} ${t} L ${e+r} ${t+o} L ${e} ${t+o} Z`:[`M ${e+n} ${t}`,`L ${e+r-n} ${t}`,`A ${n} ${n} 0 0 1 ${e+r} ${t+n}`,`L ${e+r} ${t+o-n}`,`A ${n} ${n} 0 0 1 ${e+r-n} ${t+o}`,`L ${e+n} ${t+o}`,`A ${n} ${n} 0 0 1 ${e} ${t+o-n}`,`L ${e} ${t+n}`,`A ${n} ${n} 0 0 1 ${e+n} ${t}`,"Z"].join(" ")}function st(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 o=document.createElementNS(t,"svg");o.setAttribute("width","100%"),o.setAttribute("height","100%"),o.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let n=document.createElementNS(t,"defs");o.appendChild(n);let i=[];for(let m=0;m<e.length;m++){let{rect:S,borderRadius:_}=e[m],w=S.left-.5,h=S.top-.5,l=S.width+1,$=S.height+1,T=Math.min(_+.5,l/2,$/2),R=it(w,h,l,$,T),C=`__fork-glow-${m}`,F=document.createElementNS(t,"filter");F.setAttribute("id",C),F.setAttribute("x","-100%"),F.setAttribute("y","-100%"),F.setAttribute("width","300%"),F.setAttribute("height","300%");let y=document.createElementNS(t,"feGaussianBlur");y.setAttribute("in","SourceGraphic"),y.setAttribute("stdDeviation","8"),F.appendChild(y),n.appendChild(F);let E=`__fork-mask-${m}`,c=document.createElementNS(t,"mask");c.setAttribute("id",E),c.setAttribute("maskUnits","userSpaceOnUse"),c.setAttribute("x",String(w-200)),c.setAttribute("y",String(h-200)),c.setAttribute("width",String(l+400)),c.setAttribute("height",String($+400));let u=document.createElementNS(t,"rect");u.setAttribute("x",String(w-200)),u.setAttribute("y",String(h-200)),u.setAttribute("width",String(l+400)),u.setAttribute("height",String($+400)),u.setAttribute("fill","white"),c.appendChild(u);let x=document.createElementNS(t,"path");x.setAttribute("d",R),x.setAttribute("fill","black"),c.appendChild(x),n.appendChild(c);let k=document.createElementNS(t,"g");k.setAttribute("mask",`url(#${E})`),k.setAttribute("opacity","0");let f=document.createElementNS(t,"g");f.setAttribute("filter",`url(#${C})`);let g=document.createElementNS(t,"path");g.setAttribute("d",R),g.setAttribute("fill","none"),g.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),g.setAttribute("stroke-width","6"),g.setAttribute("stroke-linecap","round"),f.appendChild(g),k.appendChild(f),o.appendChild(k);let p=document.createElementNS(t,"path");p.setAttribute("d",R),p.setAttribute("fill","none"),p.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),p.setAttribute("stroke-width","2"),p.setAttribute("stroke-linecap","round"),p.setAttribute("opacity","0"),o.appendChild(p),i.push(g,p),g.__group=k;}r.appendChild(o),document.body.appendChild(r);let s=[];for(let m=0;m<i.length;m+=2){let S=i[m],_=i[m+1],w=S.__group,h=_.getTotalLength(),l=S.getTotalLength();if(h<=0)continue;let $=h*.35;_.setAttribute("stroke-dasharray",`${$} ${h-$}`),_.setAttribute("stroke-dashoffset","0"),s.push(_.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*h,opacity:.92,offset:.06},{strokeDashoffset:-2*h,opacity:.92,offset:.92},{strokeDashoffset:-2.25*h,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let T=l*.35;S.setAttribute("stroke-dasharray",`${T} ${l-T}`),S.setAttribute("stroke-dashoffset","0"),s.push(S.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*l,offset:.06},{strokeDashoffset:-2*l,offset:.92},{strokeDashoffset:-2.25*l,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(w.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,b=()=>{if(a)return;a=true,clearTimeout(d);for(let S of s)try{S.cancel();}catch{}let m=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});m.onfinish=()=>r.remove(),window.removeEventListener("click",b);},d=setTimeout(b,14500);return setTimeout(()=>{a||window.addEventListener("click",b);},500),b}function Yt(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 o=document.createElementNS(t,"svg");o.setAttribute("width","100%"),o.setAttribute("height","100%"),o.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let n=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),n.appendChild(i),o.appendChild(n);for(let{rect:a,borderRadius:b}of e){let d=a.left,m=a.top,S=a.width,_=a.height,w=Math.min(b,S/2,_/2),h=it(d,m,S,_,w),l=document.createElementNS(t,"path");l.setAttribute("d",h),l.setAttribute("fill","none"),l.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),l.setAttribute("stroke-width","1.5"),l.setAttribute("stroke-dasharray","8 4"),l.setAttribute("stroke-linecap","round"),l.setAttribute("filter","url(#__fork-removed-shadow)"),l.setAttribute("opacity","0"),o.appendChild(l),l.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(o),document.body.appendChild(r),r}function Xt(e,t){if(e===t)return true;let r=Object.keys(e);if(r.length!==Object.keys(t).length)return false;for(let o of r)if(!Object.is(e[o],t[o]))return false;return true}var Zt=He__namespace.default.memo(function({component:t,containerRef:r,wrapperStyle:o,hostProps:n}){return Ot.jsx("div",{ref:r,style:o,children:Ot.jsx(t,{...n})})},(e,t)=>e.component===t.component&&Xt(e.hostProps,t.hostProps)),Ne=class extends He__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 at({slotId:e,children:t,githubRepo:r,shared:o,events:n}){Oe(t,e);let i=be(e),{baseUrl:s,apiKey:a,appId:b,shouldSkipAnimation:d}=j(),[m,S]=He.useState(null),_=He.useRef(null),w=He.useRef(null),h=He.useRef(null),l=He.useRef(false),$=He.useRef(null),T=He.useRef(null),R=!!(o||n),C=He.useRef(null);R&&!C.current&&(C.current=new ue(e));let F=He.useRef(n);if(F.current=n,He.useEffect(()=>{if(R)return ()=>{C.current?.destroy(),C.current=null;}},[R,e]),R&&C.current&&o)for(let[x,k]of Object.entries(o))C.current.set(x,k);He.useEffect(()=>{if(!R)return;C.current||(C.current=new ue(e));let x=C.current,k=Object.keys(F.current||{}).map(f=>x.on(f,(...g)=>F.current?.[f]?.(...g)));return ()=>k.forEach(f=>f())},[R,e]),He.useEffect(()=>{if(ot.has(e))return;ot.add(e);let x={id:e,appId:b,label:e,eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:r,mode:"direct",sharedKeys:o?Object.keys(o):[],eventNames:n?Object.keys(n):[],propsShape:"",callbackNames:[]};fetch(`${s}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify(x)}).catch(()=>{});},[e,s,a,r,b]);let y=i?.id||null;He.useEffect(()=>{if(i?.bundleUrl,_.current,w.current,!i?.bundleUrl||!y){return}let x=`${s}${i.bundleUrl.replace("bundle.js","component.js")}`,k=`__fork_animated_${e}`,f=sessionStorage.getItem(k),g=d(e),p=!g&&f!==y;if(g&&y&&sessionStorage.setItem(k,y),p&&w.current){let G=nt(w.current);h.current=G,l.current=true,`${e}${G.length}`;}window.__FORK_REACT__=He__namespace.default,window.__FORK_REACT_DOM__=Ht__namespace,window.__FORK_REACT_JSX__=Ot__namespace;let B=Date.now(),U=`${s}${i.bundleUrl.replace("bundle.js","component.css")}?t=${B}`,K=document.createElement("link");K.rel="stylesheet",K.href=U,K.dataset.forkSlot=e,document.head.appendChild(K);let V=document.createElement("script");return V.src=x+"?t="+B,V.onload=()=>{let G=window.__FORK_EXPORT__;if(G?.default){if(w.current&&h.current&&l.current){let Y=w.current.getBoundingClientRect(),O=w.current.cloneNode(true);O.style.position="fixed",O.style.top=`${Y.top}px`,O.style.left=`${Y.left}px`,O.style.width=`${Y.width}px`,O.style.height=`${Y.height}px`,O.style.flex="none",O.style.minHeight="auto",O.style.zIndex="9998",O.style.pointerEvents="none",O.style.overflow="hidden";let q=getComputedStyle(w.current).backgroundColor;O.style.backgroundColor=q&&q!=="rgba(0, 0, 0, 0)"&&q!=="transparent"?q:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(O);let W=w.current.querySelectorAll("*"),te=O.querySelectorAll("*");for(let v=0;v<W.length;v++)W[v].scrollTop!==0&&(te[v].scrollTop=W[v].scrollTop),W[v].scrollLeft!==0&&(te[v].scrollLeft=W[v].scrollLeft);$.current=O;}S(()=>G.default),_.current=y;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},V.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(V),()=>{V.remove(),K.remove(),T.current&&(clearTimeout(T.current),T.current=null),$.current&&($.current.remove(),$.current=null);}},[y,s,e]),He.useEffect(()=>{if(!l.current||!m||!w.current){`${e}${l.current}`,w.current;return}let x=h.current;if(!x){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!w.current)return;let k=nt(w.current),f=qt(x,k),g=Jt(x,k),p=$.current;if(`${e}${f.length}${g.length}`,g.length>0&&p){let B=Yt(g);T.current=setTimeout(()=>{T.current=null;let U=400;p.animate([{opacity:1},{opacity:0}],{duration:U,fill:"forwards"}),B.animate([{opacity:1},{opacity:0}],{duration:U,fill:"forwards"}),setTimeout(()=>{p.remove(),B.remove(),$.current=null,f.length>0&&(st(f));},U);},3500);}else p&&(p.remove(),$.current=null),f.length>0&&(st(f));h.current=null,l.current=false,y&&(sessionStorage.setItem(`__fork_animated_${e}`,y),`${e}`);});});},[m]);let E={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!i||i.status!=="complete"||!i.bundleUrl)return Ot.jsx("div",{ref:w,style:E,children:t});if(!m)return Ot.jsx("div",{ref:w,style:E,children:t});let u=t?.props??{};return Ot.jsx(Ne,{slotId:e,resetKey:y,fallback:Ot.jsx("div",{ref:w,style:E,children:t}),children:Ot.jsx(Zt,{component:m,containerRef:w,wrapperStyle:E,hostProps:u})})}var ct=new Set;function tr(e){return `{ ${Object.entries(e).map(([r,o])=>o==null?`${r}: unknown`:Array.isArray(o)?`${r}: ${o.length>0?typeof o[0]:"unknown"}[]`:`${r}: ${typeof o}`).join("; ")} }`}function ut(e,t=new Set){return He.Children.forEach(e,r=>{if(!He.isValidElement(r))return;let o=r.props;for(let[n,i]of Object.entries(o))typeof i=="function"&&/^on[A-Z]/.test(n)&&t.add(n);o.children&&ut(o.children,t);}),t}function rr({slotId:e,props:t,children:r,allowedFetches:o,githubRepo:n,callbacks:i,mode:s="iframe",shared:a,events:b}){if(Oe(r,e),s==="direct")return Ot.jsx(at,{slotId:e,githubRepo:n,shared:a,events:b,children:r});let d=be(e),{baseUrl:m,apiKey:S,appId:_}=j(),w=He.useRef(null),h=He.useRef(false),l=He.useRef(null),$=He.useRef(i);$.current=i;let T=He.useRef(t);T.current=t;let R=He.useRef(o);R.current=o,He.useEffect(()=>{if(typeof process<"u")return;let E=ut(r),c=new Set(i?Object.keys(i):[]),u=[...E].filter(x=>!c.has(x));u.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
2
  `+u.map(x=>` - ${x}`).join(`
3
- `)+"\n\nThe forked component will not be able to call these. Add them to the `callbacks` prop of <ForkSlot>.");},[e,r,i]),He.useEffect(()=>{lt.has(e)||(lt.add(e),fetch(`${m}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${S}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:P,label:e,propsShape:t?tr(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:n,callbackNames:i?Object.keys(i):[],mode:s||"iframe"})}).catch(()=>{}));},[e,m,S,n,P]);let C=He.useCallback(E=>{let c=w.current;if(c?.contentWindow&&h.current){let u=$.current?Object.keys($.current):[];c.contentWindow.postMessage({type:"slot:props",props:E,callbackNames:u},"*"),l.current=null;}else l.current=E;},[]),F=He.useCallback((E,c)=>{let u=R.current;return !u||u.length===0?false:u.some(x=>{let[k,f]=x.split(" "),g=c.split("?")[0];return E.toUpperCase()===k.toUpperCase()&&g.startsWith(f)})},[]);if(He.useEffect(()=>{if(!d?.bundleUrl)return;let E=async c=>{if(c.source===w.current?.contentWindow){if(c.data?.type==="slot:ready")h.current=true,w.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:R.current||[]},"*"),R.current,l.current?C(l.current):C(T.current||{});else if(c.data?.type==="slot:event"){let u=c.data.event;u?.navigate&&(window.location.hash=u.navigate);}else if(c.data?.type==="slot:clipboard-write")navigator.clipboard.writeText(c.data.text).catch(u=>{console.warn(`[ForkSlot:${e}] clipboard write failed:`,u.message);});else if(c.data?.type==="slot:callback"){let{name:u,args:x}=c.data,k=$.current?.[u];k?(k(...x||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${u}`);}else if(c.data?.type==="slot:fetch"){let{id:u,method:x,url:k,body:f}=c.data,g=w.current?.contentWindow;if(!g)return;let p=x||"GET";if(!F(p,k)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${u}: ${p} ${k} \u2014 not in allowedFetches`),g.postMessage({type:"slot:fetch-response",id:u,error:`Fetch not allowed: ${p} ${k}`},"*");return}try{let B={method:p};f&&p!=="GET"&&(B.headers={"Content-Type":"application/json"},B.body=JSON.stringify(f));let U=await fetch(k,B),K=await U.json();`${e}${u}${U.status}`,g.postMessage({type:"slot:fetch-response",id:u,data:K,status:U.status},"*");}catch(B){console.error(`[ForkSlot:${e}] fetch #${u} failed:`,B.message),g.postMessage({type:"slot:fetch-response",id:u,error:B.message},"*");}}}};return window.addEventListener("message",E),()=>{window.removeEventListener("message",E),h.current=false;}},[d?.bundleUrl,e,C,F]),He.useEffect(()=>{d?.bundleUrl&&h.current&&C(t||{});},[t,d?.bundleUrl,C]),!d||d.status!=="complete"||!d.bundleUrl)return `${e}${d?.status||"none"}${d?.bundleUrl||"none"}`,Ot.jsx(Ot.Fragment,{children:r});`${e}${d.bundleUrl}`;let y=`${m}${d.bundleUrl.replace("/bundle.js","/host")}`;return Ot.jsx("iframe",{ref:w,src:y,sandbox:"allow-scripts allow-same-origin allow-forms allow-clipboard-write",title:`Forked ${e}`,style:{width:"100%",border:"none",flex:1,minHeight:0}})}function ve({style:e={width:20,height:20},...t}){return Ot.jsxs("svg",{viewBox:"320 95 270 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:e,...t,children:[Ot.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"}),Ot.jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M387.096 174.735v188"}),Ot.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"}),Ot.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"}),Ot.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 De({onClick:e}){let[t,r]=He.useState(false),[o,n]=He.useState(false),i=t?48:40;return Ot.jsx("button",{onClick:e,onMouseEnter:()=>r(true),onMouseLeave:()=>{r(false),n(false);},onMouseDown:()=>n(true),onMouseUp:()=>n(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:o?"scale(0.95)":"scale(1)",transition:"all 300ms",cursor:"pointer",padding:0,margin:0,outline:"none",boxSizing:"border-box"},title:"Fork this app",children:Ot.jsx(ve,{style:{width:24,height:24}})})}var fr={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},pr={status:"#60a5fa",agent_message:"#a0a0a0",tool_use:"#fbbf24",build_start:"#c084fc",build_complete:"#6b7280",build_error:"#f87171",complete:"#6b7280",error:"#f87171"},mr={read:lucideReact.FileSearch,write:lucideReact.Pencil,search:lucideReact.FileSearch,shell:lucideReact.Terminal,build:lucideReact.Package},gr={read:"#60a5fa",write:"#fbbf24",search:"#60a5fa",shell:"#a78bfa",build:"#c084fc"};function je(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 yt({events:e}){let t=He.useRef(null);return He.useEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight);},[e]),Ot.jsxs(Ot.Fragment,{children:[Ot.jsx("style",{children:`
3
+ `)+"\n\nThe forked component will not be able to call these. Add them to the `callbacks` prop of <ForkSlot>.");},[e,r,i]),He.useEffect(()=>{ct.has(e)||(ct.add(e),fetch(`${m}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${S}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:_,label:e,propsShape:t?tr(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:n,callbackNames:i?Object.keys(i):[],mode:s||"iframe"})}).catch(()=>{}));},[e,m,S,n,_]);let C=He.useCallback(E=>{let c=w.current;if(c?.contentWindow&&h.current){let u=$.current?Object.keys($.current):[];c.contentWindow.postMessage({type:"slot:props",props:E,callbackNames:u},"*"),l.current=null;}else l.current=E;},[]),F=He.useCallback((E,c)=>{let u=R.current;return !u||u.length===0?false:u.some(x=>{let[k,f]=x.split(" "),g=c.split("?")[0];return E.toUpperCase()===k.toUpperCase()&&g.startsWith(f)})},[]);if(He.useEffect(()=>{if(!d?.bundleUrl)return;let E=async c=>{if(c.source===w.current?.contentWindow){if(c.data?.type==="slot:ready")h.current=true,w.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:R.current||[]},"*"),R.current,l.current?C(l.current):C(T.current||{});else if(c.data?.type==="slot:event"){let u=c.data.event;u?.navigate&&(window.location.hash=u.navigate);}else if(c.data?.type==="slot:clipboard-write")navigator.clipboard.writeText(c.data.text).catch(u=>{console.warn(`[ForkSlot:${e}] clipboard write failed:`,u.message);});else if(c.data?.type==="slot:callback"){let{name:u,args:x}=c.data,k=$.current?.[u];k?(k(...x||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${u}`);}else if(c.data?.type==="slot:fetch"){let{id:u,method:x,url:k,body:f}=c.data,g=w.current?.contentWindow;if(!g)return;let p=x||"GET";if(!F(p,k)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${u}: ${p} ${k} \u2014 not in allowedFetches`),g.postMessage({type:"slot:fetch-response",id:u,error:`Fetch not allowed: ${p} ${k}`},"*");return}try{let B={method:p};f&&p!=="GET"&&(B.headers={"Content-Type":"application/json"},B.body=JSON.stringify(f));let U=await fetch(k,B),K=await U.json();`${e}${u}${U.status}`,g.postMessage({type:"slot:fetch-response",id:u,data:K,status:U.status},"*");}catch(B){console.error(`[ForkSlot:${e}] fetch #${u} failed:`,B.message),g.postMessage({type:"slot:fetch-response",id:u,error:B.message},"*");}}}};return window.addEventListener("message",E),()=>{window.removeEventListener("message",E),h.current=false;}},[d?.bundleUrl,e,C,F]),He.useEffect(()=>{d?.bundleUrl&&h.current&&C(t||{});},[t,d?.bundleUrl,C]),!d||d.status!=="complete"||!d.bundleUrl)return `${e}${d?.status||"none"}${d?.bundleUrl||"none"}`,Ot.jsx(Ot.Fragment,{children:r});`${e}${d.bundleUrl}`;let y=`${m}${d.bundleUrl.replace("/bundle.js","/host")}`;return Ot.jsx("iframe",{ref:w,src:y,sandbox:"allow-scripts allow-same-origin allow-forms allow-clipboard-write",title:`Forked ${e}`,style:{width:"100%",border:"none",flex:1,minHeight:0}})}function we({style:e={width:20,height:20},...t}){return Ot.jsxs("svg",{viewBox:"320 95 270 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:e,...t,children:[Ot.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"}),Ot.jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M387.096 174.735v188"}),Ot.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"}),Ot.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"}),Ot.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 De({onClick:e}){let[t,r]=He.useState(false),[o,n]=He.useState(false),i=t?48:40;return Ot.jsx("button",{onClick:e,onMouseEnter:()=>r(true),onMouseLeave:()=>{r(false),n(false);},onMouseDown:()=>n(true),onMouseUp:()=>n(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:o?"scale(0.95)":"scale(1)",transition:"all 300ms",cursor:"pointer",padding:0,margin:0,outline:"none",boxSizing:"border-box"},title:"Fork this app",children:Ot.jsx(we,{style:{width:24,height:24}})})}var fr={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},pr={status:"#60a5fa",agent_message:"#a0a0a0",tool_use:"#fbbf24",build_start:"#c084fc",build_complete:"#6b7280",build_error:"#f87171",complete:"#6b7280",error:"#f87171"},mr={read:lucideReact.FileSearch,write:lucideReact.Pencil,search:lucideReact.FileSearch,shell:lucideReact.Terminal,build:lucideReact.Package},gr={read:"#60a5fa",write:"#fbbf24",search:"#60a5fa",shell:"#a78bfa",build:"#c084fc"};function je(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 bt({events:e}){let t=He.useRef(null);return He.useEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight);},[e]),Ot.jsxs(Ot.Fragment,{children:[Ot.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
- `}),Ot.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&&Ot.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"#6b7280",fontSize:"11px"},children:[Ot.jsx(lucideReact.Loader2,{style:{width:"12px",height:"12px",animation:"__fork-spin 1s linear infinite",flexShrink:0}}),"Connecting to agent..."]}),e.map((r,o)=>{let n=o===e.length-1,i=r.type==="complete"||r.type==="error"||r.type==="build_complete"||r.type==="build_error",s=n&&!i&&(r.type==="status"||r.type==="tool_use"||r.type==="build_start"),a=fr[r.type]||lucideReact.Code,b=pr[r.type]||"#9ca3af";if(r.type==="tool_use"){let d=String(r.data.category||"");a=mr[d]||lucideReact.Wrench,b=gr[d]||"#fbbf24";}return s?a=lucideReact.Loader2:!n&&r.type==="status"&&(a=lucideReact.Check,b="#4ade80"),Ot.jsxs("div",{style:{display:"flex",gap:"6px",marginBottom:"6px",lineHeight:1.625},children:[Ot.jsx(a,{style:{width:"12px",height:"12px",marginTop:"2px",flexShrink:0,color:b,...s?{animation:"__fork-spin 1s linear infinite"}:{}}}),Ot.jsx("span",{style:{color:n&&!i?"#d1d5db":"#6b7280",wordBreak:"break-all"},children:je(r)})]},o)})]})]})}var xr=["Dark mode redesign","New workflow for adding to this page","Data-dense analytics view"],kt=35,Rr="Working on Feature",Er="Built Custom Feature",wt=360,ae=350;function $r(e){return e.length<=kt?e:e.slice(0,kt-3).trimEnd()+"..."}function Ar({events:e}){let[t,r]=He.useState("Setting up environment..."),[o,n]=He.useState(true),i=He.useRef(t),s=He.useRef(false);return He.useEffect(()=>{if(!s.current){for(let b of e)if(b.type==="status"&&String(b.data.message||"").includes("Agent started")){s.current=true;break}}let a="Setting up environment...";if(s.current)for(let b=e.length-1;b>=0;b--){let d=e[b];if(d.type==="tool_use"||d.type==="build_start"||d.type==="build_complete"){a=$r(je(d));break}}if(a!==i.current){n(false);let b=setTimeout(()=>{r(a),i.current=a,n(true);},200);return ()=>clearTimeout(b)}},[e]),Ot.jsx("span",{style:{fontSize:11,color:"#d1d5db",fontWeight:500,opacity:o?1:0,transition:"opacity 0.2s ease",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},children:t})}function Cr(e){He.useLayoutEffect(()=>{if(!e||typeof document>"u")return;let t=document.body,r=t.style.marginRight,o=t.style.transition,n=getComputedStyle(t).marginRight,i=n&&n!=="0px"?n:"0px";return t.style.transition=`margin-right ${ae}ms cubic-bezier(0.22, 1, 0.36, 1)`,t.style.marginRight=`calc(${i} + ${wt}px)`,()=>{t.style.marginRight=r,window.setTimeout(()=>{t.style.transition=o;},ae+50);}},[e]);}function xe({state:e,fork:t,events:r,error:o,slotId:n,targetId:i,targetLabel:s,historyMode:a="slot",examplePrompts:b=xr,onSubmit:d,onUndo:m,onClose:S,baseUrl:P,apiKey:w,userId:h,userHash:l,appId:$,embedded:T=false}){let[R,C]=He.useState(""),[F,y]=He.useState([]),[E,c]=He.useState(false),[u,x]=He.useState(false),[k,f]=He.useState(false),[g,p]=He.useState(false),[B,U]=He.useState(false),[K,V]=He.useState(false),[G,Y]=He.useState(null),[O,q]=He.useState(false),[W,ee]=He.useState(false),[v,_]=He.useState(null),[N,z]=He.useState(false),Z=He.useRef(null),ye=He.useRef(null),{resetAllForks:Pt}=I(),X=i??n??"",_e=(s||X).replace(/[-_]+/g," ").replace(/\b\w/g,A=>A.toUpperCase()),Pe=He.useRef(""),ce=T?true:u&&!k;Cr(!T&&ce);let Mt=r.find(A=>{let L=A.data;return A.type==="status"&&L.summary})?.data?.summary||t?.summary||Rr,te=r.find(A=>{let L=A.data;return (A.type==="status"||A.type==="complete")&&typeof L?.estimateMinutes=="number"})?.data?.estimateMinutes??t?.estimateMinutes;He.useEffect(()=>{if(a==="none"){c(true);return}if(!P||!w||!h||!X||E)return;let A=new URLSearchParams({userId:h});if(l&&A.set("userHash",l),a==="slot")A.set("slotId",X);else if(a==="boundary"){if(!$){c(true);return}A.set("boundaryId",X),A.set("appId",$);}fetch(`${P}/api/v1/forks/history?${A.toString()}`,{headers:{Authorization:`Bearer ${w}`}}).then(L=>L.ok?L.json():[]).then(L=>{let H=[];for(let be of L)be.role==="user"?H.push({type:"user",text:be.content}):H.push({type:"applied",text:be.content});H.length>0&&y(H),c(true);}).catch(()=>c(true));},[w,$,P,E,a,X,l,h]),He.useEffect(()=>{e==="complete"&&q(false);},[e]),He.useEffect(()=>{if(T)return;let A=requestAnimationFrame(()=>x(true));return ()=>cancelAnimationFrame(A)},[T]),He.useEffect(()=>{if(ce&&(e==="prompting"||e==="complete")){let A=setTimeout(()=>Z.current?.focus(),T?100:ae+100);return ()=>clearTimeout(A)}},[ce,T,e]),He.useEffect(()=>{if(e==="complete"&&Pe.current){let L=r.find(H=>H.type==="complete")?.data?.summary||t?.summary||Er;y(H=>H[H.length-1]?.type==="applied"?H:[...H,{type:"applied",text:L}]),C(""),setTimeout(()=>Z.current?.focus(),200);}},[e,_e,r,t?.summary]),He.useEffect(()=>{ye.current&&(ye.current.scrollTop=ye.current.scrollHeight);},[F,e]);let Ze=()=>{R.trim()&&(Pe.current=R.trim(),y(A=>[...A,{type:"user",text:R.trim()}]),d(R.trim(),X),C(""));},Lt=async()=>{if(!(!m||W||!X)){ee(true);try{let A=await m(X);y(L=>{let H=[...L];return H.length>=2&&H[H.length-1]?.type==="applied"?H.splice(-2,2):H.length>=1&&H[H.length-1]?.type==="applied"&&H.splice(-1,1),H}),A?.removed&&y([]);}catch{}finally{ee(false);}}},Me=()=>{if(T){S();return}f(true),x(false),setTimeout(()=>S(),ae);},Bt=T?{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:wt,maxWidth:"100vw",background:"#ffffff",boxShadow:ce?"-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:ce?"translateX(0)":"translateX(100%)",transition:`transform ${ae}ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow ${ae}ms ease`,display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'};return Ot.jsxs(Ot.Fragment,{children:[Ot.jsx("style",{children:`
21
+ `}),Ot.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&&Ot.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"#6b7280",fontSize:"11px"},children:[Ot.jsx(lucideReact.Loader2,{style:{width:"12px",height:"12px",animation:"__fork-spin 1s linear infinite",flexShrink:0}}),"Connecting to agent..."]}),e.map((r,o)=>{let n=o===e.length-1,i=r.type==="complete"||r.type==="error"||r.type==="build_complete"||r.type==="build_error",s=n&&!i&&(r.type==="status"||r.type==="tool_use"||r.type==="build_start"),a=fr[r.type]||lucideReact.Code,b=pr[r.type]||"#9ca3af";if(r.type==="tool_use"){let d=String(r.data.category||"");a=mr[d]||lucideReact.Wrench,b=gr[d]||"#fbbf24";}return s?a=lucideReact.Loader2:!n&&r.type==="status"&&(a=lucideReact.Check,b="#4ade80"),Ot.jsxs("div",{style:{display:"flex",gap:"6px",marginBottom:"6px",lineHeight:1.625},children:[Ot.jsx(a,{style:{width:"12px",height:"12px",marginTop:"2px",flexShrink:0,color:b,...s?{animation:"__fork-spin 1s linear infinite"}:{}}}),Ot.jsx("span",{style:{color:n&&!i?"#d1d5db":"#6b7280",wordBreak:"break-all"},children:je(r)})]},o)})]})]})}var xr=["Dark mode redesign","New workflow for adding to this page","Data-dense analytics view"],wt=35,Rr="Working on Feature",Er="Built Custom Feature",$r=360,Fe=350;function Ar(e){return e.length<=wt?e:e.slice(0,wt-3).trimEnd()+"..."}function Cr({events:e}){let[t,r]=He.useState("Setting up environment..."),[o,n]=He.useState(true),i=He.useRef(t),s=He.useRef(false);return He.useEffect(()=>{if(!s.current){for(let b of e)if(b.type==="status"&&String(b.data.message||"").includes("Agent started")){s.current=true;break}}let a="Setting up environment...";if(s.current)for(let b=e.length-1;b>=0;b--){let d=e[b];if(d.type==="tool_use"||d.type==="build_start"||d.type==="build_complete"){a=Ar(je(d));break}}if(a!==i.current){n(false);let b=setTimeout(()=>{r(a),i.current=a,n(true);},200);return ()=>clearTimeout(b)}},[e]),Ot.jsx("span",{style:{fontSize:11,color:"#d1d5db",fontWeight:500,opacity:o?1:0,transition:"opacity 0.2s ease",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},children:t})}function Tr({children:e}){let[t,r]=He.useState(null);return He.useEffect(()=>{if(typeof document>"u")return;let o=document.createElement("div");o.setAttribute("data-fork-panel-host",""),o.style.cssText="all: initial;",document.body.appendChild(o);let n=o.attachShadow({mode:"open"});return r(n),()=>{o.remove();}},[]),t?Ht.createPortal(e,t):null}function xe({state:e,fork:t,events:r,error:o,slotId:n,targetId:i,targetLabel:s,historyMode:a="slot",examplePrompts:b=xr,onSubmit:d,onUndo:m,onClose:S,baseUrl:_,apiKey:w,userId:h,userHash:l,appId:$,embedded:T=false}){let[R,C]=He.useState(""),[F,y]=He.useState([]),[E,c]=He.useState(false),[u,x]=He.useState(false),[k,f]=He.useState(false),[g,p]=He.useState(false),[B,U]=He.useState(false),[K,V]=He.useState(false),[G,Y]=He.useState(null),[O,q]=He.useState(false),[W,te]=He.useState(false),[v,P]=He.useState(null),[N,z]=He.useState(false),Z=He.useRef(null),ge=He.useRef(null),{resetAllForks:_t}=j(),X=i??n??"",Pe=(s||X).replace(/[-_]+/g," ").replace(/\b\w/g,A=>A.toUpperCase()),_e=He.useRef(""),he=T?true:u&&!k,Mt=r.find(A=>{let L=A.data;return A.type==="status"&&L.summary})?.data?.summary||t?.summary||Rr,re=r.find(A=>{let L=A.data;return (A.type==="status"||A.type==="complete")&&typeof L?.estimateMinutes=="number"})?.data?.estimateMinutes??t?.estimateMinutes;He.useEffect(()=>{if(a==="none"){c(true);return}if(!_||!w||!h||!X||E)return;let A=new URLSearchParams({userId:h});if(l&&A.set("userHash",l),a==="slot")A.set("slotId",X);else if(a==="boundary"){if(!$){c(true);return}A.set("boundaryId",X),A.set("appId",$);}fetch(`${_}/api/v1/forks/history?${A.toString()}`,{headers:{Authorization:`Bearer ${w}`}}).then(L=>L.ok?L.json():[]).then(L=>{let H=[];for(let ye of L)ye.role==="user"?H.push({type:"user",text:ye.content}):H.push({type:"applied",text:ye.content});H.length>0&&y(H),c(true);}).catch(()=>c(true));},[w,$,_,E,a,X,l,h]),He.useEffect(()=>{e==="complete"&&q(false);},[e]),He.useEffect(()=>{if(T)return;let A=requestAnimationFrame(()=>x(true));return ()=>cancelAnimationFrame(A)},[T]),He.useEffect(()=>{if(he&&(e==="prompting"||e==="complete")){let A=setTimeout(()=>Z.current?.focus(),T?100:Fe+100);return ()=>clearTimeout(A)}},[he,T,e]),He.useEffect(()=>{if(e==="complete"&&_e.current){let L=r.find(H=>H.type==="complete")?.data?.summary||t?.summary||Er;y(H=>H[H.length-1]?.type==="applied"?H:[...H,{type:"applied",text:L}]),C(""),setTimeout(()=>Z.current?.focus(),200);}},[e,Pe,r,t?.summary]),He.useEffect(()=>{ge.current&&(ge.current.scrollTop=ge.current.scrollHeight);},[F,e]);let Ze=()=>{R.trim()&&(_e.current=R.trim(),y(A=>[...A,{type:"user",text:R.trim()}]),d(R.trim(),X),C(""));},Lt=async()=>{if(!(!m||W||!X)){te(true);try{let A=await m(X);y(L=>{let H=[...L];return H.length>=2&&H[H.length-1]?.type==="applied"?H.splice(-2,2):H.length>=1&&H[H.length-1]?.type==="applied"&&H.splice(-1,1),H}),A?.removed&&y([]);}catch{}finally{te(false);}}},Me=()=>{if(T){S();return}f(true),x(false),setTimeout(()=>S(),Fe);},Bt=T?{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:$r,maxWidth:"100vw",background:"#ffffff",boxShadow:he?"-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:he?"translateX(0)":"translateX(100%)",transition:`transform ${Fe}ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow ${Fe}ms ease`,display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'},Qe=Ot.jsxs(Ot.Fragment,{children:[Ot.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
- `}),Ot.jsxs("div",{className:"__fork-panel",style:Bt,children:[Ot.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:[Ot.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:[Ot.jsx(ve,{style:{width:16,height:16,color:"#1c4587",cursor:"pointer",flexShrink:0},onDoubleClick:async A=>{if(A.stopPropagation(),!N&&confirm("Reset all forks? This will remove all forked components.")){z(true);try{let L=await Pt();`${L?.deleted??0}`,y([]),C(""),q(!1),Me();}catch(L){console.error("[Fork] Reset failed:",L);}finally{z(false);}}}}),Ot.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:e==="running"?Mt:`Fork ${_e}`}),e==="running"&&Ot.jsx("span",{title:te?`Estimated ~${te} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:te?"#1c4587":"#9ca3af",backgroundColor:te?"rgba(28, 69, 135, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:te?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:te?`~${te}m`:"~ m"}),e==="complete"&&Ot.jsx("div",{style:{height:6,width:6,backgroundColor:"#1c4587",borderRadius:"50%",flexShrink:0}})]}),!T&&Ot.jsx("button",{onClick:Me,onMouseEnter:()=>p(true),onMouseLeave:()=>p(false),style:{padding:6,borderRadius:6,color:g?"#4b5563":"#9ca3af",backgroundColor:g?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:Ot.jsx(lucideReact.X,{style:{width:16,height:16}})})]}),Ot.jsxs("div",{ref:ye,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[e==="prompting"&&F.length===0&&Ot.jsxs("div",{style:{padding:"24px 20px",textAlign:"center"},children:[Ot.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."}),Ot.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6,justifyContent:"center"},children:b.map((A,L)=>Ot.jsx("button",{onClick:()=>{C(A),Z.current?.focus();},onMouseEnter:()=>Y(L),onMouseLeave:()=>Y(null),style:{fontSize:12,padding:"5px 12px",borderRadius:9999,color:G===L?"#1f2937":"#6b7280",backgroundColor:G===L?"#f9fafb":"transparent",border:G===L?"1px solid #d1d5db":"1px solid #e5e7eb",cursor:"pointer",transition:"color 0.15s, background-color 0.15s, border-color 0.15s",fontFamily:"inherit"},children:A},A))})]}),F.length>0&&Ot.jsx("div",{style:{padding:"16px 16px 0 16px"},children:F.map((A,L)=>Ot.jsx("div",{style:{marginBottom:L<F.length-1?10:0},children:A.type==="user"?Ot.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexDirection:"row-reverse"},children:[Ot.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:Ot.jsx(lucideReact.User,{style:{width:13,height:13,color:"#6b7280"}})}),Ot.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})]}):Ot.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[Ot.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#f0fdf4",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:Ot.jsx(lucideReact.Check,{style:{width:13,height:13,color:"#9ca3af"}})}),Ot.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:[Ot.jsx("span",{style:{flex:1},children:A.text}),m&&L===F.length-1&&e!=="running"&&Ot.jsxs("button",{onClick:H=>{H.stopPropagation(),Lt();},onMouseEnter:()=>_(L),onMouseLeave:()=>_(null),disabled:W,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:v===L?"rgba(0,0,0,0.06)":"transparent",color:v===L?"#6b7280":"#d1d5db",cursor:W?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:W?.4:1,flexShrink:0},children:[Ot.jsx(lucideReact.Undo2,{style:{width:12,height:12}}),v===L&&Ot.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"})]})]})]})},L))}),e==="running"&&Ot.jsx("div",{style:{padding:16},children:Ot.jsxs("div",{onClick:()=>q(!O),style:{backgroundColor:"#1a1a2e",borderRadius:12,overflow:"hidden",cursor:"pointer",transition:"all 0.3s cubic-bezier(0.22, 1, 0.36, 1)"},children:[Ot.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px"},children:[Ot.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[Ot.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:Ot.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),Ot.jsx(Ar,{events:r})]}),Ot.jsx("div",{style:{color:"#6b7280",flexShrink:0,marginLeft:8,transition:"transform 0.2s ease",transform:O?"rotate(180deg)":"rotate(0deg)"},children:Ot.jsx(lucideReact.ChevronDown,{style:{width:14,height:14}})})]}),Ot.jsx("div",{style:{maxHeight:O?320:0,opacity:O?1:0,transition:"max-height 0.35s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.25s ease",overflow:"hidden"},children:Ot.jsx("div",{style:{borderTop:"1px solid rgba(255,255,255,0.08)",maxHeight:320,overflowY:"auto"},children:Ot.jsx(yt,{events:r})})})]})}),e==="error"&&Ot.jsxs("div",{style:{padding:"20px 16px",textAlign:"center"},children:[Ot.jsx("div",{style:{width:36,height:36,backgroundColor:"#fef2f2",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 10px auto"},children:Ot.jsx(lucideReact.X,{style:{width:18,height:18,color:"#ef4444"}})}),Ot.jsx("p",{style:{fontSize:12,color:"#6b7280",marginBottom:10,maxWidth:260,margin:"0 auto 10px auto"},children:o}),Ot.jsxs("button",{onClick:()=>{let A=t?.prompt||Pe.current;A&&d(A,X);},onMouseEnter:()=>V(true),onMouseLeave:()=>V(false),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,color:"#4f46e5",backgroundColor:K?"#e0e7ff":"#eef2ff",border:"none",cursor:"pointer",transition:"background-color 0.15s",fontFamily:"inherit"},children:[Ot.jsx(lucideReact.RotateCcw,{style:{width:12,height:12}})," Try Again"]})]})]}),e!=="running"&&Ot.jsx("div",{style:{padding:"8px 12px 12px 12px",borderTop:"1px solid rgba(229, 231, 235, 0.6)",flexShrink:0},children:Ot.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:[Ot.jsx("textarea",{ref:Z,value:R,onChange:A=>{C(A.target.value),A.target.style.height="auto",A.target.style.height=Math.min(A.target.scrollHeight,160)+"px";},onKeyDown:A=>{A.key==="Enter"&&!A.shiftKey&&(A.preventDefault(),Ze()),A.key==="Escape"&&!T&&Me();},placeholder:F.length>0?"Ask for another change...":`Describe your ideal ${_e.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"}}),Ot.jsx("button",{onClick:Ze,disabled:!R.trim(),onMouseEnter:()=>U(true),onMouseLeave:()=>U(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:R.trim()?1:.25,transform:B&&R.trim()?"scale(1.1)":"scale(1)",background:R.trim()?"#1c4587":"rgba(0,0,0,0.12)",border:"none",cursor:R.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:Ot.jsx(lucideReact.ArrowUp,{style:{width:13,height:13}})})]})})]})]})}function vt(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 ze(e){let{apiKey:t,userId:r,userHash:o,baseUrl:n,appId:i,refreshModuleManifest:s,queueBoundaryAnimation:a}=I(),[b,d]=He.useState("idle"),[m,S]=He.useState(null),[P,w]=He.useState([]),[h,l]=He.useState(null),$=He.useRef(null),T=He.useCallback(()=>{d("prompting"),w([]),l(null),S(null);},[]),R=He.useCallback(()=>{d("idle"),$.current&&($.current.close(),$.current=null);},[]),C=He.useCallback(async y=>{try{if(!i)throw new Error("ForkProvider requires appId for module boundary prompts.");d("running"),w([]),l(null);let E={userId:r,prompt:y,boundaryId:e,appId:i};o&&(E.userHash=o);let c=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(E)});if(!c.ok){let f=await c.json().catch(()=>({}));throw new Error(f.error||`API error: ${c.status}`)}let u=await c.json();S(u);let x=new URLSearchParams({key:t});o&&(x.set("userId",r),x.set("userHash",o));let k=new EventSource(`${n}/api/v1/forks/${u.id}/events?${x.toString()}`);$.current=k,k.onmessage=f=>{try{let g=JSON.parse(f.data);if(w(p=>[...p,g]),g.type==="complete"){let p=g.data;a(e,u.id),s().catch(()=>{}).finally(()=>{let B={...u,status:"complete",moduleUrl:p.moduleUrl,cssUrls:p.cssUrls,summary:p.summary,completedAt:new Date().toISOString()};S(B),d("complete"),k.close();});}else if(g.type==="error"){let p=g.data;l(p.error||"Unknown error"),d("error"),k.close();}}catch{}},k.onerror=()=>{fetch(`${n}/api/v1/forks/${u.id}`,{headers:{Authorization:`Bearer ${t}`}}).then(f=>f.json()).then(f=>{S(f),f.status==="complete"?(a(e,f.id),s().catch(()=>{}),d("complete")):f.status==="error"&&(l(f.error||"Fork generation failed"),d("error"));}).catch(()=>{l("Connection lost"),d("error");}),k.close();};}catch(E){l(E.message),d("error");}},[t,i,n,e,a,s,o,r]),F=He.useCallback(async()=>{try{if(!i)throw new Error("ForkProvider requires appId for boundary undo.");let y={userId:r,boundaryId:e,appId:i};o&&(y.userHash=o);let E=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(y)});if(!E.ok){let u=await E.json().catch(()=>({}));throw new Error(u.error||`API error: ${E.status}`)}let c=await E.json();return await s().catch(()=>{}),c.removed?(S(null),d("prompting")):c.fork&&(S(c.fork),d("complete")),c}catch(y){throw l(y.message),y}},[t,i,n,e,s,o,r]);return {state:b,fork:m,events:P,error:h,open:T,close:R,startFork:C,undoFork:F}}function St(e){let{state:t,fork:r,events:o,error:n,open:i,close:s,startFork:a,undoFork:b}=ze(e);return {state:t,fork:r,events:o,error:n,isOpen:t!=="idle",open:i,close:s,submit:a,undo:b}}function We(){let{apiKey:e,userId:t,userHash:r,baseUrl:o,setSlotFork:n,clearSlotFork:i,skipAnimationForSlot:s}=I(),[a,b]=He.useState("idle"),[d,m]=He.useState(null),[S,P]=He.useState([]),[w,h]=He.useState(null),l=He.useRef(null),$=He.useCallback(()=>{b("prompting"),P([]),h(null),m(null);},[]),T=He.useCallback(()=>{b("idle"),l.current&&(l.current.close(),l.current=null);},[]),R=He.useCallback(async(F,y)=>{try{b("running"),P([]),h(null);let E={userId:t,prompt:F};y&&(E.slotId=y),r&&(E.userHash=r);let c=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(E)});if(!c.ok){let f=await c.json().catch(()=>({}));throw new Error(f.error||`API error: ${c.status}`)}let u=await c.json();m(u);let x=new URLSearchParams({key:e});r&&(x.set("userId",t),x.set("userHash",r));let k=new EventSource(`${o}/api/v1/forks/${u.id}/events?${x.toString()}`);l.current=k,k.onmessage=f=>{try{let g=JSON.parse(f.data);if(P(p=>[...p,g]),g.type==="complete"){let p=g.data,B={...u,status:"complete",bundleUrl:p.bundleUrl,summary:p.summary,completedAt:new Date().toISOString()};m(B),b("complete"),y&&p.bundleUrl&&n(y,B),k.close();}else if(g.type==="error"){let p=g.data;h(p.error||"Unknown error"),b("error"),k.close();}}catch{}},k.onerror=()=>{fetch(`${o}/api/v1/forks/${u.id}`,{headers:{Authorization:`Bearer ${e}`}}).then(f=>f.json()).then(f=>{m(f),f.status==="complete"?(b("complete"),y&&f.bundleUrl&&n(y,f)):f.status==="error"&&(h(f.error||"Fork generation failed"),b("error"));}).catch(()=>{h("Connection lost"),b("error");}),k.close();};}catch(E){h(E.message),b("error");}},[e,t,r,o,n]),C=He.useCallback(async F=>{try{let y={userId:t,slotId:F};r&&(y.userHash=r);let E=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(y)});if(!E.ok){let u=await E.json().catch(()=>({}));throw new Error(u.error||`API error: ${E.status}`)}let c=await E.json();return s(F),c.removed?(i(F),m(null),b("prompting")):c.fork&&(n(F,c.fork),m(c.fork)),c}catch(y){throw h(y.message),y}},[e,t,r,o,i,n]);return {state:a,fork:d,events:S,error:w,open:$,close:T,startFork:R,undoFork:C}}function Ft(){let{state:e,fork:t,events:r,error:o,open:n,close:i,startFork:s,undoFork:a}=We();return {state:e,fork:t,events:r,error:o,isOpen:e!=="idle",open:n,close:i,submit:s,undo:a}}function Ke(e){let t=vt(e),r=Ft(),o=St(t.type==="boundary"?t.id:""),{baseUrl:n,apiKey:i,userId:s,userHash:a,appId:b}=I(),d=t.type==="slot"?r:o,m=t.type==="slot"?"slot":"boundary",S=t.id,P=t.title,w=He.useCallback((l,$)=>t.type==="slot"?r.submit(l,$??t.id):o.submit(l),[o,r,t]),h=He.useCallback(l=>t.type==="slot"?r.undo(l??t.id):o.undo(),[o,r,t]);return {...d,target:t,targetId:S,targetLabel:P,historyMode:m,submit:w,undo:h,buttonProps:{onClick:d.open},panelProps:{state:d.state,fork:d.fork,events:d.events,error:d.error,...t.type==="slot"?{slotId:S,targetLabel:P,historyMode:m}:{targetId:S,targetLabel:P,historyMode:m},onSubmit:w,onUndo:h,onClose:d.close,baseUrl:n,apiKey:i,userId:s,userHash:a,appId:b}}}function he(e){let{examplePrompts:t,embedded:r}=e,o=Ke(e);return r?Ot.jsx(xe,{...o.panelProps,examplePrompts:t,embedded:true}):o.isOpen?Ot.jsx(xe,{...o.panelProps,examplePrompts:t}):Ot.jsx(De,{...o.buttonProps})}function Mr({boundaryId:e,title:t,examplePrompts:r}){return Ot.jsx(he,{boundaryId:e,title:t,examplePrompts:r})}function Ve(e){let t=Array.from(e.children).filter(o=>o instanceof HTMLElement);return t.length===1?t[0]:getComputedStyle(e).display==="contents"?null:e}function Rt(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 o=getComputedStyle(e).backgroundColor;r.style.backgroundColor=o&&o!=="rgba(0, 0, 0, 0)"&&o!=="transparent"?o:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(r);let n=e.querySelectorAll("*"),i=r.querySelectorAll("*");for(let s=0;s<n.length;s+=1)n[s].scrollTop!==0&&(i[s].scrollTop=n[s].scrollTop),n[s].scrollLeft!==0&&(i[s].scrollLeft=n[s].scrollLeft);return r}function qe(e){let t=[],r=e.querySelectorAll("*");for(let o of r){if(!(o instanceof HTMLElement))continue;let n=o.getBoundingClientRect();if(n.width<10||n.height<10||["SCRIPT","STYLE","META","LINK"].includes(o.tagName))continue;let i=getComputedStyle(o),s=parseFloat(i.borderTopLeftRadius)||0;t.push({tag:o.tagName,className:o.className||"",text:(o.textContent||"").slice(0,50).trim(),rect:n,borderRadius:s});}return t}function Et(e,t){let r=[];for(let o of t)if(!(e.find(s=>s.tag===o.tag&&s.className===o.className&&Math.abs(s.rect.top-o.rect.top)<20&&Math.abs(s.rect.left-o.rect.left)<20)||r.some(s=>o.rect.top>=s.rect.top&&o.rect.left>=s.rect.left&&o.rect.right<=s.rect.right&&o.rect.bottom<=s.rect.bottom))){for(let s=r.length-1;s>=0;s-=1){let a=r[s];a.rect.top>=o.rect.top&&a.rect.left>=o.rect.left&&a.rect.right<=o.rect.right&&a.rect.bottom<=o.rect.bottom&&r.splice(s,1);}r.push({rect:o.rect,borderRadius:o.borderRadius});}return r}function $t(e,t){let r=[];for(let o of e)if(!(t.find(s=>s.tag===o.tag&&s.className===o.className&&Math.abs(s.rect.top-o.rect.top)<20&&Math.abs(s.rect.left-o.rect.left)<20)||r.some(s=>o.rect.top>=s.rect.top&&o.rect.left>=s.rect.left&&o.rect.right<=s.rect.right&&o.rect.bottom<=s.rect.bottom))){for(let s=r.length-1;s>=0;s-=1){let a=r[s];a.rect.top>=o.rect.top&&a.rect.left>=o.rect.left&&a.rect.right<=o.rect.right&&a.rect.bottom<=o.rect.bottom&&r.splice(s,1);}r.push({rect:o.rect,borderRadius:o.borderRadius});}return r}function At(e,t,r,o,n){let i=Math.max(0,Math.min(n,r/2,o/2));return i===0?`M ${e} ${t} L ${e+r} ${t} L ${e+r} ${t+o} L ${e} ${t+o} Z`:[`M ${e+i} ${t}`,`L ${e+r-i} ${t}`,`A ${i} ${i} 0 0 1 ${e+r} ${t+i}`,`L ${e+r} ${t+o-i}`,`A ${i} ${i} 0 0 1 ${e+r-i} ${t+o}`,`L ${e+i} ${t+o}`,`A ${i} ${i} 0 0 1 ${e} ${t+o-i}`,`L ${e} ${t+i}`,`A ${i} ${i} 0 0 1 ${e+i} ${t}`,"Z"].join(" ")}function Je(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 o=document.createElementNS(t,"svg");o.setAttribute("width","100%"),o.setAttribute("height","100%"),o.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let n=document.createElementNS(t,"defs");o.appendChild(n);let i=[];for(let m=0;m<e.length;m+=1){let{rect:S,borderRadius:P}=e[m],w=S.left-.5,h=S.top-.5,l=S.width+1,$=S.height+1,T=Math.min(P+.5,l/2,$/2),R=At(w,h,l,$,T),C=`__fork-glow-${m}`,F=document.createElementNS(t,"filter");F.setAttribute("id",C),F.setAttribute("x","-100%"),F.setAttribute("y","-100%"),F.setAttribute("width","300%"),F.setAttribute("height","300%");let y=document.createElementNS(t,"feGaussianBlur");y.setAttribute("in","SourceGraphic"),y.setAttribute("stdDeviation","8"),F.appendChild(y),n.appendChild(F);let E=`__fork-mask-${m}`,c=document.createElementNS(t,"mask");c.setAttribute("id",E),c.setAttribute("maskUnits","userSpaceOnUse"),c.setAttribute("x",String(w-200)),c.setAttribute("y",String(h-200)),c.setAttribute("width",String(l+400)),c.setAttribute("height",String($+400));let u=document.createElementNS(t,"rect");u.setAttribute("x",String(w-200)),u.setAttribute("y",String(h-200)),u.setAttribute("width",String(l+400)),u.setAttribute("height",String($+400)),u.setAttribute("fill","white"),c.appendChild(u);let x=document.createElementNS(t,"path");x.setAttribute("d",R),x.setAttribute("fill","black"),c.appendChild(x),n.appendChild(c);let k=document.createElementNS(t,"g");k.setAttribute("mask",`url(#${E})`),k.setAttribute("opacity","0");let f=document.createElementNS(t,"g");f.setAttribute("filter",`url(#${C})`);let g=document.createElementNS(t,"path");g.setAttribute("d",R),g.setAttribute("fill","none"),g.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),g.setAttribute("stroke-width","6"),g.setAttribute("stroke-linecap","round"),f.appendChild(g),k.appendChild(f),o.appendChild(k);let p=document.createElementNS(t,"path");p.setAttribute("d",R),p.setAttribute("fill","none"),p.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),p.setAttribute("stroke-width","2"),p.setAttribute("stroke-linecap","round"),p.setAttribute("opacity","0"),o.appendChild(p),i.push(g,p),g.__group=k;}r.appendChild(o),document.body.appendChild(r);let s=[];for(let m=0;m<i.length;m+=2){let S=i[m],P=i[m+1],w=S.__group;if(!w)continue;let h=P.getTotalLength(),l=S.getTotalLength();if(h<=0)continue;let $=h*.35;P.setAttribute("stroke-dasharray",`${$} ${h-$}`),P.setAttribute("stroke-dashoffset","0"),s.push(P.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*h,opacity:.92,offset:.06},{strokeDashoffset:-2*h,opacity:.92,offset:.92},{strokeDashoffset:-2.25*h,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let T=l*.35;S.setAttribute("stroke-dasharray",`${T} ${l-T}`),S.setAttribute("stroke-dashoffset","0"),s.push(S.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*l,offset:.06},{strokeDashoffset:-2*l,offset:.92},{strokeDashoffset:-2.25*l,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(w.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,b=()=>{if(a)return;a=true,clearTimeout(d);for(let S of s)try{S.cancel();}catch{}let m=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});m.onfinish=()=>r.remove(),window.removeEventListener("click",b);},d=setTimeout(b,14500);return setTimeout(()=>{a||window.addEventListener("click",b);},500),b}function Ct(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 o=document.createElementNS(t,"svg");o.setAttribute("width","100%"),o.setAttribute("height","100%"),o.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let n=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),n.appendChild(i),o.appendChild(n);for(let{rect:a,borderRadius:b}of e){let d=document.createElementNS(t,"path");d.setAttribute("d",At(a.left,a.top,a.width,a.height,b)),d.setAttribute("fill","none"),d.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),d.setAttribute("stroke-width","1.5"),d.setAttribute("stroke-dasharray","8 4"),d.setAttribute("stroke-linecap","round"),d.setAttribute("filter","url(#__fork-removed-shadow)"),d.setAttribute("opacity","0"),o.appendChild(d),d.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(o),document.body.appendChild(r),r}var Te=new Map,Ye=new Map;function Nr(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function _t(e,t){let r=(t?e[t]:void 0)??e.default;if(typeof r!="function"){let o=t||"default";throw new Error(`Fork boundary module is missing a React component export: ${o}`)}return r}function Hr(e){if(!e||typeof document>"u")return Promise.resolve();let t=Te.get(e);if(t)return t;let r=document.querySelector(`link[data-fork-override-href="${e}"]`);if(r instanceof HTMLLinkElement){let n=r.sheet?Promise.resolve():new Promise((i,s)=>{let a=()=>{r.removeEventListener("load",a),r.removeEventListener("error",b),i();},b=()=>{r.removeEventListener("load",a),r.removeEventListener("error",b),s(new Error(`Failed to load boundary stylesheet: ${e}`));};r.addEventListener("load",a,{once:true}),r.addEventListener("error",b,{once:true});});return Te.set(e,n),n}let o=new Promise((n,i)=>{let s=document.createElement("link");s.rel="stylesheet",s.href=e,s.setAttribute("data-fork-override-href",e),s.onload=()=>n(),s.onerror=()=>{s.remove(),i(new Error(`Failed to load boundary stylesheet: ${e}`));},document.head.appendChild(s);}).catch(n=>{throw Te.delete(e),n});return Te.set(e,o),o}function Or(e){let t=Ye.get(e);if(t)return t;let r=import(e).catch(o=>{throw Ye.delete(e),o});return Ye.set(e,r),r}async function Ur(e,t,r){if(e)try{await Promise.all(e.cssUrls.map(i=>Hr(i)));let n=await Or(e.moduleUrl);return _t(n,r)}catch(n){console.error(`[Fork] Failed to load override for boundary "${e.boundaryId}", falling back to original module.`,n);}let o=await t();return _t(o,r)}function Dr(e){function t(r){let{appId:o,moduleOverridesEnabled:n,moduleManifestReady:i,moduleManifestVersion:s,registerBoundary:a,getBoundaryOverride:b,consumeBoundaryAnimation:d}=I(),[m,S]=He.useState(null),[P,w]=He.useState(null),h=He.useRef(null),l=He.useRef(null),$=He.useRef(null),T=He.useRef(false),R=He.useRef(null),C=He.useRef(null),F=b(e.id),y=F?`override:${F.id}`:"original",E=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if(He.useEffect(()=>()=>{C.current&&(clearTimeout(C.current),C.current=null),R.current&&(R.current.remove(),R.current=null);},[]),He.useEffect(()=>{a({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[o,a,e.id,e.exportName,E]),He.useEffect(()=>{if(n&&!i&&!m||l.current===y&&m)return;let c=false;return w(null),Ur(F,e.original,e.exportName).then(u=>{if(!c){if(F?.id&&d(e.id,F.id)&&h.current){let x=Ve(h.current);if(x){let k=qe(x);k.length>0&&($.current=k,T.current=true,C.current&&(clearTimeout(C.current),C.current=null),R.current&&R.current.remove(),R.current=Rt(x));}}l.current=y,He.startTransition(()=>{S(()=>u);});}}).catch(u=>{c||w(Nr(u));}),()=>{c=true;}},[d,y,n,i,s,F?.id,F?.moduleUrl,F?.integrity,F?.cssUrls.join("|"),e.exportName,e.original,m]),He.useEffect(()=>{if(!T.current||!m||!h.current)return;let c=false;return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(c||!h.current)return;let u=$.current,x=Ve(h.current);if($.current=null,T.current=false,!u||!x){R.current&&(R.current.remove(),R.current=null);return}let k=qe(x),f=Et(u,k),g=$t(u,k),p=R.current;if(g.length>0&&p){let B=Ct(g);C.current=setTimeout(()=>{C.current=null;let U=400;p.animate([{opacity:1},{opacity:0}],{duration:U,fill:"forwards"}),B.animate([{opacity:1},{opacity:0}],{duration:U,fill:"forwards"}),setTimeout(()=>{p.remove(),B.remove(),R.current===p&&(R.current=null),f.length>0&&Je(f);},U);},3500);}else p&&(p.remove(),R.current===p&&(R.current=null)),f.length>0&&Je(f);});}),()=>{c=true;}},[m]),P)throw P;return m?Ot.jsx("div",{ref:h,style:{display:"contents"},children:Ot.jsx(m,{...r})}):Ot.jsx(Ot.Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function jr({slotId:e,title:t,slotLabel:r,examplePrompts:o}){return Ot.jsx(he,{slotId:e,title:t,slotLabel:r,examplePrompts:o})}
44
- exports.ForkBoundaryUI=Mr;exports.ForkButton=De;exports.ForkChatInterface=he;exports.ForkPanel=xe;exports.ForkProvider=zt;exports.ForkSlot=rr;exports.ForkUI=jr;exports.forkable=Dr;exports.registerForkShared=Be;exports.useBoundaryFork=ze;exports.useFork=We;exports.useForkChatPanel=Ke;
43
+ `}),Ot.jsxs("div",{className:"__fork-panel",style:Bt,children:[Ot.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:[Ot.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:[Ot.jsx(we,{style:{width:16,height:16,color:"#1c4587",cursor:"pointer",flexShrink:0},onDoubleClick:async A=>{if(A.stopPropagation(),!N&&confirm("Reset all forks? This will remove all forked components.")){z(true);try{let L=await _t();`${L?.deleted??0}`,y([]),C(""),q(!1),Me();}catch(L){console.error("[Fork] Reset failed:",L);}finally{z(false);}}}}),Ot.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:e==="running"?Mt:`Fork ${Pe}`}),e==="running"&&Ot.jsx("span",{title:re?`Estimated ~${re} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:re?"#1c4587":"#9ca3af",backgroundColor:re?"rgba(28, 69, 135, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:re?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:re?`~${re}m`:"~ m"}),e==="complete"&&Ot.jsx("div",{style:{height:6,width:6,backgroundColor:"#1c4587",borderRadius:"50%",flexShrink:0}})]}),!T&&Ot.jsx("button",{onClick:Me,onMouseEnter:()=>p(true),onMouseLeave:()=>p(false),style:{padding:6,borderRadius:6,color:g?"#4b5563":"#9ca3af",backgroundColor:g?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:Ot.jsx(lucideReact.X,{style:{width:16,height:16}})})]}),Ot.jsxs("div",{ref:ge,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[e==="prompting"&&F.length===0&&Ot.jsxs("div",{style:{padding:"24px 20px",textAlign:"center"},children:[Ot.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."}),Ot.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6,justifyContent:"center"},children:b.map((A,L)=>Ot.jsx("button",{onClick:()=>{C(A),Z.current?.focus();},onMouseEnter:()=>Y(L),onMouseLeave:()=>Y(null),style:{fontSize:12,padding:"5px 12px",borderRadius:9999,color:G===L?"#1f2937":"#6b7280",backgroundColor:G===L?"#f9fafb":"transparent",border:G===L?"1px solid #d1d5db":"1px solid #e5e7eb",cursor:"pointer",transition:"color 0.15s, background-color 0.15s, border-color 0.15s",fontFamily:"inherit"},children:A},A))})]}),F.length>0&&Ot.jsx("div",{style:{padding:"16px 16px 0 16px"},children:F.map((A,L)=>Ot.jsx("div",{style:{marginBottom:L<F.length-1?10:0},children:A.type==="user"?Ot.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexDirection:"row-reverse"},children:[Ot.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:Ot.jsx(lucideReact.User,{style:{width:13,height:13,color:"#6b7280"}})}),Ot.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})]}):Ot.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[Ot.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#f0fdf4",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:Ot.jsx(lucideReact.Check,{style:{width:13,height:13,color:"#9ca3af"}})}),Ot.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:[Ot.jsx("span",{style:{flex:1},children:A.text}),m&&L===F.length-1&&e!=="running"&&Ot.jsxs("button",{onClick:H=>{H.stopPropagation(),Lt();},onMouseEnter:()=>P(L),onMouseLeave:()=>P(null),disabled:W,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:v===L?"rgba(0,0,0,0.06)":"transparent",color:v===L?"#6b7280":"#d1d5db",cursor:W?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:W?.4:1,flexShrink:0},children:[Ot.jsx(lucideReact.Undo2,{style:{width:12,height:12}}),v===L&&Ot.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"})]})]})]})},L))}),e==="running"&&Ot.jsx("div",{style:{padding:16},children:Ot.jsxs("div",{onClick:()=>q(!O),style:{backgroundColor:"#1a1a2e",borderRadius:12,overflow:"hidden",cursor:"pointer",transition:"all 0.3s cubic-bezier(0.22, 1, 0.36, 1)"},children:[Ot.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px"},children:[Ot.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[Ot.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:Ot.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),Ot.jsx(Cr,{events:r})]}),Ot.jsx("div",{style:{color:"#6b7280",flexShrink:0,marginLeft:8,transition:"transform 0.2s ease",transform:O?"rotate(180deg)":"rotate(0deg)"},children:Ot.jsx(lucideReact.ChevronDown,{style:{width:14,height:14}})})]}),Ot.jsx("div",{style:{maxHeight:O?320:0,opacity:O?1:0,transition:"max-height 0.35s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.25s ease",overflow:"hidden"},children:Ot.jsx("div",{style:{borderTop:"1px solid rgba(255,255,255,0.08)",maxHeight:320,overflowY:"auto"},children:Ot.jsx(bt,{events:r})})})]})}),e==="error"&&Ot.jsxs("div",{style:{padding:"20px 16px",textAlign:"center"},children:[Ot.jsx("div",{style:{width:36,height:36,backgroundColor:"#fef2f2",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 10px auto"},children:Ot.jsx(lucideReact.X,{style:{width:18,height:18,color:"#ef4444"}})}),Ot.jsx("p",{style:{fontSize:12,color:"#6b7280",marginBottom:10,maxWidth:260,margin:"0 auto 10px auto"},children:o}),Ot.jsxs("button",{onClick:()=>{let A=t?.prompt||_e.current;A&&d(A,X);},onMouseEnter:()=>V(true),onMouseLeave:()=>V(false),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,color:"#4f46e5",backgroundColor:K?"#e0e7ff":"#eef2ff",border:"none",cursor:"pointer",transition:"background-color 0.15s",fontFamily:"inherit"},children:[Ot.jsx(lucideReact.RotateCcw,{style:{width:12,height:12}})," Try Again"]})]})]}),e!=="running"&&Ot.jsx("div",{style:{padding:"8px 12px 12px 12px",borderTop:"1px solid rgba(229, 231, 235, 0.6)",flexShrink:0},children:Ot.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:[Ot.jsx("textarea",{ref:Z,value:R,onChange:A=>{C(A.target.value),A.target.style.height="auto",A.target.style.height=Math.min(A.target.scrollHeight,160)+"px";},onKeyDown:A=>{A.key==="Enter"&&!A.shiftKey&&(A.preventDefault(),Ze()),A.key==="Escape"&&!T&&Me();},placeholder:F.length>0?"Ask for another change...":`Describe your ideal ${Pe.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"}}),Ot.jsx("button",{onClick:Ze,disabled:!R.trim(),onMouseEnter:()=>U(true),onMouseLeave:()=>U(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:R.trim()?1:.25,transform:B&&R.trim()?"scale(1.1)":"scale(1)",background:R.trim()?"#1c4587":"rgba(0,0,0,0.12)",border:"none",cursor:R.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:Ot.jsx(lucideReact.ArrowUp,{style:{width:13,height:13}})})]})})]})]});return T?Qe:Ot.jsx(Tr,{children:Qe})}function vt(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 ze(e){let{apiKey:t,userId:r,userHash:o,baseUrl:n,appId:i,refreshModuleManifest:s,queueBoundaryAnimation:a}=j(),[b,d]=He.useState("idle"),[m,S]=He.useState(null),[_,w]=He.useState([]),[h,l]=He.useState(null),$=He.useRef(null),T=He.useCallback(()=>{d("prompting"),w([]),l(null),S(null);},[]),R=He.useCallback(()=>{d("idle"),$.current&&($.current.close(),$.current=null);},[]),C=He.useCallback(async y=>{try{if(!i)throw new Error("ForkProvider requires appId for module boundary prompts.");d("running"),w([]),l(null);let E={userId:r,prompt:y,boundaryId:e,appId:i};o&&(E.userHash=o);let c=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(E)});if(!c.ok){let f=await c.json().catch(()=>({}));throw new Error(f.error||`API error: ${c.status}`)}let u=await c.json();S(u);let x=new URLSearchParams({key:t});o&&(x.set("userId",r),x.set("userHash",o));let k=new EventSource(`${n}/api/v1/forks/${u.id}/events?${x.toString()}`);$.current=k,k.onmessage=f=>{try{let g=JSON.parse(f.data);if(w(p=>[...p,g]),g.type==="complete"){let p=g.data;a(e,u.id),s().catch(()=>{}).finally(()=>{let B={...u,status:"complete",moduleUrl:p.moduleUrl,cssUrls:p.cssUrls,summary:p.summary,completedAt:new Date().toISOString()};S(B),d("complete"),k.close();});}else if(g.type==="error"){let p=g.data;l(p.error||"Unknown error"),d("error"),k.close();}}catch{}},k.onerror=()=>{fetch(`${n}/api/v1/forks/${u.id}`,{headers:{Authorization:`Bearer ${t}`}}).then(f=>f.json()).then(f=>{S(f),f.status==="complete"?(a(e,f.id),s().catch(()=>{}),d("complete")):f.status==="error"&&(l(f.error||"Fork generation failed"),d("error"));}).catch(()=>{l("Connection lost"),d("error");}),k.close();};}catch(E){l(E.message),d("error");}},[t,i,n,e,a,s,o,r]),F=He.useCallback(async()=>{try{if(!i)throw new Error("ForkProvider requires appId for boundary undo.");let y={userId:r,boundaryId:e,appId:i};o&&(y.userHash=o);let E=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(y)});if(!E.ok){let u=await E.json().catch(()=>({}));throw new Error(u.error||`API error: ${E.status}`)}let c=await E.json();return await s().catch(()=>{}),c.removed?(S(null),d("prompting")):c.fork&&(S(c.fork),d("complete")),c}catch(y){throw l(y.message),y}},[t,i,n,e,s,o,r]);return {state:b,fork:m,events:_,error:h,open:T,close:R,startFork:C,undoFork:F}}function St(e){let{state:t,fork:r,events:o,error:n,open:i,close:s,startFork:a,undoFork:b}=ze(e);return {state:t,fork:r,events:o,error:n,isOpen:t!=="idle",open:i,close:s,submit:a,undo:b}}function We(){let{apiKey:e,userId:t,userHash:r,baseUrl:o,setSlotFork:n,clearSlotFork:i,skipAnimationForSlot:s}=j(),[a,b]=He.useState("idle"),[d,m]=He.useState(null),[S,_]=He.useState([]),[w,h]=He.useState(null),l=He.useRef(null),$=He.useCallback(()=>{b("prompting"),_([]),h(null),m(null);},[]),T=He.useCallback(()=>{b("idle"),l.current&&(l.current.close(),l.current=null);},[]),R=He.useCallback(async(F,y)=>{try{b("running"),_([]),h(null);let E={userId:t,prompt:F};y&&(E.slotId=y),r&&(E.userHash=r);let c=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(E)});if(!c.ok){let f=await c.json().catch(()=>({}));throw new Error(f.error||`API error: ${c.status}`)}let u=await c.json();m(u);let x=new URLSearchParams({key:e});r&&(x.set("userId",t),x.set("userHash",r));let k=new EventSource(`${o}/api/v1/forks/${u.id}/events?${x.toString()}`);l.current=k,k.onmessage=f=>{try{let g=JSON.parse(f.data);if(_(p=>[...p,g]),g.type==="complete"){let p=g.data,B={...u,status:"complete",bundleUrl:p.bundleUrl,summary:p.summary,completedAt:new Date().toISOString()};m(B),b("complete"),y&&p.bundleUrl&&n(y,B),k.close();}else if(g.type==="error"){let p=g.data;h(p.error||"Unknown error"),b("error"),k.close();}}catch{}},k.onerror=()=>{fetch(`${o}/api/v1/forks/${u.id}`,{headers:{Authorization:`Bearer ${e}`}}).then(f=>f.json()).then(f=>{m(f),f.status==="complete"?(b("complete"),y&&f.bundleUrl&&n(y,f)):f.status==="error"&&(h(f.error||"Fork generation failed"),b("error"));}).catch(()=>{h("Connection lost"),b("error");}),k.close();};}catch(E){h(E.message),b("error");}},[e,t,r,o,n]),C=He.useCallback(async F=>{try{let y={userId:t,slotId:F};r&&(y.userHash=r);let E=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(y)});if(!E.ok){let u=await E.json().catch(()=>({}));throw new Error(u.error||`API error: ${E.status}`)}let c=await E.json();return s(F),c.removed?(i(F),m(null),b("prompting")):c.fork&&(n(F,c.fork),m(c.fork)),c}catch(y){throw h(y.message),y}},[e,t,r,o,i,n]);return {state:a,fork:d,events:S,error:w,open:$,close:T,startFork:R,undoFork:C}}function Ft(){let{state:e,fork:t,events:r,error:o,open:n,close:i,startFork:s,undoFork:a}=We();return {state:e,fork:t,events:r,error:o,isOpen:e!=="idle",open:n,close:i,submit:s,undo:a}}function Ke(e){let t=vt(e),r=Ft(),o=St(t.type==="boundary"?t.id:""),{baseUrl:n,apiKey:i,userId:s,userHash:a,appId:b}=j(),d=t.type==="slot"?r:o,m=t.type==="slot"?"slot":"boundary",S=t.id,_=t.title,w=He.useCallback((l,$)=>t.type==="slot"?r.submit(l,$??t.id):o.submit(l),[o,r,t]),h=He.useCallback(l=>t.type==="slot"?r.undo(l??t.id):o.undo(),[o,r,t]);return {...d,target:t,targetId:S,targetLabel:_,historyMode:m,submit:w,undo:h,buttonProps:{onClick:d.open},panelProps:{state:d.state,fork:d.fork,events:d.events,error:d.error,...t.type==="slot"?{slotId:S,targetLabel:_,historyMode:m}:{targetId:S,targetLabel:_,historyMode:m},onSubmit:w,onUndo:h,onClose:d.close,baseUrl:n,apiKey:i,userId:s,userHash:a,appId:b}}}function me(e){let{examplePrompts:t,embedded:r}=e,o=Ke(e);return r?Ot.jsx(xe,{...o.panelProps,examplePrompts:t,embedded:true}):o.isOpen?Ot.jsx(xe,{...o.panelProps,examplePrompts:t}):Ot.jsx(De,{...o.buttonProps})}function Lr({boundaryId:e,title:t,examplePrompts:r}){return Ot.jsx(me,{boundaryId:e,title:t,examplePrompts:r})}function Ve(e){let t=Array.from(e.children).filter(o=>o instanceof HTMLElement);return t.length===1?t[0]:getComputedStyle(e).display==="contents"?null:e}function Rt(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 o=getComputedStyle(e).backgroundColor;r.style.backgroundColor=o&&o!=="rgba(0, 0, 0, 0)"&&o!=="transparent"?o:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(r);let n=e.querySelectorAll("*"),i=r.querySelectorAll("*");for(let s=0;s<n.length;s+=1)n[s].scrollTop!==0&&(i[s].scrollTop=n[s].scrollTop),n[s].scrollLeft!==0&&(i[s].scrollLeft=n[s].scrollLeft);return r}function qe(e){let t=[],r=e.querySelectorAll("*");for(let o of r){if(!(o instanceof HTMLElement))continue;let n=o.getBoundingClientRect();if(n.width<10||n.height<10||["SCRIPT","STYLE","META","LINK"].includes(o.tagName))continue;let i=getComputedStyle(o),s=parseFloat(i.borderTopLeftRadius)||0;t.push({tag:o.tagName,className:o.className||"",text:(o.textContent||"").slice(0,50).trim(),rect:n,borderRadius:s});}return t}function Et(e,t){let r=[];for(let o of t)if(!(e.find(s=>s.tag===o.tag&&s.className===o.className&&Math.abs(s.rect.top-o.rect.top)<20&&Math.abs(s.rect.left-o.rect.left)<20)||r.some(s=>o.rect.top>=s.rect.top&&o.rect.left>=s.rect.left&&o.rect.right<=s.rect.right&&o.rect.bottom<=s.rect.bottom))){for(let s=r.length-1;s>=0;s-=1){let a=r[s];a.rect.top>=o.rect.top&&a.rect.left>=o.rect.left&&a.rect.right<=o.rect.right&&a.rect.bottom<=o.rect.bottom&&r.splice(s,1);}r.push({rect:o.rect,borderRadius:o.borderRadius});}return r}function $t(e,t){let r=[];for(let o of e)if(!(t.find(s=>s.tag===o.tag&&s.className===o.className&&Math.abs(s.rect.top-o.rect.top)<20&&Math.abs(s.rect.left-o.rect.left)<20)||r.some(s=>o.rect.top>=s.rect.top&&o.rect.left>=s.rect.left&&o.rect.right<=s.rect.right&&o.rect.bottom<=s.rect.bottom))){for(let s=r.length-1;s>=0;s-=1){let a=r[s];a.rect.top>=o.rect.top&&a.rect.left>=o.rect.left&&a.rect.right<=o.rect.right&&a.rect.bottom<=o.rect.bottom&&r.splice(s,1);}r.push({rect:o.rect,borderRadius:o.borderRadius});}return r}function At(e,t,r,o,n){let i=Math.max(0,Math.min(n,r/2,o/2));return i===0?`M ${e} ${t} L ${e+r} ${t} L ${e+r} ${t+o} L ${e} ${t+o} Z`:[`M ${e+i} ${t}`,`L ${e+r-i} ${t}`,`A ${i} ${i} 0 0 1 ${e+r} ${t+i}`,`L ${e+r} ${t+o-i}`,`A ${i} ${i} 0 0 1 ${e+r-i} ${t+o}`,`L ${e+i} ${t+o}`,`A ${i} ${i} 0 0 1 ${e} ${t+o-i}`,`L ${e} ${t+i}`,`A ${i} ${i} 0 0 1 ${e+i} ${t}`,"Z"].join(" ")}function Je(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 o=document.createElementNS(t,"svg");o.setAttribute("width","100%"),o.setAttribute("height","100%"),o.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let n=document.createElementNS(t,"defs");o.appendChild(n);let i=[];for(let m=0;m<e.length;m+=1){let{rect:S,borderRadius:_}=e[m],w=S.left-.5,h=S.top-.5,l=S.width+1,$=S.height+1,T=Math.min(_+.5,l/2,$/2),R=At(w,h,l,$,T),C=`__fork-glow-${m}`,F=document.createElementNS(t,"filter");F.setAttribute("id",C),F.setAttribute("x","-100%"),F.setAttribute("y","-100%"),F.setAttribute("width","300%"),F.setAttribute("height","300%");let y=document.createElementNS(t,"feGaussianBlur");y.setAttribute("in","SourceGraphic"),y.setAttribute("stdDeviation","8"),F.appendChild(y),n.appendChild(F);let E=`__fork-mask-${m}`,c=document.createElementNS(t,"mask");c.setAttribute("id",E),c.setAttribute("maskUnits","userSpaceOnUse"),c.setAttribute("x",String(w-200)),c.setAttribute("y",String(h-200)),c.setAttribute("width",String(l+400)),c.setAttribute("height",String($+400));let u=document.createElementNS(t,"rect");u.setAttribute("x",String(w-200)),u.setAttribute("y",String(h-200)),u.setAttribute("width",String(l+400)),u.setAttribute("height",String($+400)),u.setAttribute("fill","white"),c.appendChild(u);let x=document.createElementNS(t,"path");x.setAttribute("d",R),x.setAttribute("fill","black"),c.appendChild(x),n.appendChild(c);let k=document.createElementNS(t,"g");k.setAttribute("mask",`url(#${E})`),k.setAttribute("opacity","0");let f=document.createElementNS(t,"g");f.setAttribute("filter",`url(#${C})`);let g=document.createElementNS(t,"path");g.setAttribute("d",R),g.setAttribute("fill","none"),g.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),g.setAttribute("stroke-width","6"),g.setAttribute("stroke-linecap","round"),f.appendChild(g),k.appendChild(f),o.appendChild(k);let p=document.createElementNS(t,"path");p.setAttribute("d",R),p.setAttribute("fill","none"),p.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),p.setAttribute("stroke-width","2"),p.setAttribute("stroke-linecap","round"),p.setAttribute("opacity","0"),o.appendChild(p),i.push(g,p),g.__group=k;}r.appendChild(o),document.body.appendChild(r);let s=[];for(let m=0;m<i.length;m+=2){let S=i[m],_=i[m+1],w=S.__group;if(!w)continue;let h=_.getTotalLength(),l=S.getTotalLength();if(h<=0)continue;let $=h*.35;_.setAttribute("stroke-dasharray",`${$} ${h-$}`),_.setAttribute("stroke-dashoffset","0"),s.push(_.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*h,opacity:.92,offset:.06},{strokeDashoffset:-2*h,opacity:.92,offset:.92},{strokeDashoffset:-2.25*h,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let T=l*.35;S.setAttribute("stroke-dasharray",`${T} ${l-T}`),S.setAttribute("stroke-dashoffset","0"),s.push(S.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*l,offset:.06},{strokeDashoffset:-2*l,offset:.92},{strokeDashoffset:-2.25*l,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(w.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,b=()=>{if(a)return;a=true,clearTimeout(d);for(let S of s)try{S.cancel();}catch{}let m=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});m.onfinish=()=>r.remove(),window.removeEventListener("click",b);},d=setTimeout(b,14500);return setTimeout(()=>{a||window.addEventListener("click",b);},500),b}function Ct(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 o=document.createElementNS(t,"svg");o.setAttribute("width","100%"),o.setAttribute("height","100%"),o.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let n=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),n.appendChild(i),o.appendChild(n);for(let{rect:a,borderRadius:b}of e){let d=document.createElementNS(t,"path");d.setAttribute("d",At(a.left,a.top,a.width,a.height,b)),d.setAttribute("fill","none"),d.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),d.setAttribute("stroke-width","1.5"),d.setAttribute("stroke-dasharray","8 4"),d.setAttribute("stroke-linecap","round"),d.setAttribute("filter","url(#__fork-removed-shadow)"),d.setAttribute("opacity","0"),o.appendChild(d),d.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(o),document.body.appendChild(r),r}var Te=new Map,Ye=new Map;function Hr(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function Pt(e,t){let r=(t?e[t]:void 0)??e.default;if(typeof r!="function"){let o=t||"default";throw new Error(`Fork boundary module is missing a React component export: ${o}`)}return r}function Or(e){if(!e||typeof document>"u")return Promise.resolve();let t=Te.get(e);if(t)return t;let r=document.querySelector(`link[data-fork-override-href="${e}"]`);if(r instanceof HTMLLinkElement){let n=r.sheet?Promise.resolve():new Promise((i,s)=>{let a=()=>{r.removeEventListener("load",a),r.removeEventListener("error",b),i();},b=()=>{r.removeEventListener("load",a),r.removeEventListener("error",b),s(new Error(`Failed to load boundary stylesheet: ${e}`));};r.addEventListener("load",a,{once:true}),r.addEventListener("error",b,{once:true});});return Te.set(e,n),n}let o=new Promise((n,i)=>{let s=document.createElement("link");s.rel="stylesheet",s.href=e,s.setAttribute("data-fork-override-href",e),s.onload=()=>n(),s.onerror=()=>{s.remove(),i(new Error(`Failed to load boundary stylesheet: ${e}`));},document.head.appendChild(s);}).catch(n=>{throw Te.delete(e),n});return Te.set(e,o),o}function Ur(e){let t=Ye.get(e);if(t)return t;let r=import(e).catch(o=>{throw Ye.delete(e),o});return Ye.set(e,r),r}async function Dr(e,t,r){if(e)try{await Promise.all(e.cssUrls.map(i=>Or(i)));let n=await Ur(e.moduleUrl);return Pt(n,r)}catch(n){console.error(`[Fork] Failed to load override for boundary "${e.boundaryId}", falling back to original module.`,n);}let o=await t();return Pt(o,r)}function Ir(e){function t(r){let{appId:o,moduleOverridesEnabled:n,moduleManifestReady:i,moduleManifestVersion:s,registerBoundary:a,getBoundaryOverride:b,consumeBoundaryAnimation:d}=j(),[m,S]=He.useState(null),[_,w]=He.useState(null),h=He.useRef(null),l=He.useRef(null),$=He.useRef(null),T=He.useRef(false),R=He.useRef(null),C=He.useRef(null),F=b(e.id),y=F?`override:${F.id}`:"original",E=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if(He.useEffect(()=>()=>{C.current&&(clearTimeout(C.current),C.current=null),R.current&&(R.current.remove(),R.current=null);},[]),He.useEffect(()=>{a({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[o,a,e.id,e.exportName,E]),He.useEffect(()=>{if(n&&!i&&!m||l.current===y&&m)return;let c=false;return w(null),Dr(F,e.original,e.exportName).then(u=>{if(!c){if(F?.id&&d(e.id,F.id)&&h.current){let x=Ve(h.current);if(x){let k=qe(x);k.length>0&&($.current=k,T.current=true,C.current&&(clearTimeout(C.current),C.current=null),R.current&&R.current.remove(),R.current=Rt(x));}}l.current=y,He.startTransition(()=>{S(()=>u);});}}).catch(u=>{c||w(Hr(u));}),()=>{c=true;}},[d,y,n,i,s,F?.id,F?.moduleUrl,F?.integrity,F?.cssUrls.join("|"),e.exportName,e.original,m]),He.useEffect(()=>{if(!T.current||!m||!h.current)return;let c=false;return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(c||!h.current)return;let u=$.current,x=Ve(h.current);if($.current=null,T.current=false,!u||!x){R.current&&(R.current.remove(),R.current=null);return}let k=qe(x),f=Et(u,k),g=$t(u,k),p=R.current;if(g.length>0&&p){let B=Ct(g);C.current=setTimeout(()=>{C.current=null;let U=400;p.animate([{opacity:1},{opacity:0}],{duration:U,fill:"forwards"}),B.animate([{opacity:1},{opacity:0}],{duration:U,fill:"forwards"}),setTimeout(()=>{p.remove(),B.remove(),R.current===p&&(R.current=null),f.length>0&&Je(f);},U);},3500);}else p&&(p.remove(),R.current===p&&(R.current=null)),f.length>0&&Je(f);});}),()=>{c=true;}},[m]),_)throw _;return m?Ot.jsx("div",{ref:h,style:{display:"contents"},children:Ot.jsx(m,{...r})}):Ot.jsx(Ot.Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function zr({slotId:e,title:t,slotLabel:r,examplePrompts:o}){return Ot.jsx(me,{slotId:e,title:t,slotLabel:r,examplePrompts:o})}
44
+ exports.ForkBoundaryUI=Lr;exports.ForkButton=De;exports.ForkChatInterface=me;exports.ForkPanel=xe;exports.ForkProvider=zt;exports.ForkSlot=rr;exports.ForkUI=zr;exports.forkable=Ir;exports.registerForkShared=Be;exports.useBoundaryFork=ze;exports.useFork=We;exports.useForkChatPanel=Ke;
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import*as He from'react';import He__default,{createContext,useState,useRef,useEffect,useCallback,startTransition,Children,useContext,isValidElement,useLayoutEffect}from'react';import*as Ht from'react-dom';import*as Ot from'react/jsx-runtime';import {jsx,Fragment,jsxs}from'react/jsx-runtime';import*as Ut from'react/jsx-dev-runtime';import {X,User,Check,Undo2,ChevronDown,RotateCcw,ArrowUp,Loader2,AlertCircle,Sparkles,Package,Wrench,MessageSquare,Code,Terminal,FileSearch,Pencil}from'lucide-react';var re="__FORK_SHARED__";function Le(){var t,r,o,n;let e=globalThis;return e[re]||(e[re]={}),(t=e[re]).react||(t.react=He),(r=e[re])["react-dom"]||(r["react-dom"]=Ht),(o=e[re])["react/jsx-runtime"]||(o["react/jsx-runtime"]=Ot),(n=e[re])["react/jsx-dev-runtime"]||(n["react/jsx-dev-runtime"]=Ut),e[re]}function Be(e){return Object.assign(Le(),e)}var et=createContext(null);function Qe(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function jt(e,t){let r={};for(let[o,n]of Object.entries(t.boundaries||{}))r[o]={...n,moduleUrl:Qe(e,n.moduleUrl),cssUrls:Array.isArray(n.cssUrls)?n.cssUrls.map(i=>Qe(e,i)):[]};return r}function zt(e){let{apiKey:t,baseUrl:r,children:o,appId:n,shared:i}=e,s="userId"in e?e.userId:void 0,a="authUrl"in e?e.authUrl:void 0,[b,d]=useState({}),[m,S]=useState(s?{userId:s,userHash:void 0}:null),[P,w]=useState(!!s),[h,l]=useState({}),[$,T]=useState(!n),[R,C]=useState(0),F=useRef(new Map),y=useRef(new Map),[E,c]=useState(0),u=useRef(new Set),x=useRef(new Map),k=useRef(void 0);Le(),i&&k.current!==i&&(Be(i),k.current=i),useEffect(()=>{a&&(w(false),fetch(a,{credentials:"include"}).then(v=>{if(!v.ok)throw new Error(`Auth endpoint returned ${v.status}`);return v.json()}).then(v=>{if(!v.userId||typeof v.userId!="string")throw new Error("authUrl response must include userId");S({userId:v.userId,userHash:v.userHash});}).catch(v=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",v.message);}).finally(()=>{w(true);}));},[a]),useEffect(()=>{!a&&s&&(S({userId:s,userHash:void 0}),w(true));},[s,a]);let f=m?.userId??"",g=m?.userHash,p=!!n,B=useCallback(async()=>{if(!p){l({}),T(true),C(_=>_+1);return}if(!P){T(false);return}if(!f||!n){l({}),T(true),C(_=>_+1);return}let v=new URLSearchParams({appId:n,userId:f});g&&v.set("userHash",g),T(false);try{let _=await fetch(`${r}/api/v1/boundaries/manifest?${v.toString()}`,{headers:{Authorization:`Bearer ${t}`}});if(!_.ok)throw new Error(`${_.status}`);let N=await _.json();l(jt(r,N));}catch(_){console.error("[ForkProvider] Failed to fetch module override manifest:",_.message),l({});}finally{C(_=>_+1),T(true);}},[t,n,r,P,p,g,f]);useEffect(()=>{if(!f)return;let v=new URLSearchParams({userId:f});g&&v.set("userHash",g),fetch(`${r}/api/v1/forks/active?${v.toString()}`,{headers:{Authorization:`Bearer ${t}`}}).then(_=>{if(!_.ok)throw new Error(`${_.status}`);return _.json()}).then(_=>{_&&typeof _=="object"&&d(_);}).catch(()=>{});},[t,f,g,r]),useEffect(()=>{B();},[B]);let U=useCallback((v,_)=>{d(N=>({...N,[v]:_}));},[]),K=useCallback(v=>{d(_=>{let N={..._};return delete N[v],N});},[]),V=useCallback(v=>{u.current.add(v);},[]),G=useCallback(v=>u.current.has(v)?(u.current.delete(v),true):false,[]),Y=useCallback((v,_)=>{x.current.set(v,_);},[]),O=useCallback((v,_)=>x.current.get(v)!==_?false:(x.current.delete(v),true),[]),q=useCallback(v=>{if(!n)return;let _=JSON.stringify(v);F.current.get(v.id)===_||y.current.get(v.id)?.signature===_||(y.current.set(v.id,{boundary:v,signature:_}),c(z=>z+1));},[n]);useEffect(()=>{if(!n||y.current.size===0)return;let v=setTimeout(()=>{let _=Array.from(y.current.values());_.length!==0&&fetch(`${r}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:n,boundaries:_.map(N=>N.boundary)})}).then(N=>{if(!N.ok)throw new Error(`${N.status}`)}).then(()=>{for(let N of _)y.current.get(N.boundary.id)?.signature===N.signature&&(y.current.delete(N.boundary.id),F.current.set(N.boundary.id,N.signature));}).catch(N=>{console.error("[ForkProvider] Failed to register module boundaries:",N.message);});},50);return ()=>{clearTimeout(v);}},[t,n,r,E]);let W=useCallback(v=>h[v],[h]),ee=useCallback(async()=>{if(!g)throw new Error("Reset requires verified user identity (provide authUrl / userHash).");let v=new URLSearchParams({userId:f,userHash:g}),_=await fetch(`${r}/api/v1/forks/all?${v.toString()}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}});if(!_.ok){let z=await _.json().catch(()=>({}));throw new Error(z.error||`API error: ${_.status}`)}let N=await _.json().catch(()=>({}));d({}),l({}),T(true),C(z=>z+1),u.current.clear(),x.current.clear();try{for(let z=sessionStorage.length-1;z>=0;z-=1){let Z=sessionStorage.key(z);Z&&Z.startsWith("__fork_animated_")&&sessionStorage.removeItem(Z);}}catch{}return N},[t,r,g,f]);return jsx(et.Provider,{value:{apiKey:t,userId:f,userHash:g,baseUrl:r,appId:n,forks:b,moduleOverridesEnabled:p,moduleManifestReady:$,moduleManifestVersion:R,setSlotFork:U,clearSlotFork:K,skipAnimationForSlot:V,shouldSkipAnimation:G,queueBoundaryAnimation:Y,consumeBoundaryAnimation:O,registerBoundary:q,getBoundaryOverride:W,refreshModuleManifest:B,resetAllForks:ee},children:o})}function I(){let e=useContext(et);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function ke(e){return I().forks[e]}var fe=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 o=this.values.get(t);if(Object.is(o,r))return;if(o!==void 0&&r!==null&&o!==null&&typeof o=="object"&&typeof r=="object")try{if(JSON.stringify(o)===JSON.stringify(r))return}catch{}this.values.set(t,r),this.snapshots.set(t,r);let n=this.listeners.get(t);n&&n.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(o=>this.subscribe(t,o),()=>this.getSnapshot(t)):(console.warn("[ForkBridge] React.useSyncExternalStore not available, returning static value"),this.values.get(t))}emit(t,...r){let o=this.eventHandlers.get(t);o&&o.forEach(n=>n(...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 Oe(e,t){let r;try{r=Children.only(e);}catch{let n=Children.count(e);throw new Error(`<ForkSlot slotId="${t}"> must wrap exactly one React component, got ${n} children. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`)}let o=r.type;if(typeof o=="string")throw new Error(`<ForkSlot slotId="${t}"> child must be a React component (function or class), not an HTML element <${o}>. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`);if(typeof o=="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 rt=new Set;function ot(e){let t=[],r=e.querySelectorAll("*");for(let o of r){if(!(o instanceof HTMLElement))continue;let n=o.getBoundingClientRect();if(n.width<10||n.height<10||["SCRIPT","STYLE","META","LINK"].includes(o.tagName))continue;let i=getComputedStyle(o),s=parseFloat(i.borderTopLeftRadius)||0;t.push({tag:o.tagName,className:o.className||"",text:(o.textContent||"").slice(0,50).trim(),rect:n,borderRadius:s});}return t}function qt(e,t){let r=[];for(let o of t)if(!e.find(i=>i.tag===o.tag&&i.className===o.className&&Math.abs(i.rect.top-o.rect.top)<20&&Math.abs(i.rect.left-o.rect.left)<20)&&!r.some(s=>o.rect.top>=s.rect.top&&o.rect.left>=s.rect.left&&o.rect.right<=s.rect.right&&o.rect.bottom<=s.rect.bottom)){for(let s=r.length-1;s>=0;s--){let a=r[s];a.rect.top>=o.rect.top&&a.rect.left>=o.rect.left&&a.rect.right<=o.rect.right&&a.rect.bottom<=o.rect.bottom&&r.splice(s,1);}r.push({rect:o.rect,borderRadius:o.borderRadius});}return r}function Jt(e,t){let r=[];for(let o of e)if(!t.find(i=>i.tag===o.tag&&i.className===o.className&&Math.abs(i.rect.top-o.rect.top)<20&&Math.abs(i.rect.left-o.rect.left)<20)&&!r.some(s=>o.rect.top>=s.rect.top&&o.rect.left>=s.rect.left&&o.rect.right<=s.rect.right&&o.rect.bottom<=s.rect.bottom)){for(let s=r.length-1;s>=0;s--){let a=r[s];a.rect.top>=o.rect.top&&a.rect.left>=o.rect.left&&a.rect.right<=o.rect.right&&a.rect.bottom<=o.rect.bottom&&r.splice(s,1);}r.push({rect:o.rect,borderRadius:o.borderRadius});}return r}function st(e,t,r,o,n){return n=Math.max(0,Math.min(n,r/2,o/2)),n===0?`M ${e} ${t} L ${e+r} ${t} L ${e+r} ${t+o} L ${e} ${t+o} Z`:[`M ${e+n} ${t}`,`L ${e+r-n} ${t}`,`A ${n} ${n} 0 0 1 ${e+r} ${t+n}`,`L ${e+r} ${t+o-n}`,`A ${n} ${n} 0 0 1 ${e+r-n} ${t+o}`,`L ${e+n} ${t+o}`,`A ${n} ${n} 0 0 1 ${e} ${t+o-n}`,`L ${e} ${t+n}`,`A ${n} ${n} 0 0 1 ${e+n} ${t}`,"Z"].join(" ")}function nt(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 o=document.createElementNS(t,"svg");o.setAttribute("width","100%"),o.setAttribute("height","100%"),o.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let n=document.createElementNS(t,"defs");o.appendChild(n);let i=[];for(let m=0;m<e.length;m++){let{rect:S,borderRadius:P}=e[m],w=S.left-.5,h=S.top-.5,l=S.width+1,$=S.height+1,T=Math.min(P+.5,l/2,$/2),R=st(w,h,l,$,T),C=`__fork-glow-${m}`,F=document.createElementNS(t,"filter");F.setAttribute("id",C),F.setAttribute("x","-100%"),F.setAttribute("y","-100%"),F.setAttribute("width","300%"),F.setAttribute("height","300%");let y=document.createElementNS(t,"feGaussianBlur");y.setAttribute("in","SourceGraphic"),y.setAttribute("stdDeviation","8"),F.appendChild(y),n.appendChild(F);let E=`__fork-mask-${m}`,c=document.createElementNS(t,"mask");c.setAttribute("id",E),c.setAttribute("maskUnits","userSpaceOnUse"),c.setAttribute("x",String(w-200)),c.setAttribute("y",String(h-200)),c.setAttribute("width",String(l+400)),c.setAttribute("height",String($+400));let u=document.createElementNS(t,"rect");u.setAttribute("x",String(w-200)),u.setAttribute("y",String(h-200)),u.setAttribute("width",String(l+400)),u.setAttribute("height",String($+400)),u.setAttribute("fill","white"),c.appendChild(u);let x=document.createElementNS(t,"path");x.setAttribute("d",R),x.setAttribute("fill","black"),c.appendChild(x),n.appendChild(c);let k=document.createElementNS(t,"g");k.setAttribute("mask",`url(#${E})`),k.setAttribute("opacity","0");let f=document.createElementNS(t,"g");f.setAttribute("filter",`url(#${C})`);let g=document.createElementNS(t,"path");g.setAttribute("d",R),g.setAttribute("fill","none"),g.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),g.setAttribute("stroke-width","6"),g.setAttribute("stroke-linecap","round"),f.appendChild(g),k.appendChild(f),o.appendChild(k);let p=document.createElementNS(t,"path");p.setAttribute("d",R),p.setAttribute("fill","none"),p.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),p.setAttribute("stroke-width","2"),p.setAttribute("stroke-linecap","round"),p.setAttribute("opacity","0"),o.appendChild(p),i.push(g,p),g.__group=k;}r.appendChild(o),document.body.appendChild(r);let s=[];for(let m=0;m<i.length;m+=2){let S=i[m],P=i[m+1],w=S.__group,h=P.getTotalLength(),l=S.getTotalLength();if(h<=0)continue;let $=h*.35;P.setAttribute("stroke-dasharray",`${$} ${h-$}`),P.setAttribute("stroke-dashoffset","0"),s.push(P.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*h,opacity:.92,offset:.06},{strokeDashoffset:-2*h,opacity:.92,offset:.92},{strokeDashoffset:-2.25*h,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let T=l*.35;S.setAttribute("stroke-dasharray",`${T} ${l-T}`),S.setAttribute("stroke-dashoffset","0"),s.push(S.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*l,offset:.06},{strokeDashoffset:-2*l,offset:.92},{strokeDashoffset:-2.25*l,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(w.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,b=()=>{if(a)return;a=true,clearTimeout(d);for(let S of s)try{S.cancel();}catch{}let m=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});m.onfinish=()=>r.remove(),window.removeEventListener("click",b);},d=setTimeout(b,14500);return setTimeout(()=>{a||window.addEventListener("click",b);},500),b}function Yt(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 o=document.createElementNS(t,"svg");o.setAttribute("width","100%"),o.setAttribute("height","100%"),o.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let n=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),n.appendChild(i),o.appendChild(n);for(let{rect:a,borderRadius:b}of e){let d=a.left,m=a.top,S=a.width,P=a.height,w=Math.min(b,S/2,P/2),h=st(d,m,S,P,w),l=document.createElementNS(t,"path");l.setAttribute("d",h),l.setAttribute("fill","none"),l.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),l.setAttribute("stroke-width","1.5"),l.setAttribute("stroke-dasharray","8 4"),l.setAttribute("stroke-linecap","round"),l.setAttribute("filter","url(#__fork-removed-shadow)"),l.setAttribute("opacity","0"),o.appendChild(l),l.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(o),document.body.appendChild(r),r}function Xt(e,t){if(e===t)return true;let r=Object.keys(e);if(r.length!==Object.keys(t).length)return false;for(let o of r)if(!Object.is(e[o],t[o]))return false;return true}var Zt=He__default.memo(function({component:t,containerRef:r,wrapperStyle:o,hostProps:n}){return jsx("div",{ref:r,style:o,children:jsx(t,{...n})})},(e,t)=>e.component===t.component&&Xt(e.hostProps,t.hostProps)),Ne=class extends He__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 it({slotId:e,children:t,githubRepo:r,shared:o,events:n}){Oe(t,e);let i=ke(e),{baseUrl:s,apiKey:a,appId:b,shouldSkipAnimation:d}=I(),[m,S]=useState(null),P=useRef(null),w=useRef(null),h=useRef(null),l=useRef(false),$=useRef(null),T=useRef(null),R=!!(o||n),C=useRef(null);R&&!C.current&&(C.current=new fe(e));let F=useRef(n);if(F.current=n,useEffect(()=>{if(R)return ()=>{C.current?.destroy(),C.current=null;}},[R,e]),R&&C.current&&o)for(let[x,k]of Object.entries(o))C.current.set(x,k);useEffect(()=>{if(!R)return;C.current||(C.current=new fe(e));let x=C.current,k=Object.keys(F.current||{}).map(f=>x.on(f,(...g)=>F.current?.[f]?.(...g)));return ()=>k.forEach(f=>f())},[R,e]),useEffect(()=>{if(rt.has(e))return;rt.add(e);let x={id:e,appId:b,label:e,eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:r,mode:"direct",sharedKeys:o?Object.keys(o):[],eventNames:n?Object.keys(n):[],propsShape:"",callbackNames:[]};fetch(`${s}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify(x)}).catch(()=>{});},[e,s,a,r,b]);let y=i?.id||null;useEffect(()=>{if(i?.bundleUrl,P.current,w.current,!i?.bundleUrl||!y){return}let x=`${s}${i.bundleUrl.replace("bundle.js","component.js")}`,k=`__fork_animated_${e}`,f=sessionStorage.getItem(k),g=d(e),p=!g&&f!==y;if(g&&y&&sessionStorage.setItem(k,y),p&&w.current){let G=ot(w.current);h.current=G,l.current=true,`${e}${G.length}`;}window.__FORK_REACT__=He__default,window.__FORK_REACT_DOM__=Ht,window.__FORK_REACT_JSX__=Ot;let B=Date.now(),U=`${s}${i.bundleUrl.replace("bundle.js","component.css")}?t=${B}`,K=document.createElement("link");K.rel="stylesheet",K.href=U,K.dataset.forkSlot=e,document.head.appendChild(K);let V=document.createElement("script");return V.src=x+"?t="+B,V.onload=()=>{let G=window.__FORK_EXPORT__;if(G?.default){if(w.current&&h.current&&l.current){let Y=w.current.getBoundingClientRect(),O=w.current.cloneNode(true);O.style.position="fixed",O.style.top=`${Y.top}px`,O.style.left=`${Y.left}px`,O.style.width=`${Y.width}px`,O.style.height=`${Y.height}px`,O.style.flex="none",O.style.minHeight="auto",O.style.zIndex="9998",O.style.pointerEvents="none",O.style.overflow="hidden";let q=getComputedStyle(w.current).backgroundColor;O.style.backgroundColor=q&&q!=="rgba(0, 0, 0, 0)"&&q!=="transparent"?q:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(O);let W=w.current.querySelectorAll("*"),ee=O.querySelectorAll("*");for(let v=0;v<W.length;v++)W[v].scrollTop!==0&&(ee[v].scrollTop=W[v].scrollTop),W[v].scrollLeft!==0&&(ee[v].scrollLeft=W[v].scrollLeft);$.current=O;}S(()=>G.default),P.current=y;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},V.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(V),()=>{V.remove(),K.remove(),T.current&&(clearTimeout(T.current),T.current=null),$.current&&($.current.remove(),$.current=null);}},[y,s,e]),useEffect(()=>{if(!l.current||!m||!w.current){`${e}${l.current}`,w.current;return}let x=h.current;if(!x){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!w.current)return;let k=ot(w.current),f=qt(x,k),g=Jt(x,k),p=$.current;if(`${e}${f.length}${g.length}`,g.length>0&&p){let B=Yt(g);T.current=setTimeout(()=>{T.current=null;let U=400;p.animate([{opacity:1},{opacity:0}],{duration:U,fill:"forwards"}),B.animate([{opacity:1},{opacity:0}],{duration:U,fill:"forwards"}),setTimeout(()=>{p.remove(),B.remove(),$.current=null,f.length>0&&(nt(f));},U);},3500);}else p&&(p.remove(),$.current=null),f.length>0&&(nt(f));h.current=null,l.current=false,y&&(sessionStorage.setItem(`__fork_animated_${e}`,y),`${e}`);});});},[m]);let E={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!i||i.status!=="complete"||!i.bundleUrl)return jsx("div",{ref:w,style:E,children:t});if(!m)return jsx("div",{ref:w,style:E,children:t});let u=t?.props??{};return jsx(Ne,{slotId:e,resetKey:y,fallback:jsx("div",{ref:w,style:E,children:t}),children:jsx(Zt,{component:m,containerRef:w,wrapperStyle:E,hostProps:u})})}var lt=new Set;function tr(e){return `{ ${Object.entries(e).map(([r,o])=>o==null?`${r}: unknown`:Array.isArray(o)?`${r}: ${o.length>0?typeof o[0]:"unknown"}[]`:`${r}: ${typeof o}`).join("; ")} }`}function ct(e,t=new Set){return Children.forEach(e,r=>{if(!isValidElement(r))return;let o=r.props;for(let[n,i]of Object.entries(o))typeof i=="function"&&/^on[A-Z]/.test(n)&&t.add(n);o.children&&ct(o.children,t);}),t}function rr({slotId:e,props:t,children:r,allowedFetches:o,githubRepo:n,callbacks:i,mode:s="iframe",shared:a,events:b}){if(Oe(r,e),s==="direct")return jsx(it,{slotId:e,githubRepo:n,shared:a,events:b,children:r});let d=ke(e),{baseUrl:m,apiKey:S,appId:P}=I(),w=useRef(null),h=useRef(false),l=useRef(null),$=useRef(i);$.current=i;let T=useRef(t);T.current=t;let R=useRef(o);R.current=o,useEffect(()=>{if(typeof process<"u")return;let E=ct(r),c=new Set(i?Object.keys(i):[]),u=[...E].filter(x=>!c.has(x));u.length>0&&console.error(`[ForkSlot:${e}] Missing bridged callbacks! The following callback props are used by children but not passed to ForkSlot's \`callbacks\` prop:
1
+ import*as He from'react';import He__default,{createContext,useState,useRef,useEffect,useCallback,startTransition,Children,useContext,isValidElement}from'react';import*as Ht from'react-dom';import {createPortal}from'react-dom';import*as Ot from'react/jsx-runtime';import {jsx,Fragment,jsxs}from'react/jsx-runtime';import*as Ut from'react/jsx-dev-runtime';import {X,User,Check,Undo2,ChevronDown,RotateCcw,ArrowUp,Loader2,AlertCircle,Sparkles,Package,Wrench,MessageSquare,Code,Terminal,FileSearch,Pencil}from'lucide-react';var oe="__FORK_SHARED__";function Le(){var t,r,o,n;let e=globalThis;return e[oe]||(e[oe]={}),(t=e[oe]).react||(t.react=He),(r=e[oe])["react-dom"]||(r["react-dom"]=Ht),(o=e[oe])["react/jsx-runtime"]||(o["react/jsx-runtime"]=Ot),(n=e[oe])["react/jsx-dev-runtime"]||(n["react/jsx-dev-runtime"]=Ut),e[oe]}function Be(e){return Object.assign(Le(),e)}var tt=createContext(null);function et(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function jt(e,t){let r={};for(let[o,n]of Object.entries(t.boundaries||{}))r[o]={...n,moduleUrl:et(e,n.moduleUrl),cssUrls:Array.isArray(n.cssUrls)?n.cssUrls.map(i=>et(e,i)):[]};return r}function zt(e){let{apiKey:t,baseUrl:r,children:o,appId:n,shared:i}=e,s="userId"in e?e.userId:void 0,a="authUrl"in e?e.authUrl:void 0,[b,d]=useState({}),[m,S]=useState(s?{userId:s,userHash:void 0}:null),[_,w]=useState(!!s),[h,l]=useState({}),[$,T]=useState(!n),[R,C]=useState(0),F=useRef(new Map),y=useRef(new Map),[E,c]=useState(0),u=useRef(new Set),x=useRef(new Map),k=useRef(void 0);Le(),i&&k.current!==i&&(Be(i),k.current=i),useEffect(()=>{a&&(w(false),fetch(a,{credentials:"include"}).then(v=>{if(!v.ok)throw new Error(`Auth endpoint returned ${v.status}`);return v.json()}).then(v=>{if(!v.userId||typeof v.userId!="string")throw new Error("authUrl response must include userId");S({userId:v.userId,userHash:v.userHash});}).catch(v=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",v.message);}).finally(()=>{w(true);}));},[a]),useEffect(()=>{!a&&s&&(S({userId:s,userHash:void 0}),w(true));},[s,a]);let f=m?.userId??"",g=m?.userHash,p=!!n,B=useCallback(async()=>{if(!p){l({}),T(true),C(P=>P+1);return}if(!_){T(false);return}if(!f||!n){l({}),T(true),C(P=>P+1);return}let v=new URLSearchParams({appId:n,userId:f});g&&v.set("userHash",g),T(false);try{let P=await fetch(`${r}/api/v1/boundaries/manifest?${v.toString()}`,{headers:{Authorization:`Bearer ${t}`}});if(!P.ok)throw new Error(`${P.status}`);let N=await P.json();l(jt(r,N));}catch(P){console.error("[ForkProvider] Failed to fetch module override manifest:",P.message),l({});}finally{C(P=>P+1),T(true);}},[t,n,r,_,p,g,f]);useEffect(()=>{if(!f)return;let v=new URLSearchParams({userId:f});g&&v.set("userHash",g),fetch(`${r}/api/v1/forks/active?${v.toString()}`,{headers:{Authorization:`Bearer ${t}`}}).then(P=>{if(!P.ok)throw new Error(`${P.status}`);return P.json()}).then(P=>{P&&typeof P=="object"&&d(P);}).catch(()=>{});},[t,f,g,r]),useEffect(()=>{B();},[B]);let U=useCallback((v,P)=>{d(N=>({...N,[v]:P}));},[]),K=useCallback(v=>{d(P=>{let N={...P};return delete N[v],N});},[]),V=useCallback(v=>{u.current.add(v);},[]),G=useCallback(v=>u.current.has(v)?(u.current.delete(v),true):false,[]),Y=useCallback((v,P)=>{x.current.set(v,P);},[]),O=useCallback((v,P)=>x.current.get(v)!==P?false:(x.current.delete(v),true),[]),q=useCallback(v=>{if(!n)return;let P=JSON.stringify(v);F.current.get(v.id)===P||y.current.get(v.id)?.signature===P||(y.current.set(v.id,{boundary:v,signature:P}),c(z=>z+1));},[n]);useEffect(()=>{if(!n||y.current.size===0)return;let v=setTimeout(()=>{let P=Array.from(y.current.values());P.length!==0&&fetch(`${r}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:n,boundaries:P.map(N=>N.boundary)})}).then(N=>{if(!N.ok)throw new Error(`${N.status}`)}).then(()=>{for(let N of P)y.current.get(N.boundary.id)?.signature===N.signature&&(y.current.delete(N.boundary.id),F.current.set(N.boundary.id,N.signature));}).catch(N=>{console.error("[ForkProvider] Failed to register module boundaries:",N.message);});},50);return ()=>{clearTimeout(v);}},[t,n,r,E]);let W=useCallback(v=>h[v],[h]),te=useCallback(async()=>{if(!g)throw new Error("Reset requires verified user identity (provide authUrl / userHash).");let v=new URLSearchParams({userId:f,userHash:g}),P=await fetch(`${r}/api/v1/forks/all?${v.toString()}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}});if(!P.ok){let z=await P.json().catch(()=>({}));throw new Error(z.error||`API error: ${P.status}`)}let N=await P.json().catch(()=>({}));d({}),l({}),T(true),C(z=>z+1),u.current.clear(),x.current.clear();try{for(let z=sessionStorage.length-1;z>=0;z-=1){let Z=sessionStorage.key(z);Z&&Z.startsWith("__fork_animated_")&&sessionStorage.removeItem(Z);}}catch{}return N},[t,r,g,f]);return jsx(tt.Provider,{value:{apiKey:t,userId:f,userHash:g,baseUrl:r,appId:n,forks:b,moduleOverridesEnabled:p,moduleManifestReady:$,moduleManifestVersion:R,setSlotFork:U,clearSlotFork:K,skipAnimationForSlot:V,shouldSkipAnimation:G,queueBoundaryAnimation:Y,consumeBoundaryAnimation:O,registerBoundary:q,getBoundaryOverride:W,refreshModuleManifest:B,resetAllForks:te},children:o})}function j(){let e=useContext(tt);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function be(e){return j().forks[e]}var ue=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 o=this.values.get(t);if(Object.is(o,r))return;if(o!==void 0&&r!==null&&o!==null&&typeof o=="object"&&typeof r=="object")try{if(JSON.stringify(o)===JSON.stringify(r))return}catch{}this.values.set(t,r),this.snapshots.set(t,r);let n=this.listeners.get(t);n&&n.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(o=>this.subscribe(t,o),()=>this.getSnapshot(t)):(console.warn("[ForkBridge] React.useSyncExternalStore not available, returning static value"),this.values.get(t))}emit(t,...r){let o=this.eventHandlers.get(t);o&&o.forEach(n=>n(...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 Oe(e,t){let r;try{r=Children.only(e);}catch{let n=Children.count(e);throw new Error(`<ForkSlot slotId="${t}"> must wrap exactly one React component, got ${n} children. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`)}let o=r.type;if(typeof o=="string")throw new Error(`<ForkSlot slotId="${t}"> child must be a React component (function or class), not an HTML element <${o}>. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`);if(typeof o=="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 ot=new Set;function nt(e){let t=[],r=e.querySelectorAll("*");for(let o of r){if(!(o instanceof HTMLElement))continue;let n=o.getBoundingClientRect();if(n.width<10||n.height<10||["SCRIPT","STYLE","META","LINK"].includes(o.tagName))continue;let i=getComputedStyle(o),s=parseFloat(i.borderTopLeftRadius)||0;t.push({tag:o.tagName,className:o.className||"",text:(o.textContent||"").slice(0,50).trim(),rect:n,borderRadius:s});}return t}function qt(e,t){let r=[];for(let o of t)if(!e.find(i=>i.tag===o.tag&&i.className===o.className&&Math.abs(i.rect.top-o.rect.top)<20&&Math.abs(i.rect.left-o.rect.left)<20)&&!r.some(s=>o.rect.top>=s.rect.top&&o.rect.left>=s.rect.left&&o.rect.right<=s.rect.right&&o.rect.bottom<=s.rect.bottom)){for(let s=r.length-1;s>=0;s--){let a=r[s];a.rect.top>=o.rect.top&&a.rect.left>=o.rect.left&&a.rect.right<=o.rect.right&&a.rect.bottom<=o.rect.bottom&&r.splice(s,1);}r.push({rect:o.rect,borderRadius:o.borderRadius});}return r}function Jt(e,t){let r=[];for(let o of e)if(!t.find(i=>i.tag===o.tag&&i.className===o.className&&Math.abs(i.rect.top-o.rect.top)<20&&Math.abs(i.rect.left-o.rect.left)<20)&&!r.some(s=>o.rect.top>=s.rect.top&&o.rect.left>=s.rect.left&&o.rect.right<=s.rect.right&&o.rect.bottom<=s.rect.bottom)){for(let s=r.length-1;s>=0;s--){let a=r[s];a.rect.top>=o.rect.top&&a.rect.left>=o.rect.left&&a.rect.right<=o.rect.right&&a.rect.bottom<=o.rect.bottom&&r.splice(s,1);}r.push({rect:o.rect,borderRadius:o.borderRadius});}return r}function it(e,t,r,o,n){return n=Math.max(0,Math.min(n,r/2,o/2)),n===0?`M ${e} ${t} L ${e+r} ${t} L ${e+r} ${t+o} L ${e} ${t+o} Z`:[`M ${e+n} ${t}`,`L ${e+r-n} ${t}`,`A ${n} ${n} 0 0 1 ${e+r} ${t+n}`,`L ${e+r} ${t+o-n}`,`A ${n} ${n} 0 0 1 ${e+r-n} ${t+o}`,`L ${e+n} ${t+o}`,`A ${n} ${n} 0 0 1 ${e} ${t+o-n}`,`L ${e} ${t+n}`,`A ${n} ${n} 0 0 1 ${e+n} ${t}`,"Z"].join(" ")}function st(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 o=document.createElementNS(t,"svg");o.setAttribute("width","100%"),o.setAttribute("height","100%"),o.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let n=document.createElementNS(t,"defs");o.appendChild(n);let i=[];for(let m=0;m<e.length;m++){let{rect:S,borderRadius:_}=e[m],w=S.left-.5,h=S.top-.5,l=S.width+1,$=S.height+1,T=Math.min(_+.5,l/2,$/2),R=it(w,h,l,$,T),C=`__fork-glow-${m}`,F=document.createElementNS(t,"filter");F.setAttribute("id",C),F.setAttribute("x","-100%"),F.setAttribute("y","-100%"),F.setAttribute("width","300%"),F.setAttribute("height","300%");let y=document.createElementNS(t,"feGaussianBlur");y.setAttribute("in","SourceGraphic"),y.setAttribute("stdDeviation","8"),F.appendChild(y),n.appendChild(F);let E=`__fork-mask-${m}`,c=document.createElementNS(t,"mask");c.setAttribute("id",E),c.setAttribute("maskUnits","userSpaceOnUse"),c.setAttribute("x",String(w-200)),c.setAttribute("y",String(h-200)),c.setAttribute("width",String(l+400)),c.setAttribute("height",String($+400));let u=document.createElementNS(t,"rect");u.setAttribute("x",String(w-200)),u.setAttribute("y",String(h-200)),u.setAttribute("width",String(l+400)),u.setAttribute("height",String($+400)),u.setAttribute("fill","white"),c.appendChild(u);let x=document.createElementNS(t,"path");x.setAttribute("d",R),x.setAttribute("fill","black"),c.appendChild(x),n.appendChild(c);let k=document.createElementNS(t,"g");k.setAttribute("mask",`url(#${E})`),k.setAttribute("opacity","0");let f=document.createElementNS(t,"g");f.setAttribute("filter",`url(#${C})`);let g=document.createElementNS(t,"path");g.setAttribute("d",R),g.setAttribute("fill","none"),g.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),g.setAttribute("stroke-width","6"),g.setAttribute("stroke-linecap","round"),f.appendChild(g),k.appendChild(f),o.appendChild(k);let p=document.createElementNS(t,"path");p.setAttribute("d",R),p.setAttribute("fill","none"),p.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),p.setAttribute("stroke-width","2"),p.setAttribute("stroke-linecap","round"),p.setAttribute("opacity","0"),o.appendChild(p),i.push(g,p),g.__group=k;}r.appendChild(o),document.body.appendChild(r);let s=[];for(let m=0;m<i.length;m+=2){let S=i[m],_=i[m+1],w=S.__group,h=_.getTotalLength(),l=S.getTotalLength();if(h<=0)continue;let $=h*.35;_.setAttribute("stroke-dasharray",`${$} ${h-$}`),_.setAttribute("stroke-dashoffset","0"),s.push(_.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*h,opacity:.92,offset:.06},{strokeDashoffset:-2*h,opacity:.92,offset:.92},{strokeDashoffset:-2.25*h,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let T=l*.35;S.setAttribute("stroke-dasharray",`${T} ${l-T}`),S.setAttribute("stroke-dashoffset","0"),s.push(S.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*l,offset:.06},{strokeDashoffset:-2*l,offset:.92},{strokeDashoffset:-2.25*l,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(w.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,b=()=>{if(a)return;a=true,clearTimeout(d);for(let S of s)try{S.cancel();}catch{}let m=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});m.onfinish=()=>r.remove(),window.removeEventListener("click",b);},d=setTimeout(b,14500);return setTimeout(()=>{a||window.addEventListener("click",b);},500),b}function Yt(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 o=document.createElementNS(t,"svg");o.setAttribute("width","100%"),o.setAttribute("height","100%"),o.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let n=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),n.appendChild(i),o.appendChild(n);for(let{rect:a,borderRadius:b}of e){let d=a.left,m=a.top,S=a.width,_=a.height,w=Math.min(b,S/2,_/2),h=it(d,m,S,_,w),l=document.createElementNS(t,"path");l.setAttribute("d",h),l.setAttribute("fill","none"),l.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),l.setAttribute("stroke-width","1.5"),l.setAttribute("stroke-dasharray","8 4"),l.setAttribute("stroke-linecap","round"),l.setAttribute("filter","url(#__fork-removed-shadow)"),l.setAttribute("opacity","0"),o.appendChild(l),l.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(o),document.body.appendChild(r),r}function Xt(e,t){if(e===t)return true;let r=Object.keys(e);if(r.length!==Object.keys(t).length)return false;for(let o of r)if(!Object.is(e[o],t[o]))return false;return true}var Zt=He__default.memo(function({component:t,containerRef:r,wrapperStyle:o,hostProps:n}){return jsx("div",{ref:r,style:o,children:jsx(t,{...n})})},(e,t)=>e.component===t.component&&Xt(e.hostProps,t.hostProps)),Ne=class extends He__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 at({slotId:e,children:t,githubRepo:r,shared:o,events:n}){Oe(t,e);let i=be(e),{baseUrl:s,apiKey:a,appId:b,shouldSkipAnimation:d}=j(),[m,S]=useState(null),_=useRef(null),w=useRef(null),h=useRef(null),l=useRef(false),$=useRef(null),T=useRef(null),R=!!(o||n),C=useRef(null);R&&!C.current&&(C.current=new ue(e));let F=useRef(n);if(F.current=n,useEffect(()=>{if(R)return ()=>{C.current?.destroy(),C.current=null;}},[R,e]),R&&C.current&&o)for(let[x,k]of Object.entries(o))C.current.set(x,k);useEffect(()=>{if(!R)return;C.current||(C.current=new ue(e));let x=C.current,k=Object.keys(F.current||{}).map(f=>x.on(f,(...g)=>F.current?.[f]?.(...g)));return ()=>k.forEach(f=>f())},[R,e]),useEffect(()=>{if(ot.has(e))return;ot.add(e);let x={id:e,appId:b,label:e,eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:r,mode:"direct",sharedKeys:o?Object.keys(o):[],eventNames:n?Object.keys(n):[],propsShape:"",callbackNames:[]};fetch(`${s}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify(x)}).catch(()=>{});},[e,s,a,r,b]);let y=i?.id||null;useEffect(()=>{if(i?.bundleUrl,_.current,w.current,!i?.bundleUrl||!y){return}let x=`${s}${i.bundleUrl.replace("bundle.js","component.js")}`,k=`__fork_animated_${e}`,f=sessionStorage.getItem(k),g=d(e),p=!g&&f!==y;if(g&&y&&sessionStorage.setItem(k,y),p&&w.current){let G=nt(w.current);h.current=G,l.current=true,`${e}${G.length}`;}window.__FORK_REACT__=He__default,window.__FORK_REACT_DOM__=Ht,window.__FORK_REACT_JSX__=Ot;let B=Date.now(),U=`${s}${i.bundleUrl.replace("bundle.js","component.css")}?t=${B}`,K=document.createElement("link");K.rel="stylesheet",K.href=U,K.dataset.forkSlot=e,document.head.appendChild(K);let V=document.createElement("script");return V.src=x+"?t="+B,V.onload=()=>{let G=window.__FORK_EXPORT__;if(G?.default){if(w.current&&h.current&&l.current){let Y=w.current.getBoundingClientRect(),O=w.current.cloneNode(true);O.style.position="fixed",O.style.top=`${Y.top}px`,O.style.left=`${Y.left}px`,O.style.width=`${Y.width}px`,O.style.height=`${Y.height}px`,O.style.flex="none",O.style.minHeight="auto",O.style.zIndex="9998",O.style.pointerEvents="none",O.style.overflow="hidden";let q=getComputedStyle(w.current).backgroundColor;O.style.backgroundColor=q&&q!=="rgba(0, 0, 0, 0)"&&q!=="transparent"?q:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(O);let W=w.current.querySelectorAll("*"),te=O.querySelectorAll("*");for(let v=0;v<W.length;v++)W[v].scrollTop!==0&&(te[v].scrollTop=W[v].scrollTop),W[v].scrollLeft!==0&&(te[v].scrollLeft=W[v].scrollLeft);$.current=O;}S(()=>G.default),_.current=y;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},V.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(V),()=>{V.remove(),K.remove(),T.current&&(clearTimeout(T.current),T.current=null),$.current&&($.current.remove(),$.current=null);}},[y,s,e]),useEffect(()=>{if(!l.current||!m||!w.current){`${e}${l.current}`,w.current;return}let x=h.current;if(!x){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!w.current)return;let k=nt(w.current),f=qt(x,k),g=Jt(x,k),p=$.current;if(`${e}${f.length}${g.length}`,g.length>0&&p){let B=Yt(g);T.current=setTimeout(()=>{T.current=null;let U=400;p.animate([{opacity:1},{opacity:0}],{duration:U,fill:"forwards"}),B.animate([{opacity:1},{opacity:0}],{duration:U,fill:"forwards"}),setTimeout(()=>{p.remove(),B.remove(),$.current=null,f.length>0&&(st(f));},U);},3500);}else p&&(p.remove(),$.current=null),f.length>0&&(st(f));h.current=null,l.current=false,y&&(sessionStorage.setItem(`__fork_animated_${e}`,y),`${e}`);});});},[m]);let E={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!i||i.status!=="complete"||!i.bundleUrl)return jsx("div",{ref:w,style:E,children:t});if(!m)return jsx("div",{ref:w,style:E,children:t});let u=t?.props??{};return jsx(Ne,{slotId:e,resetKey:y,fallback:jsx("div",{ref:w,style:E,children:t}),children:jsx(Zt,{component:m,containerRef:w,wrapperStyle:E,hostProps:u})})}var ct=new Set;function tr(e){return `{ ${Object.entries(e).map(([r,o])=>o==null?`${r}: unknown`:Array.isArray(o)?`${r}: ${o.length>0?typeof o[0]:"unknown"}[]`:`${r}: ${typeof o}`).join("; ")} }`}function ut(e,t=new Set){return Children.forEach(e,r=>{if(!isValidElement(r))return;let o=r.props;for(let[n,i]of Object.entries(o))typeof i=="function"&&/^on[A-Z]/.test(n)&&t.add(n);o.children&&ut(o.children,t);}),t}function rr({slotId:e,props:t,children:r,allowedFetches:o,githubRepo:n,callbacks:i,mode:s="iframe",shared:a,events:b}){if(Oe(r,e),s==="direct")return jsx(at,{slotId:e,githubRepo:n,shared:a,events:b,children:r});let d=be(e),{baseUrl:m,apiKey:S,appId:_}=j(),w=useRef(null),h=useRef(false),l=useRef(null),$=useRef(i);$.current=i;let T=useRef(t);T.current=t;let R=useRef(o);R.current=o,useEffect(()=>{if(typeof process<"u")return;let E=ut(r),c=new Set(i?Object.keys(i):[]),u=[...E].filter(x=>!c.has(x));u.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
2
  `+u.map(x=>` - ${x}`).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(()=>{lt.has(e)||(lt.add(e),fetch(`${m}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${S}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:P,label:e,propsShape:t?tr(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:n,callbackNames:i?Object.keys(i):[],mode:s||"iframe"})}).catch(()=>{}));},[e,m,S,n,P]);let C=useCallback(E=>{let c=w.current;if(c?.contentWindow&&h.current){let u=$.current?Object.keys($.current):[];c.contentWindow.postMessage({type:"slot:props",props:E,callbackNames:u},"*"),l.current=null;}else l.current=E;},[]),F=useCallback((E,c)=>{let u=R.current;return !u||u.length===0?false:u.some(x=>{let[k,f]=x.split(" "),g=c.split("?")[0];return E.toUpperCase()===k.toUpperCase()&&g.startsWith(f)})},[]);if(useEffect(()=>{if(!d?.bundleUrl)return;let E=async c=>{if(c.source===w.current?.contentWindow){if(c.data?.type==="slot:ready")h.current=true,w.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:R.current||[]},"*"),R.current,l.current?C(l.current):C(T.current||{});else if(c.data?.type==="slot:event"){let u=c.data.event;u?.navigate&&(window.location.hash=u.navigate);}else if(c.data?.type==="slot:clipboard-write")navigator.clipboard.writeText(c.data.text).catch(u=>{console.warn(`[ForkSlot:${e}] clipboard write failed:`,u.message);});else if(c.data?.type==="slot:callback"){let{name:u,args:x}=c.data,k=$.current?.[u];k?(k(...x||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${u}`);}else if(c.data?.type==="slot:fetch"){let{id:u,method:x,url:k,body:f}=c.data,g=w.current?.contentWindow;if(!g)return;let p=x||"GET";if(!F(p,k)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${u}: ${p} ${k} \u2014 not in allowedFetches`),g.postMessage({type:"slot:fetch-response",id:u,error:`Fetch not allowed: ${p} ${k}`},"*");return}try{let B={method:p};f&&p!=="GET"&&(B.headers={"Content-Type":"application/json"},B.body=JSON.stringify(f));let U=await fetch(k,B),K=await U.json();`${e}${u}${U.status}`,g.postMessage({type:"slot:fetch-response",id:u,data:K,status:U.status},"*");}catch(B){console.error(`[ForkSlot:${e}] fetch #${u} failed:`,B.message),g.postMessage({type:"slot:fetch-response",id:u,error:B.message},"*");}}}};return window.addEventListener("message",E),()=>{window.removeEventListener("message",E),h.current=false;}},[d?.bundleUrl,e,C,F]),useEffect(()=>{d?.bundleUrl&&h.current&&C(t||{});},[t,d?.bundleUrl,C]),!d||d.status!=="complete"||!d.bundleUrl)return `${e}${d?.status||"none"}${d?.bundleUrl||"none"}`,jsx(Fragment,{children:r});`${e}${d.bundleUrl}`;let y=`${m}${d.bundleUrl.replace("/bundle.js","/host")}`;return jsx("iframe",{ref:w,src:y,sandbox:"allow-scripts allow-same-origin allow-forms allow-clipboard-write",title:`Forked ${e}`,style:{width:"100%",border:"none",flex:1,minHeight:0}})}function ve({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 De({onClick:e}){let[t,r]=useState(false),[o,n]=useState(false),i=t?48:40;return jsx("button",{onClick:e,onMouseEnter:()=>r(true),onMouseLeave:()=>{r(false),n(false);},onMouseDown:()=>n(true),onMouseUp:()=>n(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:o?"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(ve,{style:{width:24,height:24}})})}var fr={status:Loader2,agent_message:MessageSquare,tool_use:Wrench,build_start:Package,build_complete:Check,build_error:AlertCircle,complete:Sparkles,error:AlertCircle},pr={status:"#60a5fa",agent_message:"#a0a0a0",tool_use:"#fbbf24",build_start:"#c084fc",build_complete:"#6b7280",build_error:"#f87171",complete:"#6b7280",error:"#f87171"},mr={read:FileSearch,write:Pencil,search:FileSearch,shell:Terminal,build:Package},gr={read:"#60a5fa",write:"#fbbf24",search:"#60a5fa",shell:"#a78bfa",build:"#c084fc"};function je(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 yt({events:e}){let t=useRef(null);return useEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight);},[e]),jsxs(Fragment,{children:[jsx("style",{children:`
3
+ `)+"\n\nThe forked component will not be able to call these. Add them to the `callbacks` prop of <ForkSlot>.");},[e,r,i]),useEffect(()=>{ct.has(e)||(ct.add(e),fetch(`${m}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${S}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:_,label:e,propsShape:t?tr(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:n,callbackNames:i?Object.keys(i):[],mode:s||"iframe"})}).catch(()=>{}));},[e,m,S,n,_]);let C=useCallback(E=>{let c=w.current;if(c?.contentWindow&&h.current){let u=$.current?Object.keys($.current):[];c.contentWindow.postMessage({type:"slot:props",props:E,callbackNames:u},"*"),l.current=null;}else l.current=E;},[]),F=useCallback((E,c)=>{let u=R.current;return !u||u.length===0?false:u.some(x=>{let[k,f]=x.split(" "),g=c.split("?")[0];return E.toUpperCase()===k.toUpperCase()&&g.startsWith(f)})},[]);if(useEffect(()=>{if(!d?.bundleUrl)return;let E=async c=>{if(c.source===w.current?.contentWindow){if(c.data?.type==="slot:ready")h.current=true,w.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:R.current||[]},"*"),R.current,l.current?C(l.current):C(T.current||{});else if(c.data?.type==="slot:event"){let u=c.data.event;u?.navigate&&(window.location.hash=u.navigate);}else if(c.data?.type==="slot:clipboard-write")navigator.clipboard.writeText(c.data.text).catch(u=>{console.warn(`[ForkSlot:${e}] clipboard write failed:`,u.message);});else if(c.data?.type==="slot:callback"){let{name:u,args:x}=c.data,k=$.current?.[u];k?(k(...x||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${u}`);}else if(c.data?.type==="slot:fetch"){let{id:u,method:x,url:k,body:f}=c.data,g=w.current?.contentWindow;if(!g)return;let p=x||"GET";if(!F(p,k)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${u}: ${p} ${k} \u2014 not in allowedFetches`),g.postMessage({type:"slot:fetch-response",id:u,error:`Fetch not allowed: ${p} ${k}`},"*");return}try{let B={method:p};f&&p!=="GET"&&(B.headers={"Content-Type":"application/json"},B.body=JSON.stringify(f));let U=await fetch(k,B),K=await U.json();`${e}${u}${U.status}`,g.postMessage({type:"slot:fetch-response",id:u,data:K,status:U.status},"*");}catch(B){console.error(`[ForkSlot:${e}] fetch #${u} failed:`,B.message),g.postMessage({type:"slot:fetch-response",id:u,error:B.message},"*");}}}};return window.addEventListener("message",E),()=>{window.removeEventListener("message",E),h.current=false;}},[d?.bundleUrl,e,C,F]),useEffect(()=>{d?.bundleUrl&&h.current&&C(t||{});},[t,d?.bundleUrl,C]),!d||d.status!=="complete"||!d.bundleUrl)return `${e}${d?.status||"none"}${d?.bundleUrl||"none"}`,jsx(Fragment,{children:r});`${e}${d.bundleUrl}`;let y=`${m}${d.bundleUrl.replace("/bundle.js","/host")}`;return jsx("iframe",{ref:w,src:y,sandbox:"allow-scripts allow-same-origin allow-forms allow-clipboard-write",title:`Forked ${e}`,style:{width:"100%",border:"none",flex:1,minHeight:0}})}function we({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 De({onClick:e}){let[t,r]=useState(false),[o,n]=useState(false),i=t?48:40;return jsx("button",{onClick:e,onMouseEnter:()=>r(true),onMouseLeave:()=>{r(false),n(false);},onMouseDown:()=>n(true),onMouseUp:()=>n(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:o?"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(we,{style:{width:24,height:24}})})}var fr={status:Loader2,agent_message:MessageSquare,tool_use:Wrench,build_start:Package,build_complete:Check,build_error:AlertCircle,complete:Sparkles,error:AlertCircle},pr={status:"#60a5fa",agent_message:"#a0a0a0",tool_use:"#fbbf24",build_start:"#c084fc",build_complete:"#6b7280",build_error:"#f87171",complete:"#6b7280",error:"#f87171"},mr={read:FileSearch,write:Pencil,search:FileSearch,shell:Terminal,build:Package},gr={read:"#60a5fa",write:"#fbbf24",search:"#60a5fa",shell:"#a78bfa",build:"#c084fc"};function je(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 bt({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 He from'react';import He__default,{createContext,useState,useRef,useEf
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,o)=>{let n=o===e.length-1,i=r.type==="complete"||r.type==="error"||r.type==="build_complete"||r.type==="build_error",s=n&&!i&&(r.type==="status"||r.type==="tool_use"||r.type==="build_start"),a=fr[r.type]||Code,b=pr[r.type]||"#9ca3af";if(r.type==="tool_use"){let d=String(r.data.category||"");a=mr[d]||Wrench,b=gr[d]||"#fbbf24";}return s?a=Loader2:!n&&r.type==="status"&&(a=Check,b="#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:b,...s?{animation:"__fork-spin 1s linear infinite"}:{}}}),jsx("span",{style:{color:n&&!i?"#d1d5db":"#6b7280",wordBreak:"break-all"},children:je(r)})]},o)})]})]})}var xr=["Dark mode redesign","New workflow for adding to this page","Data-dense analytics view"],kt=35,Rr="Working on Feature",Er="Built Custom Feature",wt=360,ae=350;function $r(e){return e.length<=kt?e:e.slice(0,kt-3).trimEnd()+"..."}function Ar({events:e}){let[t,r]=useState("Setting up environment..."),[o,n]=useState(true),i=useRef(t),s=useRef(false);return useEffect(()=>{if(!s.current){for(let b of e)if(b.type==="status"&&String(b.data.message||"").includes("Agent started")){s.current=true;break}}let a="Setting up environment...";if(s.current)for(let b=e.length-1;b>=0;b--){let d=e[b];if(d.type==="tool_use"||d.type==="build_start"||d.type==="build_complete"){a=$r(je(d));break}}if(a!==i.current){n(false);let b=setTimeout(()=>{r(a),i.current=a,n(true);},200);return ()=>clearTimeout(b)}},[e]),jsx("span",{style:{fontSize:11,color:"#d1d5db",fontWeight:500,opacity:o?1:0,transition:"opacity 0.2s ease",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},children:t})}function Cr(e){useLayoutEffect(()=>{if(!e||typeof document>"u")return;let t=document.body,r=t.style.marginRight,o=t.style.transition,n=getComputedStyle(t).marginRight,i=n&&n!=="0px"?n:"0px";return t.style.transition=`margin-right ${ae}ms cubic-bezier(0.22, 1, 0.36, 1)`,t.style.marginRight=`calc(${i} + ${wt}px)`,()=>{t.style.marginRight=r,window.setTimeout(()=>{t.style.transition=o;},ae+50);}},[e]);}function xe({state:e,fork:t,events:r,error:o,slotId:n,targetId:i,targetLabel:s,historyMode:a="slot",examplePrompts:b=xr,onSubmit:d,onUndo:m,onClose:S,baseUrl:P,apiKey:w,userId:h,userHash:l,appId:$,embedded:T=false}){let[R,C]=useState(""),[F,y]=useState([]),[E,c]=useState(false),[u,x]=useState(false),[k,f]=useState(false),[g,p]=useState(false),[B,U]=useState(false),[K,V]=useState(false),[G,Y]=useState(null),[O,q]=useState(false),[W,ee]=useState(false),[v,_]=useState(null),[N,z]=useState(false),Z=useRef(null),ye=useRef(null),{resetAllForks:Pt}=I(),X$1=i??n??"",_e=(s||X$1).replace(/[-_]+/g," ").replace(/\b\w/g,A=>A.toUpperCase()),Pe=useRef(""),ce=T?true:u&&!k;Cr(!T&&ce);let Mt=r.find(A=>{let L=A.data;return A.type==="status"&&L.summary})?.data?.summary||t?.summary||Rr,te=r.find(A=>{let L=A.data;return (A.type==="status"||A.type==="complete")&&typeof L?.estimateMinutes=="number"})?.data?.estimateMinutes??t?.estimateMinutes;useEffect(()=>{if(a==="none"){c(true);return}if(!P||!w||!h||!X$1||E)return;let A=new URLSearchParams({userId:h});if(l&&A.set("userHash",l),a==="slot")A.set("slotId",X$1);else if(a==="boundary"){if(!$){c(true);return}A.set("boundaryId",X$1),A.set("appId",$);}fetch(`${P}/api/v1/forks/history?${A.toString()}`,{headers:{Authorization:`Bearer ${w}`}}).then(L=>L.ok?L.json():[]).then(L=>{let H=[];for(let be of L)be.role==="user"?H.push({type:"user",text:be.content}):H.push({type:"applied",text:be.content});H.length>0&&y(H),c(true);}).catch(()=>c(true));},[w,$,P,E,a,X$1,l,h]),useEffect(()=>{e==="complete"&&q(false);},[e]),useEffect(()=>{if(T)return;let A=requestAnimationFrame(()=>x(true));return ()=>cancelAnimationFrame(A)},[T]),useEffect(()=>{if(ce&&(e==="prompting"||e==="complete")){let A=setTimeout(()=>Z.current?.focus(),T?100:ae+100);return ()=>clearTimeout(A)}},[ce,T,e]),useEffect(()=>{if(e==="complete"&&Pe.current){let L=r.find(H=>H.type==="complete")?.data?.summary||t?.summary||Er;y(H=>H[H.length-1]?.type==="applied"?H:[...H,{type:"applied",text:L}]),C(""),setTimeout(()=>Z.current?.focus(),200);}},[e,_e,r,t?.summary]),useEffect(()=>{ye.current&&(ye.current.scrollTop=ye.current.scrollHeight);},[F,e]);let Ze=()=>{R.trim()&&(Pe.current=R.trim(),y(A=>[...A,{type:"user",text:R.trim()}]),d(R.trim(),X$1),C(""));},Lt=async()=>{if(!(!m||W||!X$1)){ee(true);try{let A=await m(X$1);y(L=>{let H=[...L];return H.length>=2&&H[H.length-1]?.type==="applied"?H.splice(-2,2):H.length>=1&&H[H.length-1]?.type==="applied"&&H.splice(-1,1),H}),A?.removed&&y([]);}catch{}finally{ee(false);}}},Me=()=>{if(T){S();return}f(true),x(false),setTimeout(()=>S(),ae);},Bt=T?{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:wt,maxWidth:"100vw",background:"#ffffff",boxShadow:ce?"-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:ce?"translateX(0)":"translateX(100%)",transition:`transform ${ae}ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow ${ae}ms ease`,display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'};return 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,o)=>{let n=o===e.length-1,i=r.type==="complete"||r.type==="error"||r.type==="build_complete"||r.type==="build_error",s=n&&!i&&(r.type==="status"||r.type==="tool_use"||r.type==="build_start"),a=fr[r.type]||Code,b=pr[r.type]||"#9ca3af";if(r.type==="tool_use"){let d=String(r.data.category||"");a=mr[d]||Wrench,b=gr[d]||"#fbbf24";}return s?a=Loader2:!n&&r.type==="status"&&(a=Check,b="#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:b,...s?{animation:"__fork-spin 1s linear infinite"}:{}}}),jsx("span",{style:{color:n&&!i?"#d1d5db":"#6b7280",wordBreak:"break-all"},children:je(r)})]},o)})]})]})}var xr=["Dark mode redesign","New workflow for adding to this page","Data-dense analytics view"],wt=35,Rr="Working on Feature",Er="Built Custom Feature",$r=360,Fe=350;function Ar(e){return e.length<=wt?e:e.slice(0,wt-3).trimEnd()+"..."}function Cr({events:e}){let[t,r]=useState("Setting up environment..."),[o,n]=useState(true),i=useRef(t),s=useRef(false);return useEffect(()=>{if(!s.current){for(let b of e)if(b.type==="status"&&String(b.data.message||"").includes("Agent started")){s.current=true;break}}let a="Setting up environment...";if(s.current)for(let b=e.length-1;b>=0;b--){let d=e[b];if(d.type==="tool_use"||d.type==="build_start"||d.type==="build_complete"){a=Ar(je(d));break}}if(a!==i.current){n(false);let b=setTimeout(()=>{r(a),i.current=a,n(true);},200);return ()=>clearTimeout(b)}},[e]),jsx("span",{style:{fontSize:11,color:"#d1d5db",fontWeight:500,opacity:o?1:0,transition:"opacity 0.2s ease",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},children:t})}function Tr({children:e}){let[t,r]=useState(null);return useEffect(()=>{if(typeof document>"u")return;let o=document.createElement("div");o.setAttribute("data-fork-panel-host",""),o.style.cssText="all: initial;",document.body.appendChild(o);let n=o.attachShadow({mode:"open"});return r(n),()=>{o.remove();}},[]),t?createPortal(e,t):null}function xe({state:e,fork:t,events:r,error:o,slotId:n,targetId:i,targetLabel:s,historyMode:a="slot",examplePrompts:b=xr,onSubmit:d,onUndo:m,onClose:S,baseUrl:_,apiKey:w,userId:h,userHash:l,appId:$,embedded:T=false}){let[R,C]=useState(""),[F,y]=useState([]),[E,c]=useState(false),[u,x]=useState(false),[k,f]=useState(false),[g,p]=useState(false),[B,U]=useState(false),[K,V]=useState(false),[G,Y]=useState(null),[O,q]=useState(false),[W,te]=useState(false),[v,P]=useState(null),[N,z]=useState(false),Z=useRef(null),ge=useRef(null),{resetAllForks:_t}=j(),X$1=i??n??"",Pe=(s||X$1).replace(/[-_]+/g," ").replace(/\b\w/g,A=>A.toUpperCase()),_e=useRef(""),he=T?true:u&&!k,Mt=r.find(A=>{let L=A.data;return A.type==="status"&&L.summary})?.data?.summary||t?.summary||Rr,re=r.find(A=>{let L=A.data;return (A.type==="status"||A.type==="complete")&&typeof L?.estimateMinutes=="number"})?.data?.estimateMinutes??t?.estimateMinutes;useEffect(()=>{if(a==="none"){c(true);return}if(!_||!w||!h||!X$1||E)return;let A=new URLSearchParams({userId:h});if(l&&A.set("userHash",l),a==="slot")A.set("slotId",X$1);else if(a==="boundary"){if(!$){c(true);return}A.set("boundaryId",X$1),A.set("appId",$);}fetch(`${_}/api/v1/forks/history?${A.toString()}`,{headers:{Authorization:`Bearer ${w}`}}).then(L=>L.ok?L.json():[]).then(L=>{let H=[];for(let ye of L)ye.role==="user"?H.push({type:"user",text:ye.content}):H.push({type:"applied",text:ye.content});H.length>0&&y(H),c(true);}).catch(()=>c(true));},[w,$,_,E,a,X$1,l,h]),useEffect(()=>{e==="complete"&&q(false);},[e]),useEffect(()=>{if(T)return;let A=requestAnimationFrame(()=>x(true));return ()=>cancelAnimationFrame(A)},[T]),useEffect(()=>{if(he&&(e==="prompting"||e==="complete")){let A=setTimeout(()=>Z.current?.focus(),T?100:Fe+100);return ()=>clearTimeout(A)}},[he,T,e]),useEffect(()=>{if(e==="complete"&&_e.current){let L=r.find(H=>H.type==="complete")?.data?.summary||t?.summary||Er;y(H=>H[H.length-1]?.type==="applied"?H:[...H,{type:"applied",text:L}]),C(""),setTimeout(()=>Z.current?.focus(),200);}},[e,Pe,r,t?.summary]),useEffect(()=>{ge.current&&(ge.current.scrollTop=ge.current.scrollHeight);},[F,e]);let Ze=()=>{R.trim()&&(_e.current=R.trim(),y(A=>[...A,{type:"user",text:R.trim()}]),d(R.trim(),X$1),C(""));},Lt=async()=>{if(!(!m||W||!X$1)){te(true);try{let A=await m(X$1);y(L=>{let H=[...L];return H.length>=2&&H[H.length-1]?.type==="applied"?H.splice(-2,2):H.length>=1&&H[H.length-1]?.type==="applied"&&H.splice(-1,1),H}),A?.removed&&y([]);}catch{}finally{te(false);}}},Me=()=>{if(T){S();return}f(true),x(false),setTimeout(()=>S(),Fe);},Bt=T?{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:$r,maxWidth:"100vw",background:"#ffffff",boxShadow:he?"-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:he?"translateX(0)":"translateX(100%)",transition:`transform ${Fe}ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow ${Fe}ms ease`,display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'},Qe=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 He from'react';import He__default,{createContext,useState,useRef,useEf
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:Bt,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(ve,{style:{width:16,height:16,color:"#1c4587",cursor:"pointer",flexShrink:0},onDoubleClick:async A=>{if(A.stopPropagation(),!N&&confirm("Reset all forks? This will remove all forked components.")){z(true);try{let L=await Pt();`${L?.deleted??0}`,y([]),C(""),q(!1),Me();}catch(L){console.error("[Fork] Reset failed:",L);}finally{z(false);}}}}),jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:e==="running"?Mt:`Fork ${_e}`}),e==="running"&&jsx("span",{title:te?`Estimated ~${te} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:te?"#1c4587":"#9ca3af",backgroundColor:te?"rgba(28, 69, 135, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:te?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:te?`~${te}m`:"~ m"}),e==="complete"&&jsx("div",{style:{height:6,width:6,backgroundColor:"#1c4587",borderRadius:"50%",flexShrink:0}})]}),!T&&jsx("button",{onClick:Me,onMouseEnter:()=>p(true),onMouseLeave:()=>p(false),style:{padding:6,borderRadius:6,color:g?"#4b5563":"#9ca3af",backgroundColor:g?"#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:ye,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[e==="prompting"&&F.length===0&&jsxs("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."}),jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6,justifyContent:"center"},children:b.map((A,L)=>jsx("button",{onClick:()=>{C(A),Z.current?.focus();},onMouseEnter:()=>Y(L),onMouseLeave:()=>Y(null),style:{fontSize:12,padding:"5px 12px",borderRadius:9999,color:G===L?"#1f2937":"#6b7280",backgroundColor:G===L?"#f9fafb":"transparent",border:G===L?"1px solid #d1d5db":"1px solid #e5e7eb",cursor:"pointer",transition:"color 0.15s, background-color 0.15s, border-color 0.15s",fontFamily:"inherit"},children:A},A))})]}),F.length>0&&jsx("div",{style:{padding:"16px 16px 0 16px"},children:F.map((A,L)=>jsx("div",{style:{marginBottom:L<F.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}),m&&L===F.length-1&&e!=="running"&&jsxs("button",{onClick:H=>{H.stopPropagation(),Lt();},onMouseEnter:()=>_(L),onMouseLeave:()=>_(null),disabled:W,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:v===L?"rgba(0,0,0,0.06)":"transparent",color:v===L?"#6b7280":"#d1d5db",cursor:W?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:W?.4:1,flexShrink:0},children:[jsx(Undo2,{style:{width:12,height:12}}),v===L&&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"})]})]})]})},L))}),e==="running"&&jsx("div",{style:{padding:16},children:jsxs("div",{onClick:()=>q(!O),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(Ar,{events:r})]}),jsx("div",{style:{color:"#6b7280",flexShrink:0,marginLeft:8,transition:"transform 0.2s ease",transform:O?"rotate(180deg)":"rotate(0deg)"},children:jsx(ChevronDown,{style:{width:14,height:14}})})]}),jsx("div",{style:{maxHeight:O?320:0,opacity:O?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(yt,{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:o}),jsxs("button",{onClick:()=>{let A=t?.prompt||Pe.current;A&&d(A,X$1);},onMouseEnter:()=>V(true),onMouseLeave:()=>V(false),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,color:"#4f46e5",backgroundColor:K?"#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:Z,value:R,onChange:A=>{C(A.target.value),A.target.style.height="auto",A.target.style.height=Math.min(A.target.scrollHeight,160)+"px";},onKeyDown:A=>{A.key==="Enter"&&!A.shiftKey&&(A.preventDefault(),Ze()),A.key==="Escape"&&!T&&Me();},placeholder:F.length>0?"Ask for another change...":`Describe your ideal ${_e.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:Ze,disabled:!R.trim(),onMouseEnter:()=>U(true),onMouseLeave:()=>U(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:R.trim()?1:.25,transform:B&&R.trim()?"scale(1.1)":"scale(1)",background:R.trim()?"#1c4587":"rgba(0,0,0,0.12)",border:"none",cursor:R.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:jsx(ArrowUp,{style:{width:13,height:13}})})]})})]})]})}function vt(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 ze(e){let{apiKey:t,userId:r,userHash:o,baseUrl:n,appId:i,refreshModuleManifest:s,queueBoundaryAnimation:a}=I(),[b,d]=useState("idle"),[m,S]=useState(null),[P,w]=useState([]),[h,l]=useState(null),$=useRef(null),T=useCallback(()=>{d("prompting"),w([]),l(null),S(null);},[]),R=useCallback(()=>{d("idle"),$.current&&($.current.close(),$.current=null);},[]),C=useCallback(async y=>{try{if(!i)throw new Error("ForkProvider requires appId for module boundary prompts.");d("running"),w([]),l(null);let E={userId:r,prompt:y,boundaryId:e,appId:i};o&&(E.userHash=o);let c=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(E)});if(!c.ok){let f=await c.json().catch(()=>({}));throw new Error(f.error||`API error: ${c.status}`)}let u=await c.json();S(u);let x=new URLSearchParams({key:t});o&&(x.set("userId",r),x.set("userHash",o));let k=new EventSource(`${n}/api/v1/forks/${u.id}/events?${x.toString()}`);$.current=k,k.onmessage=f=>{try{let g=JSON.parse(f.data);if(w(p=>[...p,g]),g.type==="complete"){let p=g.data;a(e,u.id),s().catch(()=>{}).finally(()=>{let B={...u,status:"complete",moduleUrl:p.moduleUrl,cssUrls:p.cssUrls,summary:p.summary,completedAt:new Date().toISOString()};S(B),d("complete"),k.close();});}else if(g.type==="error"){let p=g.data;l(p.error||"Unknown error"),d("error"),k.close();}}catch{}},k.onerror=()=>{fetch(`${n}/api/v1/forks/${u.id}`,{headers:{Authorization:`Bearer ${t}`}}).then(f=>f.json()).then(f=>{S(f),f.status==="complete"?(a(e,f.id),s().catch(()=>{}),d("complete")):f.status==="error"&&(l(f.error||"Fork generation failed"),d("error"));}).catch(()=>{l("Connection lost"),d("error");}),k.close();};}catch(E){l(E.message),d("error");}},[t,i,n,e,a,s,o,r]),F=useCallback(async()=>{try{if(!i)throw new Error("ForkProvider requires appId for boundary undo.");let y={userId:r,boundaryId:e,appId:i};o&&(y.userHash=o);let E=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(y)});if(!E.ok){let u=await E.json().catch(()=>({}));throw new Error(u.error||`API error: ${E.status}`)}let c=await E.json();return await s().catch(()=>{}),c.removed?(S(null),d("prompting")):c.fork&&(S(c.fork),d("complete")),c}catch(y){throw l(y.message),y}},[t,i,n,e,s,o,r]);return {state:b,fork:m,events:P,error:h,open:T,close:R,startFork:C,undoFork:F}}function St(e){let{state:t,fork:r,events:o,error:n,open:i,close:s,startFork:a,undoFork:b}=ze(e);return {state:t,fork:r,events:o,error:n,isOpen:t!=="idle",open:i,close:s,submit:a,undo:b}}function We(){let{apiKey:e,userId:t,userHash:r,baseUrl:o,setSlotFork:n,clearSlotFork:i,skipAnimationForSlot:s}=I(),[a,b]=useState("idle"),[d,m]=useState(null),[S,P]=useState([]),[w,h]=useState(null),l=useRef(null),$=useCallback(()=>{b("prompting"),P([]),h(null),m(null);},[]),T=useCallback(()=>{b("idle"),l.current&&(l.current.close(),l.current=null);},[]),R=useCallback(async(F,y)=>{try{b("running"),P([]),h(null);let E={userId:t,prompt:F};y&&(E.slotId=y),r&&(E.userHash=r);let c=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(E)});if(!c.ok){let f=await c.json().catch(()=>({}));throw new Error(f.error||`API error: ${c.status}`)}let u=await c.json();m(u);let x=new URLSearchParams({key:e});r&&(x.set("userId",t),x.set("userHash",r));let k=new EventSource(`${o}/api/v1/forks/${u.id}/events?${x.toString()}`);l.current=k,k.onmessage=f=>{try{let g=JSON.parse(f.data);if(P(p=>[...p,g]),g.type==="complete"){let p=g.data,B={...u,status:"complete",bundleUrl:p.bundleUrl,summary:p.summary,completedAt:new Date().toISOString()};m(B),b("complete"),y&&p.bundleUrl&&n(y,B),k.close();}else if(g.type==="error"){let p=g.data;h(p.error||"Unknown error"),b("error"),k.close();}}catch{}},k.onerror=()=>{fetch(`${o}/api/v1/forks/${u.id}`,{headers:{Authorization:`Bearer ${e}`}}).then(f=>f.json()).then(f=>{m(f),f.status==="complete"?(b("complete"),y&&f.bundleUrl&&n(y,f)):f.status==="error"&&(h(f.error||"Fork generation failed"),b("error"));}).catch(()=>{h("Connection lost"),b("error");}),k.close();};}catch(E){h(E.message),b("error");}},[e,t,r,o,n]),C=useCallback(async F=>{try{let y={userId:t,slotId:F};r&&(y.userHash=r);let E=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(y)});if(!E.ok){let u=await E.json().catch(()=>({}));throw new Error(u.error||`API error: ${E.status}`)}let c=await E.json();return s(F),c.removed?(i(F),m(null),b("prompting")):c.fork&&(n(F,c.fork),m(c.fork)),c}catch(y){throw h(y.message),y}},[e,t,r,o,i,n]);return {state:a,fork:d,events:S,error:w,open:$,close:T,startFork:R,undoFork:C}}function Ft(){let{state:e,fork:t,events:r,error:o,open:n,close:i,startFork:s,undoFork:a}=We();return {state:e,fork:t,events:r,error:o,isOpen:e!=="idle",open:n,close:i,submit:s,undo:a}}function Ke(e){let t=vt(e),r=Ft(),o=St(t.type==="boundary"?t.id:""),{baseUrl:n,apiKey:i,userId:s,userHash:a,appId:b}=I(),d=t.type==="slot"?r:o,m=t.type==="slot"?"slot":"boundary",S=t.id,P=t.title,w=useCallback((l,$)=>t.type==="slot"?r.submit(l,$??t.id):o.submit(l),[o,r,t]),h=useCallback(l=>t.type==="slot"?r.undo(l??t.id):o.undo(),[o,r,t]);return {...d,target:t,targetId:S,targetLabel:P,historyMode:m,submit:w,undo:h,buttonProps:{onClick:d.open},panelProps:{state:d.state,fork:d.fork,events:d.events,error:d.error,...t.type==="slot"?{slotId:S,targetLabel:P,historyMode:m}:{targetId:S,targetLabel:P,historyMode:m},onSubmit:w,onUndo:h,onClose:d.close,baseUrl:n,apiKey:i,userId:s,userHash:a,appId:b}}}function he(e){let{examplePrompts:t,embedded:r}=e,o=Ke(e);return r?jsx(xe,{...o.panelProps,examplePrompts:t,embedded:true}):o.isOpen?jsx(xe,{...o.panelProps,examplePrompts:t}):jsx(De,{...o.buttonProps})}function Mr({boundaryId:e,title:t,examplePrompts:r}){return jsx(he,{boundaryId:e,title:t,examplePrompts:r})}function Ve(e){let t=Array.from(e.children).filter(o=>o instanceof HTMLElement);return t.length===1?t[0]:getComputedStyle(e).display==="contents"?null:e}function Rt(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 o=getComputedStyle(e).backgroundColor;r.style.backgroundColor=o&&o!=="rgba(0, 0, 0, 0)"&&o!=="transparent"?o:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(r);let n=e.querySelectorAll("*"),i=r.querySelectorAll("*");for(let s=0;s<n.length;s+=1)n[s].scrollTop!==0&&(i[s].scrollTop=n[s].scrollTop),n[s].scrollLeft!==0&&(i[s].scrollLeft=n[s].scrollLeft);return r}function qe(e){let t=[],r=e.querySelectorAll("*");for(let o of r){if(!(o instanceof HTMLElement))continue;let n=o.getBoundingClientRect();if(n.width<10||n.height<10||["SCRIPT","STYLE","META","LINK"].includes(o.tagName))continue;let i=getComputedStyle(o),s=parseFloat(i.borderTopLeftRadius)||0;t.push({tag:o.tagName,className:o.className||"",text:(o.textContent||"").slice(0,50).trim(),rect:n,borderRadius:s});}return t}function Et(e,t){let r=[];for(let o of t)if(!(e.find(s=>s.tag===o.tag&&s.className===o.className&&Math.abs(s.rect.top-o.rect.top)<20&&Math.abs(s.rect.left-o.rect.left)<20)||r.some(s=>o.rect.top>=s.rect.top&&o.rect.left>=s.rect.left&&o.rect.right<=s.rect.right&&o.rect.bottom<=s.rect.bottom))){for(let s=r.length-1;s>=0;s-=1){let a=r[s];a.rect.top>=o.rect.top&&a.rect.left>=o.rect.left&&a.rect.right<=o.rect.right&&a.rect.bottom<=o.rect.bottom&&r.splice(s,1);}r.push({rect:o.rect,borderRadius:o.borderRadius});}return r}function $t(e,t){let r=[];for(let o of e)if(!(t.find(s=>s.tag===o.tag&&s.className===o.className&&Math.abs(s.rect.top-o.rect.top)<20&&Math.abs(s.rect.left-o.rect.left)<20)||r.some(s=>o.rect.top>=s.rect.top&&o.rect.left>=s.rect.left&&o.rect.right<=s.rect.right&&o.rect.bottom<=s.rect.bottom))){for(let s=r.length-1;s>=0;s-=1){let a=r[s];a.rect.top>=o.rect.top&&a.rect.left>=o.rect.left&&a.rect.right<=o.rect.right&&a.rect.bottom<=o.rect.bottom&&r.splice(s,1);}r.push({rect:o.rect,borderRadius:o.borderRadius});}return r}function At(e,t,r,o,n){let i=Math.max(0,Math.min(n,r/2,o/2));return i===0?`M ${e} ${t} L ${e+r} ${t} L ${e+r} ${t+o} L ${e} ${t+o} Z`:[`M ${e+i} ${t}`,`L ${e+r-i} ${t}`,`A ${i} ${i} 0 0 1 ${e+r} ${t+i}`,`L ${e+r} ${t+o-i}`,`A ${i} ${i} 0 0 1 ${e+r-i} ${t+o}`,`L ${e+i} ${t+o}`,`A ${i} ${i} 0 0 1 ${e} ${t+o-i}`,`L ${e} ${t+i}`,`A ${i} ${i} 0 0 1 ${e+i} ${t}`,"Z"].join(" ")}function Je(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 o=document.createElementNS(t,"svg");o.setAttribute("width","100%"),o.setAttribute("height","100%"),o.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let n=document.createElementNS(t,"defs");o.appendChild(n);let i=[];for(let m=0;m<e.length;m+=1){let{rect:S,borderRadius:P}=e[m],w=S.left-.5,h=S.top-.5,l=S.width+1,$=S.height+1,T=Math.min(P+.5,l/2,$/2),R=At(w,h,l,$,T),C=`__fork-glow-${m}`,F=document.createElementNS(t,"filter");F.setAttribute("id",C),F.setAttribute("x","-100%"),F.setAttribute("y","-100%"),F.setAttribute("width","300%"),F.setAttribute("height","300%");let y=document.createElementNS(t,"feGaussianBlur");y.setAttribute("in","SourceGraphic"),y.setAttribute("stdDeviation","8"),F.appendChild(y),n.appendChild(F);let E=`__fork-mask-${m}`,c=document.createElementNS(t,"mask");c.setAttribute("id",E),c.setAttribute("maskUnits","userSpaceOnUse"),c.setAttribute("x",String(w-200)),c.setAttribute("y",String(h-200)),c.setAttribute("width",String(l+400)),c.setAttribute("height",String($+400));let u=document.createElementNS(t,"rect");u.setAttribute("x",String(w-200)),u.setAttribute("y",String(h-200)),u.setAttribute("width",String(l+400)),u.setAttribute("height",String($+400)),u.setAttribute("fill","white"),c.appendChild(u);let x=document.createElementNS(t,"path");x.setAttribute("d",R),x.setAttribute("fill","black"),c.appendChild(x),n.appendChild(c);let k=document.createElementNS(t,"g");k.setAttribute("mask",`url(#${E})`),k.setAttribute("opacity","0");let f=document.createElementNS(t,"g");f.setAttribute("filter",`url(#${C})`);let g=document.createElementNS(t,"path");g.setAttribute("d",R),g.setAttribute("fill","none"),g.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),g.setAttribute("stroke-width","6"),g.setAttribute("stroke-linecap","round"),f.appendChild(g),k.appendChild(f),o.appendChild(k);let p=document.createElementNS(t,"path");p.setAttribute("d",R),p.setAttribute("fill","none"),p.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),p.setAttribute("stroke-width","2"),p.setAttribute("stroke-linecap","round"),p.setAttribute("opacity","0"),o.appendChild(p),i.push(g,p),g.__group=k;}r.appendChild(o),document.body.appendChild(r);let s=[];for(let m=0;m<i.length;m+=2){let S=i[m],P=i[m+1],w=S.__group;if(!w)continue;let h=P.getTotalLength(),l=S.getTotalLength();if(h<=0)continue;let $=h*.35;P.setAttribute("stroke-dasharray",`${$} ${h-$}`),P.setAttribute("stroke-dashoffset","0"),s.push(P.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*h,opacity:.92,offset:.06},{strokeDashoffset:-2*h,opacity:.92,offset:.92},{strokeDashoffset:-2.25*h,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let T=l*.35;S.setAttribute("stroke-dasharray",`${T} ${l-T}`),S.setAttribute("stroke-dashoffset","0"),s.push(S.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*l,offset:.06},{strokeDashoffset:-2*l,offset:.92},{strokeDashoffset:-2.25*l,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(w.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,b=()=>{if(a)return;a=true,clearTimeout(d);for(let S of s)try{S.cancel();}catch{}let m=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});m.onfinish=()=>r.remove(),window.removeEventListener("click",b);},d=setTimeout(b,14500);return setTimeout(()=>{a||window.addEventListener("click",b);},500),b}function Ct(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 o=document.createElementNS(t,"svg");o.setAttribute("width","100%"),o.setAttribute("height","100%"),o.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let n=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),n.appendChild(i),o.appendChild(n);for(let{rect:a,borderRadius:b}of e){let d=document.createElementNS(t,"path");d.setAttribute("d",At(a.left,a.top,a.width,a.height,b)),d.setAttribute("fill","none"),d.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),d.setAttribute("stroke-width","1.5"),d.setAttribute("stroke-dasharray","8 4"),d.setAttribute("stroke-linecap","round"),d.setAttribute("filter","url(#__fork-removed-shadow)"),d.setAttribute("opacity","0"),o.appendChild(d),d.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(o),document.body.appendChild(r),r}var Te=new Map,Ye=new Map;function Nr(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function _t(e,t){let r=(t?e[t]:void 0)??e.default;if(typeof r!="function"){let o=t||"default";throw new Error(`Fork boundary module is missing a React component export: ${o}`)}return r}function Hr(e){if(!e||typeof document>"u")return Promise.resolve();let t=Te.get(e);if(t)return t;let r=document.querySelector(`link[data-fork-override-href="${e}"]`);if(r instanceof HTMLLinkElement){let n=r.sheet?Promise.resolve():new Promise((i,s)=>{let a=()=>{r.removeEventListener("load",a),r.removeEventListener("error",b),i();},b=()=>{r.removeEventListener("load",a),r.removeEventListener("error",b),s(new Error(`Failed to load boundary stylesheet: ${e}`));};r.addEventListener("load",a,{once:true}),r.addEventListener("error",b,{once:true});});return Te.set(e,n),n}let o=new Promise((n,i)=>{let s=document.createElement("link");s.rel="stylesheet",s.href=e,s.setAttribute("data-fork-override-href",e),s.onload=()=>n(),s.onerror=()=>{s.remove(),i(new Error(`Failed to load boundary stylesheet: ${e}`));},document.head.appendChild(s);}).catch(n=>{throw Te.delete(e),n});return Te.set(e,o),o}function Or(e){let t=Ye.get(e);if(t)return t;let r=import(e).catch(o=>{throw Ye.delete(e),o});return Ye.set(e,r),r}async function Ur(e,t,r){if(e)try{await Promise.all(e.cssUrls.map(i=>Hr(i)));let n=await Or(e.moduleUrl);return _t(n,r)}catch(n){console.error(`[Fork] Failed to load override for boundary "${e.boundaryId}", falling back to original module.`,n);}let o=await t();return _t(o,r)}function Dr(e){function t(r){let{appId:o,moduleOverridesEnabled:n,moduleManifestReady:i,moduleManifestVersion:s,registerBoundary:a,getBoundaryOverride:b,consumeBoundaryAnimation:d}=I(),[m,S]=useState(null),[P,w]=useState(null),h=useRef(null),l=useRef(null),$=useRef(null),T=useRef(false),R=useRef(null),C=useRef(null),F=b(e.id),y=F?`override:${F.id}`:"original",E=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if(useEffect(()=>()=>{C.current&&(clearTimeout(C.current),C.current=null),R.current&&(R.current.remove(),R.current=null);},[]),useEffect(()=>{a({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[o,a,e.id,e.exportName,E]),useEffect(()=>{if(n&&!i&&!m||l.current===y&&m)return;let c=false;return w(null),Ur(F,e.original,e.exportName).then(u=>{if(!c){if(F?.id&&d(e.id,F.id)&&h.current){let x=Ve(h.current);if(x){let k=qe(x);k.length>0&&($.current=k,T.current=true,C.current&&(clearTimeout(C.current),C.current=null),R.current&&R.current.remove(),R.current=Rt(x));}}l.current=y,startTransition(()=>{S(()=>u);});}}).catch(u=>{c||w(Nr(u));}),()=>{c=true;}},[d,y,n,i,s,F?.id,F?.moduleUrl,F?.integrity,F?.cssUrls.join("|"),e.exportName,e.original,m]),useEffect(()=>{if(!T.current||!m||!h.current)return;let c=false;return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(c||!h.current)return;let u=$.current,x=Ve(h.current);if($.current=null,T.current=false,!u||!x){R.current&&(R.current.remove(),R.current=null);return}let k=qe(x),f=Et(u,k),g=$t(u,k),p=R.current;if(g.length>0&&p){let B=Ct(g);C.current=setTimeout(()=>{C.current=null;let U=400;p.animate([{opacity:1},{opacity:0}],{duration:U,fill:"forwards"}),B.animate([{opacity:1},{opacity:0}],{duration:U,fill:"forwards"}),setTimeout(()=>{p.remove(),B.remove(),R.current===p&&(R.current=null),f.length>0&&Je(f);},U);},3500);}else p&&(p.remove(),R.current===p&&(R.current=null)),f.length>0&&Je(f);});}),()=>{c=true;}},[m]),P)throw P;return m?jsx("div",{ref:h,style:{display:"contents"},children:jsx(m,{...r})}):jsx(Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function jr({slotId:e,title:t,slotLabel:r,examplePrompts:o}){return jsx(he,{slotId:e,title:t,slotLabel:r,examplePrompts:o})}
44
- export{Mr as ForkBoundaryUI,De as ForkButton,he as ForkChatInterface,xe as ForkPanel,zt as ForkProvider,rr as ForkSlot,jr as ForkUI,Dr as forkable,Be as registerForkShared,ze as useBoundaryFork,We as useFork,Ke as useForkChatPanel};
43
+ `}),jsxs("div",{className:"__fork-panel",style:Bt,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(we,{style:{width:16,height:16,color:"#1c4587",cursor:"pointer",flexShrink:0},onDoubleClick:async A=>{if(A.stopPropagation(),!N&&confirm("Reset all forks? This will remove all forked components.")){z(true);try{let L=await _t();`${L?.deleted??0}`,y([]),C(""),q(!1),Me();}catch(L){console.error("[Fork] Reset failed:",L);}finally{z(false);}}}}),jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:e==="running"?Mt:`Fork ${Pe}`}),e==="running"&&jsx("span",{title:re?`Estimated ~${re} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:re?"#1c4587":"#9ca3af",backgroundColor:re?"rgba(28, 69, 135, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:re?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:re?`~${re}m`:"~ m"}),e==="complete"&&jsx("div",{style:{height:6,width:6,backgroundColor:"#1c4587",borderRadius:"50%",flexShrink:0}})]}),!T&&jsx("button",{onClick:Me,onMouseEnter:()=>p(true),onMouseLeave:()=>p(false),style:{padding:6,borderRadius:6,color:g?"#4b5563":"#9ca3af",backgroundColor:g?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:jsx(X,{style:{width:16,height:16}})})]}),jsxs("div",{ref:ge,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[e==="prompting"&&F.length===0&&jsxs("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."}),jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6,justifyContent:"center"},children:b.map((A,L)=>jsx("button",{onClick:()=>{C(A),Z.current?.focus();},onMouseEnter:()=>Y(L),onMouseLeave:()=>Y(null),style:{fontSize:12,padding:"5px 12px",borderRadius:9999,color:G===L?"#1f2937":"#6b7280",backgroundColor:G===L?"#f9fafb":"transparent",border:G===L?"1px solid #d1d5db":"1px solid #e5e7eb",cursor:"pointer",transition:"color 0.15s, background-color 0.15s, border-color 0.15s",fontFamily:"inherit"},children:A},A))})]}),F.length>0&&jsx("div",{style:{padding:"16px 16px 0 16px"},children:F.map((A,L)=>jsx("div",{style:{marginBottom:L<F.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}),m&&L===F.length-1&&e!=="running"&&jsxs("button",{onClick:H=>{H.stopPropagation(),Lt();},onMouseEnter:()=>P(L),onMouseLeave:()=>P(null),disabled:W,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:v===L?"rgba(0,0,0,0.06)":"transparent",color:v===L?"#6b7280":"#d1d5db",cursor:W?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:W?.4:1,flexShrink:0},children:[jsx(Undo2,{style:{width:12,height:12}}),v===L&&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"})]})]})]})},L))}),e==="running"&&jsx("div",{style:{padding:16},children:jsxs("div",{onClick:()=>q(!O),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(Cr,{events:r})]}),jsx("div",{style:{color:"#6b7280",flexShrink:0,marginLeft:8,transition:"transform 0.2s ease",transform:O?"rotate(180deg)":"rotate(0deg)"},children:jsx(ChevronDown,{style:{width:14,height:14}})})]}),jsx("div",{style:{maxHeight:O?320:0,opacity:O?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(bt,{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:o}),jsxs("button",{onClick:()=>{let A=t?.prompt||_e.current;A&&d(A,X$1);},onMouseEnter:()=>V(true),onMouseLeave:()=>V(false),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,color:"#4f46e5",backgroundColor:K?"#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:Z,value:R,onChange:A=>{C(A.target.value),A.target.style.height="auto",A.target.style.height=Math.min(A.target.scrollHeight,160)+"px";},onKeyDown:A=>{A.key==="Enter"&&!A.shiftKey&&(A.preventDefault(),Ze()),A.key==="Escape"&&!T&&Me();},placeholder:F.length>0?"Ask for another change...":`Describe your ideal ${Pe.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:Ze,disabled:!R.trim(),onMouseEnter:()=>U(true),onMouseLeave:()=>U(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:R.trim()?1:.25,transform:B&&R.trim()?"scale(1.1)":"scale(1)",background:R.trim()?"#1c4587":"rgba(0,0,0,0.12)",border:"none",cursor:R.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:jsx(ArrowUp,{style:{width:13,height:13}})})]})})]})]});return T?Qe:jsx(Tr,{children:Qe})}function vt(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 ze(e){let{apiKey:t,userId:r,userHash:o,baseUrl:n,appId:i,refreshModuleManifest:s,queueBoundaryAnimation:a}=j(),[b,d]=useState("idle"),[m,S]=useState(null),[_,w]=useState([]),[h,l]=useState(null),$=useRef(null),T=useCallback(()=>{d("prompting"),w([]),l(null),S(null);},[]),R=useCallback(()=>{d("idle"),$.current&&($.current.close(),$.current=null);},[]),C=useCallback(async y=>{try{if(!i)throw new Error("ForkProvider requires appId for module boundary prompts.");d("running"),w([]),l(null);let E={userId:r,prompt:y,boundaryId:e,appId:i};o&&(E.userHash=o);let c=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(E)});if(!c.ok){let f=await c.json().catch(()=>({}));throw new Error(f.error||`API error: ${c.status}`)}let u=await c.json();S(u);let x=new URLSearchParams({key:t});o&&(x.set("userId",r),x.set("userHash",o));let k=new EventSource(`${n}/api/v1/forks/${u.id}/events?${x.toString()}`);$.current=k,k.onmessage=f=>{try{let g=JSON.parse(f.data);if(w(p=>[...p,g]),g.type==="complete"){let p=g.data;a(e,u.id),s().catch(()=>{}).finally(()=>{let B={...u,status:"complete",moduleUrl:p.moduleUrl,cssUrls:p.cssUrls,summary:p.summary,completedAt:new Date().toISOString()};S(B),d("complete"),k.close();});}else if(g.type==="error"){let p=g.data;l(p.error||"Unknown error"),d("error"),k.close();}}catch{}},k.onerror=()=>{fetch(`${n}/api/v1/forks/${u.id}`,{headers:{Authorization:`Bearer ${t}`}}).then(f=>f.json()).then(f=>{S(f),f.status==="complete"?(a(e,f.id),s().catch(()=>{}),d("complete")):f.status==="error"&&(l(f.error||"Fork generation failed"),d("error"));}).catch(()=>{l("Connection lost"),d("error");}),k.close();};}catch(E){l(E.message),d("error");}},[t,i,n,e,a,s,o,r]),F=useCallback(async()=>{try{if(!i)throw new Error("ForkProvider requires appId for boundary undo.");let y={userId:r,boundaryId:e,appId:i};o&&(y.userHash=o);let E=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(y)});if(!E.ok){let u=await E.json().catch(()=>({}));throw new Error(u.error||`API error: ${E.status}`)}let c=await E.json();return await s().catch(()=>{}),c.removed?(S(null),d("prompting")):c.fork&&(S(c.fork),d("complete")),c}catch(y){throw l(y.message),y}},[t,i,n,e,s,o,r]);return {state:b,fork:m,events:_,error:h,open:T,close:R,startFork:C,undoFork:F}}function St(e){let{state:t,fork:r,events:o,error:n,open:i,close:s,startFork:a,undoFork:b}=ze(e);return {state:t,fork:r,events:o,error:n,isOpen:t!=="idle",open:i,close:s,submit:a,undo:b}}function We(){let{apiKey:e,userId:t,userHash:r,baseUrl:o,setSlotFork:n,clearSlotFork:i,skipAnimationForSlot:s}=j(),[a,b]=useState("idle"),[d,m]=useState(null),[S,_]=useState([]),[w,h]=useState(null),l=useRef(null),$=useCallback(()=>{b("prompting"),_([]),h(null),m(null);},[]),T=useCallback(()=>{b("idle"),l.current&&(l.current.close(),l.current=null);},[]),R=useCallback(async(F,y)=>{try{b("running"),_([]),h(null);let E={userId:t,prompt:F};y&&(E.slotId=y),r&&(E.userHash=r);let c=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(E)});if(!c.ok){let f=await c.json().catch(()=>({}));throw new Error(f.error||`API error: ${c.status}`)}let u=await c.json();m(u);let x=new URLSearchParams({key:e});r&&(x.set("userId",t),x.set("userHash",r));let k=new EventSource(`${o}/api/v1/forks/${u.id}/events?${x.toString()}`);l.current=k,k.onmessage=f=>{try{let g=JSON.parse(f.data);if(_(p=>[...p,g]),g.type==="complete"){let p=g.data,B={...u,status:"complete",bundleUrl:p.bundleUrl,summary:p.summary,completedAt:new Date().toISOString()};m(B),b("complete"),y&&p.bundleUrl&&n(y,B),k.close();}else if(g.type==="error"){let p=g.data;h(p.error||"Unknown error"),b("error"),k.close();}}catch{}},k.onerror=()=>{fetch(`${o}/api/v1/forks/${u.id}`,{headers:{Authorization:`Bearer ${e}`}}).then(f=>f.json()).then(f=>{m(f),f.status==="complete"?(b("complete"),y&&f.bundleUrl&&n(y,f)):f.status==="error"&&(h(f.error||"Fork generation failed"),b("error"));}).catch(()=>{h("Connection lost"),b("error");}),k.close();};}catch(E){h(E.message),b("error");}},[e,t,r,o,n]),C=useCallback(async F=>{try{let y={userId:t,slotId:F};r&&(y.userHash=r);let E=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(y)});if(!E.ok){let u=await E.json().catch(()=>({}));throw new Error(u.error||`API error: ${E.status}`)}let c=await E.json();return s(F),c.removed?(i(F),m(null),b("prompting")):c.fork&&(n(F,c.fork),m(c.fork)),c}catch(y){throw h(y.message),y}},[e,t,r,o,i,n]);return {state:a,fork:d,events:S,error:w,open:$,close:T,startFork:R,undoFork:C}}function Ft(){let{state:e,fork:t,events:r,error:o,open:n,close:i,startFork:s,undoFork:a}=We();return {state:e,fork:t,events:r,error:o,isOpen:e!=="idle",open:n,close:i,submit:s,undo:a}}function Ke(e){let t=vt(e),r=Ft(),o=St(t.type==="boundary"?t.id:""),{baseUrl:n,apiKey:i,userId:s,userHash:a,appId:b}=j(),d=t.type==="slot"?r:o,m=t.type==="slot"?"slot":"boundary",S=t.id,_=t.title,w=useCallback((l,$)=>t.type==="slot"?r.submit(l,$??t.id):o.submit(l),[o,r,t]),h=useCallback(l=>t.type==="slot"?r.undo(l??t.id):o.undo(),[o,r,t]);return {...d,target:t,targetId:S,targetLabel:_,historyMode:m,submit:w,undo:h,buttonProps:{onClick:d.open},panelProps:{state:d.state,fork:d.fork,events:d.events,error:d.error,...t.type==="slot"?{slotId:S,targetLabel:_,historyMode:m}:{targetId:S,targetLabel:_,historyMode:m},onSubmit:w,onUndo:h,onClose:d.close,baseUrl:n,apiKey:i,userId:s,userHash:a,appId:b}}}function me(e){let{examplePrompts:t,embedded:r}=e,o=Ke(e);return r?jsx(xe,{...o.panelProps,examplePrompts:t,embedded:true}):o.isOpen?jsx(xe,{...o.panelProps,examplePrompts:t}):jsx(De,{...o.buttonProps})}function Lr({boundaryId:e,title:t,examplePrompts:r}){return jsx(me,{boundaryId:e,title:t,examplePrompts:r})}function Ve(e){let t=Array.from(e.children).filter(o=>o instanceof HTMLElement);return t.length===1?t[0]:getComputedStyle(e).display==="contents"?null:e}function Rt(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 o=getComputedStyle(e).backgroundColor;r.style.backgroundColor=o&&o!=="rgba(0, 0, 0, 0)"&&o!=="transparent"?o:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(r);let n=e.querySelectorAll("*"),i=r.querySelectorAll("*");for(let s=0;s<n.length;s+=1)n[s].scrollTop!==0&&(i[s].scrollTop=n[s].scrollTop),n[s].scrollLeft!==0&&(i[s].scrollLeft=n[s].scrollLeft);return r}function qe(e){let t=[],r=e.querySelectorAll("*");for(let o of r){if(!(o instanceof HTMLElement))continue;let n=o.getBoundingClientRect();if(n.width<10||n.height<10||["SCRIPT","STYLE","META","LINK"].includes(o.tagName))continue;let i=getComputedStyle(o),s=parseFloat(i.borderTopLeftRadius)||0;t.push({tag:o.tagName,className:o.className||"",text:(o.textContent||"").slice(0,50).trim(),rect:n,borderRadius:s});}return t}function Et(e,t){let r=[];for(let o of t)if(!(e.find(s=>s.tag===o.tag&&s.className===o.className&&Math.abs(s.rect.top-o.rect.top)<20&&Math.abs(s.rect.left-o.rect.left)<20)||r.some(s=>o.rect.top>=s.rect.top&&o.rect.left>=s.rect.left&&o.rect.right<=s.rect.right&&o.rect.bottom<=s.rect.bottom))){for(let s=r.length-1;s>=0;s-=1){let a=r[s];a.rect.top>=o.rect.top&&a.rect.left>=o.rect.left&&a.rect.right<=o.rect.right&&a.rect.bottom<=o.rect.bottom&&r.splice(s,1);}r.push({rect:o.rect,borderRadius:o.borderRadius});}return r}function $t(e,t){let r=[];for(let o of e)if(!(t.find(s=>s.tag===o.tag&&s.className===o.className&&Math.abs(s.rect.top-o.rect.top)<20&&Math.abs(s.rect.left-o.rect.left)<20)||r.some(s=>o.rect.top>=s.rect.top&&o.rect.left>=s.rect.left&&o.rect.right<=s.rect.right&&o.rect.bottom<=s.rect.bottom))){for(let s=r.length-1;s>=0;s-=1){let a=r[s];a.rect.top>=o.rect.top&&a.rect.left>=o.rect.left&&a.rect.right<=o.rect.right&&a.rect.bottom<=o.rect.bottom&&r.splice(s,1);}r.push({rect:o.rect,borderRadius:o.borderRadius});}return r}function At(e,t,r,o,n){let i=Math.max(0,Math.min(n,r/2,o/2));return i===0?`M ${e} ${t} L ${e+r} ${t} L ${e+r} ${t+o} L ${e} ${t+o} Z`:[`M ${e+i} ${t}`,`L ${e+r-i} ${t}`,`A ${i} ${i} 0 0 1 ${e+r} ${t+i}`,`L ${e+r} ${t+o-i}`,`A ${i} ${i} 0 0 1 ${e+r-i} ${t+o}`,`L ${e+i} ${t+o}`,`A ${i} ${i} 0 0 1 ${e} ${t+o-i}`,`L ${e} ${t+i}`,`A ${i} ${i} 0 0 1 ${e+i} ${t}`,"Z"].join(" ")}function Je(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 o=document.createElementNS(t,"svg");o.setAttribute("width","100%"),o.setAttribute("height","100%"),o.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let n=document.createElementNS(t,"defs");o.appendChild(n);let i=[];for(let m=0;m<e.length;m+=1){let{rect:S,borderRadius:_}=e[m],w=S.left-.5,h=S.top-.5,l=S.width+1,$=S.height+1,T=Math.min(_+.5,l/2,$/2),R=At(w,h,l,$,T),C=`__fork-glow-${m}`,F=document.createElementNS(t,"filter");F.setAttribute("id",C),F.setAttribute("x","-100%"),F.setAttribute("y","-100%"),F.setAttribute("width","300%"),F.setAttribute("height","300%");let y=document.createElementNS(t,"feGaussianBlur");y.setAttribute("in","SourceGraphic"),y.setAttribute("stdDeviation","8"),F.appendChild(y),n.appendChild(F);let E=`__fork-mask-${m}`,c=document.createElementNS(t,"mask");c.setAttribute("id",E),c.setAttribute("maskUnits","userSpaceOnUse"),c.setAttribute("x",String(w-200)),c.setAttribute("y",String(h-200)),c.setAttribute("width",String(l+400)),c.setAttribute("height",String($+400));let u=document.createElementNS(t,"rect");u.setAttribute("x",String(w-200)),u.setAttribute("y",String(h-200)),u.setAttribute("width",String(l+400)),u.setAttribute("height",String($+400)),u.setAttribute("fill","white"),c.appendChild(u);let x=document.createElementNS(t,"path");x.setAttribute("d",R),x.setAttribute("fill","black"),c.appendChild(x),n.appendChild(c);let k=document.createElementNS(t,"g");k.setAttribute("mask",`url(#${E})`),k.setAttribute("opacity","0");let f=document.createElementNS(t,"g");f.setAttribute("filter",`url(#${C})`);let g=document.createElementNS(t,"path");g.setAttribute("d",R),g.setAttribute("fill","none"),g.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),g.setAttribute("stroke-width","6"),g.setAttribute("stroke-linecap","round"),f.appendChild(g),k.appendChild(f),o.appendChild(k);let p=document.createElementNS(t,"path");p.setAttribute("d",R),p.setAttribute("fill","none"),p.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),p.setAttribute("stroke-width","2"),p.setAttribute("stroke-linecap","round"),p.setAttribute("opacity","0"),o.appendChild(p),i.push(g,p),g.__group=k;}r.appendChild(o),document.body.appendChild(r);let s=[];for(let m=0;m<i.length;m+=2){let S=i[m],_=i[m+1],w=S.__group;if(!w)continue;let h=_.getTotalLength(),l=S.getTotalLength();if(h<=0)continue;let $=h*.35;_.setAttribute("stroke-dasharray",`${$} ${h-$}`),_.setAttribute("stroke-dashoffset","0"),s.push(_.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*h,opacity:.92,offset:.06},{strokeDashoffset:-2*h,opacity:.92,offset:.92},{strokeDashoffset:-2.25*h,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let T=l*.35;S.setAttribute("stroke-dasharray",`${T} ${l-T}`),S.setAttribute("stroke-dashoffset","0"),s.push(S.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*l,offset:.06},{strokeDashoffset:-2*l,offset:.92},{strokeDashoffset:-2.25*l,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(w.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,b=()=>{if(a)return;a=true,clearTimeout(d);for(let S of s)try{S.cancel();}catch{}let m=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});m.onfinish=()=>r.remove(),window.removeEventListener("click",b);},d=setTimeout(b,14500);return setTimeout(()=>{a||window.addEventListener("click",b);},500),b}function Ct(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 o=document.createElementNS(t,"svg");o.setAttribute("width","100%"),o.setAttribute("height","100%"),o.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let n=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),n.appendChild(i),o.appendChild(n);for(let{rect:a,borderRadius:b}of e){let d=document.createElementNS(t,"path");d.setAttribute("d",At(a.left,a.top,a.width,a.height,b)),d.setAttribute("fill","none"),d.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),d.setAttribute("stroke-width","1.5"),d.setAttribute("stroke-dasharray","8 4"),d.setAttribute("stroke-linecap","round"),d.setAttribute("filter","url(#__fork-removed-shadow)"),d.setAttribute("opacity","0"),o.appendChild(d),d.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(o),document.body.appendChild(r),r}var Te=new Map,Ye=new Map;function Hr(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function Pt(e,t){let r=(t?e[t]:void 0)??e.default;if(typeof r!="function"){let o=t||"default";throw new Error(`Fork boundary module is missing a React component export: ${o}`)}return r}function Or(e){if(!e||typeof document>"u")return Promise.resolve();let t=Te.get(e);if(t)return t;let r=document.querySelector(`link[data-fork-override-href="${e}"]`);if(r instanceof HTMLLinkElement){let n=r.sheet?Promise.resolve():new Promise((i,s)=>{let a=()=>{r.removeEventListener("load",a),r.removeEventListener("error",b),i();},b=()=>{r.removeEventListener("load",a),r.removeEventListener("error",b),s(new Error(`Failed to load boundary stylesheet: ${e}`));};r.addEventListener("load",a,{once:true}),r.addEventListener("error",b,{once:true});});return Te.set(e,n),n}let o=new Promise((n,i)=>{let s=document.createElement("link");s.rel="stylesheet",s.href=e,s.setAttribute("data-fork-override-href",e),s.onload=()=>n(),s.onerror=()=>{s.remove(),i(new Error(`Failed to load boundary stylesheet: ${e}`));},document.head.appendChild(s);}).catch(n=>{throw Te.delete(e),n});return Te.set(e,o),o}function Ur(e){let t=Ye.get(e);if(t)return t;let r=import(e).catch(o=>{throw Ye.delete(e),o});return Ye.set(e,r),r}async function Dr(e,t,r){if(e)try{await Promise.all(e.cssUrls.map(i=>Or(i)));let n=await Ur(e.moduleUrl);return Pt(n,r)}catch(n){console.error(`[Fork] Failed to load override for boundary "${e.boundaryId}", falling back to original module.`,n);}let o=await t();return Pt(o,r)}function Ir(e){function t(r){let{appId:o,moduleOverridesEnabled:n,moduleManifestReady:i,moduleManifestVersion:s,registerBoundary:a,getBoundaryOverride:b,consumeBoundaryAnimation:d}=j(),[m,S]=useState(null),[_,w]=useState(null),h=useRef(null),l=useRef(null),$=useRef(null),T=useRef(false),R=useRef(null),C=useRef(null),F=b(e.id),y=F?`override:${F.id}`:"original",E=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if(useEffect(()=>()=>{C.current&&(clearTimeout(C.current),C.current=null),R.current&&(R.current.remove(),R.current=null);},[]),useEffect(()=>{a({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[o,a,e.id,e.exportName,E]),useEffect(()=>{if(n&&!i&&!m||l.current===y&&m)return;let c=false;return w(null),Dr(F,e.original,e.exportName).then(u=>{if(!c){if(F?.id&&d(e.id,F.id)&&h.current){let x=Ve(h.current);if(x){let k=qe(x);k.length>0&&($.current=k,T.current=true,C.current&&(clearTimeout(C.current),C.current=null),R.current&&R.current.remove(),R.current=Rt(x));}}l.current=y,startTransition(()=>{S(()=>u);});}}).catch(u=>{c||w(Hr(u));}),()=>{c=true;}},[d,y,n,i,s,F?.id,F?.moduleUrl,F?.integrity,F?.cssUrls.join("|"),e.exportName,e.original,m]),useEffect(()=>{if(!T.current||!m||!h.current)return;let c=false;return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(c||!h.current)return;let u=$.current,x=Ve(h.current);if($.current=null,T.current=false,!u||!x){R.current&&(R.current.remove(),R.current=null);return}let k=qe(x),f=Et(u,k),g=$t(u,k),p=R.current;if(g.length>0&&p){let B=Ct(g);C.current=setTimeout(()=>{C.current=null;let U=400;p.animate([{opacity:1},{opacity:0}],{duration:U,fill:"forwards"}),B.animate([{opacity:1},{opacity:0}],{duration:U,fill:"forwards"}),setTimeout(()=>{p.remove(),B.remove(),R.current===p&&(R.current=null),f.length>0&&Je(f);},U);},3500);}else p&&(p.remove(),R.current===p&&(R.current=null)),f.length>0&&Je(f);});}),()=>{c=true;}},[m]),_)throw _;return m?jsx("div",{ref:h,style:{display:"contents"},children:jsx(m,{...r})}):jsx(Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function zr({slotId:e,title:t,slotLabel:r,examplePrompts:o}){return jsx(me,{slotId:e,title:t,slotLabel:r,examplePrompts:o})}
44
+ export{Lr as ForkBoundaryUI,De as ForkButton,me as ForkChatInterface,xe as ForkPanel,zt as ForkProvider,rr as ForkSlot,zr as ForkUI,Ir as forkable,Be as registerForkShared,ze as useBoundaryFork,We as useFork,Ke as useForkChatPanel};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fork-api/chat-sdk",
3
- "version": "0.1.129",
3
+ "version": "0.1.131",
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",