@fork-api/chat-sdk 0.1.134 → 0.1.136

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 ht=require('react'),Or=require('react-dom'),Br=require('react/jsx-runtime'),Hr=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 ht__namespace=/*#__PURE__*/_interopNamespace(ht);var Or__namespace=/*#__PURE__*/_interopNamespace(Or);var Br__namespace=/*#__PURE__*/_interopNamespace(Br);var Hr__namespace=/*#__PURE__*/_interopNamespace(Hr);var ue="__FORK_SHARED__";function it(){var t,r,n,o;let e=globalThis;return e[ue]||(e[ue]={}),(t=e[ue]).react||(t.react=ht__namespace),(r=e[ue])["react-dom"]||(r["react-dom"]=Or__namespace),(n=e[ue])["react/jsx-runtime"]||(n["react/jsx-runtime"]=Br__namespace),(o=e[ue])["react/jsx-dev-runtime"]||(o["react/jsx-dev-runtime"]=Hr__namespace),e[ue]}function at(e){return Object.assign(it(),e)}var Nr="__fork_preview_session__";function Oe(e){return `${Nr}${e}`}var K={apiKey:null,session:null},lt=new Set;function ct(){for(let e of lt)try{e();}catch(t){console.error("[fork-preview] subscriber threw",t);}}function Bt(e){let t=Date.parse(e.expires_at);return Number.isFinite(t)?t<=Date.now():true}function Dr(e){if(typeof window>"u")return null;try{let t=window.sessionStorage.getItem(Oe(e));if(!t)return null;let r=JSON.parse(t);return !r||typeof r!="object"||typeof r.preview_session_id!="string"?null:Bt(r)?(window.sessionStorage.removeItem(Oe(e)),null):r}catch{return null}}function Ht(e,t){if(!(typeof window>"u"))try{t?window.sessionStorage.setItem(Oe(e),JSON.stringify(t)):window.sessionStorage.removeItem(Oe(e));}catch{}}function we(e){K.apiKey!==e&&(K.apiKey=e,K.session=Dr(e),ct());}function de(){return K.session?Bt(K.session)?(ut(null),null):K.session:null}function ut(e){K.session=e,K.apiKey&&Ht(K.apiKey,e),ct();}function ve(e){K.session&&K.session.fork_id!==e&&(K.session={...K.session,fork_id:e},K.apiKey&&Ht(K.apiKey,K.session),ct());}function dt(e){return lt.add(e),()=>{lt.delete(e);}}var Nt="__fork_preview";function Dt(){if(typeof window>"u")return null;let e=window.location.hash;if(!e||e.length<2)return null;let r=new URLSearchParams(e.slice(1)).get(Nt);return typeof r=="string"&&r.length>0?r:null}function ft(e){if(typeof window>"u")return false;try{if(window.sessionStorage.getItem(`__fork_preview_session__${e}`))return !0}catch{}return zt()!==null}function jt(){if(typeof window>"u")return;let e=window.location.hash;if(!e||e.length<2)return;let t=new URLSearchParams(e.slice(1));t.delete(Nt);let r=t.toString(),n=r?`#${r}`:"";try{window.history.replaceState(null,"",window.location.pathname+window.location.search+n);}catch{}}var fe=null;function zt(){if(fe)return fe;let e=Dt();return e?(fe=e,jt(),fe):null}async function pt(e,t){we(e);let r=de();if(r)return fe=null,r;let n=fe??Dt();if(fe=null,!n)return null;jt();try{let o=await fetch(`${t}/api/v1/preview/activate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({token:n})});if(!o.ok){let a=await o.json().catch(()=>({}));return console.warn(`[fork-preview] activate failed (${o.status}): ${a.error??"unknown"}`),null}let i=await o.json(),s={preview_session_id:i.preview_session_id,tenant_id:i.tenant_id,app_id:i.app_id,target:i.target,target_user_id:i.target_user_id,operator_id:i.operator_id,container_id:i.container_id??null,container_name:i.container_name??i.target_user_id,fork_id:i.fork_id??null,expires_at:i.expires_at};return ut(s),s}catch(o){return console.warn("[fork-preview] activate threw",o),null}}function zr(){return de()}function Wr(){return null}function Be(){return ht.useSyncExternalStore(dt,zr,Wr)}function Z(){let e=de();if(!e)return {};let t={"X-Fork-Preview-Session":e.preview_session_id};return e.fork_id&&(t["X-Fork-Preview-Fork-Id"]=e.fork_id),t}async function He(e){let t=new URLSearchParams({app:e.appId,user:e.userId});e.containerId&&t.set("containerId",e.containerId);let r=`${e.baseUrl}/api/v1/manifest?${t.toString()}`,n={Authorization:`Bearer ${e.apiKey}`,"X-Fork-App-Id":e.appId,"X-Fork-User-Id":e.userId,...e.extraHeaders??{}};e.userHash&&(n["X-Fork-User-Hash"]=e.userHash),e.previous?.etag&&(n["If-None-Match"]=e.previous.etag);let o=await fetch(r,{headers:n,signal:e.signal});if(o.status===304)return null;if(!o.ok)throw new Error(`manifest ${o.status} ${o.statusText}`);let i=await o.json(),s={};for(let[a,d]of Object.entries(i.modules)){let f=d.moduleUrl??d.bundleUrl??null,c=d.legacyModuleUrl??d.legacyBundleUrl??null;s[a]={forkId:d.forkId,moduleUrl:f,legacyModuleUrl:c,bundleUrl:d.bundleUrl??f,legacyBundleUrl:d.legacyBundleUrl??c,cssUrls:d.cssUrls??[],integrity:d.integrity,metadata:d.metadata,buildId:d.buildId,updatedAt:d.updatedAt};}return {containerId:i.containerId,slots:i.slots,modules:s,generatedAt:i.generatedAt,etag:o.headers.get("ETag")??void 0}}var Kr="fork:manifest:v1";function gt(e,t,r){return `${Kr}:${e}:${t}:${r}`}function Gr(e,t,r){if(typeof window>"u")return null;try{let n=window.localStorage.getItem(gt(e,t,r));return n?JSON.parse(n):null}catch{return null}}function Vr(e,t,r,n){if(!(typeof window>"u"))try{window.localStorage.setItem(gt(e,t,r),JSON.stringify(n));}catch{}}function qr(e,t,r){if(!(typeof window>"u"))try{window.localStorage.removeItem(gt(e,t,r));}catch{}}function Jr(e,t){if(!e||!t)return e!==t;if(e.containerId!==t.containerId)return true;let r=Object.entries(e.slots),n=Object.entries(t.slots);if(r.length!==n.length)return true;for(let[s,a]of r){let d=t.slots[s];if(!d||d.forkId!==a.forkId||d.buildId!==a.buildId)return true}let o=Object.entries(e.modules),i=Object.entries(t.modules);if(o.length!==i.length)return true;for(let[s,a]of o){let d=t.modules[s];if(!d||d.forkId!==a.forkId||d.buildId!==a.buildId)return true}return false}var Gt=ht.createContext(null);function xe(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function Zr(e,t){let r={};for(let[n,o]of Object.entries(t.boundaries||{}))r[n]={...o,moduleUrl:xe(e,o.moduleUrl),cssUrls:Array.isArray(o.cssUrls)?o.cssUrls.map(i=>xe(e,i)):[]};return r}function Wt(e,t,r,n){let o={};for(let[i,s]of Object.entries(t.slots)){let a=s.bundleUrl??s.legacyBundleUrl;a&&(o[i]={id:s.forkId,userId:r,prompt:"",status:"complete",slotId:i,appId:n,bundleUrl:xe(e,a),createdAt:s.updatedAt,completedAt:s.updatedAt});}return o}function Kt(e,t){let r={};for(let[n,o]of Object.entries(t.modules)){let i=o.moduleUrl??o.legacyModuleUrl??o.bundleUrl??"";i&&(r[n]={id:o.forkId,boundaryId:n,moduleUrl:xe(e,i),cssUrls:(o.cssUrls??[]).map(s=>xe(e,s)),integrity:o.integrity,metadata:o.metadata,createdAt:o.updatedAt});}return r}function Qr(e){let{apiKey:t,baseUrl:r,children:n,appId:o,shared:i}=e,s="userId"in e?e.userId:void 0,a="authUrl"in e?e.authUrl:void 0,[d]=ht.useState(()=>(we(t),ft(t))),[f,c]=ht.useState({}),[F,P]=ht.useState(s?{userId:s,userHash:void 0}:null),[x,v]=ht.useState(!!s||d),[y,h]=ht.useState({}),[C,R]=ht.useState(!o),[T,$]=ht.useState(0),[M,w]=ht.useState(null),k=ht.useRef(new Map),l=ht.useRef(new Map),[E,S]=ht.useState(0),u=ht.useRef(new Set),p=ht.useRef(new Map),g=ht.useRef(void 0);it(),ht.useEffect(()=>{return pt(t,r).then(()=>{}),()=>{}},[]);let I=Be();i&&g.current!==i&&(at(i),g.current=i),ht.useEffect(()=>{a&&(d||(v(false),fetch(a,{credentials:"include"}).then(_=>{if(!_.ok)throw new Error(`Auth endpoint returned ${_.status}`);return _.json()}).then(_=>{if(!_.userId||typeof _.userId!="string")throw new Error("authUrl response must include userId");P({userId:_.userId,userHash:_.userHash});}).catch(_=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",_.message);}).finally(()=>{v(true);})));},[a,d]),ht.useEffect(()=>{!a&&s&&(P({userId:s,userHash:void 0}),v(true));},[s,a]);let z=F?.userId??"",Y=F?.userHash,H=I?I.target_user_id:z,D=I?void 0:Y,V=!!o,N=ht.useCallback(async()=>{if(!V){w(null),h({}),R(true),$(b=>b+1);return}if(!x){R(false);return}if(!H||!o){w(null),h({}),R(true),$(b=>b+1);return}if(R(false),!I){try{let b=await He({baseUrl:r,apiKey:t,appId:o,userId:H,userHash:D});b&&(w(b.containerId),c(Wt(r,b,H,o)),h(Kt(r,b)));}catch(b){console.error("[ForkProvider] Failed to fetch fork manifest:",b.message),w(null),c({}),h({});}finally{$(b=>b+1),R(true);}return}if(w(I.container_id??null),I.container_id){try{let b=await He({baseUrl:r,apiKey:t,appId:o,userId:H,containerId:I.container_id,extraHeaders:Z()});b&&(c(Wt(r,b,H,o)),h(Kt(r,b)));}catch(b){console.error("[ForkProvider] Failed to fetch preview container manifest:",b.message),c({}),h({});}finally{$(b=>b+1),R(true);}return}let _=new URLSearchParams({appId:o,userId:H});D&&_.set("userHash",D);try{let b=await fetch(`${r}/api/v1/boundaries/manifest?${_.toString()}`,{headers:{Authorization:`Bearer ${t}`,...Z()}});if(!b.ok)throw new Error(`${b.status}`);let O=await b.json();h(Zr(r,O));}catch(b){console.error("[ForkProvider] Failed to fetch module override manifest:",b.message),h({});}finally{$(b=>b+1),R(true);}},[t,o,r,x,V,D,H,I?.preview_session_id,I?.fork_id,I?.container_id]);ht.useEffect(()=>{if(!H||o&&(!I||I.container_id))return;let _=new URLSearchParams({userId:H});D&&_.set("userHash",D),fetch(`${r}/api/v1/forks/active?${_.toString()}`,{headers:{Authorization:`Bearer ${t}`,...Z()}}).then(b=>{if(!b.ok)throw new Error(`${b.status}`);return b.json()}).then(b=>{b&&typeof b=="object"&&c(b);}).catch(()=>{});},[t,o,H,D,r,I?.preview_session_id,I?.fork_id]),ht.useEffect(()=>{N();},[N]);let Q=ht.useCallback((_,b)=>{c(O=>({...O,[_]:b}));},[]),ee=ht.useCallback(_=>{c(b=>{let O={...b};return delete O[_],O});},[]),ie=ht.useCallback(_=>{u.current.add(_);},[]),q=ht.useCallback(_=>u.current.has(_)?(u.current.delete(_),true):false,[]),Qe=ht.useCallback((_,b)=>{p.current.set(_,b);},[]),_e=ht.useCallback((_,b)=>p.current.get(_)!==b?false:(p.current.delete(_),true),[]),ke=ht.useCallback(_=>{if(!o)return;let b=JSON.stringify(_);k.current.get(_.id)===b||l.current.get(_.id)?.signature===b||(l.current.set(_.id,{boundary:_,signature:b}),S(W=>W+1));},[o]);ht.useEffect(()=>{if(!o||l.current.size===0)return;let _=setTimeout(()=>{let b=Array.from(l.current.values());b.length!==0&&fetch(`${r}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:o,boundaries:b.map(O=>O.boundary)})}).then(O=>{if(!O.ok)throw new Error(`${O.status}`)}).then(()=>{for(let O of b)l.current.get(O.boundary.id)?.signature===O.signature&&(l.current.delete(O.boundary.id),k.current.set(O.boundary.id,O.signature));}).catch(O=>{console.error("[ForkProvider] Failed to register module boundaries:",O.message);});},50);return ()=>{clearTimeout(_);}},[t,o,r,E]);let be=ht.useCallback(_=>y[_],[y]),J=ht.useCallback(async()=>{if(!H)throw new Error("Reset requires a resolved user identity.");let _=new URLSearchParams({userId:H});D&&_.set("userHash",D);let b=await fetch(`${r}/api/v1/forks/all?${_.toString()}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`,...Z()}});if(!b.ok){let W=await b.json().catch(()=>({}));throw new Error(W.error||`API error: ${b.status}`)}let O=await b.json().catch(()=>({}));c({}),h({}),R(true),$(W=>W+1),u.current.clear(),p.current.clear();try{for(let W=sessionStorage.length-1;W>=0;W-=1){let ae=sessionStorage.key(W);ae&&ae.startsWith("__fork_animated_")&&sessionStorage.removeItem(ae);}}catch{}return O},[t,r,D,H]);return Br.jsx(Gt.Provider,{value:{apiKey:t,userId:H,userHash:D,baseUrl:r,appId:o,forks:f,moduleOverridesEnabled:V,moduleManifestReady:C,moduleManifestVersion:T,currentContainerId:M,previewSession:I,setSlotFork:Q,clearSlotFork:ee,skipAnimationForSlot:ie,shouldSkipAnimation:q,queueBoundaryAnimation:Qe,consumeBoundaryAnimation:_e,registerBoundary:ke,getBoundaryOverride:be,refreshModuleManifest:N,resetAllForks:J},children:n})}function G(){let e=ht.useContext(Gt);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function Ne(e){return G().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 n=this.values.get(t);if(Object.is(n,r))return;if(n!==void 0&&r!==null&&n!==null&&typeof n=="object"&&typeof r=="object")try{if(JSON.stringify(n)===JSON.stringify(r))return}catch{}this.values.set(t,r),this.snapshots.set(t,r);let o=this.listeners.get(t);o&&o.forEach(i=>i());}get(t){return this.values.get(t)}getSnapshot(t){return this.snapshots.get(t)}subscribe(t,r){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(r),()=>{this.listeners.get(t)?.delete(r);}}useValue(t){let r=window.__FORK_REACT__;return r?.useSyncExternalStore?r.useSyncExternalStore(n=>this.subscribe(t,n),()=>this.getSnapshot(t)):(console.warn("[ForkBridge] React.useSyncExternalStore not available, returning static value"),this.values.get(t))}emit(t,...r){let n=this.eventHandlers.get(t);n&&n.forEach(o=>o(...r));}on(t,r){return this.eventHandlers.has(t)||this.eventHandlers.set(t,new Set),this.eventHandlers.get(t).add(r),()=>{this.eventHandlers.get(t)?.delete(r);}}destroy(){this.listeners.clear(),this.eventHandlers.clear(),this.values.clear(),this.snapshots.clear();let t=window.__FORK_BRIDGE__;t&&delete t[this.slotId];}};function yt(e,t){let r;try{r=ht.Children.only(e);}catch{let o=ht.Children.count(e);throw new Error(`<ForkSlot slotId="${t}"> must wrap exactly one React component, got ${o} children. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`)}let n=r.type;if(typeof n=="string")throw new Error(`<ForkSlot slotId="${t}"> child must be a React component (function or class), not an HTML element <${n}>. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`);if(typeof n=="symbol")throw new Error(`<ForkSlot slotId="${t}"> child must be a single React component, not a fragment or special React element. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`);return r}var qt=new Set;function Jt(e){let t=[],r=e.querySelectorAll("*");for(let n of r){if(!(n instanceof HTMLElement))continue;let o=n.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(n.tagName))continue;let i=getComputedStyle(n),s=parseFloat(i.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:s});}return t}function on(e,t){let r=[];for(let n of t)if(!e.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)&&!r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom)){for(let s=r.length-1;s>=0;s--){let a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function sn(e,t){let r=[];for(let n of e)if(!t.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)&&!r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom)){for(let s=r.length-1;s>=0;s--){let a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Yt(e,t,r,n,o){return o=Math.max(0,Math.min(o,r/2,n/2)),o===0?`M ${e} ${t} L ${e+r} ${t} L ${e+r} ${t+n} L ${e} ${t+n} Z`:[`M ${e+o} ${t}`,`L ${e+r-o} ${t}`,`A ${o} ${o} 0 0 1 ${e+r} ${t+o}`,`L ${e+r} ${t+n-o}`,`A ${o} ${o} 0 0 1 ${e+r-o} ${t+n}`,`L ${e+o} ${t+n}`,`A ${o} ${o} 0 0 1 ${e} ${t+n-o}`,`L ${e} ${t+o}`,`A ${o} ${o} 0 0 1 ${e+o} ${t}`,"Z"].join(" ")}function Xt(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-highlights","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");n.appendChild(o);let i=[];for(let c=0;c<e.length;c++){let{rect:F,borderRadius:P}=e[c],x=F.left-.5,v=F.top-.5,y=F.width+1,h=F.height+1,C=Math.min(P+.5,y/2,h/2),R=Yt(x,v,y,h,C),T=`__fork-glow-${c}`,$=document.createElementNS(t,"filter");$.setAttribute("id",T),$.setAttribute("x","-100%"),$.setAttribute("y","-100%"),$.setAttribute("width","300%"),$.setAttribute("height","300%");let M=document.createElementNS(t,"feGaussianBlur");M.setAttribute("in","SourceGraphic"),M.setAttribute("stdDeviation","8"),$.appendChild(M),o.appendChild($);let w=`__fork-mask-${c}`,k=document.createElementNS(t,"mask");k.setAttribute("id",w),k.setAttribute("maskUnits","userSpaceOnUse"),k.setAttribute("x",String(x-200)),k.setAttribute("y",String(v-200)),k.setAttribute("width",String(y+400)),k.setAttribute("height",String(h+400));let l=document.createElementNS(t,"rect");l.setAttribute("x",String(x-200)),l.setAttribute("y",String(v-200)),l.setAttribute("width",String(y+400)),l.setAttribute("height",String(h+400)),l.setAttribute("fill","white"),k.appendChild(l);let E=document.createElementNS(t,"path");E.setAttribute("d",R),E.setAttribute("fill","black"),k.appendChild(E),o.appendChild(k);let S=document.createElementNS(t,"g");S.setAttribute("mask",`url(#${w})`),S.setAttribute("opacity","0");let u=document.createElementNS(t,"g");u.setAttribute("filter",`url(#${T})`);let p=document.createElementNS(t,"path");p.setAttribute("d",R),p.setAttribute("fill","none"),p.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),p.setAttribute("stroke-width","6"),p.setAttribute("stroke-linecap","round"),u.appendChild(p),S.appendChild(u),n.appendChild(S);let g=document.createElementNS(t,"path");g.setAttribute("d",R),g.setAttribute("fill","none"),g.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),g.setAttribute("stroke-width","2"),g.setAttribute("stroke-linecap","round"),g.setAttribute("opacity","0"),n.appendChild(g),i.push(p,g),p.__group=S;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let c=0;c<i.length;c+=2){let F=i[c],P=i[c+1],x=F.__group,v=P.getTotalLength(),y=F.getTotalLength();if(v<=0)continue;let h=v*.35;P.setAttribute("stroke-dasharray",`${h} ${v-h}`),P.setAttribute("stroke-dashoffset","0"),s.push(P.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*v,opacity:.92,offset:.06},{strokeDashoffset:-2*v,opacity:.92,offset:.92},{strokeDashoffset:-2.25*v,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let C=y*.35;F.setAttribute("stroke-dasharray",`${C} ${y-C}`),F.setAttribute("stroke-dashoffset","0"),s.push(F.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*y,offset:.06},{strokeDashoffset:-2*y,offset:.92},{strokeDashoffset:-2.25*y,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(x.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,d=()=>{if(a)return;a=true,clearTimeout(f);for(let F of s)try{F.cancel();}catch{}let c=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});c.onfinish=()=>r.remove(),window.removeEventListener("click",d);},f=setTimeout(d,14500);return setTimeout(()=>{a||window.addEventListener("click",d);},500),d}function an(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-removed","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs"),i=document.createElementNS(t,"filter");i.setAttribute("id","__fork-removed-shadow"),i.setAttribute("x","-10%"),i.setAttribute("y","-10%"),i.setAttribute("width","120%"),i.setAttribute("height","120%");let s=document.createElementNS(t,"feDropShadow");s.setAttribute("dx","0"),s.setAttribute("dy","1"),s.setAttribute("stdDeviation","2"),s.setAttribute("flood-color","rgba(0,0,0,0.15)"),i.appendChild(s),o.appendChild(i),n.appendChild(o);for(let{rect:a,borderRadius:d}of e){let f=a.left,c=a.top,F=a.width,P=a.height,x=Math.min(d,F/2,P/2),v=Yt(f,c,F,P,x),y=document.createElementNS(t,"path");y.setAttribute("d",v),y.setAttribute("fill","none"),y.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),y.setAttribute("stroke-width","1.5"),y.setAttribute("stroke-dasharray","8 4"),y.setAttribute("stroke-linecap","round"),y.setAttribute("filter","url(#__fork-removed-shadow)"),y.setAttribute("opacity","0"),n.appendChild(y),y.animate([{opacity:0,offset:0},{opacity:.6,offset:.08},{opacity:.05,offset:.45},{opacity:.6,offset:.85},{opacity:.05,offset:1}],{duration:5e3,easing:"ease-in-out",fill:"forwards"});}return r.appendChild(n),document.body.appendChild(r),r}function ln(e,t){if(e===t)return true;let r=Object.keys(e);if(r.length!==Object.keys(t).length)return false;for(let n of r)if(!Object.is(e[n],t[n]))return false;return true}var cn=ht__namespace.default.memo(function({component:t,containerRef:r,wrapperStyle:n,hostProps:o}){return Br.jsx("div",{ref:r,style:n,children:Br.jsx(t,{...o})})},(e,t)=>e.component===t.component&&ln(e.hostProps,t.hostProps)),mt=class extends ht__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 Zt({slotId:e,children:t,githubRepo:r,shared:n,events:o}){yt(t,e);let i=Ne(e),{baseUrl:s,apiKey:a,appId:d,shouldSkipAnimation:f}=G(),[c,F]=ht.useState(null),P=ht.useRef(null),x=ht.useRef(null),v=ht.useRef(null),y=ht.useRef(false),h=ht.useRef(null),C=ht.useRef(null),R=!!(n||o),T=ht.useRef(null);R&&!T.current&&(T.current=new Fe(e));let $=ht.useRef(o);if($.current=o,ht.useEffect(()=>{if(R)return ()=>{T.current?.destroy(),T.current=null;}},[R,e]),R&&T.current&&n)for(let[E,S]of Object.entries(n))T.current.set(E,S);ht.useEffect(()=>{if(!R)return;T.current||(T.current=new Fe(e));let E=T.current,S=Object.keys($.current||{}).map(u=>E.on(u,(...p)=>$.current?.[u]?.(...p)));return ()=>S.forEach(u=>u())},[R,e]),ht.useEffect(()=>{if(qt.has(e))return;qt.add(e);let E={id:e,appId:d,label:e,eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:r,mode:"direct",sharedKeys:n?Object.keys(n):[],eventNames:o?Object.keys(o):[],propsShape:"",callbackNames:[]};fetch(`${s}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify(E)}).catch(()=>{});},[e,s,a,r,d]);let M=i?.id||null;ht.useEffect(()=>{if(i?.bundleUrl,P.current,x.current,!i?.bundleUrl||!M){return}let E=`${s}${i.bundleUrl.replace("bundle.js","component.js")}`,S=`__fork_animated_${e}`,u=sessionStorage.getItem(S),p=f(e),g=!p&&u!==M;if(p&&M&&sessionStorage.setItem(S,M),g&&x.current){let D=Jt(x.current);v.current=D,y.current=true,`${e}${D.length}`;}window.__FORK_REACT__=ht__namespace.default,window.__FORK_REACT_DOM__=Or__namespace,window.__FORK_REACT_JSX__=Br__namespace;let I=Date.now(),z=`${s}${i.bundleUrl.replace("bundle.js","component.css")}?t=${I}`,Y=document.createElement("link");Y.rel="stylesheet",Y.href=z,Y.dataset.forkSlot=e,document.head.appendChild(Y);let H=document.createElement("script");return H.src=E+"?t="+I,H.onload=()=>{let D=window.__FORK_EXPORT__;if(D?.default){if(x.current&&v.current&&y.current){let V=x.current.getBoundingClientRect(),N=x.current.cloneNode(true);N.style.position="fixed",N.style.top=`${V.top}px`,N.style.left=`${V.left}px`,N.style.width=`${V.width}px`,N.style.height=`${V.height}px`,N.style.flex="none",N.style.minHeight="auto",N.style.zIndex="9998",N.style.pointerEvents="none",N.style.overflow="hidden";let Q=getComputedStyle(x.current).backgroundColor;N.style.backgroundColor=Q&&Q!=="rgba(0, 0, 0, 0)"&&Q!=="transparent"?Q:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(N);let ee=x.current.querySelectorAll("*"),ie=N.querySelectorAll("*");for(let q=0;q<ee.length;q++)ee[q].scrollTop!==0&&(ie[q].scrollTop=ee[q].scrollTop),ee[q].scrollLeft!==0&&(ie[q].scrollLeft=ee[q].scrollLeft);h.current=N;}F(()=>D.default),P.current=M;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},H.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(H),()=>{H.remove(),Y.remove(),C.current&&(clearTimeout(C.current),C.current=null),h.current&&(h.current.remove(),h.current=null);}},[M,s,e]),ht.useEffect(()=>{if(!y.current||!c||!x.current){`${e}${y.current}`,x.current;return}let E=v.current;if(!E){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!x.current)return;let S=Jt(x.current),u=on(E,S),p=sn(E,S),g=h.current;if(`${e}${u.length}${p.length}`,p.length>0&&g){let I=an(p);C.current=setTimeout(()=>{C.current=null;let z=400;g.animate([{opacity:1},{opacity:0}],{duration:z,fill:"forwards"}),I.animate([{opacity:1},{opacity:0}],{duration:z,fill:"forwards"}),setTimeout(()=>{g.remove(),I.remove(),h.current=null,u.length>0&&(Xt(u));},z);},3500);}else g&&(g.remove(),h.current=null),u.length>0&&(Xt(u));v.current=null,y.current=false,M&&(sessionStorage.setItem(`__fork_animated_${e}`,M),`${e}`);});});},[c]);let w={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!i||i.status!=="complete"||!i.bundleUrl)return Br.jsx("div",{ref:x,style:w,children:t});if(!c)return Br.jsx("div",{ref:x,style:w,children:t});let l=t?.props??{};return Br.jsx(mt,{slotId:e,resetKey:M,fallback:Br.jsx("div",{ref:x,style:w,children:t}),children:Br.jsx(cn,{component:c,containerRef:x,wrapperStyle:w,hostProps:l})})}var er=new Set;function fn(e){return `{ ${Object.entries(e).map(([r,n])=>n==null?`${r}: unknown`:Array.isArray(n)?`${r}: ${n.length>0?typeof n[0]:"unknown"}[]`:`${r}: ${typeof n}`).join("; ")} }`}function tr(e,t=new Set){return ht.Children.forEach(e,r=>{if(!ht.isValidElement(r))return;let n=r.props;for(let[o,i]of Object.entries(n))typeof i=="function"&&/^on[A-Z]/.test(o)&&t.add(o);n.children&&tr(n.children,t);}),t}function pn({slotId:e,props:t,children:r,allowedFetches:n,githubRepo:o,callbacks:i,mode:s="iframe",shared:a,events:d}){if(yt(r,e),s==="direct")return Br.jsx(Zt,{slotId:e,githubRepo:o,shared:a,events:d,children:r});let f=Ne(e),{baseUrl:c,apiKey:F,appId:P}=G(),x=ht.useRef(null),v=ht.useRef(false),y=ht.useRef(null),h=ht.useRef(i);h.current=i;let C=ht.useRef(t);C.current=t;let R=ht.useRef(n);R.current=n,ht.useEffect(()=>{if(typeof process<"u")return;let w=tr(r),k=new Set(i?Object.keys(i):[]),l=[...w].filter(E=>!k.has(E));l.length>0&&console.error(`[ForkSlot:${e}] Missing bridged callbacks! The following callback props are used by children but not passed to ForkSlot's \`callbacks\` prop:
2
- `+l.map(E=>` - ${E}`).join(`
3
- `)+"\n\nThe forked component will not be able to call these. Add them to the `callbacks` prop of <ForkSlot>.");},[e,r,i]),ht.useEffect(()=>{er.has(e)||(er.add(e),fetch(`${c}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${F}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:P,label:e,propsShape:t?fn(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:o,callbackNames:i?Object.keys(i):[],mode:s||"iframe"})}).catch(()=>{}));},[e,c,F,o,P]);let T=ht.useCallback(w=>{let k=x.current;if(k?.contentWindow&&v.current){let l=h.current?Object.keys(h.current):[];k.contentWindow.postMessage({type:"slot:props",props:w,callbackNames:l},"*"),y.current=null;}else y.current=w;},[]),$=ht.useCallback((w,k)=>{let l=R.current;return !l||l.length===0?false:l.some(E=>{let[S,u]=E.split(" "),p=k.split("?")[0];return w.toUpperCase()===S.toUpperCase()&&p.startsWith(u)})},[]);if(ht.useEffect(()=>{if(!f?.bundleUrl)return;let w=async k=>{if(k.source===x.current?.contentWindow){if(k.data?.type==="slot:ready")v.current=true,x.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:R.current||[]},"*"),R.current,y.current?T(y.current):T(C.current||{});else if(k.data?.type==="slot:event"){let l=k.data.event;l?.navigate&&(window.location.hash=l.navigate);}else if(k.data?.type==="slot:clipboard-write")navigator.clipboard.writeText(k.data.text).catch(l=>{console.warn(`[ForkSlot:${e}] clipboard write failed:`,l.message);});else if(k.data?.type==="slot:callback"){let{name:l,args:E}=k.data,S=h.current?.[l];S?(S(...E||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${l}`);}else if(k.data?.type==="slot:fetch"){let{id:l,method:E,url:S,body:u}=k.data,p=x.current?.contentWindow;if(!p)return;let g=E||"GET";if(!$(g,S)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${l}: ${g} ${S} \u2014 not in allowedFetches`),p.postMessage({type:"slot:fetch-response",id:l,error:`Fetch not allowed: ${g} ${S}`},"*");return}try{let I={method:g};u&&g!=="GET"&&(I.headers={"Content-Type":"application/json"},I.body=JSON.stringify(u));let z=await fetch(S,I),Y=await z.json();`${e}${l}${z.status}`,p.postMessage({type:"slot:fetch-response",id:l,data:Y,status:z.status},"*");}catch(I){console.error(`[ForkSlot:${e}] fetch #${l} failed:`,I.message),p.postMessage({type:"slot:fetch-response",id:l,error:I.message},"*");}}}};return window.addEventListener("message",w),()=>{window.removeEventListener("message",w),v.current=false;}},[f?.bundleUrl,e,T,$]),ht.useEffect(()=>{f?.bundleUrl&&v.current&&T(t||{});},[t,f?.bundleUrl,T]),!f||f.status!=="complete"||!f.bundleUrl)return `${e}${f?.status||"none"}${f?.bundleUrl||"none"}`,Br.jsx(Br.Fragment,{children:r});`${e}${f.bundleUrl}`;let M=`${c}${f.bundleUrl.replace("/bundle.js","/host")}`;return Br.jsx("iframe",{ref:x,src:M,sandbox:"allow-scripts allow-same-origin allow-forms allow-clipboard-write",title:`Forked ${e}`,style:{width:"100%",border:"none",flex:1,minHeight:0}})}function je({style:e={width:20,height:20},...t}){return Br.jsxs("svg",{viewBox:"320 95 270 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:e,...t,children:[Br.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"}),Br.jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M387.096 174.735v188"}),Br.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"}),Br.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"}),Br.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 bt({onClick:e}){let[t,r]=ht.useState(false),[n,o]=ht.useState(false),i=t?48:40;return Br.jsx("button",{onClick:e,onMouseEnter:()=>r(true),onMouseLeave:()=>{r(false),o(false);},onMouseDown:()=>o(true),onMouseUp:()=>o(false),style:{position:"fixed",bottom:24,right:24,zIndex:40,width:i,height:i,borderRadius:"50%",backgroundColor:t?"rgba(255, 255, 255, 1)":"rgba(255, 255, 255, 0.3)",border:t?"1px solid rgba(156, 163, 175, 1)":"1px solid rgba(156, 163, 175, 0.3)",display:"flex",alignItems:"center",justifyContent:"center",color:t?"#1c4587":"rgba(28, 69, 135, 0.5)",boxShadow:t?"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1)":"0 1px 2px 0 rgba(0, 0, 0, 0.05)",transform:n?"scale(0.95)":"scale(1)",transition:"all 300ms",cursor:"pointer",padding:0,margin:0,outline:"none",boxSizing:"border-box"},title:"Fork this app",children:Br.jsx(je,{style:{width:24,height:24}})})}var xn={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},Fn={status:"#60a5fa",agent_message:"#a0a0a0",tool_use:"#fbbf24",build_start:"#c084fc",build_complete:"#6b7280",build_error:"#f87171",complete:"#6b7280",error:"#f87171"},Rn={read:lucideReact.FileSearch,write:lucideReact.Pencil,search:lucideReact.FileSearch,shell:lucideReact.Terminal,build:lucideReact.Package},En={read:"#60a5fa",write:"#fbbf24",search:"#60a5fa",shell:"#a78bfa",build:"#c084fc"};function vt(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 cr({events:e}){let t=ht.useRef(null);return ht.useEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight);},[e]),Br.jsxs(Br.Fragment,{children:[Br.jsx("style",{children:`
1
+ 'use strict';var xt=require('react'),Xr=require('react-dom'),Yr=require('react/jsx-runtime'),Zr=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 xt__namespace=/*#__PURE__*/_interopNamespace(xt);var Xr__namespace=/*#__PURE__*/_interopNamespace(Xr);var Yr__namespace=/*#__PURE__*/_interopNamespace(Yr);var Zr__namespace=/*#__PURE__*/_interopNamespace(Zr);var me="__FORK_SHARED__";function ft(){var t,r,n,o;let e=globalThis;return e[me]||(e[me]={}),(t=e[me]).react||(t.react=xt__namespace),(r=e[me])["react-dom"]||(r["react-dom"]=Xr__namespace),(n=e[me])["react/jsx-runtime"]||(n["react/jsx-runtime"]=Yr__namespace),(o=e[me])["react/jsx-dev-runtime"]||(o["react/jsx-dev-runtime"]=Zr__namespace),e[me]}function pt(e){return Object.assign(ft(),e)}var Qr="__fork_preview_session__";function ze(e){return `${Qr}${e}`}var H={apiKey:null,session:null},gt=new Set;function We(){for(let e of gt)try{e();}catch(t){console.error("[fork-preview] subscriber threw",t);}}function Jt(e){let t=Date.parse(e.expires_at);return Number.isFinite(t)?t<=Date.now():true}function en(e){if(typeof window>"u")return null;try{let t=window.sessionStorage.getItem(ze(e));if(!t)return null;let r=JSON.parse(t);return !r||typeof r!="object"||typeof r.preview_session_id!="string"?null:Jt(r)?(window.sessionStorage.removeItem(ze(e)),null):r}catch{return null}}function mt(e,t){if(!(typeof window>"u"))try{t?window.sessionStorage.setItem(ze(e),JSON.stringify(t)):window.sessionStorage.removeItem(ze(e));}catch{}}function Ee(e){H.apiKey!==e&&(H.apiKey=e,H.session=en(e),We());}function he(){return H.session?Jt(H.session)?(ht(null),null):H.session:null}function ht(e){H.session=e,H.apiKey&&mt(H.apiKey,e),We();}function _e(e){H.session&&H.session.fork_id!==e&&(H.session={...H.session,fork_id:e},H.apiKey&&mt(H.apiKey,H.session),We());}function yt(e,t){H.session&&(H.session.container_id===e&&H.session.container_name===t||(H.session={...H.session,container_id:e,container_name:t??H.session.container_name??H.session.target_user_id,fork_id:null},H.apiKey&&mt(H.apiKey,H.session),We()));}function kt(e){return gt.add(e),()=>{gt.delete(e);}}var qt="__fork_preview";function Xt(){if(typeof window>"u")return null;let e=window.location.hash;if(!e||e.length<2)return null;let r=new URLSearchParams(e.slice(1)).get(qt);return typeof r=="string"&&r.length>0?r:null}function bt(e){if(typeof window>"u")return false;try{if(window.sessionStorage.getItem(`__fork_preview_session__${e}`))return !0}catch{}return Zt()!==null}function Yt(){if(typeof window>"u")return;let e=window.location.hash;if(!e||e.length<2)return;let t=new URLSearchParams(e.slice(1));t.delete(qt);let r=t.toString(),n=r?`#${r}`:"";try{window.history.replaceState(null,"",window.location.pathname+window.location.search+n);}catch{}}var ye=null;function Zt(){if(ye)return ye;let e=Xt();return e?(ye=e,Yt(),ye):null}async function wt(e,t){Ee(e);let r=he();if(r)return ye=null,r;let n=ye??Xt();if(ye=null,!n)return null;Yt();try{let o=await fetch(`${t}/api/v1/preview/activate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({token:n})});if(!o.ok){let a=await o.json().catch(()=>({}));return console.warn(`[fork-preview] activate failed (${o.status}): ${a.error??"unknown"}`),null}let i=await o.json(),s={preview_session_id:i.preview_session_id,tenant_id:i.tenant_id,app_id:i.app_id,target:i.target,target_user_id:i.target_user_id,operator_id:i.operator_id,container_id:i.container_id??null,container_name:i.container_name??i.target_user_id,fork_id:i.fork_id??null,expires_at:i.expires_at};return ht(s),s}catch(o){return console.warn("[fork-preview] activate threw",o),null}}function rn(){return he()}function nn(){return null}function Ke(){return xt.useSyncExternalStore(kt,rn,nn)}function G(){let e=he();if(!e)return {};let t={"X-Fork-Preview-Session":e.preview_session_id};return e.fork_id&&(t["X-Fork-Preview-Fork-Id"]=e.fork_id),t}async function Ge(e){let t=new URLSearchParams({app:e.appId,user:e.userId});e.containerId&&t.set("containerId",e.containerId);let r=`${e.baseUrl}/api/v1/manifest?${t.toString()}`,n={Authorization:`Bearer ${e.apiKey}`,"X-Fork-App-Id":e.appId,"X-Fork-User-Id":e.userId,...e.extraHeaders??{}};e.userHash&&(n["X-Fork-User-Hash"]=e.userHash),e.previous?.etag&&(n["If-None-Match"]=e.previous.etag);let o=await fetch(r,{headers:n,signal:e.signal});if(o.status===304)return null;if(!o.ok)throw new Error(`manifest ${o.status} ${o.statusText}`);let i=await o.json(),s={};for(let[a,f]of Object.entries(i.modules)){let p=f.moduleUrl??f.bundleUrl??null,d=f.legacyModuleUrl??f.legacyBundleUrl??null;s[a]={forkId:f.forkId,moduleUrl:p,legacyModuleUrl:d,bundleUrl:f.bundleUrl??p,legacyBundleUrl:f.legacyBundleUrl??d,cssUrls:f.cssUrls??[],integrity:f.integrity,metadata:f.metadata,buildId:f.buildId,updatedAt:f.updatedAt};}return {containerId:i.containerId,slots:i.slots,modules:s,generatedAt:i.generatedAt,etag:o.headers.get("ETag")??void 0}}var on="fork:manifest:v1";function vt(e,t,r){return `${on}:${e}:${t}:${r}`}function sn(e,t,r){if(typeof window>"u")return null;try{let n=window.localStorage.getItem(vt(e,t,r));return n?JSON.parse(n):null}catch{return null}}function an(e,t,r,n){if(!(typeof window>"u"))try{window.localStorage.setItem(vt(e,t,r),JSON.stringify(n));}catch{}}function ln(e,t,r){if(!(typeof window>"u"))try{window.localStorage.removeItem(vt(e,t,r));}catch{}}function cn(e,t){if(!e||!t)return e!==t;if(e.containerId!==t.containerId)return true;let r=Object.entries(e.slots),n=Object.entries(t.slots);if(r.length!==n.length)return true;for(let[s,a]of r){let f=t.slots[s];if(!f||f.forkId!==a.forkId||f.buildId!==a.buildId)return true}let o=Object.entries(e.modules),i=Object.entries(t.modules);if(o.length!==i.length)return true;for(let[s,a]of o){let f=t.modules[s];if(!f||f.forkId!==a.forkId||f.buildId!==a.buildId)return true}return false}var tr=xt.createContext(null);function Ae(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function fn(e,t){let r={};for(let[n,o]of Object.entries(t.boundaries||{}))r[n]={...o,moduleUrl:Ae(e,o.moduleUrl),cssUrls:Array.isArray(o.cssUrls)?o.cssUrls.map(i=>Ae(e,i)):[]};return r}function Qt(e,t,r,n){let o={};for(let[i,s]of Object.entries(t.slots)){let a=s.bundleUrl??s.legacyBundleUrl;a&&(o[i]={id:s.forkId,userId:r,prompt:"",status:"complete",slotId:i,appId:n,bundleUrl:Ae(e,a),createdAt:s.updatedAt,completedAt:s.updatedAt});}return o}function er(e,t){let r={};for(let[n,o]of Object.entries(t.modules)){let i=o.moduleUrl??o.legacyModuleUrl??o.bundleUrl??"";i&&(r[n]={id:o.forkId,boundaryId:n,moduleUrl:Ae(e,i),cssUrls:(o.cssUrls??[]).map(s=>Ae(e,s)),integrity:o.integrity,metadata:o.metadata,createdAt:o.updatedAt});}return r}function pn(e){let{apiKey:t,baseUrl:r,children:n,appId:o,shared:i}=e,s="userId"in e?e.userId:void 0,a="authUrl"in e?e.authUrl:void 0,[f]=xt.useState(()=>(Ee(t),bt(t))),[p,d]=xt.useState({}),[S,P]=xt.useState(s?{userId:s,userHash:void 0}:null),[R,x]=xt.useState(!!s||f),[y,h]=xt.useState({}),[T,_]=xt.useState(!o),[M,$]=xt.useState(0),[I,v]=xt.useState(null),k=xt.useRef(new Map),l=xt.useRef(new Map),[A,F]=xt.useState(0),u=xt.useRef(new Set),g=xt.useRef(new Map),m=xt.useRef(void 0);ft(),xt.useEffect(()=>{return wt(t,r).then(()=>{}),()=>{}},[]);let L=Ke();i&&m.current!==i&&(pt(i),m.current=i),xt.useEffect(()=>{a&&(f||(x(false),fetch(a,{credentials:"include"}).then(E=>{if(!E.ok)throw new Error(`Auth endpoint returned ${E.status}`);return E.json()}).then(E=>{if(!E.userId||typeof E.userId!="string")throw new Error("authUrl response must include userId");P({userId:E.userId,userHash:E.userHash});}).catch(E=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",E.message);}).finally(()=>{x(true);})));},[a,f]),xt.useEffect(()=>{!a&&s&&(P({userId:s,userHash:void 0}),x(true));},[s,a]);let W=S?.userId??"",ee=S?.userHash,N=L?L.target_user_id:W,z=L?void 0:ee,J=!!o,D=xt.useCallback(async()=>{if(!J){v(null),h({}),_(true),$(w=>w+1);return}if(!R){_(false);return}if(!N||!o){v(null),h({}),_(true),$(w=>w+1);return}if(_(false),!L){try{let w=await Ge({baseUrl:r,apiKey:t,appId:o,userId:N,userHash:z});w&&(v(w.containerId),d(Qt(r,w,N,o)),h(er(r,w)));}catch(w){console.error("[ForkProvider] Failed to fetch fork manifest:",w.message),v(null),d({}),h({});}finally{$(w=>w+1),_(true);}return}if(v(L.container_id??null),L.container_id){try{let w=await Ge({baseUrl:r,apiKey:t,appId:o,userId:N,containerId:L.container_id,extraHeaders:G()});w&&(d(Qt(r,w,N,o)),h(er(r,w)));}catch(w){console.error("[ForkProvider] Failed to fetch preview container manifest:",w.message),d({}),h({});}finally{$(w=>w+1),_(true);}return}let E=new URLSearchParams({appId:o,userId:N});z&&E.set("userHash",z);try{let w=await fetch(`${r}/api/v1/boundaries/manifest?${E.toString()}`,{headers:{Authorization:`Bearer ${t}`,...G()}});if(!w.ok)throw new Error(`${w.status}`);let U=await w.json();h(fn(r,U));}catch(w){console.error("[ForkProvider] Failed to fetch module override manifest:",w.message),h({});}finally{$(w=>w+1),_(true);}},[t,o,r,R,J,z,N,L?.preview_session_id,L?.fork_id,L?.container_id]);xt.useEffect(()=>{if(!N||o&&(!L||L.container_id))return;let E=new URLSearchParams({userId:N});z&&E.set("userHash",z),fetch(`${r}/api/v1/forks/active?${E.toString()}`,{headers:{Authorization:`Bearer ${t}`,...G()}}).then(w=>{if(!w.ok)throw new Error(`${w.status}`);return w.json()}).then(w=>{w&&typeof w=="object"&&d(w);}).catch(()=>{});},[t,o,N,z,r,L?.preview_session_id,L?.fork_id]),xt.useEffect(()=>{D();},[D]);let te=xt.useCallback((E,w)=>{d(U=>({...U,[E]:w}));},[]),ne=xt.useCallback(E=>{d(w=>{let U={...w};return delete U[E],U});},[]),ue=xt.useCallback(E=>{u.current.add(E);},[]),q=xt.useCallback(E=>u.current.has(E)?(u.current.delete(E),true):false,[]),it=xt.useCallback((E,w)=>{g.current.set(E,w);},[]),Ie=xt.useCallback((E,w)=>g.current.get(E)!==w?false:(g.current.delete(E),true),[]),Fe=xt.useCallback(E=>{if(!o)return;let w=JSON.stringify(E);k.current.get(E.id)===w||l.current.get(E.id)?.signature===w||(l.current.set(E.id,{boundary:E,signature:w}),F(K=>K+1));},[o]);xt.useEffect(()=>{if(!o||l.current.size===0)return;let E=setTimeout(()=>{let w=Array.from(l.current.values());w.length!==0&&fetch(`${r}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:o,boundaries:w.map(U=>U.boundary)})}).then(U=>{if(!U.ok)throw new Error(`${U.status}`)}).then(()=>{for(let U of w)l.current.get(U.boundary.id)?.signature===U.signature&&(l.current.delete(U.boundary.id),k.current.set(U.boundary.id,U.signature));}).catch(U=>{console.error("[ForkProvider] Failed to register module boundaries:",U.message);});},50);return ()=>{clearTimeout(E);}},[t,o,r,A]);let ie=xt.useCallback(E=>y[E],[y]),X=xt.useCallback(async()=>{if(!N)throw new Error("Reset requires a resolved user identity.");let E=new URLSearchParams({userId:N});z&&E.set("userHash",z);let w=await fetch(`${r}/api/v1/forks/all?${E.toString()}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`,...G()}});if(!w.ok){let K=await w.json().catch(()=>({}));throw new Error(K.error||`API error: ${w.status}`)}let U=await w.json().catch(()=>({}));d({}),h({}),_(true),$(K=>K+1),u.current.clear(),g.current.clear();try{for(let K=sessionStorage.length-1;K>=0;K-=1){let ae=sessionStorage.key(K);ae&&ae.startsWith("__fork_animated_")&&sessionStorage.removeItem(ae);}}catch{}return U},[t,r,z,N]);return Yr.jsx(tr.Provider,{value:{apiKey:t,userId:N,userHash:z,baseUrl:r,appId:o,forks:p,moduleOverridesEnabled:J,moduleManifestReady:T,moduleManifestVersion:M,currentContainerId:I,previewSession:L,setSlotFork:te,clearSlotFork:ne,skipAnimationForSlot:ue,shouldSkipAnimation:q,queueBoundaryAnimation:it,consumeBoundaryAnimation:Ie,registerBoundary:Fe,getBoundaryOverride:ie,refreshModuleManifest:D,resetAllForks:X},children:n})}function V(){let e=xt.useContext(tr);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function Ve(e){return V().forks[e]}var Ce=class{constructor(t){this.values=new Map;this.snapshots=new Map;this.listeners=new Map;this.eventHandlers=new Map;this.slotId=t,window.__FORK_BRIDGE__||(window.__FORK_BRIDGE__={}),window.__FORK_BRIDGE__[t]=this;}set(t,r){let n=this.values.get(t);if(Object.is(n,r))return;if(n!==void 0&&r!==null&&n!==null&&typeof n=="object"&&typeof r=="object")try{if(JSON.stringify(n)===JSON.stringify(r))return}catch{}this.values.set(t,r),this.snapshots.set(t,r);let o=this.listeners.get(t);o&&o.forEach(i=>i());}get(t){return this.values.get(t)}getSnapshot(t){return this.snapshots.get(t)}subscribe(t,r){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(r),()=>{this.listeners.get(t)?.delete(r);}}useValue(t){let r=window.__FORK_REACT__;return r?.useSyncExternalStore?r.useSyncExternalStore(n=>this.subscribe(t,n),()=>this.getSnapshot(t)):(console.warn("[ForkBridge] React.useSyncExternalStore not available, returning static value"),this.values.get(t))}emit(t,...r){let n=this.eventHandlers.get(t);n&&n.forEach(o=>o(...r));}on(t,r){return this.eventHandlers.has(t)||this.eventHandlers.set(t,new Set),this.eventHandlers.get(t).add(r),()=>{this.eventHandlers.get(t)?.delete(r);}}destroy(){this.listeners.clear(),this.eventHandlers.clear(),this.values.clear(),this.snapshots.clear();let t=window.__FORK_BRIDGE__;t&&delete t[this.slotId];}};function Ft(e,t){let r;try{r=xt.Children.only(e);}catch{let o=xt.Children.count(e);throw new Error(`<ForkSlot slotId="${t}"> must wrap exactly one React component, got ${o} children. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`)}let n=r.type;if(typeof n=="string")throw new Error(`<ForkSlot slotId="${t}"> child must be a React component (function or class), not an HTML element <${n}>. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`);if(typeof n=="symbol")throw new Error(`<ForkSlot slotId="${t}"> child must be a single React component, not a fragment or special React element. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`);return r}var nr=new Set;function or(e){let t=[],r=e.querySelectorAll("*");for(let n of r){if(!(n instanceof HTMLElement))continue;let o=n.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(n.tagName))continue;let i=getComputedStyle(n),s=parseFloat(i.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:s});}return t}function kn(e,t){let r=[];for(let n of t)if(!e.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)&&!r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom)){for(let s=r.length-1;s>=0;s--){let a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function bn(e,t){let r=[];for(let n of e)if(!t.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)&&!r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom)){for(let s=r.length-1;s>=0;s--){let a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function ir(e,t,r,n,o){return o=Math.max(0,Math.min(o,r/2,n/2)),o===0?`M ${e} ${t} L ${e+r} ${t} L ${e+r} ${t+n} L ${e} ${t+n} Z`:[`M ${e+o} ${t}`,`L ${e+r-o} ${t}`,`A ${o} ${o} 0 0 1 ${e+r} ${t+o}`,`L ${e+r} ${t+n-o}`,`A ${o} ${o} 0 0 1 ${e+r-o} ${t+n}`,`L ${e+o} ${t+n}`,`A ${o} ${o} 0 0 1 ${e} ${t+n-o}`,`L ${e} ${t+o}`,`A ${o} ${o} 0 0 1 ${e+o} ${t}`,"Z"].join(" ")}function sr(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-highlights","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");n.appendChild(o);let i=[];for(let d=0;d<e.length;d++){let{rect:S,borderRadius:P}=e[d],R=S.left-.5,x=S.top-.5,y=S.width+1,h=S.height+1,T=Math.min(P+.5,y/2,h/2),_=ir(R,x,y,h,T),M=`__fork-glow-${d}`,$=document.createElementNS(t,"filter");$.setAttribute("id",M),$.setAttribute("x","-100%"),$.setAttribute("y","-100%"),$.setAttribute("width","300%"),$.setAttribute("height","300%");let I=document.createElementNS(t,"feGaussianBlur");I.setAttribute("in","SourceGraphic"),I.setAttribute("stdDeviation","8"),$.appendChild(I),o.appendChild($);let v=`__fork-mask-${d}`,k=document.createElementNS(t,"mask");k.setAttribute("id",v),k.setAttribute("maskUnits","userSpaceOnUse"),k.setAttribute("x",String(R-200)),k.setAttribute("y",String(x-200)),k.setAttribute("width",String(y+400)),k.setAttribute("height",String(h+400));let l=document.createElementNS(t,"rect");l.setAttribute("x",String(R-200)),l.setAttribute("y",String(x-200)),l.setAttribute("width",String(y+400)),l.setAttribute("height",String(h+400)),l.setAttribute("fill","white"),k.appendChild(l);let A=document.createElementNS(t,"path");A.setAttribute("d",_),A.setAttribute("fill","black"),k.appendChild(A),o.appendChild(k);let F=document.createElementNS(t,"g");F.setAttribute("mask",`url(#${v})`),F.setAttribute("opacity","0");let u=document.createElementNS(t,"g");u.setAttribute("filter",`url(#${M})`);let g=document.createElementNS(t,"path");g.setAttribute("d",_),g.setAttribute("fill","none"),g.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),g.setAttribute("stroke-width","6"),g.setAttribute("stroke-linecap","round"),u.appendChild(g),F.appendChild(u),n.appendChild(F);let m=document.createElementNS(t,"path");m.setAttribute("d",_),m.setAttribute("fill","none"),m.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),m.setAttribute("stroke-width","2"),m.setAttribute("stroke-linecap","round"),m.setAttribute("opacity","0"),n.appendChild(m),i.push(g,m),g.__group=F;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let d=0;d<i.length;d+=2){let S=i[d],P=i[d+1],R=S.__group,x=P.getTotalLength(),y=S.getTotalLength();if(x<=0)continue;let h=x*.35;P.setAttribute("stroke-dasharray",`${h} ${x-h}`),P.setAttribute("stroke-dashoffset","0"),s.push(P.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*x,opacity:.92,offset:.06},{strokeDashoffset:-2*x,opacity:.92,offset:.92},{strokeDashoffset:-2.25*x,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let T=y*.35;S.setAttribute("stroke-dasharray",`${T} ${y-T}`),S.setAttribute("stroke-dashoffset","0"),s.push(S.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*y,offset:.06},{strokeDashoffset:-2*y,offset:.92},{strokeDashoffset:-2.25*y,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(R.animate([{opacity:0,offset:0},{opacity:.92,offset:.06},{opacity:.92,offset:.92},{opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));}let a=false,f=()=>{if(a)return;a=true,clearTimeout(p);for(let S of s)try{S.cancel();}catch{}let d=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});d.onfinish=()=>r.remove(),window.removeEventListener("click",f);},p=setTimeout(f,14500);return setTimeout(()=>{a||window.addEventListener("click",f);},500),f}function wn(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-removed","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs"),i=document.createElementNS(t,"filter");i.setAttribute("id","__fork-removed-shadow"),i.setAttribute("x","-10%"),i.setAttribute("y","-10%"),i.setAttribute("width","120%"),i.setAttribute("height","120%");let s=document.createElementNS(t,"feDropShadow");s.setAttribute("dx","0"),s.setAttribute("dy","1"),s.setAttribute("stdDeviation","2"),s.setAttribute("flood-color","rgba(0,0,0,0.15)"),i.appendChild(s),o.appendChild(i),n.appendChild(o);for(let{rect:a,borderRadius:f}of e){let p=a.left,d=a.top,S=a.width,P=a.height,R=Math.min(f,S/2,P/2),x=ir(p,d,S,P,R),y=document.createElementNS(t,"path");y.setAttribute("d",x),y.setAttribute("fill","none"),y.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),y.setAttribute("stroke-width","1.5"),y.setAttribute("stroke-dasharray","8 4"),y.setAttribute("stroke-linecap","round"),y.setAttribute("filter","url(#__fork-removed-shadow)"),y.setAttribute("opacity","0"),n.appendChild(y),y.animate([{opacity:0,offset:0},{opacity:.6,offset:.08},{opacity:.05,offset:.45},{opacity:.6,offset:.85},{opacity:.05,offset:1}],{duration:5e3,easing:"ease-in-out",fill:"forwards"});}return r.appendChild(n),document.body.appendChild(r),r}function vn(e,t){if(e===t)return true;let r=Object.keys(e);if(r.length!==Object.keys(t).length)return false;for(let n of r)if(!Object.is(e[n],t[n]))return false;return true}var Sn=xt__namespace.default.memo(function({component:t,containerRef:r,wrapperStyle:n,hostProps:o}){return Yr.jsx("div",{ref:r,style:n,children:Yr.jsx(t,{...o})})},(e,t)=>e.component===t.component&&vn(e.hostProps,t.hostProps)),St=class extends xt__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 ar({slotId:e,children:t,githubRepo:r,shared:n,events:o}){Ft(t,e);let i=Ve(e),{baseUrl:s,apiKey:a,appId:f,shouldSkipAnimation:p}=V(),[d,S]=xt.useState(null),P=xt.useRef(null),R=xt.useRef(null),x=xt.useRef(null),y=xt.useRef(false),h=xt.useRef(null),T=xt.useRef(null),_=!!(n||o),M=xt.useRef(null);_&&!M.current&&(M.current=new Ce(e));let $=xt.useRef(o);if($.current=o,xt.useEffect(()=>{if(_)return ()=>{M.current?.destroy(),M.current=null;}},[_,e]),_&&M.current&&n)for(let[A,F]of Object.entries(n))M.current.set(A,F);xt.useEffect(()=>{if(!_)return;M.current||(M.current=new Ce(e));let A=M.current,F=Object.keys($.current||{}).map(u=>A.on(u,(...g)=>$.current?.[u]?.(...g)));return ()=>F.forEach(u=>u())},[_,e]),xt.useEffect(()=>{if(nr.has(e))return;nr.add(e);let A={id:e,appId:f,label:e,eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:r,mode:"direct",sharedKeys:n?Object.keys(n):[],eventNames:o?Object.keys(o):[],propsShape:"",callbackNames:[]};fetch(`${s}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify(A)}).catch(()=>{});},[e,s,a,r,f]);let I=i?.id||null;xt.useEffect(()=>{if(i?.bundleUrl,P.current,R.current,!i?.bundleUrl||!I){return}let A=`${s}${i.bundleUrl.replace("bundle.js","component.js")}`,F=`__fork_animated_${e}`,u=sessionStorage.getItem(F),g=p(e),m=!g&&u!==I;if(g&&I&&sessionStorage.setItem(F,I),m&&R.current){let z=or(R.current);x.current=z,y.current=true,`${e}${z.length}`;}window.__FORK_REACT__=xt__namespace.default,window.__FORK_REACT_DOM__=Xr__namespace,window.__FORK_REACT_JSX__=Yr__namespace;let L=Date.now(),W=`${s}${i.bundleUrl.replace("bundle.js","component.css")}?t=${L}`,ee=document.createElement("link");ee.rel="stylesheet",ee.href=W,ee.dataset.forkSlot=e,document.head.appendChild(ee);let N=document.createElement("script");return N.src=A+"?t="+L,N.onload=()=>{let z=window.__FORK_EXPORT__;if(z?.default){if(R.current&&x.current&&y.current){let J=R.current.getBoundingClientRect(),D=R.current.cloneNode(true);D.style.position="fixed",D.style.top=`${J.top}px`,D.style.left=`${J.left}px`,D.style.width=`${J.width}px`,D.style.height=`${J.height}px`,D.style.flex="none",D.style.minHeight="auto",D.style.zIndex="9998",D.style.pointerEvents="none",D.style.overflow="hidden";let te=getComputedStyle(R.current).backgroundColor;D.style.backgroundColor=te&&te!=="rgba(0, 0, 0, 0)"&&te!=="transparent"?te:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(D);let ne=R.current.querySelectorAll("*"),ue=D.querySelectorAll("*");for(let q=0;q<ne.length;q++)ne[q].scrollTop!==0&&(ue[q].scrollTop=ne[q].scrollTop),ne[q].scrollLeft!==0&&(ue[q].scrollLeft=ne[q].scrollLeft);h.current=D;}S(()=>z.default),P.current=I;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},N.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(N),()=>{N.remove(),ee.remove(),T.current&&(clearTimeout(T.current),T.current=null),h.current&&(h.current.remove(),h.current=null);}},[I,s,e]),xt.useEffect(()=>{if(!y.current||!d||!R.current){`${e}${y.current}`,R.current;return}let A=x.current;if(!A){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!R.current)return;let F=or(R.current),u=kn(A,F),g=bn(A,F),m=h.current;if(`${e}${u.length}${g.length}`,g.length>0&&m){let L=wn(g);T.current=setTimeout(()=>{T.current=null;let W=400;m.animate([{opacity:1},{opacity:0}],{duration:W,fill:"forwards"}),L.animate([{opacity:1},{opacity:0}],{duration:W,fill:"forwards"}),setTimeout(()=>{m.remove(),L.remove(),h.current=null,u.length>0&&(sr(u));},W);},3500);}else m&&(m.remove(),h.current=null),u.length>0&&(sr(u));x.current=null,y.current=false,I&&(sessionStorage.setItem(`__fork_animated_${e}`,I),`${e}`);});});},[d]);let v={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!i||i.status!=="complete"||!i.bundleUrl)return Yr.jsx("div",{ref:R,style:v,children:t});if(!d)return Yr.jsx("div",{ref:R,style:v,children:t});let l=t?.props??{};return Yr.jsx(St,{slotId:e,resetKey:I,fallback:Yr.jsx("div",{ref:R,style:v,children:t}),children:Yr.jsx(Sn,{component:d,containerRef:R,wrapperStyle:v,hostProps:l})})}var cr=new Set;function Rn(e){return `{ ${Object.entries(e).map(([r,n])=>n==null?`${r}: unknown`:Array.isArray(n)?`${r}: ${n.length>0?typeof n[0]:"unknown"}[]`:`${r}: ${typeof n}`).join("; ")} }`}function dr(e,t=new Set){return xt.Children.forEach(e,r=>{if(!xt.isValidElement(r))return;let n=r.props;for(let[o,i]of Object.entries(n))typeof i=="function"&&/^on[A-Z]/.test(o)&&t.add(o);n.children&&dr(n.children,t);}),t}function En({slotId:e,props:t,children:r,allowedFetches:n,githubRepo:o,callbacks:i,mode:s="iframe",shared:a,events:f}){if(Ft(r,e),s==="direct")return Yr.jsx(ar,{slotId:e,githubRepo:o,shared:a,events:f,children:r});let p=Ve(e),{baseUrl:d,apiKey:S,appId:P}=V(),R=xt.useRef(null),x=xt.useRef(false),y=xt.useRef(null),h=xt.useRef(i);h.current=i;let T=xt.useRef(t);T.current=t;let _=xt.useRef(n);_.current=n,xt.useEffect(()=>{if(typeof process<"u")return;let v=dr(r),k=new Set(i?Object.keys(i):[]),l=[...v].filter(A=>!k.has(A));l.length>0&&console.error(`[ForkSlot:${e}] Missing bridged callbacks! The following callback props are used by children but not passed to ForkSlot's \`callbacks\` prop:
2
+ `+l.map(A=>` - ${A}`).join(`
3
+ `)+"\n\nThe forked component will not be able to call these. Add them to the `callbacks` prop of <ForkSlot>.");},[e,r,i]),xt.useEffect(()=>{cr.has(e)||(cr.add(e),fetch(`${d}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${S}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:P,label:e,propsShape:t?Rn(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:o,callbackNames:i?Object.keys(i):[],mode:s||"iframe"})}).catch(()=>{}));},[e,d,S,o,P]);let M=xt.useCallback(v=>{let k=R.current;if(k?.contentWindow&&x.current){let l=h.current?Object.keys(h.current):[];k.contentWindow.postMessage({type:"slot:props",props:v,callbackNames:l},"*"),y.current=null;}else y.current=v;},[]),$=xt.useCallback((v,k)=>{let l=_.current;return !l||l.length===0?false:l.some(A=>{let[F,u]=A.split(" "),g=k.split("?")[0];return v.toUpperCase()===F.toUpperCase()&&g.startsWith(u)})},[]);if(xt.useEffect(()=>{if(!p?.bundleUrl)return;let v=async k=>{if(k.source===R.current?.contentWindow){if(k.data?.type==="slot:ready")x.current=true,R.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:_.current||[]},"*"),_.current,y.current?M(y.current):M(T.current||{});else if(k.data?.type==="slot:event"){let l=k.data.event;l?.navigate&&(window.location.hash=l.navigate);}else if(k.data?.type==="slot:clipboard-write")navigator.clipboard.writeText(k.data.text).catch(l=>{console.warn(`[ForkSlot:${e}] clipboard write failed:`,l.message);});else if(k.data?.type==="slot:callback"){let{name:l,args:A}=k.data,F=h.current?.[l];F?(F(...A||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${l}`);}else if(k.data?.type==="slot:fetch"){let{id:l,method:A,url:F,body:u}=k.data,g=R.current?.contentWindow;if(!g)return;let m=A||"GET";if(!$(m,F)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${l}: ${m} ${F} \u2014 not in allowedFetches`),g.postMessage({type:"slot:fetch-response",id:l,error:`Fetch not allowed: ${m} ${F}`},"*");return}try{let L={method:m};u&&m!=="GET"&&(L.headers={"Content-Type":"application/json"},L.body=JSON.stringify(u));let W=await fetch(F,L),ee=await W.json();`${e}${l}${W.status}`,g.postMessage({type:"slot:fetch-response",id:l,data:ee,status:W.status},"*");}catch(L){console.error(`[ForkSlot:${e}] fetch #${l} failed:`,L.message),g.postMessage({type:"slot:fetch-response",id:l,error:L.message},"*");}}}};return window.addEventListener("message",v),()=>{window.removeEventListener("message",v),x.current=false;}},[p?.bundleUrl,e,M,$]),xt.useEffect(()=>{p?.bundleUrl&&x.current&&M(t||{});},[t,p?.bundleUrl,M]),!p||p.status!=="complete"||!p.bundleUrl)return `${e}${p?.status||"none"}${p?.bundleUrl||"none"}`,Yr.jsx(Yr.Fragment,{children:r});`${e}${p.bundleUrl}`;let I=`${d}${p.bundleUrl.replace("/bundle.js","/host")}`;return Yr.jsx("iframe",{ref:R,src:I,sandbox:"allow-scripts allow-same-origin allow-forms allow-clipboard-write",title:`Forked ${e}`,style:{width:"100%",border:"none",flex:1,minHeight:0}})}function qe({style:e={width:20,height:20},...t}){return Yr.jsxs("svg",{viewBox:"320 95 270 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:e,...t,children:[Yr.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"}),Yr.jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M387.096 174.735v188"}),Yr.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"}),Yr.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"}),Yr.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 Et({onClick:e}){let[t,r]=xt.useState(false),[n,o]=xt.useState(false),i=t?48:40;return Yr.jsx("button",{onClick:e,onMouseEnter:()=>r(true),onMouseLeave:()=>{r(false),o(false);},onMouseDown:()=>o(true),onMouseUp:()=>o(false),style:{position:"fixed",bottom:24,right:24,zIndex:40,width:i,height:i,borderRadius:"50%",backgroundColor:t?"rgba(255, 255, 255, 1)":"rgba(255, 255, 255, 0.3)",border:t?"1px solid rgba(156, 163, 175, 1)":"1px solid rgba(156, 163, 175, 0.3)",display:"flex",alignItems:"center",justifyContent:"center",color:t?"#1c4587":"rgba(28, 69, 135, 0.5)",boxShadow:t?"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1)":"0 1px 2px 0 rgba(0, 0, 0, 0.05)",transform:n?"scale(0.95)":"scale(1)",transition:"all 300ms",cursor:"pointer",padding:0,margin:0,outline:"none",boxSizing:"border-box"},title:"Fork this app",children:Yr.jsx(qe,{style:{width:24,height:24}})})}var On={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},Un={status:"#60a5fa",agent_message:"#a0a0a0",tool_use:"#fbbf24",build_start:"#c084fc",build_complete:"#6b7280",build_error:"#f87171",complete:"#6b7280",error:"#f87171"},Bn={read:lucideReact.FileSearch,write:lucideReact.Pencil,search:lucideReact.FileSearch,shell:lucideReact.Terminal,build:lucideReact.Package},Hn={read:"#60a5fa",write:"#fbbf24",search:"#60a5fa",shell:"#a78bfa",build:"#c084fc"};function $t(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 kr({events:e}){let t=xt.useRef(null);return xt.useEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight);},[e]),Yr.jsxs(Yr.Fragment,{children:[Yr.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
- `}),Br.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&&Br.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"#6b7280",fontSize:"11px"},children:[Br.jsx(lucideReact.Loader2,{style:{width:"12px",height:"12px",animation:"__fork-spin 1s linear infinite",flexShrink:0}}),"Connecting to agent..."]}),e.map((r,n)=>{let o=n===e.length-1,i=r.type==="complete"||r.type==="error"||r.type==="build_complete"||r.type==="build_error",s=o&&!i&&(r.type==="status"||r.type==="tool_use"||r.type==="build_start"),a=xn[r.type]||lucideReact.Code,d=Fn[r.type]||"#9ca3af";if(r.type==="tool_use"){let f=String(r.data.category||"");a=Rn[f]||lucideReact.Wrench,d=En[f]||"#fbbf24";}return s?a=lucideReact.Loader2:!o&&r.type==="status"&&(a=lucideReact.Check,d="#4ade80"),Br.jsxs("div",{style:{display:"flex",gap:"6px",marginBottom:"6px",lineHeight:1.625},children:[Br.jsx(a,{style:{width:"12px",height:"12px",marginTop:"2px",flexShrink:0,color:d,...s?{animation:"__fork-spin 1s linear infinite"}:{}}}),Br.jsx("span",{style:{color:o&&!i?"#d1d5db":"#6b7280",wordBreak:"break-all"},children:vt(r)})]},n)})]})]})}var pr=35,In="Working on Feature",Ln="Built Custom Feature",gr=360,Ke=350;function Un(e){return e.length<=pr?e:e.slice(0,pr-3).trimEnd()+"..."}function On({events:e}){let[t,r]=ht.useState("Setting up environment..."),[n,o]=ht.useState(true),i=ht.useRef(t),s=ht.useRef(false);return ht.useEffect(()=>{if(!s.current){for(let d of e)if(d.type==="status"&&String(d.data.message||"").includes("Agent started")){s.current=true;break}}let a="Setting up environment...";if(s.current)for(let d=e.length-1;d>=0;d--){let f=e[d];if(f.type==="tool_use"||f.type==="build_start"||f.type==="build_complete"){a=Un(vt(f));break}}if(a!==i.current){o(false);let d=setTimeout(()=>{r(a),i.current=a,o(true);},200);return ()=>clearTimeout(d)}},[e]),Br.jsx("span",{style:{fontSize:11,color:"#d1d5db",fontWeight:500,opacity:n?1:0,transition:"opacity 0.2s ease",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},children:t})}function Bn({children:e}){let[t,r]=ht.useState(null);return ht.useEffect(()=>{if(typeof document>"u")return;let n=document.createElement("div");n.setAttribute("data-fork-panel-host",""),n.style.cssText="all: initial;",document.body.appendChild(n);let o=n.attachShadow({mode:"open"});return r(o),()=>{n.remove();}},[]),t?Or.createPortal(e,t):null}function Ge({state:e,fork:t,events:r,error:n,slotId:o,targetId:i,targetLabel:s,historyMode:a="slot",onSubmit:d,onUndo:f,onClose:c,baseUrl:F,apiKey:P,userId:x,userHash:v,appId:y,embedded:h=false}){let[C,R]=ht.useState(""),[T,$]=ht.useState([]),[M,w]=ht.useState(false),[k,l]=ht.useState(false),[E,S]=ht.useState(false),[u,p]=ht.useState(false),[g,I]=ht.useState(false),[z,Y]=ht.useState(false),[H,D]=ht.useState(false),[V,N]=ht.useState(false),[Q,ee]=ht.useState(false),[ie,q]=ht.useState(null),[Qe,_e]=ht.useState(false),[ke,be]=ht.useState([]),[J,_]=ht.useState(null),[b,O]=ht.useState(false),[W,ae]=ht.useState(false),[$r,Ct]=ht.useState(false),[_r,Tt]=ht.useState(null),[ge,Mt]=ht.useState(null),et=ht.useRef(null),Ae=ht.useRef(null),{resetAllForks:Ar,previewSession:Pe,currentContainerId:Pr}=G(),Ce=Pe?.container_id??Pr,It=!!Pe,ne=ge!==null,Lt=ht.useRef(c);ht.useEffect(()=>{Lt.current=c;});let tt=ht.useRef(null),Te=ht.useRef(false),Ut=typeof window<"u"&&"documentPictureInPicture"in window,Cr=async()=>{if(!(!Ut||ne))try{let m=await window.documentPictureInPicture.requestWindow({width:gr,height:640});m.document.body.style.margin="0",m.document.body.style.padding="0",m.document.body.style.height="100vh",m.document.body.style.overflow="hidden",m.document.body.style.background="#ffffff";try{let L=document.adoptedStyleSheets??[];L.length>0&&(m.document.adoptedStyleSheets=[...L]);}catch{}m.addEventListener("pagehide",()=>{tt.current=null,Mt(null),Te.current||Lt.current(),Te.current=!1;},{once:!0}),tt.current=m,Mt(m);}catch(m){console.warn("[Fork] PiP open failed:",m);}},Tr=()=>{ge&&(Te.current=true,ge.close());};ht.useEffect(()=>()=>{Te.current=true,tt.current?.close();},[]);let oe=i??o??"",Me=(s||oe).replace(/[-_]+/g," ").replace(/\b\w/g,m=>m.toUpperCase()),rt=ht.useRef(""),Ie=h?true:k&&!E,Mr=r.find(m=>{let L=m.data;return m.type==="status"&&L.summary})?.data?.summary||t?.summary||In,ce=r.find(m=>{let L=m.data;return (m.type==="status"||m.type==="complete")&&typeof L?.estimateMinutes=="number"})?.data?.estimateMinutes??t?.estimateMinutes;ht.useEffect(()=>{if(a==="none"){w(true);return}if(!F||!P||!x||!oe||M||!b)return;let m=new URLSearchParams({userId:x});if(v&&m.set("userHash",v),J&&m.set("containerId",J),a==="slot")m.set("slotId",oe);else if(a==="boundary"){if(!y){w(true);return}m.set("boundaryId",oe),m.set("appId",y);}fetch(`${F}/api/v1/forks/history?${m.toString()}`,{headers:{Authorization:`Bearer ${P}`}}).then(L=>L.ok?L.json():[]).then(L=>{let U=[];for(let Ue of L)Ue.role==="user"?U.push({type:"user",text:Ue.content}):U.push({type:"applied",text:Ue.content});$(U),w(true);}).catch(()=>w(true));},[P,y,F,M,a,oe,v,x,J,b]),ht.useEffect(()=>{e==="complete"&&N(false);},[e]),ht.useEffect(()=>{if(h&&a==="none"){be([]),_(null),O(true);return}Ce?(be([{id:Ce,name:It?Pe?.container_name||"Preview container":"Primary container",createdAt:""}]),_(Ce)):(be([]),_(null)),O(true);},[Ce,h,a,It,Pe?.container_name]);let Le=ht.useRef(void 0);ht.useEffect(()=>{if(b){if(Le.current===void 0){Le.current=J;return}Le.current!==J&&(Le.current=J,$([]),w(false));}},[J,b]);let nt=ht.useRef(null);ht.useEffect(()=>{if(!W)return;let m=U=>{nt.current&&(nt.current.contains(U.target)||ae(false));},L=U=>{U.key==="Escape"&&ae(false);};return document.addEventListener("mousedown",m,true),document.addEventListener("keydown",L,true),()=>{document.removeEventListener("mousedown",m,true),document.removeEventListener("keydown",L,true);}},[W]),ht.useEffect(()=>{if(h)return;let m=requestAnimationFrame(()=>l(true));return ()=>cancelAnimationFrame(m)},[h]),ht.useEffect(()=>{let m=h||ne;if((m||Ie)&&(e==="prompting"||e==="complete")){let L=setTimeout(()=>et.current?.focus(),m?100:Ke+100);return ()=>clearTimeout(L)}},[Ie,h,ne,e]),ht.useEffect(()=>{if(e==="complete"&&rt.current){let L=r.find(U=>U.type==="complete")?.data?.summary||t?.summary||Ln;$(U=>U[U.length-1]?.type==="applied"?U:[...U,{type:"applied",text:L}]),R(""),setTimeout(()=>et.current?.focus(),200);}},[e,Me,r,t?.summary]),ht.useEffect(()=>{Ae.current&&(Ae.current.scrollTop=Ae.current.scrollHeight);},[T,e]);let Ot=()=>{C.trim()&&(rt.current=C.trim(),$(m=>[...m,{type:"user",text:C.trim()}]),d(C.trim(),oe,J),R(""));},Ir=async()=>{if(!(!f||Q||!oe)){ee(true);try{let m=await f(oe);$(L=>{let U=[...L];return U.length>=2&&U[U.length-1]?.type==="applied"?U.splice(-2,2):U.length>=1&&U[U.length-1]?.type==="applied"&&U.splice(-1,1),U}),m?.removed&&$([]);}catch{}finally{ee(false);}}},ot=()=>{if(h){c();return}if(ne){ge?.close();return}S(true),l(false),setTimeout(()=>c(),Ke);},Lr=h||ne?{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:gr,maxWidth:"100vw",background:"#ffffff",boxShadow:Ie?"-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:Ie?"translateX(0)":"translateX(100%)",transition:`transform ${Ke}ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow ${Ke}ms ease`,display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'},st=Br.jsxs(Br.Fragment,{children:[Br.jsx("style",{children:`
21
+ `}),Yr.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&&Yr.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"#6b7280",fontSize:"11px"},children:[Yr.jsx(lucideReact.Loader2,{style:{width:"12px",height:"12px",animation:"__fork-spin 1s linear infinite",flexShrink:0}}),"Connecting to agent..."]}),e.map((r,n)=>{let o=n===e.length-1,i=r.type==="complete"||r.type==="error"||r.type==="build_complete"||r.type==="build_error",s=o&&!i&&(r.type==="status"||r.type==="tool_use"||r.type==="build_start"),a=On[r.type]||lucideReact.Code,f=Un[r.type]||"#9ca3af";if(r.type==="tool_use"){let p=String(r.data.category||"");a=Bn[p]||lucideReact.Wrench,f=Hn[p]||"#fbbf24";}return s?a=lucideReact.Loader2:!o&&r.type==="status"&&(a=lucideReact.Check,f="#4ade80"),Yr.jsxs("div",{style:{display:"flex",gap:"6px",marginBottom:"6px",lineHeight:1.625},children:[Yr.jsx(a,{style:{width:"12px",height:"12px",marginTop:"2px",flexShrink:0,color:f,...s?{animation:"__fork-spin 1s linear infinite"}:{}}}),Yr.jsx("span",{style:{color:o&&!i?"#d1d5db":"#6b7280",wordBreak:"break-all"},children:$t(r)})]},n)})]})]})}var Sr=35,Vn="Working on Feature",Jn="Built Custom Feature",xr=360,Ze=350;function qn(e){return e.length<=Sr?e:e.slice(0,Sr-3).trimEnd()+"..."}function Xn({events:e}){let[t,r]=xt.useState("Setting up environment..."),[n,o]=xt.useState(true),i=xt.useRef(t),s=xt.useRef(false);return xt.useEffect(()=>{if(!s.current){for(let f of e)if(f.type==="status"&&String(f.data.message||"").includes("Agent started")){s.current=true;break}}let a="Setting up environment...";if(s.current)for(let f=e.length-1;f>=0;f--){let p=e[f];if(p.type==="tool_use"||p.type==="build_start"||p.type==="build_complete"){a=qn($t(p));break}}if(a!==i.current){o(false);let f=setTimeout(()=>{r(a),i.current=a,o(true);},200);return ()=>clearTimeout(f)}},[e]),Yr.jsx("span",{style:{fontSize:11,color:"#d1d5db",fontWeight:500,opacity:n?1:0,transition:"opacity 0.2s ease",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},children:t})}function Yn({children:e}){let[t,r]=xt.useState(null);return xt.useEffect(()=>{if(typeof document>"u")return;let n=document.createElement("div");n.setAttribute("data-fork-panel-host",""),n.style.cssText="all: initial;",document.body.appendChild(n);let o=n.attachShadow({mode:"open"});return r(o),()=>{n.remove();}},[]),t?Xr.createPortal(e,t):null}function Qe({state:e,fork:t,events:r,error:n,slotId:o,targetId:i,targetLabel:s,historyMode:a="slot",onSubmit:f,onUndo:p,onClose:d,baseUrl:S,apiKey:P,userId:R,userHash:x,appId:y,embedded:h=false}){let[T,_]=xt.useState(""),[M,$]=xt.useState([]),[I,v]=xt.useState(false),[k,l]=xt.useState(false),[A,F]=xt.useState(false),[u,g]=xt.useState(false),[m,L]=xt.useState(false),[W,ee]=xt.useState(false),[N,z]=xt.useState(false),[J,D]=xt.useState(false),[te,ne]=xt.useState(false),[ue,q]=xt.useState(null),[it,Ie]=xt.useState(false),[Fe,ie]=xt.useState([]),[X,E]=xt.useState(null),[w,U]=xt.useState(false),[K,ae]=xt.useState(false),[Or,Bt]=xt.useState(false),[Ur,Ht]=xt.useState(null),[re,Le]=xt.useState(null),[Br,Nt]=xt.useState(false),[Dt,be]=xt.useState(null),[Hr,Re]=xt.useState(false),[we,jt]=xt.useState(null),at=xt.useRef(null),Oe=xt.useRef(null),{resetAllForks:Nr,previewSession:Y,currentContainerId:Dr}=V(),pe=Y?.container_id??Dr,Ue=!!(Y&&Hr),le=we!==null,zt=xt.useRef(d);xt.useEffect(()=>{zt.current=d;});let lt=xt.useRef(null),Be=xt.useRef(false),Wt=typeof window<"u"&&"documentPictureInPicture"in window,jr=async()=>{if(!(!Wt||le))try{let c=await window.documentPictureInPicture.requestWindow({width:xr,height:640});c.document.body.style.margin="0",c.document.body.style.padding="0",c.document.body.style.height="100vh",c.document.body.style.overflow="hidden",c.document.body.style.background="#ffffff";try{let b=document.adoptedStyleSheets??[];b.length>0&&(c.document.adoptedStyleSheets=[...b]);}catch{}c.addEventListener("pagehide",()=>{lt.current=null,jt(null),Be.current||zt.current(),Be.current=!1;},{once:!0}),lt.current=c,jt(c);}catch(c){console.warn("[Fork] PiP open failed:",c);}},zr=()=>{we&&(Be.current=true,we.close());};xt.useEffect(()=>()=>{Be.current=true,lt.current?.close();},[]);let ce=i??o??"",He=(s||ce).replace(/[-_]+/g," ").replace(/\b\w/g,c=>c.toUpperCase()),ct=xt.useRef(""),Ne=h?true:k&&!A,Wr=r.find(c=>{let b=c.data;return c.type==="status"&&b.summary})?.data?.summary||t?.summary||Vn,ge=r.find(c=>{let b=c.data;return (c.type==="status"||c.type==="complete")&&typeof b?.estimateMinutes=="number"})?.data?.estimateMinutes??t?.estimateMinutes;xt.useEffect(()=>{if(a==="none"){v(true);return}if(!S||!P||!R||!ce||I||!w)return;let c=new URLSearchParams({userId:R});if(x&&c.set("userHash",x),X&&c.set("containerId",X),a==="slot")c.set("slotId",ce);else if(a==="boundary"){if(!y){v(true);return}c.set("boundaryId",ce),c.set("appId",y);}fetch(`${S}/api/v1/forks/history?${c.toString()}`,{headers:{Authorization:`Bearer ${P}`}}).then(b=>b.ok?b.json():[]).then(b=>{let O=[];for(let Z of b)Z.role==="user"?O.push({type:"user",text:Z.content}):O.push({type:"applied",text:Z.content});$(O),v(true);}).catch(()=>v(true));},[P,y,S,I,a,ce,x,R,X,w]),xt.useEffect(()=>{e==="complete"&&D(false);},[e]),xt.useEffect(()=>{if(h&&a==="none"){ie([]),E(null),U(true),Re(false);return}if(Y){let c=false;return U(false),Re(false),be(null),fetch(`${S}/api/v1/preview/${encodeURIComponent(Y.preview_session_id)}/containers`,{headers:{Authorization:`Bearer ${P}`,...G()}}).then(b=>{if(!b.ok)throw new Error(`${b.status}`);return b.json()}).then(b=>{c||(ie(b.containers),E(b.currentContainerId??Y.container_id??null),Re(true));}).catch(b=>{c||(Re(false),be(b instanceof Error?b.message:String(b)),pe?(ie([{id:pe,name:Y.container_name||"Primary container",createdAt:"",hasAccess:true,isPrimary:true}]),E(pe)):(ie([]),E(null)));}).finally(()=>{c||U(true);}),()=>{c=true;}}pe?(ie([{id:pe,name:"Primary container",createdAt:""}]),E(pe)):(ie([]),E(null)),U(true),Re(false);},[P,pe,S,h,a,Y?.container_id,Y?.container_name,Y?.preview_session_id]);let De=xt.useRef(void 0);xt.useEffect(()=>{if(w){if(De.current===void 0){De.current=X;return}De.current!==X&&(De.current=X,$([]),v(false));}},[X,w]);let je=xt.useRef(null);xt.useEffect(()=>{if(!K)return;let c=O=>{if(!je.current)return;let Z=typeof O.composedPath=="function"?O.composedPath():[];je.current.contains(O.target)||Z.includes(je.current)||ae(false);},b=O=>{O.key==="Escape"&&ae(false);};return document.addEventListener("mousedown",c,true),document.addEventListener("keydown",b,true),()=>{document.removeEventListener("mousedown",c,true),document.removeEventListener("keydown",b,true);}},[K]),xt.useEffect(()=>{if(h)return;let c=requestAnimationFrame(()=>l(true));return ()=>cancelAnimationFrame(c)},[h]),xt.useEffect(()=>{let c=h||le;if((c||Ne)&&(e==="prompting"||e==="complete")){let b=setTimeout(()=>at.current?.focus(),c?100:Ze+100);return ()=>clearTimeout(b)}},[Ne,h,le,e]),xt.useEffect(()=>{if(e==="complete"&&ct.current){let b=r.find(O=>O.type==="complete")?.data?.summary||t?.summary||Jn;$(O=>O[O.length-1]?.type==="applied"?O:[...O,{type:"applied",text:b}]),_(""),setTimeout(()=>at.current?.focus(),200);}},[e,He,r,t?.summary]),xt.useEffect(()=>{Oe.current&&(Oe.current.scrollTop=Oe.current.scrollHeight);},[M,e]);let Kt=()=>{T.trim()&&(ct.current=T.trim(),$(c=>[...c,{type:"user",text:T.trim()}]),f(T.trim(),ce,X),_(""));},Gt=c=>{yt(c.session.containerId,c.session.containerName),E(c.session.containerId),ie(b=>{let O=b.filter(Z=>Z.id!==c.container.id);return [{...c.container,isPrimary:true,hasAccess:true},...O.map(Z=>({...Z,isPrimary:false}))]}),$([]),v(false);},Kr=async c=>{if(!(!Y||!Ue||re)){Le(c),be(null);try{let b=await fetch(`${S}/api/v1/preview/${encodeURIComponent(Y.preview_session_id)}/containers/${encodeURIComponent(c)}/primary`,{method:"POST",headers:{Authorization:`Bearer ${P}`,...G()}});if(!b.ok){let O=await b.json().catch(()=>({}));throw new Error(O.error||`API error: ${b.status}`)}Gt(await b.json()),ae(!1);}catch(b){be(b instanceof Error?b.message:String(b));}finally{Le(null);}}},Gr=async()=>{if(!Y||!Ue||re)return;let c=window.prompt("Container name","New container");if(!(!c||!c.trim())){Le("__new__"),be(null);try{let b=await fetch(`${S}/api/v1/preview/${encodeURIComponent(Y.preview_session_id)}/containers`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${P}`,...G()},body:JSON.stringify({name:c.trim()})});if(!b.ok){let O=await b.json().catch(()=>({}));throw new Error(O.error||`API error: ${b.status}`)}Gt(await b.json()),ae(!1);}catch(b){be(b instanceof Error?b.message:String(b));}finally{Le(null);}}},Vr=async()=>{if(!(!p||te||!ce)){ne(true);try{let c=await p(ce);$(b=>{let O=[...b];return O.length>=2&&O[O.length-1]?.type==="applied"?O.splice(-2,2):O.length>=1&&O[O.length-1]?.type==="applied"&&O.splice(-1,1),O}),c?.removed&&$([]);}catch{}finally{ne(false);}}},dt=()=>{if(h){d();return}if(le){we?.close();return}F(true),l(false),setTimeout(()=>d(),Ze);},Jr=h||le?{position:"relative",width:"100%",height:"100%",background:"#ffffff",display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'}:{position:"fixed",top:0,right:0,bottom:0,zIndex:2147483e3,width:xr,maxWidth:"100vw",background:"#ffffff",boxShadow:Ne?"-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:Ne?"translateX(0)":"translateX(100%)",transition:`transform ${Ze}ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow ${Ze}ms ease`,display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'},Vt=Fe.find(c=>c.id===X)?.name??(w?`Fork ${He}`:"Loading..."),ut=Yr.jsxs(Yr.Fragment,{children:[Yr.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
- `}),Br.jsxs("div",{className:"__fork-panel",style:Lr,children:[Br.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:[Br.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:[Br.jsx(je,{style:{width:16,height:16,color:"#1c4587",cursor:"pointer",flexShrink:0},onDoubleClick:async m=>{if(m.stopPropagation(),!Qe&&confirm("Reset all forks? This will remove all forked components.")){_e(true);try{let L=await Ar();`${L?.deleted??0}`,$([]),R(""),N(!1),ot();}catch(L){console.error("[Fork] Reset failed:",L);}finally{_e(false);}}}}),e==="running"?Br.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:Mr}):ke.length===0?Br.jsxs("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:["Fork ",Me]}):Br.jsxs("div",{ref:nt,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[Br.jsxs("button",{type:"button",onClick:()=>{ae(m=>!m);},onMouseEnter:()=>Ct(true),onMouseLeave:()=>Ct(false),"aria-haspopup":"menu","aria-expanded":W,style:{display:"inline-flex",alignItems:"center",gap:4,padding:"3px 6px",border:"1px solid transparent",borderRadius:6,background:$r||W?"#f3f4f6":"transparent",fontSize:13,fontWeight:600,color:"#111827",fontFamily:"inherit",cursor:"pointer",maxWidth:180,minWidth:0,transition:"background-color 0.12s"},children:[Br.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:ke.find(m=>m.id===J)?.name??(b?`Fork ${Me}`:"Loading\u2026")}),Br.jsx(lucideReact.ChevronDown,{style:{width:12,height:12,color:"#6b7280",flexShrink:0,transform:W?"rotate(180deg)":void 0,transition:"transform 0.15s"}})]}),W&&Br.jsx("div",{role:"menu",style:{position:"absolute",top:"calc(100% + 4px)",left:0,minWidth:200,maxWidth:260,background:"#ffffff",border:"1px solid #e5e7eb",borderRadius:8,boxShadow:"0 4px 12px rgba(0,0,0,0.08), 0 1px 3px rgba(0,0,0,0.06)",padding:4,zIndex:2147483001},children:ke.map(m=>{let L=m.id===J,U=_r===m.id;return Br.jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>Tt(m.id),onMouseLeave:()=>Tt(null),onClick:()=>{ae(false),m.id!==J&&_(m.id);},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:U?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:"pointer",textAlign:"left",fontWeight:L?600:400},children:[Br.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:L&&Br.jsx(lucideReact.Check,{style:{width:12,height:12}})}),Br.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:m.name})]},m.id)})})]}),e==="running"&&Br.jsx("span",{title:ce?`Estimated ~${ce} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:ce?"#1c4587":"#9ca3af",backgroundColor:ce?"rgba(28, 69, 135, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:ce?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:ce?`~${ce}m`:"~ m"}),e==="complete"&&Br.jsx("div",{style:{height:6,width:6,backgroundColor:"#1c4587",borderRadius:"50%",flexShrink:0}})]}),!h&&Br.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[Ut&&Br.jsx("button",{onClick:ne?Tr:Cr,onMouseEnter:()=>I(true),onMouseLeave:()=>I(false),title:ne?"Redock to sidebar":"Pop out into window",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:ne?Br.jsx(lucideReact.PictureInPicture,{style:{width:16,height:16}}):Br.jsx(lucideReact.PictureInPicture2,{style:{width:16,height:16}})}),Br.jsx("button",{onClick:ot,onMouseEnter:()=>p(true),onMouseLeave:()=>p(false),style:{padding:6,borderRadius:6,color:u?"#4b5563":"#9ca3af",backgroundColor:u?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:Br.jsx(lucideReact.X,{style:{width:16,height:16}})})]})]}),Br.jsxs("div",{ref:Ae,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[e==="prompting"&&T.length===0&&Br.jsx("div",{style:{padding:"24px 20px",textAlign:"center"},children:Br.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."})}),T.length>0&&Br.jsx("div",{style:{padding:"16px 16px 0 16px"},children:T.map((m,L)=>Br.jsx("div",{style:{marginBottom:L<T.length-1?10:0},children:m.type==="user"?Br.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexDirection:"row-reverse"},children:[Br.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:Br.jsx(lucideReact.User,{style:{width:13,height:13,color:"#6b7280"}})}),Br.jsx("div",{style:{backgroundColor:"#f3f4f6",borderRadius:"12px 4px 12px 12px",padding:"8px 12px",fontSize:13,color:"#374151",lineHeight:1.5,maxWidth:"75%"},children:m.text})]}):Br.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[Br.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#f0fdf4",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:Br.jsx(lucideReact.Check,{style:{width:13,height:13,color:"#9ca3af"}})}),Br.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:[Br.jsx("span",{style:{flex:1},children:m.text}),f&&L===T.length-1&&e!=="running"&&Br.jsxs("button",{onClick:U=>{U.stopPropagation(),Ir();},onMouseEnter:()=>q(L),onMouseLeave:()=>q(null),disabled:Q,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:ie===L?"rgba(0,0,0,0.06)":"transparent",color:ie===L?"#6b7280":"#d1d5db",cursor:Q?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:Q?.4:1,flexShrink:0},children:[Br.jsx(lucideReact.Undo2,{style:{width:12,height:12}}),ie===L&&Br.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"&&Br.jsx("div",{style:{padding:16},children:Br.jsxs("div",{onClick:()=>N(!V),style:{backgroundColor:"#1a1a2e",borderRadius:12,overflow:"hidden",cursor:"pointer",transition:"all 0.3s cubic-bezier(0.22, 1, 0.36, 1)"},children:[Br.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px"},children:[Br.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[Br.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:Br.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),Br.jsx(On,{events:r})]}),Br.jsx("div",{style:{color:"#6b7280",flexShrink:0,marginLeft:8,transition:"transform 0.2s ease",transform:V?"rotate(180deg)":"rotate(0deg)"},children:Br.jsx(lucideReact.ChevronDown,{style:{width:14,height:14}})})]}),Br.jsx("div",{style:{maxHeight:V?320:0,opacity:V?1:0,transition:"max-height 0.35s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.25s ease",overflow:"hidden"},children:Br.jsx("div",{style:{borderTop:"1px solid rgba(255,255,255,0.08)",maxHeight:320,overflowY:"auto"},children:Br.jsx(cr,{events:r})})})]})}),e==="error"&&Br.jsxs("div",{style:{padding:"20px 16px",textAlign:"center"},children:[Br.jsx("div",{style:{width:36,height:36,backgroundColor:"#fef2f2",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 10px auto"},children:Br.jsx(lucideReact.X,{style:{width:18,height:18,color:"#ef4444"}})}),Br.jsx("p",{style:{fontSize:12,color:"#6b7280",marginBottom:10,maxWidth:260,margin:"0 auto 10px auto"},children:n}),Br.jsxs("button",{onClick:()=>{let m=t?.prompt||rt.current;m&&d(m,oe);},onMouseEnter:()=>D(true),onMouseLeave:()=>D(false),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,color:"#4f46e5",backgroundColor:H?"#e0e7ff":"#eef2ff",border:"none",cursor:"pointer",transition:"background-color 0.15s",fontFamily:"inherit"},children:[Br.jsx(lucideReact.RotateCcw,{style:{width:12,height:12}})," Try Again"]})]})]}),e!=="running"&&Br.jsx("div",{style:{padding:"8px 12px 12px 12px",borderTop:"1px solid rgba(229, 231, 235, 0.6)",flexShrink:0},children:Br.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:[Br.jsx("textarea",{ref:et,value:C,onChange:m=>{R(m.target.value),m.target.style.height="auto",m.target.style.height=Math.min(m.target.scrollHeight,160)+"px";},onKeyDown:m=>{m.key==="Enter"&&!m.shiftKey&&(m.preventDefault(),Ot()),m.key==="Escape"&&!h&&ot();},placeholder:T.length>0?"Ask for another change...":`Describe your ideal ${Me.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"}}),Br.jsx("button",{onClick:Ot,disabled:!C.trim(),onMouseEnter:()=>Y(true),onMouseLeave:()=>Y(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:C.trim()?1:.25,transform:z&&C.trim()?"scale(1.1)":"scale(1)",background:C.trim()?"#1c4587":"rgba(0,0,0,0.12)",border:"none",cursor:C.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:Br.jsx(lucideReact.ArrowUp,{style:{width:13,height:13}})})]})})]})]});return h?st:ne&&ge?Or.createPortal(st,ge.document.body):Br.jsx(Bn,{children:st})}function hr(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 St(e){let{apiKey:t,userId:r,userHash:n,baseUrl:o,appId:i,previewSession:s,refreshModuleManifest:a,queueBoundaryAnimation:d}=G(),[f,c]=ht.useState("idle"),[F,P]=ht.useState(null),[x,v]=ht.useState([]),[y,h]=ht.useState(null),C=ht.useRef(null),R=ht.useCallback(()=>{c("prompting"),v([]),h(null),P(null);},[]),T=ht.useCallback(()=>{c("idle"),C.current&&(C.current.close(),C.current=null);},[]);ht.useEffect(()=>{s&&s.target.kind==="module"&&s.target.id===e&&c(w=>w==="idle"?"prompting":w);},[s?.preview_session_id,s?.target.id,e]);let $=ht.useCallback(async(w,k)=>{try{if(!i)throw new Error("ForkProvider requires appId for module boundary prompts.");c("running"),v([]),h(null);let l;if(s){let u=await fetch(`${o}/api/v1/preview/${encodeURIComponent(s.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...Z()},body:JSON.stringify({prompt:w,...s.fork_id?{fork_id:s.fork_id}:{}})});if(!u.ok){let I=await u.json().catch(()=>({}));throw new Error(I.error||`API error: ${u.status}`)}let p=await u.json();ve(p.fork_id),l=await(await fetch(`${o}/api/v1/forks/${p.fork_id}`,{headers:{Authorization:`Bearer ${t}`,...Z()}})).json();}else {let u={userId:r,prompt:w,boundaryId:e,appId:i};k&&(u.containerId=k),n&&(u.userHash=n);let p=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(u)});if(!p.ok){let g=await p.json().catch(()=>({}));throw new Error(g.error||`API error: ${p.status}`)}l=await p.json();}P(l);let E=new URLSearchParams({key:t});n&&(E.set("userId",r),E.set("userHash",n));let S=new EventSource(`${o}/api/v1/forks/${l.id}/events?${E.toString()}`);C.current=S,S.onmessage=u=>{try{let p=JSON.parse(u.data);if(v(g=>[...g,p]),p.type==="complete"){let g=p.data;d(e,l.id),a().catch(()=>{}).finally(()=>{let I={...l,status:"complete",moduleUrl:g.moduleUrl,cssUrls:g.cssUrls,summary:g.summary,completedAt:new Date().toISOString()};P(I),c("complete"),S.close();});}else if(p.type==="error"){let g=p.data;h(g.error||"Unknown error"),c("error"),S.close();}}catch{}},S.onerror=()=>{fetch(`${o}/api/v1/forks/${l.id}`,{headers:{Authorization:`Bearer ${t}`}}).then(u=>u.json()).then(u=>{P(u),u.status==="complete"?(d(e,u.id),a().catch(()=>{}),c("complete")):u.status==="error"&&(h(u.error||"Fork generation failed"),c("error"));}).catch(()=>{h("Connection lost"),c("error");}),S.close();};}catch(l){h(l.message),c("error");}},[t,i,o,e,s,d,a,n,r]),M=ht.useCallback(async()=>{try{if(!i)throw new Error("ForkProvider requires appId for boundary undo.");let w={userId:r,boundaryId:e,appId:i};n&&(w.userHash=n);let k=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(w)});if(!k.ok){let E=await k.json().catch(()=>({}));throw new Error(E.error||`API error: ${k.status}`)}let l=await k.json();return await a().catch(()=>{}),l.removed?(P(null),c("prompting")):l.fork&&(P(l.fork),c("complete")),l}catch(w){throw h(w.message),w}},[t,i,o,e,a,n,r]);return {state:f,fork:F,events:x,error:y,open:R,close:T,startFork:$,undoFork:M}}function yr(e){let{state:t,fork:r,events:n,error:o,open:i,close:s,startFork:a,undoFork:d}=St(e);return {state:t,fork:r,events:n,error:o,isOpen:t!=="idle",open:i,close:s,submit:a,undo:d}}function xt(){let{apiKey:e,userId:t,userHash:r,baseUrl:n,previewSession:o,setSlotFork:i,clearSlotFork:s,skipAnimationForSlot:a}=G(),[d,f]=ht.useState("idle"),[c,F]=ht.useState(null),[P,x]=ht.useState([]),[v,y]=ht.useState(null),h=ht.useRef(null),C=ht.useCallback(()=>{f("prompting"),x([]),y(null),F(null);},[]),R=ht.useCallback(()=>{f("idle"),h.current&&(h.current.close(),h.current=null);},[]);ht.useEffect(()=>{o&&o.target.kind==="slot"&&f(M=>M==="idle"?"prompting":M);},[o?.preview_session_id,o?.target.kind]);let T=ht.useCallback(async(M,w,k)=>{try{f("running"),x([]),y(null);let l;if(o){let u=await fetch(`${n}/api/v1/preview/${encodeURIComponent(o.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...Z()},body:JSON.stringify({prompt:M,...o.fork_id?{fork_id:o.fork_id}:{}})});if(!u.ok){let I=await u.json().catch(()=>({}));throw new Error(I.error||`API error: ${u.status}`)}let p=await u.json();ve(p.fork_id),l=await(await fetch(`${n}/api/v1/forks/${p.fork_id}`,{headers:{Authorization:`Bearer ${e}`,...Z()}})).json();}else {let u={userId:t,prompt:M};w&&(u.slotId=w),k&&(u.containerId=k),r&&(u.userHash=r);let p=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(u)});if(!p.ok){let g=await p.json().catch(()=>({}));throw new Error(g.error||`API error: ${p.status}`)}l=await p.json();}F(l);let E=new URLSearchParams({key:e});r&&(E.set("userId",t),E.set("userHash",r));let S=new EventSource(`${n}/api/v1/forks/${l.id}/events?${E.toString()}`);h.current=S,S.onmessage=u=>{try{let p=JSON.parse(u.data);if(x(g=>[...g,p]),p.type==="complete"){let g=p.data,I={...l,status:"complete",bundleUrl:g.bundleUrl,summary:g.summary,completedAt:new Date().toISOString()};F(I),f("complete"),w&&g.bundleUrl&&i(w,I),S.close();}else if(p.type==="error"){let g=p.data;y(g.error||"Unknown error"),f("error"),S.close();}}catch{}},S.onerror=()=>{fetch(`${n}/api/v1/forks/${l.id}`,{headers:{Authorization:`Bearer ${e}`}}).then(u=>u.json()).then(u=>{F(u),u.status==="complete"?(f("complete"),w&&u.bundleUrl&&i(w,u)):u.status==="error"&&(y(u.error||"Fork generation failed"),f("error"));}).catch(()=>{y("Connection lost"),f("error");}),S.close();};}catch(l){y(l.message),f("error");}},[e,t,r,n,o,i]),$=ht.useCallback(async M=>{try{let w={userId:t,slotId:M};r&&(w.userHash=r);let k=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(w)});if(!k.ok){let E=await k.json().catch(()=>({}));throw new Error(E.error||`API error: ${k.status}`)}let l=await k.json();return a(M),l.removed?(s(M),F(null),f("prompting")):l.fork&&(i(M,l.fork),F(l.fork)),l}catch(w){throw y(w.message),w}},[e,t,r,n,s,i]);return {state:d,fork:c,events:P,error:v,open:C,close:R,startFork:T,undoFork:$}}function kr(){let{state:e,fork:t,events:r,error:n,open:o,close:i,startFork:s,undoFork:a}=xt();return {state:e,fork:t,events:r,error:n,isOpen:e!=="idle",open:o,close:i,submit:s,undo:a}}function Ft(e){let t=hr(e),r=kr(),n=yr(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:i,userId:s,userHash:a,appId:d}=G(),f=t.type==="slot"?r:n,c=t.type==="slot"?"slot":"boundary",F=t.id,P=t.title,x=ht.useCallback((y,h,C)=>t.type==="slot"?r.submit(y,h??t.id,C):n.submit(y,C),[n,r,t]),v=ht.useCallback(y=>t.type==="slot"?r.undo(y??t.id):n.undo(),[n,r,t]);return {...f,target:t,targetId:F,targetLabel:P,historyMode:c,submit:x,undo:v,buttonProps:{onClick:f.open},panelProps:{state:f.state,fork:f.fork,events:f.events,error:f.error,...t.type==="slot"?{slotId:F,targetLabel:P,historyMode:c}:{targetId:F,targetLabel:P,historyMode:c},onSubmit:x,onUndo:v,onClose:f.close,baseUrl:o,apiKey:i,userId:s,userHash:a,appId:d}}}function $e(e){let{embedded:t}=e,r=Ft(e);return t?Br.jsx(Ge,{...r.panelProps,embedded:true}):r.isOpen?Br.jsx(Ge,{...r.panelProps}):Br.jsx(bt,{...r.buttonProps})}function Wn({boundaryId:e,title:t}){return Br.jsx($e,{boundaryId:e,title:t})}function Et(e){let t=Array.from(e.children).filter(n=>n instanceof HTMLElement);return t.length===1?t[0]:getComputedStyle(e).display==="contents"?null:e}function wr(e){let t=e.getBoundingClientRect(),r=e.cloneNode(true);r.style.position="fixed",r.style.top=`${t.top}px`,r.style.left=`${t.left}px`,r.style.width=`${t.width}px`,r.style.height=`${t.height}px`,r.style.flex="none",r.style.minHeight="auto",r.style.zIndex="9998",r.style.pointerEvents="none",r.style.overflow="hidden";let n=getComputedStyle(e).backgroundColor;r.style.backgroundColor=n&&n!=="rgba(0, 0, 0, 0)"&&n!=="transparent"?n:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(r);let o=e.querySelectorAll("*"),i=r.querySelectorAll("*");for(let s=0;s<o.length;s+=1)o[s].scrollTop!==0&&(i[s].scrollTop=o[s].scrollTop),o[s].scrollLeft!==0&&(i[s].scrollLeft=o[s].scrollLeft);return r}function $t(e){let t=[],r=e.querySelectorAll("*");for(let n of r){if(!(n instanceof HTMLElement))continue;let o=n.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(n.tagName))continue;let i=getComputedStyle(n),s=parseFloat(i.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:s});}return t}function vr(e,t){let r=[];for(let n of t)if(!(e.find(s=>s.tag===n.tag&&s.className===n.className&&Math.abs(s.rect.top-n.rect.top)<20&&Math.abs(s.rect.left-n.rect.left)<20)||r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom))){for(let s=r.length-1;s>=0;s-=1){let a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Sr(e,t){let r=[];for(let n of e)if(!(t.find(s=>s.tag===n.tag&&s.className===n.className&&Math.abs(s.rect.top-n.rect.top)<20&&Math.abs(s.rect.left-n.rect.left)<20)||r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom))){for(let s=r.length-1;s>=0;s-=1){let a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function xr(e,t,r,n,o){let i=Math.max(0,Math.min(o,r/2,n/2));return i===0?`M ${e} ${t} L ${e+r} ${t} L ${e+r} ${t+n} L ${e} ${t+n} Z`:[`M ${e+i} ${t}`,`L ${e+r-i} ${t}`,`A ${i} ${i} 0 0 1 ${e+r} ${t+i}`,`L ${e+r} ${t+n-i}`,`A ${i} ${i} 0 0 1 ${e+r-i} ${t+n}`,`L ${e+i} ${t+n}`,`A ${i} ${i} 0 0 1 ${e} ${t+n-i}`,`L ${e} ${t+i}`,`A ${i} ${i} 0 0 1 ${e+i} ${t}`,"Z"].join(" ")}function _t(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-highlights","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");n.appendChild(o);let i=[];for(let c=0;c<e.length;c+=1){let{rect:F,borderRadius:P}=e[c],x=F.left-.5,v=F.top-.5,y=F.width+1,h=F.height+1,C=Math.min(P+.5,y/2,h/2),R=xr(x,v,y,h,C),T=`__fork-glow-${c}`,$=document.createElementNS(t,"filter");$.setAttribute("id",T),$.setAttribute("x","-100%"),$.setAttribute("y","-100%"),$.setAttribute("width","300%"),$.setAttribute("height","300%");let M=document.createElementNS(t,"feGaussianBlur");M.setAttribute("in","SourceGraphic"),M.setAttribute("stdDeviation","8"),$.appendChild(M),o.appendChild($);let w=`__fork-mask-${c}`,k=document.createElementNS(t,"mask");k.setAttribute("id",w),k.setAttribute("maskUnits","userSpaceOnUse"),k.setAttribute("x",String(x-200)),k.setAttribute("y",String(v-200)),k.setAttribute("width",String(y+400)),k.setAttribute("height",String(h+400));let l=document.createElementNS(t,"rect");l.setAttribute("x",String(x-200)),l.setAttribute("y",String(v-200)),l.setAttribute("width",String(y+400)),l.setAttribute("height",String(h+400)),l.setAttribute("fill","white"),k.appendChild(l);let E=document.createElementNS(t,"path");E.setAttribute("d",R),E.setAttribute("fill","black"),k.appendChild(E),o.appendChild(k);let S=document.createElementNS(t,"g");S.setAttribute("mask",`url(#${w})`),S.setAttribute("opacity","0");let u=document.createElementNS(t,"g");u.setAttribute("filter",`url(#${T})`);let p=document.createElementNS(t,"path");p.setAttribute("d",R),p.setAttribute("fill","none"),p.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),p.setAttribute("stroke-width","6"),p.setAttribute("stroke-linecap","round"),u.appendChild(p),S.appendChild(u),n.appendChild(S);let g=document.createElementNS(t,"path");g.setAttribute("d",R),g.setAttribute("fill","none"),g.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),g.setAttribute("stroke-width","2"),g.setAttribute("stroke-linecap","round"),g.setAttribute("opacity","0"),n.appendChild(g),i.push(p,g),p.__group=S;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let c=0;c<i.length;c+=2){let F=i[c],P=i[c+1],x=F.__group;if(!x)continue;let v=P.getTotalLength(),y=F.getTotalLength();if(v<=0)continue;let h=v*.35;P.setAttribute("stroke-dasharray",`${h} ${v-h}`),P.setAttribute("stroke-dashoffset","0"),s.push(P.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*v,opacity:.92,offset:.06},{strokeDashoffset:-2*v,opacity:.92,offset:.92},{strokeDashoffset:-2.25*v,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let C=y*.35;F.setAttribute("stroke-dasharray",`${C} ${y-C}`),F.setAttribute("stroke-dashoffset","0"),s.push(F.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*y,offset:.06},{strokeDashoffset:-2*y,offset:.92},{strokeDashoffset:-2.25*y,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(x.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,d=()=>{if(a)return;a=true,clearTimeout(f);for(let F of s)try{F.cancel();}catch{}let c=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});c.onfinish=()=>r.remove(),window.removeEventListener("click",d);},f=setTimeout(d,14500);return setTimeout(()=>{a||window.addEventListener("click",d);},500),d}function Fr(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-removed","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs"),i=document.createElementNS(t,"filter");i.setAttribute("id","__fork-removed-shadow"),i.setAttribute("x","-10%"),i.setAttribute("y","-10%"),i.setAttribute("width","120%"),i.setAttribute("height","120%");let s=document.createElementNS(t,"feDropShadow");s.setAttribute("dx","0"),s.setAttribute("dy","1"),s.setAttribute("stdDeviation","2"),s.setAttribute("flood-color","rgba(0,0,0,0.15)"),i.appendChild(s),o.appendChild(i),n.appendChild(o);for(let{rect:a,borderRadius:d}of e){let f=document.createElementNS(t,"path");f.setAttribute("d",xr(a.left,a.top,a.width,a.height,d)),f.setAttribute("fill","none"),f.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),f.setAttribute("stroke-width","1.5"),f.setAttribute("stroke-dasharray","8 4"),f.setAttribute("stroke-linecap","round"),f.setAttribute("filter","url(#__fork-removed-shadow)"),f.setAttribute("opacity","0"),n.appendChild(f),f.animate([{opacity:0,offset:0},{opacity:.6,offset:.08},{opacity:.05,offset:.45},{opacity:.6,offset:.85},{opacity:.05,offset:1}],{duration:5e3,easing:"ease-in-out",fill:"forwards"});}return r.appendChild(n),document.body.appendChild(r),r}var Ze=new Map,At=new Map;function Vn(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function Er(e,t){let r=(t?e[t]:void 0)??e.default;if(typeof r!="function"){let n=t||"default";throw new Error(`Fork boundary module is missing a React component export: ${n}`)}return r}function qn(e){if(!e||typeof document>"u")return Promise.resolve();let t=Ze.get(e);if(t)return t;let r=document.querySelector(`link[data-fork-override-href="${e}"]`);if(r instanceof HTMLLinkElement){let o=r.sheet?Promise.resolve():new Promise((i,s)=>{let a=()=>{r.removeEventListener("load",a),r.removeEventListener("error",d),i();},d=()=>{r.removeEventListener("load",a),r.removeEventListener("error",d),s(new Error(`Failed to load boundary stylesheet: ${e}`));};r.addEventListener("load",a,{once:true}),r.addEventListener("error",d,{once:true});});return Ze.set(e,o),o}let n=new Promise((o,i)=>{let s=document.createElement("link");s.rel="stylesheet",s.href=e,s.setAttribute("data-fork-override-href",e),s.onload=()=>o(),s.onerror=()=>{s.remove(),i(new Error(`Failed to load boundary stylesheet: ${e}`));},document.head.appendChild(s);}).catch(o=>{throw Ze.delete(e),o});return Ze.set(e,n),n}function Jn(e){let t=At.get(e);if(t)return t;let r=import(e).catch(n=>{throw At.delete(e),n});return At.set(e,r),r}async function Xn(e,t,r){if(e)try{await Promise.all(e.cssUrls.map(i=>qn(i)));let o=await Jn(e.moduleUrl);return Er(o,r)}catch(o){console.error(`[Fork] Failed to load override for boundary "${e.boundaryId}", falling back to original module.`,o);}let n=await t();return Er(n,r)}function Yn(e){function t(r){let{appId:n,moduleOverridesEnabled:o,moduleManifestReady:i,moduleManifestVersion:s,registerBoundary:a,getBoundaryOverride:d,consumeBoundaryAnimation:f}=G(),[c,F]=ht.useState(null),[P,x]=ht.useState(null),v=ht.useRef(null),y=ht.useRef(null),h=ht.useRef(null),C=ht.useRef(false),R=ht.useRef(null),T=ht.useRef(null),$=d(e.id),M=$?`override:${$.id}`:"original",w=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if(ht.useEffect(()=>()=>{T.current&&(clearTimeout(T.current),T.current=null),R.current&&(R.current.remove(),R.current=null);},[]),ht.useEffect(()=>{a({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[n,a,e.id,e.exportName,w]),ht.useEffect(()=>{if(o&&!i&&!c||y.current===M&&c)return;let k=false;return x(null),Xn($,e.original,e.exportName).then(l=>{if(!k){if($?.id&&f(e.id,$.id)&&v.current){let E=Et(v.current);if(E){let S=$t(E);S.length>0&&(h.current=S,C.current=true,T.current&&(clearTimeout(T.current),T.current=null),R.current&&R.current.remove(),R.current=wr(E));}}y.current=M,ht.startTransition(()=>{F(()=>l);});}}).catch(l=>{k||x(Vn(l));}),()=>{k=true;}},[f,M,o,i,s,$?.id,$?.moduleUrl,$?.integrity,$?.cssUrls.join("|"),e.exportName,e.original,c]),ht.useEffect(()=>{if(!C.current||!c||!v.current)return;let k=false;return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(k||!v.current)return;let l=h.current,E=Et(v.current);if(h.current=null,C.current=false,!l||!E){R.current&&(R.current.remove(),R.current=null);return}let S=$t(E),u=vr(l,S),p=Sr(l,S),g=R.current;if(p.length>0&&g){let I=Fr(p);T.current=setTimeout(()=>{T.current=null;let z=400;g.animate([{opacity:1},{opacity:0}],{duration:z,fill:"forwards"}),I.animate([{opacity:1},{opacity:0}],{duration:z,fill:"forwards"}),setTimeout(()=>{g.remove(),I.remove(),R.current===g&&(R.current=null),u.length>0&&_t(u);},z);},3500);}else g&&(g.remove(),R.current===g&&(R.current=null)),u.length>0&&_t(u);});}),()=>{k=true;}},[c]),P)throw P;return c?Br.jsx("div",{ref:v,style:{display:"contents"},children:Br.jsx(c,{...r})}):Br.jsx(Br.Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function Qn({slotId:e,title:t,slotLabel:r}){return Br.jsx($e,{slotId:e,title:t,slotLabel:r})}
44
- exports.ForkBoundaryUI=Wn;exports.ForkButton=bt;exports.ForkChatInterface=$e;exports.ForkPanel=Ge;exports.ForkProvider=Qr;exports.ForkSlot=pn;exports.ForkUI=Qn;exports.clearCachedManifest=qr;exports.forkable=Yn;exports.loadManifest=He;exports.manifestDiffers=Jr;exports.readCachedManifest=Gr;exports.registerForkShared=at;exports.useBoundaryFork=St;exports.useFork=xt;exports.useForkChatPanel=Ft;exports.usePreviewSession=Be;exports.writeCachedManifest=Vr;
43
+ `}),Yr.jsxs("div",{className:"__fork-panel",style:Jr,children:[Yr.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:[Yr.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:[Yr.jsx(qe,{style:{width:16,height:16,color:"#1c4587",cursor:"pointer",flexShrink:0},onDoubleClick:async c=>{if(c.stopPropagation(),!it&&confirm("Reset all forks? This will remove all forked components.")){Ie(true);try{let b=await Nr();`${b?.deleted??0}`,$([]),_(""),D(!1),dt();}catch(b){console.error("[Fork] Reset failed:",b);}finally{Ie(false);}}}}),e==="running"?Yr.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:Wr}):Fe.length===0&&!Ue?Yr.jsxs("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:["Fork ",He]}):Ue?Yr.jsxs("div",{ref:je,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[Yr.jsxs("button",{type:"button",onClick:()=>{ae(c=>!c);},onMouseEnter:()=>Bt(true),onMouseLeave:()=>Bt(false),"aria-haspopup":"menu","aria-expanded":K,style:{display:"inline-flex",alignItems:"center",gap:4,padding:"3px 6px",border:"1px solid transparent",borderRadius:6,background:Or||K?"#f3f4f6":"transparent",fontSize:13,fontWeight:600,color:"#111827",fontFamily:"inherit",cursor:"pointer",maxWidth:180,minWidth:0,transition:"background-color 0.12s"},children:[Yr.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:Vt}),Yr.jsx(lucideReact.ChevronDown,{style:{width:12,height:12,color:"#6b7280",flexShrink:0,transform:K?"rotate(180deg)":void 0,transition:"transform 0.15s"}})]}),K&&Yr.jsxs("div",{role:"menu",style:{position:"absolute",top:"calc(100% + 4px)",left:0,minWidth:200,maxWidth:260,background:"#ffffff",border:"1px solid #e5e7eb",borderRadius:8,boxShadow:"0 4px 12px rgba(0,0,0,0.08), 0 1px 3px rgba(0,0,0,0.06)",padding:4,zIndex:2147483001},children:[Fe.map(c=>{let b=c.id===X,O=Ur===c.id,Z=re===c.id;return Yr.jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>Ht(c.id),onMouseLeave:()=>Ht(null),onClick:()=>{c.id!==X&&Kr(c.id);},disabled:!!re,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:O?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:re?"default":"pointer",textAlign:"left",fontWeight:b?600:400,opacity:re&&!Z?.55:1},children:[Yr.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:b&&Yr.jsx(lucideReact.Check,{style:{width:12,height:12}})}),Yr.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Z?"Switching...":c.name})]},c.id)}),Yr.jsx("div",{style:{height:1,background:"#e5e7eb",margin:"4px 0"}}),Yr.jsx("button",{type:"button",role:"menuitem",onMouseEnter:()=>Nt(true),onMouseLeave:()=>Nt(false),onClick:()=>{Gr();},disabled:!!re,style:{display:"flex",alignItems:"center",width:"100%",padding:"6px 8px",border:"none",background:Br?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:re?"default":"pointer",textAlign:"left",opacity:re&&re!=="__new__"?.55:1},children:re==="__new__"?"Creating...":"+ New container"}),Dt&&Yr.jsx("div",{style:{padding:"6px 8px",fontSize:11,lineHeight:1.35,color:"#b91c1c"},children:Dt})]})]}):Yr.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:Vt}),e==="running"&&Yr.jsx("span",{title:ge?`Estimated ~${ge} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:ge?"#1c4587":"#9ca3af",backgroundColor:ge?"rgba(28, 69, 135, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:ge?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:ge?`~${ge}m`:"~ m"}),e==="complete"&&Yr.jsx("div",{style:{height:6,width:6,backgroundColor:"#1c4587",borderRadius:"50%",flexShrink:0}})]}),!h&&Yr.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[Wt&&Yr.jsx("button",{onClick:le?zr:jr,onMouseEnter:()=>L(true),onMouseLeave:()=>L(false),title:le?"Redock to sidebar":"Pop out into window",style:{padding:6,borderRadius:6,color:m?"#4b5563":"#9ca3af",backgroundColor:m?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:le?Yr.jsx(lucideReact.PictureInPicture,{style:{width:16,height:16}}):Yr.jsx(lucideReact.PictureInPicture2,{style:{width:16,height:16}})}),Yr.jsx("button",{onClick:dt,onMouseEnter:()=>g(true),onMouseLeave:()=>g(false),style:{padding:6,borderRadius:6,color:u?"#4b5563":"#9ca3af",backgroundColor:u?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:Yr.jsx(lucideReact.X,{style:{width:16,height:16}})})]})]}),Yr.jsxs("div",{ref:Oe,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[e==="prompting"&&M.length===0&&Yr.jsx("div",{style:{padding:"24px 20px",textAlign:"center"},children:Yr.jsx("p",{style:{fontSize:13,color:"#6b7280",marginBottom:14,lineHeight:1.625,margin:"0 0 14px 0"},children:"Describe the feature you want to build."})}),M.length>0&&Yr.jsx("div",{style:{padding:"16px 16px 0 16px"},children:M.map((c,b)=>Yr.jsx("div",{style:{marginBottom:b<M.length-1?10:0},children:c.type==="user"?Yr.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexDirection:"row-reverse"},children:[Yr.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:Yr.jsx(lucideReact.User,{style:{width:13,height:13,color:"#6b7280"}})}),Yr.jsx("div",{style:{backgroundColor:"#f3f4f6",borderRadius:"12px 4px 12px 12px",padding:"8px 12px",fontSize:13,color:"#374151",lineHeight:1.5,maxWidth:"75%"},children:c.text})]}):Yr.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[Yr.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#f0fdf4",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:Yr.jsx(lucideReact.Check,{style:{width:13,height:13,color:"#9ca3af"}})}),Yr.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:[Yr.jsx("span",{style:{flex:1},children:c.text}),p&&b===M.length-1&&e!=="running"&&Yr.jsxs("button",{onClick:O=>{O.stopPropagation(),Vr();},onMouseEnter:()=>q(b),onMouseLeave:()=>q(null),disabled:te,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:ue===b?"rgba(0,0,0,0.06)":"transparent",color:ue===b?"#6b7280":"#d1d5db",cursor:te?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:te?.4:1,flexShrink:0},children:[Yr.jsx(lucideReact.Undo2,{style:{width:12,height:12}}),ue===b&&Yr.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"})]})]})]})},b))}),e==="running"&&Yr.jsx("div",{style:{padding:16},children:Yr.jsxs("div",{onClick:()=>D(!J),style:{backgroundColor:"#1a1a2e",borderRadius:12,overflow:"hidden",cursor:"pointer",transition:"all 0.3s cubic-bezier(0.22, 1, 0.36, 1)"},children:[Yr.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px"},children:[Yr.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[Yr.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:Yr.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),Yr.jsx(Xn,{events:r})]}),Yr.jsx("div",{style:{color:"#6b7280",flexShrink:0,marginLeft:8,transition:"transform 0.2s ease",transform:J?"rotate(180deg)":"rotate(0deg)"},children:Yr.jsx(lucideReact.ChevronDown,{style:{width:14,height:14}})})]}),Yr.jsx("div",{style:{maxHeight:J?320:0,opacity:J?1:0,transition:"max-height 0.35s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.25s ease",overflow:"hidden"},children:Yr.jsx("div",{style:{borderTop:"1px solid rgba(255,255,255,0.08)",maxHeight:320,overflowY:"auto"},children:Yr.jsx(kr,{events:r})})})]})}),e==="error"&&Yr.jsxs("div",{style:{padding:"20px 16px",textAlign:"center"},children:[Yr.jsx("div",{style:{width:36,height:36,backgroundColor:"#fef2f2",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 10px auto"},children:Yr.jsx(lucideReact.X,{style:{width:18,height:18,color:"#ef4444"}})}),Yr.jsx("p",{style:{fontSize:12,color:"#6b7280",marginBottom:10,maxWidth:260,margin:"0 auto 10px auto"},children:n}),Yr.jsxs("button",{onClick:()=>{let c=t?.prompt||ct.current;c&&f(c,ce);},onMouseEnter:()=>z(true),onMouseLeave:()=>z(false),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,color:"#4f46e5",backgroundColor:N?"#e0e7ff":"#eef2ff",border:"none",cursor:"pointer",transition:"background-color 0.15s",fontFamily:"inherit"},children:[Yr.jsx(lucideReact.RotateCcw,{style:{width:12,height:12}})," Try Again"]})]})]}),e!=="running"&&Yr.jsx("div",{style:{padding:"8px 12px 12px 12px",borderTop:"1px solid rgba(229, 231, 235, 0.6)",flexShrink:0},children:Yr.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:[Yr.jsx("textarea",{ref:at,value:T,onChange:c=>{_(c.target.value),c.target.style.height="auto",c.target.style.height=Math.min(c.target.scrollHeight,160)+"px";},onKeyDown:c=>{c.key==="Enter"&&!c.shiftKey&&(c.preventDefault(),Kt()),c.key==="Escape"&&!h&&dt();},placeholder:M.length>0?"Ask for another change...":`Describe your ideal ${He.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"}}),Yr.jsx("button",{onClick:Kt,disabled:!T.trim(),onMouseEnter:()=>ee(true),onMouseLeave:()=>ee(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:T.trim()?1:.25,transform:W&&T.trim()?"scale(1.1)":"scale(1)",background:T.trim()?"#1c4587":"rgba(0,0,0,0.12)",border:"none",cursor:T.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:Yr.jsx(lucideReact.ArrowUp,{style:{width:13,height:13}})})]})})]})]});return h?ut:le&&we?Xr.createPortal(ut,we.document.body):Yr.jsx(Yn,{children:ut})}function Rr(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 At(e){let{apiKey:t,userId:r,userHash:n,baseUrl:o,appId:i,previewSession:s,refreshModuleManifest:a,queueBoundaryAnimation:f}=V(),[p,d]=xt.useState("idle"),[S,P]=xt.useState(null),[R,x]=xt.useState([]),[y,h]=xt.useState(null),T=xt.useRef(null),_=xt.useCallback(()=>{d("prompting"),x([]),h(null),P(null);},[]),M=xt.useCallback(()=>{d("idle"),T.current&&(T.current.close(),T.current=null);},[]);xt.useEffect(()=>{s&&s.target.kind==="module"&&s.target.id===e&&d(v=>v==="idle"?"prompting":v);},[s?.preview_session_id,s?.target.id,e]);let $=xt.useCallback(async(v,k)=>{try{if(!i)throw new Error("ForkProvider requires appId for module boundary prompts.");d("running"),x([]),h(null);let l;if(s){let u=await fetch(`${o}/api/v1/preview/${encodeURIComponent(s.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...G()},body:JSON.stringify({prompt:v,...s.fork_id?{fork_id:s.fork_id}:{}})});if(!u.ok){let L=await u.json().catch(()=>({}));throw new Error(L.error||`API error: ${u.status}`)}let g=await u.json();_e(g.fork_id),l=await(await fetch(`${o}/api/v1/forks/${g.fork_id}`,{headers:{Authorization:`Bearer ${t}`,...G()}})).json();}else {let u={userId:r,prompt:v,boundaryId:e,appId:i};k&&(u.containerId=k),n&&(u.userHash=n);let g=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(u)});if(!g.ok){let m=await g.json().catch(()=>({}));throw new Error(m.error||`API error: ${g.status}`)}l=await g.json();}P(l);let A=new URLSearchParams({key:t});n&&(A.set("userId",r),A.set("userHash",n));let F=new EventSource(`${o}/api/v1/forks/${l.id}/events?${A.toString()}`);T.current=F,F.onmessage=u=>{try{let g=JSON.parse(u.data);if(x(m=>[...m,g]),g.type==="complete"){let m=g.data;f(e,l.id),a().catch(()=>{}).finally(()=>{let L={...l,status:"complete",moduleUrl:m.moduleUrl,cssUrls:m.cssUrls,summary:m.summary,completedAt:new Date().toISOString()};P(L),d("complete"),F.close();});}else if(g.type==="error"){let m=g.data;h(m.error||"Unknown error"),d("error"),F.close();}}catch{}},F.onerror=()=>{fetch(`${o}/api/v1/forks/${l.id}`,{headers:{Authorization:`Bearer ${t}`}}).then(u=>u.json()).then(u=>{P(u),u.status==="complete"?(f(e,u.id),a().catch(()=>{}),d("complete")):u.status==="error"&&(h(u.error||"Fork generation failed"),d("error"));}).catch(()=>{h("Connection lost"),d("error");}),F.close();};}catch(l){h(l.message),d("error");}},[t,i,o,e,s,f,a,n,r]),I=xt.useCallback(async()=>{try{if(!i)throw new Error("ForkProvider requires appId for boundary undo.");let v={userId:r,boundaryId:e,appId:i};n&&(v.userHash=n);let k=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(v)});if(!k.ok){let A=await k.json().catch(()=>({}));throw new Error(A.error||`API error: ${k.status}`)}let l=await k.json();return await a().catch(()=>{}),l.removed?(P(null),d("prompting")):l.fork&&(P(l.fork),d("complete")),l}catch(v){throw h(v.message),v}},[t,i,o,e,a,n,r]);return {state:p,fork:S,events:R,error:y,open:_,close:M,startFork:$,undoFork:I}}function Er(e){let{state:t,fork:r,events:n,error:o,open:i,close:s,startFork:a,undoFork:f}=At(e);return {state:t,fork:r,events:n,error:o,isOpen:t!=="idle",open:i,close:s,submit:a,undo:f}}function Ct(){let{apiKey:e,userId:t,userHash:r,baseUrl:n,previewSession:o,setSlotFork:i,clearSlotFork:s,skipAnimationForSlot:a}=V(),[f,p]=xt.useState("idle"),[d,S]=xt.useState(null),[P,R]=xt.useState([]),[x,y]=xt.useState(null),h=xt.useRef(null),T=xt.useCallback(()=>{p("prompting"),R([]),y(null),S(null);},[]),_=xt.useCallback(()=>{p("idle"),h.current&&(h.current.close(),h.current=null);},[]);xt.useEffect(()=>{o&&o.target.kind==="slot"&&p(I=>I==="idle"?"prompting":I);},[o?.preview_session_id,o?.target.kind]);let M=xt.useCallback(async(I,v,k)=>{try{p("running"),R([]),y(null);let l;if(o){let u=await fetch(`${n}/api/v1/preview/${encodeURIComponent(o.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...G()},body:JSON.stringify({prompt:I,...o.fork_id?{fork_id:o.fork_id}:{}})});if(!u.ok){let L=await u.json().catch(()=>({}));throw new Error(L.error||`API error: ${u.status}`)}let g=await u.json();_e(g.fork_id),l=await(await fetch(`${n}/api/v1/forks/${g.fork_id}`,{headers:{Authorization:`Bearer ${e}`,...G()}})).json();}else {let u={userId:t,prompt:I};v&&(u.slotId=v),k&&(u.containerId=k),r&&(u.userHash=r);let g=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(u)});if(!g.ok){let m=await g.json().catch(()=>({}));throw new Error(m.error||`API error: ${g.status}`)}l=await g.json();}S(l);let A=new URLSearchParams({key:e});r&&(A.set("userId",t),A.set("userHash",r));let F=new EventSource(`${n}/api/v1/forks/${l.id}/events?${A.toString()}`);h.current=F,F.onmessage=u=>{try{let g=JSON.parse(u.data);if(R(m=>[...m,g]),g.type==="complete"){let m=g.data,L={...l,status:"complete",bundleUrl:m.bundleUrl,summary:m.summary,completedAt:new Date().toISOString()};S(L),p("complete"),v&&m.bundleUrl&&i(v,L),F.close();}else if(g.type==="error"){let m=g.data;y(m.error||"Unknown error"),p("error"),F.close();}}catch{}},F.onerror=()=>{fetch(`${n}/api/v1/forks/${l.id}`,{headers:{Authorization:`Bearer ${e}`}}).then(u=>u.json()).then(u=>{S(u),u.status==="complete"?(p("complete"),v&&u.bundleUrl&&i(v,u)):u.status==="error"&&(y(u.error||"Fork generation failed"),p("error"));}).catch(()=>{y("Connection lost"),p("error");}),F.close();};}catch(l){y(l.message),p("error");}},[e,t,r,n,o,i]),$=xt.useCallback(async I=>{try{let v={userId:t,slotId:I};r&&(v.userHash=r);let k=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(v)});if(!k.ok){let A=await k.json().catch(()=>({}));throw new Error(A.error||`API error: ${k.status}`)}let l=await k.json();return a(I),l.removed?(s(I),S(null),p("prompting")):l.fork&&(i(I,l.fork),S(l.fork)),l}catch(v){throw y(v.message),v}},[e,t,r,n,s,i]);return {state:f,fork:d,events:P,error:x,open:T,close:_,startFork:M,undoFork:$}}function _r(){let{state:e,fork:t,events:r,error:n,open:o,close:i,startFork:s,undoFork:a}=Ct();return {state:e,fork:t,events:r,error:n,isOpen:e!=="idle",open:o,close:i,submit:s,undo:a}}function Pt(e){let t=Rr(e),r=_r(),n=Er(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:i,userId:s,userHash:a,appId:f}=V(),p=t.type==="slot"?r:n,d=t.type==="slot"?"slot":"boundary",S=t.id,P=t.title,R=xt.useCallback((y,h,T)=>t.type==="slot"?r.submit(y,h??t.id,T):n.submit(y,T),[n,r,t]),x=xt.useCallback(y=>t.type==="slot"?r.undo(y??t.id):n.undo(),[n,r,t]);return {...p,target:t,targetId:S,targetLabel:P,historyMode:d,submit:R,undo:x,buttonProps:{onClick:p.open},panelProps:{state:p.state,fork:p.fork,events:p.events,error:p.error,...t.type==="slot"?{slotId:S,targetLabel:P,historyMode:d}:{targetId:S,targetLabel:P,historyMode:d},onSubmit:R,onUndo:x,onClose:p.close,baseUrl:o,apiKey:i,userId:s,userHash:a,appId:f}}}function Me(e){let{embedded:t}=e,r=Pt(e);return t?Yr.jsx(Qe,{...r.panelProps,embedded:true}):r.isOpen?Yr.jsx(Qe,{...r.panelProps}):Yr.jsx(Et,{...r.buttonProps})}function no({boundaryId:e,title:t}){return Yr.jsx(Me,{boundaryId:e,title:t})}function Mt(e){let t=Array.from(e.children).filter(n=>n instanceof HTMLElement);return t.length===1?t[0]:getComputedStyle(e).display==="contents"?null:e}function Ar(e){let t=e.getBoundingClientRect(),r=e.cloneNode(true);r.style.position="fixed",r.style.top=`${t.top}px`,r.style.left=`${t.left}px`,r.style.width=`${t.width}px`,r.style.height=`${t.height}px`,r.style.flex="none",r.style.minHeight="auto",r.style.zIndex="9998",r.style.pointerEvents="none",r.style.overflow="hidden";let n=getComputedStyle(e).backgroundColor;r.style.backgroundColor=n&&n!=="rgba(0, 0, 0, 0)"&&n!=="transparent"?n:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(r);let o=e.querySelectorAll("*"),i=r.querySelectorAll("*");for(let s=0;s<o.length;s+=1)o[s].scrollTop!==0&&(i[s].scrollTop=o[s].scrollTop),o[s].scrollLeft!==0&&(i[s].scrollLeft=o[s].scrollLeft);return r}function It(e){let t=[],r=e.querySelectorAll("*");for(let n of r){if(!(n instanceof HTMLElement))continue;let o=n.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(n.tagName))continue;let i=getComputedStyle(n),s=parseFloat(i.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:s});}return t}function Cr(e,t){let r=[];for(let n of t)if(!(e.find(s=>s.tag===n.tag&&s.className===n.className&&Math.abs(s.rect.top-n.rect.top)<20&&Math.abs(s.rect.left-n.rect.left)<20)||r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom))){for(let s=r.length-1;s>=0;s-=1){let a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Pr(e,t){let r=[];for(let n of e)if(!(t.find(s=>s.tag===n.tag&&s.className===n.className&&Math.abs(s.rect.top-n.rect.top)<20&&Math.abs(s.rect.left-n.rect.left)<20)||r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom))){for(let s=r.length-1;s>=0;s-=1){let a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Tr(e,t,r,n,o){let i=Math.max(0,Math.min(o,r/2,n/2));return i===0?`M ${e} ${t} L ${e+r} ${t} L ${e+r} ${t+n} L ${e} ${t+n} Z`:[`M ${e+i} ${t}`,`L ${e+r-i} ${t}`,`A ${i} ${i} 0 0 1 ${e+r} ${t+i}`,`L ${e+r} ${t+n-i}`,`A ${i} ${i} 0 0 1 ${e+r-i} ${t+n}`,`L ${e+i} ${t+n}`,`A ${i} ${i} 0 0 1 ${e} ${t+n-i}`,`L ${e} ${t+i}`,`A ${i} ${i} 0 0 1 ${e+i} ${t}`,"Z"].join(" ")}function Lt(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-highlights","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");n.appendChild(o);let i=[];for(let d=0;d<e.length;d+=1){let{rect:S,borderRadius:P}=e[d],R=S.left-.5,x=S.top-.5,y=S.width+1,h=S.height+1,T=Math.min(P+.5,y/2,h/2),_=Tr(R,x,y,h,T),M=`__fork-glow-${d}`,$=document.createElementNS(t,"filter");$.setAttribute("id",M),$.setAttribute("x","-100%"),$.setAttribute("y","-100%"),$.setAttribute("width","300%"),$.setAttribute("height","300%");let I=document.createElementNS(t,"feGaussianBlur");I.setAttribute("in","SourceGraphic"),I.setAttribute("stdDeviation","8"),$.appendChild(I),o.appendChild($);let v=`__fork-mask-${d}`,k=document.createElementNS(t,"mask");k.setAttribute("id",v),k.setAttribute("maskUnits","userSpaceOnUse"),k.setAttribute("x",String(R-200)),k.setAttribute("y",String(x-200)),k.setAttribute("width",String(y+400)),k.setAttribute("height",String(h+400));let l=document.createElementNS(t,"rect");l.setAttribute("x",String(R-200)),l.setAttribute("y",String(x-200)),l.setAttribute("width",String(y+400)),l.setAttribute("height",String(h+400)),l.setAttribute("fill","white"),k.appendChild(l);let A=document.createElementNS(t,"path");A.setAttribute("d",_),A.setAttribute("fill","black"),k.appendChild(A),o.appendChild(k);let F=document.createElementNS(t,"g");F.setAttribute("mask",`url(#${v})`),F.setAttribute("opacity","0");let u=document.createElementNS(t,"g");u.setAttribute("filter",`url(#${M})`);let g=document.createElementNS(t,"path");g.setAttribute("d",_),g.setAttribute("fill","none"),g.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),g.setAttribute("stroke-width","6"),g.setAttribute("stroke-linecap","round"),u.appendChild(g),F.appendChild(u),n.appendChild(F);let m=document.createElementNS(t,"path");m.setAttribute("d",_),m.setAttribute("fill","none"),m.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),m.setAttribute("stroke-width","2"),m.setAttribute("stroke-linecap","round"),m.setAttribute("opacity","0"),n.appendChild(m),i.push(g,m),g.__group=F;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let d=0;d<i.length;d+=2){let S=i[d],P=i[d+1],R=S.__group;if(!R)continue;let x=P.getTotalLength(),y=S.getTotalLength();if(x<=0)continue;let h=x*.35;P.setAttribute("stroke-dasharray",`${h} ${x-h}`),P.setAttribute("stroke-dashoffset","0"),s.push(P.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*x,opacity:.92,offset:.06},{strokeDashoffset:-2*x,opacity:.92,offset:.92},{strokeDashoffset:-2.25*x,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let T=y*.35;S.setAttribute("stroke-dasharray",`${T} ${y-T}`),S.setAttribute("stroke-dashoffset","0"),s.push(S.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*y,offset:.06},{strokeDashoffset:-2*y,offset:.92},{strokeDashoffset:-2.25*y,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(R.animate([{opacity:0,offset:0},{opacity:.92,offset:.06},{opacity:.92,offset:.92},{opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));}let a=false,f=()=>{if(a)return;a=true,clearTimeout(p);for(let S of s)try{S.cancel();}catch{}let d=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});d.onfinish=()=>r.remove(),window.removeEventListener("click",f);},p=setTimeout(f,14500);return setTimeout(()=>{a||window.addEventListener("click",f);},500),f}function Mr(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-removed","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs"),i=document.createElementNS(t,"filter");i.setAttribute("id","__fork-removed-shadow"),i.setAttribute("x","-10%"),i.setAttribute("y","-10%"),i.setAttribute("width","120%"),i.setAttribute("height","120%");let s=document.createElementNS(t,"feDropShadow");s.setAttribute("dx","0"),s.setAttribute("dy","1"),s.setAttribute("stdDeviation","2"),s.setAttribute("flood-color","rgba(0,0,0,0.15)"),i.appendChild(s),o.appendChild(i),n.appendChild(o);for(let{rect:a,borderRadius:f}of e){let p=document.createElementNS(t,"path");p.setAttribute("d",Tr(a.left,a.top,a.width,a.height,f)),p.setAttribute("fill","none"),p.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),p.setAttribute("stroke-width","1.5"),p.setAttribute("stroke-dasharray","8 4"),p.setAttribute("stroke-linecap","round"),p.setAttribute("filter","url(#__fork-removed-shadow)"),p.setAttribute("opacity","0"),n.appendChild(p),p.animate([{opacity:0,offset:0},{opacity:.6,offset:.08},{opacity:.05,offset:.45},{opacity:.6,offset:.85},{opacity:.05,offset:1}],{duration:5e3,easing:"ease-in-out",fill:"forwards"});}return r.appendChild(n),document.body.appendChild(r),r}var st=new Map,Ot=new Map;function io(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function Lr(e,t){let r=(t?e[t]:void 0)??e.default;if(typeof r!="function"){let n=t||"default";throw new Error(`Fork boundary module is missing a React component export: ${n}`)}return r}function ao(e){if(!e||typeof document>"u")return Promise.resolve();let t=st.get(e);if(t)return t;let r=document.querySelector(`link[data-fork-override-href="${e}"]`);if(r instanceof HTMLLinkElement){let o=r.sheet?Promise.resolve():new Promise((i,s)=>{let a=()=>{r.removeEventListener("load",a),r.removeEventListener("error",f),i();},f=()=>{r.removeEventListener("load",a),r.removeEventListener("error",f),s(new Error(`Failed to load boundary stylesheet: ${e}`));};r.addEventListener("load",a,{once:true}),r.addEventListener("error",f,{once:true});});return st.set(e,o),o}let n=new Promise((o,i)=>{let s=document.createElement("link");s.rel="stylesheet",s.href=e,s.setAttribute("data-fork-override-href",e),s.onload=()=>o(),s.onerror=()=>{s.remove(),i(new Error(`Failed to load boundary stylesheet: ${e}`));},document.head.appendChild(s);}).catch(o=>{throw st.delete(e),o});return st.set(e,n),n}function lo(e){let t=Ot.get(e);if(t)return t;let r=import(e).catch(n=>{throw Ot.delete(e),n});return Ot.set(e,r),r}async function co(e,t,r){if(e)try{await Promise.all(e.cssUrls.map(i=>ao(i)));let o=await lo(e.moduleUrl);return Lr(o,r)}catch(o){console.error(`[Fork] Failed to load override for boundary "${e.boundaryId}", falling back to original module.`,o);}let n=await t();return Lr(n,r)}function uo(e){function t(r){let{appId:n,moduleOverridesEnabled:o,moduleManifestReady:i,moduleManifestVersion:s,registerBoundary:a,getBoundaryOverride:f,consumeBoundaryAnimation:p}=V(),[d,S]=xt.useState(null),[P,R]=xt.useState(null),x=xt.useRef(null),y=xt.useRef(null),h=xt.useRef(null),T=xt.useRef(false),_=xt.useRef(null),M=xt.useRef(null),$=f(e.id),I=$?`override:${$.id}`:"original",v=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if(xt.useEffect(()=>()=>{M.current&&(clearTimeout(M.current),M.current=null),_.current&&(_.current.remove(),_.current=null);},[]),xt.useEffect(()=>{a({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[n,a,e.id,e.exportName,v]),xt.useEffect(()=>{if(o&&!i&&!d||y.current===I&&d)return;let k=false;return R(null),co($,e.original,e.exportName).then(l=>{if(!k){if($?.id&&p(e.id,$.id)&&x.current){let A=Mt(x.current);if(A){let F=It(A);F.length>0&&(h.current=F,T.current=true,M.current&&(clearTimeout(M.current),M.current=null),_.current&&_.current.remove(),_.current=Ar(A));}}y.current=I,xt.startTransition(()=>{S(()=>l);});}}).catch(l=>{k||R(io(l));}),()=>{k=true;}},[p,I,o,i,s,$?.id,$?.moduleUrl,$?.integrity,$?.cssUrls.join("|"),e.exportName,e.original,d]),xt.useEffect(()=>{if(!T.current||!d||!x.current)return;let k=false;return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(k||!x.current)return;let l=h.current,A=Mt(x.current);if(h.current=null,T.current=false,!l||!A){_.current&&(_.current.remove(),_.current=null);return}let F=It(A),u=Cr(l,F),g=Pr(l,F),m=_.current;if(g.length>0&&m){let L=Mr(g);M.current=setTimeout(()=>{M.current=null;let W=400;m.animate([{opacity:1},{opacity:0}],{duration:W,fill:"forwards"}),L.animate([{opacity:1},{opacity:0}],{duration:W,fill:"forwards"}),setTimeout(()=>{m.remove(),L.remove(),_.current===m&&(_.current=null),u.length>0&&Lt(u);},W);},3500);}else m&&(m.remove(),_.current===m&&(_.current=null)),u.length>0&&Lt(u);});}),()=>{k=true;}},[d]),P)throw P;return d?Yr.jsx("div",{ref:x,style:{display:"contents"},children:Yr.jsx(d,{...r})}):Yr.jsx(Yr.Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function po({slotId:e,title:t,slotLabel:r}){return Yr.jsx(Me,{slotId:e,title:t,slotLabel:r})}
44
+ exports.ForkBoundaryUI=no;exports.ForkButton=Et;exports.ForkChatInterface=Me;exports.ForkPanel=Qe;exports.ForkProvider=pn;exports.ForkSlot=En;exports.ForkUI=po;exports.clearCachedManifest=ln;exports.forkable=uo;exports.loadManifest=Ge;exports.manifestDiffers=cn;exports.readCachedManifest=sn;exports.registerForkShared=pt;exports.useBoundaryFork=At;exports.useFork=Ct;exports.useForkChatPanel=Pt;exports.usePreviewSession=Ke;exports.writeCachedManifest=an;
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import*as ht from'react';import ht__default,{createContext,useSyncExternalStore,useState,useRef,useEffect,useCallback,startTransition,Children,useContext,isValidElement}from'react';import*as Or from'react-dom';import {createPortal}from'react-dom';import*as Br from'react/jsx-runtime';import {jsx,Fragment,jsxs}from'react/jsx-runtime';import*as Hr from'react/jsx-dev-runtime';import {ChevronDown,Check,PictureInPicture,PictureInPicture2,X,User,Undo2,RotateCcw,ArrowUp,Loader2,AlertCircle,Sparkles,Package,Wrench,MessageSquare,Code,Terminal,FileSearch,Pencil}from'lucide-react';var ue="__FORK_SHARED__";function it(){var t,r,n,o;let e=globalThis;return e[ue]||(e[ue]={}),(t=e[ue]).react||(t.react=ht),(r=e[ue])["react-dom"]||(r["react-dom"]=Or),(n=e[ue])["react/jsx-runtime"]||(n["react/jsx-runtime"]=Br),(o=e[ue])["react/jsx-dev-runtime"]||(o["react/jsx-dev-runtime"]=Hr),e[ue]}function at(e){return Object.assign(it(),e)}var Nr="__fork_preview_session__";function Oe(e){return `${Nr}${e}`}var K={apiKey:null,session:null},lt=new Set;function ct(){for(let e of lt)try{e();}catch(t){console.error("[fork-preview] subscriber threw",t);}}function Bt(e){let t=Date.parse(e.expires_at);return Number.isFinite(t)?t<=Date.now():true}function Dr(e){if(typeof window>"u")return null;try{let t=window.sessionStorage.getItem(Oe(e));if(!t)return null;let r=JSON.parse(t);return !r||typeof r!="object"||typeof r.preview_session_id!="string"?null:Bt(r)?(window.sessionStorage.removeItem(Oe(e)),null):r}catch{return null}}function Ht(e,t){if(!(typeof window>"u"))try{t?window.sessionStorage.setItem(Oe(e),JSON.stringify(t)):window.sessionStorage.removeItem(Oe(e));}catch{}}function we(e){K.apiKey!==e&&(K.apiKey=e,K.session=Dr(e),ct());}function de(){return K.session?Bt(K.session)?(ut(null),null):K.session:null}function ut(e){K.session=e,K.apiKey&&Ht(K.apiKey,e),ct();}function ve(e){K.session&&K.session.fork_id!==e&&(K.session={...K.session,fork_id:e},K.apiKey&&Ht(K.apiKey,K.session),ct());}function dt(e){return lt.add(e),()=>{lt.delete(e);}}var Nt="__fork_preview";function Dt(){if(typeof window>"u")return null;let e=window.location.hash;if(!e||e.length<2)return null;let r=new URLSearchParams(e.slice(1)).get(Nt);return typeof r=="string"&&r.length>0?r:null}function ft(e){if(typeof window>"u")return false;try{if(window.sessionStorage.getItem(`__fork_preview_session__${e}`))return !0}catch{}return zt()!==null}function jt(){if(typeof window>"u")return;let e=window.location.hash;if(!e||e.length<2)return;let t=new URLSearchParams(e.slice(1));t.delete(Nt);let r=t.toString(),n=r?`#${r}`:"";try{window.history.replaceState(null,"",window.location.pathname+window.location.search+n);}catch{}}var fe=null;function zt(){if(fe)return fe;let e=Dt();return e?(fe=e,jt(),fe):null}async function pt(e,t){we(e);let r=de();if(r)return fe=null,r;let n=fe??Dt();if(fe=null,!n)return null;jt();try{let o=await fetch(`${t}/api/v1/preview/activate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({token:n})});if(!o.ok){let a=await o.json().catch(()=>({}));return console.warn(`[fork-preview] activate failed (${o.status}): ${a.error??"unknown"}`),null}let i=await o.json(),s={preview_session_id:i.preview_session_id,tenant_id:i.tenant_id,app_id:i.app_id,target:i.target,target_user_id:i.target_user_id,operator_id:i.operator_id,container_id:i.container_id??null,container_name:i.container_name??i.target_user_id,fork_id:i.fork_id??null,expires_at:i.expires_at};return ut(s),s}catch(o){return console.warn("[fork-preview] activate threw",o),null}}function zr(){return de()}function Wr(){return null}function Be(){return useSyncExternalStore(dt,zr,Wr)}function Z(){let e=de();if(!e)return {};let t={"X-Fork-Preview-Session":e.preview_session_id};return e.fork_id&&(t["X-Fork-Preview-Fork-Id"]=e.fork_id),t}async function He(e){let t=new URLSearchParams({app:e.appId,user:e.userId});e.containerId&&t.set("containerId",e.containerId);let r=`${e.baseUrl}/api/v1/manifest?${t.toString()}`,n={Authorization:`Bearer ${e.apiKey}`,"X-Fork-App-Id":e.appId,"X-Fork-User-Id":e.userId,...e.extraHeaders??{}};e.userHash&&(n["X-Fork-User-Hash"]=e.userHash),e.previous?.etag&&(n["If-None-Match"]=e.previous.etag);let o=await fetch(r,{headers:n,signal:e.signal});if(o.status===304)return null;if(!o.ok)throw new Error(`manifest ${o.status} ${o.statusText}`);let i=await o.json(),s={};for(let[a,d]of Object.entries(i.modules)){let f=d.moduleUrl??d.bundleUrl??null,c=d.legacyModuleUrl??d.legacyBundleUrl??null;s[a]={forkId:d.forkId,moduleUrl:f,legacyModuleUrl:c,bundleUrl:d.bundleUrl??f,legacyBundleUrl:d.legacyBundleUrl??c,cssUrls:d.cssUrls??[],integrity:d.integrity,metadata:d.metadata,buildId:d.buildId,updatedAt:d.updatedAt};}return {containerId:i.containerId,slots:i.slots,modules:s,generatedAt:i.generatedAt,etag:o.headers.get("ETag")??void 0}}var Kr="fork:manifest:v1";function gt(e,t,r){return `${Kr}:${e}:${t}:${r}`}function Gr(e,t,r){if(typeof window>"u")return null;try{let n=window.localStorage.getItem(gt(e,t,r));return n?JSON.parse(n):null}catch{return null}}function Vr(e,t,r,n){if(!(typeof window>"u"))try{window.localStorage.setItem(gt(e,t,r),JSON.stringify(n));}catch{}}function qr(e,t,r){if(!(typeof window>"u"))try{window.localStorage.removeItem(gt(e,t,r));}catch{}}function Jr(e,t){if(!e||!t)return e!==t;if(e.containerId!==t.containerId)return true;let r=Object.entries(e.slots),n=Object.entries(t.slots);if(r.length!==n.length)return true;for(let[s,a]of r){let d=t.slots[s];if(!d||d.forkId!==a.forkId||d.buildId!==a.buildId)return true}let o=Object.entries(e.modules),i=Object.entries(t.modules);if(o.length!==i.length)return true;for(let[s,a]of o){let d=t.modules[s];if(!d||d.forkId!==a.forkId||d.buildId!==a.buildId)return true}return false}var Gt=createContext(null);function xe(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function Zr(e,t){let r={};for(let[n,o]of Object.entries(t.boundaries||{}))r[n]={...o,moduleUrl:xe(e,o.moduleUrl),cssUrls:Array.isArray(o.cssUrls)?o.cssUrls.map(i=>xe(e,i)):[]};return r}function Wt(e,t,r,n){let o={};for(let[i,s]of Object.entries(t.slots)){let a=s.bundleUrl??s.legacyBundleUrl;a&&(o[i]={id:s.forkId,userId:r,prompt:"",status:"complete",slotId:i,appId:n,bundleUrl:xe(e,a),createdAt:s.updatedAt,completedAt:s.updatedAt});}return o}function Kt(e,t){let r={};for(let[n,o]of Object.entries(t.modules)){let i=o.moduleUrl??o.legacyModuleUrl??o.bundleUrl??"";i&&(r[n]={id:o.forkId,boundaryId:n,moduleUrl:xe(e,i),cssUrls:(o.cssUrls??[]).map(s=>xe(e,s)),integrity:o.integrity,metadata:o.metadata,createdAt:o.updatedAt});}return r}function Qr(e){let{apiKey:t,baseUrl:r,children:n,appId:o,shared:i}=e,s="userId"in e?e.userId:void 0,a="authUrl"in e?e.authUrl:void 0,[d]=useState(()=>(we(t),ft(t))),[f,c]=useState({}),[F,P]=useState(s?{userId:s,userHash:void 0}:null),[x,v]=useState(!!s||d),[y,h]=useState({}),[C,R]=useState(!o),[T,$]=useState(0),[M,w]=useState(null),k=useRef(new Map),l=useRef(new Map),[E,S]=useState(0),u=useRef(new Set),p=useRef(new Map),g=useRef(void 0);it(),useEffect(()=>{return pt(t,r).then(()=>{}),()=>{}},[]);let I=Be();i&&g.current!==i&&(at(i),g.current=i),useEffect(()=>{a&&(d||(v(false),fetch(a,{credentials:"include"}).then(_=>{if(!_.ok)throw new Error(`Auth endpoint returned ${_.status}`);return _.json()}).then(_=>{if(!_.userId||typeof _.userId!="string")throw new Error("authUrl response must include userId");P({userId:_.userId,userHash:_.userHash});}).catch(_=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",_.message);}).finally(()=>{v(true);})));},[a,d]),useEffect(()=>{!a&&s&&(P({userId:s,userHash:void 0}),v(true));},[s,a]);let z=F?.userId??"",Y=F?.userHash,H=I?I.target_user_id:z,D=I?void 0:Y,V=!!o,N=useCallback(async()=>{if(!V){w(null),h({}),R(true),$(b=>b+1);return}if(!x){R(false);return}if(!H||!o){w(null),h({}),R(true),$(b=>b+1);return}if(R(false),!I){try{let b=await He({baseUrl:r,apiKey:t,appId:o,userId:H,userHash:D});b&&(w(b.containerId),c(Wt(r,b,H,o)),h(Kt(r,b)));}catch(b){console.error("[ForkProvider] Failed to fetch fork manifest:",b.message),w(null),c({}),h({});}finally{$(b=>b+1),R(true);}return}if(w(I.container_id??null),I.container_id){try{let b=await He({baseUrl:r,apiKey:t,appId:o,userId:H,containerId:I.container_id,extraHeaders:Z()});b&&(c(Wt(r,b,H,o)),h(Kt(r,b)));}catch(b){console.error("[ForkProvider] Failed to fetch preview container manifest:",b.message),c({}),h({});}finally{$(b=>b+1),R(true);}return}let _=new URLSearchParams({appId:o,userId:H});D&&_.set("userHash",D);try{let b=await fetch(`${r}/api/v1/boundaries/manifest?${_.toString()}`,{headers:{Authorization:`Bearer ${t}`,...Z()}});if(!b.ok)throw new Error(`${b.status}`);let O=await b.json();h(Zr(r,O));}catch(b){console.error("[ForkProvider] Failed to fetch module override manifest:",b.message),h({});}finally{$(b=>b+1),R(true);}},[t,o,r,x,V,D,H,I?.preview_session_id,I?.fork_id,I?.container_id]);useEffect(()=>{if(!H||o&&(!I||I.container_id))return;let _=new URLSearchParams({userId:H});D&&_.set("userHash",D),fetch(`${r}/api/v1/forks/active?${_.toString()}`,{headers:{Authorization:`Bearer ${t}`,...Z()}}).then(b=>{if(!b.ok)throw new Error(`${b.status}`);return b.json()}).then(b=>{b&&typeof b=="object"&&c(b);}).catch(()=>{});},[t,o,H,D,r,I?.preview_session_id,I?.fork_id]),useEffect(()=>{N();},[N]);let Q=useCallback((_,b)=>{c(O=>({...O,[_]:b}));},[]),ee=useCallback(_=>{c(b=>{let O={...b};return delete O[_],O});},[]),ie=useCallback(_=>{u.current.add(_);},[]),q=useCallback(_=>u.current.has(_)?(u.current.delete(_),true):false,[]),Qe=useCallback((_,b)=>{p.current.set(_,b);},[]),_e=useCallback((_,b)=>p.current.get(_)!==b?false:(p.current.delete(_),true),[]),ke=useCallback(_=>{if(!o)return;let b=JSON.stringify(_);k.current.get(_.id)===b||l.current.get(_.id)?.signature===b||(l.current.set(_.id,{boundary:_,signature:b}),S(W=>W+1));},[o]);useEffect(()=>{if(!o||l.current.size===0)return;let _=setTimeout(()=>{let b=Array.from(l.current.values());b.length!==0&&fetch(`${r}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:o,boundaries:b.map(O=>O.boundary)})}).then(O=>{if(!O.ok)throw new Error(`${O.status}`)}).then(()=>{for(let O of b)l.current.get(O.boundary.id)?.signature===O.signature&&(l.current.delete(O.boundary.id),k.current.set(O.boundary.id,O.signature));}).catch(O=>{console.error("[ForkProvider] Failed to register module boundaries:",O.message);});},50);return ()=>{clearTimeout(_);}},[t,o,r,E]);let be=useCallback(_=>y[_],[y]),J=useCallback(async()=>{if(!H)throw new Error("Reset requires a resolved user identity.");let _=new URLSearchParams({userId:H});D&&_.set("userHash",D);let b=await fetch(`${r}/api/v1/forks/all?${_.toString()}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`,...Z()}});if(!b.ok){let W=await b.json().catch(()=>({}));throw new Error(W.error||`API error: ${b.status}`)}let O=await b.json().catch(()=>({}));c({}),h({}),R(true),$(W=>W+1),u.current.clear(),p.current.clear();try{for(let W=sessionStorage.length-1;W>=0;W-=1){let ae=sessionStorage.key(W);ae&&ae.startsWith("__fork_animated_")&&sessionStorage.removeItem(ae);}}catch{}return O},[t,r,D,H]);return jsx(Gt.Provider,{value:{apiKey:t,userId:H,userHash:D,baseUrl:r,appId:o,forks:f,moduleOverridesEnabled:V,moduleManifestReady:C,moduleManifestVersion:T,currentContainerId:M,previewSession:I,setSlotFork:Q,clearSlotFork:ee,skipAnimationForSlot:ie,shouldSkipAnimation:q,queueBoundaryAnimation:Qe,consumeBoundaryAnimation:_e,registerBoundary:ke,getBoundaryOverride:be,refreshModuleManifest:N,resetAllForks:J},children:n})}function G(){let e=useContext(Gt);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function Ne(e){return G().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 n=this.values.get(t);if(Object.is(n,r))return;if(n!==void 0&&r!==null&&n!==null&&typeof n=="object"&&typeof r=="object")try{if(JSON.stringify(n)===JSON.stringify(r))return}catch{}this.values.set(t,r),this.snapshots.set(t,r);let o=this.listeners.get(t);o&&o.forEach(i=>i());}get(t){return this.values.get(t)}getSnapshot(t){return this.snapshots.get(t)}subscribe(t,r){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(r),()=>{this.listeners.get(t)?.delete(r);}}useValue(t){let r=window.__FORK_REACT__;return r?.useSyncExternalStore?r.useSyncExternalStore(n=>this.subscribe(t,n),()=>this.getSnapshot(t)):(console.warn("[ForkBridge] React.useSyncExternalStore not available, returning static value"),this.values.get(t))}emit(t,...r){let n=this.eventHandlers.get(t);n&&n.forEach(o=>o(...r));}on(t,r){return this.eventHandlers.has(t)||this.eventHandlers.set(t,new Set),this.eventHandlers.get(t).add(r),()=>{this.eventHandlers.get(t)?.delete(r);}}destroy(){this.listeners.clear(),this.eventHandlers.clear(),this.values.clear(),this.snapshots.clear();let t=window.__FORK_BRIDGE__;t&&delete t[this.slotId];}};function yt(e,t){let r;try{r=Children.only(e);}catch{let o=Children.count(e);throw new Error(`<ForkSlot slotId="${t}"> must wrap exactly one React component, got ${o} children. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`)}let n=r.type;if(typeof n=="string")throw new Error(`<ForkSlot slotId="${t}"> child must be a React component (function or class), not an HTML element <${n}>. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`);if(typeof n=="symbol")throw new Error(`<ForkSlot slotId="${t}"> child must be a single React component, not a fragment or special React element. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`);return r}var qt=new Set;function Jt(e){let t=[],r=e.querySelectorAll("*");for(let n of r){if(!(n instanceof HTMLElement))continue;let o=n.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(n.tagName))continue;let i=getComputedStyle(n),s=parseFloat(i.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:s});}return t}function on(e,t){let r=[];for(let n of t)if(!e.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)&&!r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom)){for(let s=r.length-1;s>=0;s--){let a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function sn(e,t){let r=[];for(let n of e)if(!t.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)&&!r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom)){for(let s=r.length-1;s>=0;s--){let a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Yt(e,t,r,n,o){return o=Math.max(0,Math.min(o,r/2,n/2)),o===0?`M ${e} ${t} L ${e+r} ${t} L ${e+r} ${t+n} L ${e} ${t+n} Z`:[`M ${e+o} ${t}`,`L ${e+r-o} ${t}`,`A ${o} ${o} 0 0 1 ${e+r} ${t+o}`,`L ${e+r} ${t+n-o}`,`A ${o} ${o} 0 0 1 ${e+r-o} ${t+n}`,`L ${e+o} ${t+n}`,`A ${o} ${o} 0 0 1 ${e} ${t+n-o}`,`L ${e} ${t+o}`,`A ${o} ${o} 0 0 1 ${e+o} ${t}`,"Z"].join(" ")}function Xt(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-highlights","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");n.appendChild(o);let i=[];for(let c=0;c<e.length;c++){let{rect:F,borderRadius:P}=e[c],x=F.left-.5,v=F.top-.5,y=F.width+1,h=F.height+1,C=Math.min(P+.5,y/2,h/2),R=Yt(x,v,y,h,C),T=`__fork-glow-${c}`,$=document.createElementNS(t,"filter");$.setAttribute("id",T),$.setAttribute("x","-100%"),$.setAttribute("y","-100%"),$.setAttribute("width","300%"),$.setAttribute("height","300%");let M=document.createElementNS(t,"feGaussianBlur");M.setAttribute("in","SourceGraphic"),M.setAttribute("stdDeviation","8"),$.appendChild(M),o.appendChild($);let w=`__fork-mask-${c}`,k=document.createElementNS(t,"mask");k.setAttribute("id",w),k.setAttribute("maskUnits","userSpaceOnUse"),k.setAttribute("x",String(x-200)),k.setAttribute("y",String(v-200)),k.setAttribute("width",String(y+400)),k.setAttribute("height",String(h+400));let l=document.createElementNS(t,"rect");l.setAttribute("x",String(x-200)),l.setAttribute("y",String(v-200)),l.setAttribute("width",String(y+400)),l.setAttribute("height",String(h+400)),l.setAttribute("fill","white"),k.appendChild(l);let E=document.createElementNS(t,"path");E.setAttribute("d",R),E.setAttribute("fill","black"),k.appendChild(E),o.appendChild(k);let S=document.createElementNS(t,"g");S.setAttribute("mask",`url(#${w})`),S.setAttribute("opacity","0");let u=document.createElementNS(t,"g");u.setAttribute("filter",`url(#${T})`);let p=document.createElementNS(t,"path");p.setAttribute("d",R),p.setAttribute("fill","none"),p.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),p.setAttribute("stroke-width","6"),p.setAttribute("stroke-linecap","round"),u.appendChild(p),S.appendChild(u),n.appendChild(S);let g=document.createElementNS(t,"path");g.setAttribute("d",R),g.setAttribute("fill","none"),g.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),g.setAttribute("stroke-width","2"),g.setAttribute("stroke-linecap","round"),g.setAttribute("opacity","0"),n.appendChild(g),i.push(p,g),p.__group=S;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let c=0;c<i.length;c+=2){let F=i[c],P=i[c+1],x=F.__group,v=P.getTotalLength(),y=F.getTotalLength();if(v<=0)continue;let h=v*.35;P.setAttribute("stroke-dasharray",`${h} ${v-h}`),P.setAttribute("stroke-dashoffset","0"),s.push(P.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*v,opacity:.92,offset:.06},{strokeDashoffset:-2*v,opacity:.92,offset:.92},{strokeDashoffset:-2.25*v,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let C=y*.35;F.setAttribute("stroke-dasharray",`${C} ${y-C}`),F.setAttribute("stroke-dashoffset","0"),s.push(F.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*y,offset:.06},{strokeDashoffset:-2*y,offset:.92},{strokeDashoffset:-2.25*y,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(x.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,d=()=>{if(a)return;a=true,clearTimeout(f);for(let F of s)try{F.cancel();}catch{}let c=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});c.onfinish=()=>r.remove(),window.removeEventListener("click",d);},f=setTimeout(d,14500);return setTimeout(()=>{a||window.addEventListener("click",d);},500),d}function an(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-removed","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs"),i=document.createElementNS(t,"filter");i.setAttribute("id","__fork-removed-shadow"),i.setAttribute("x","-10%"),i.setAttribute("y","-10%"),i.setAttribute("width","120%"),i.setAttribute("height","120%");let s=document.createElementNS(t,"feDropShadow");s.setAttribute("dx","0"),s.setAttribute("dy","1"),s.setAttribute("stdDeviation","2"),s.setAttribute("flood-color","rgba(0,0,0,0.15)"),i.appendChild(s),o.appendChild(i),n.appendChild(o);for(let{rect:a,borderRadius:d}of e){let f=a.left,c=a.top,F=a.width,P=a.height,x=Math.min(d,F/2,P/2),v=Yt(f,c,F,P,x),y=document.createElementNS(t,"path");y.setAttribute("d",v),y.setAttribute("fill","none"),y.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),y.setAttribute("stroke-width","1.5"),y.setAttribute("stroke-dasharray","8 4"),y.setAttribute("stroke-linecap","round"),y.setAttribute("filter","url(#__fork-removed-shadow)"),y.setAttribute("opacity","0"),n.appendChild(y),y.animate([{opacity:0,offset:0},{opacity:.6,offset:.08},{opacity:.05,offset:.45},{opacity:.6,offset:.85},{opacity:.05,offset:1}],{duration:5e3,easing:"ease-in-out",fill:"forwards"});}return r.appendChild(n),document.body.appendChild(r),r}function ln(e,t){if(e===t)return true;let r=Object.keys(e);if(r.length!==Object.keys(t).length)return false;for(let n of r)if(!Object.is(e[n],t[n]))return false;return true}var cn=ht__default.memo(function({component:t,containerRef:r,wrapperStyle:n,hostProps:o}){return jsx("div",{ref:r,style:n,children:jsx(t,{...o})})},(e,t)=>e.component===t.component&&ln(e.hostProps,t.hostProps)),mt=class extends ht__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 Zt({slotId:e,children:t,githubRepo:r,shared:n,events:o}){yt(t,e);let i=Ne(e),{baseUrl:s,apiKey:a,appId:d,shouldSkipAnimation:f}=G(),[c,F]=useState(null),P=useRef(null),x=useRef(null),v=useRef(null),y=useRef(false),h=useRef(null),C=useRef(null),R=!!(n||o),T=useRef(null);R&&!T.current&&(T.current=new Fe(e));let $=useRef(o);if($.current=o,useEffect(()=>{if(R)return ()=>{T.current?.destroy(),T.current=null;}},[R,e]),R&&T.current&&n)for(let[E,S]of Object.entries(n))T.current.set(E,S);useEffect(()=>{if(!R)return;T.current||(T.current=new Fe(e));let E=T.current,S=Object.keys($.current||{}).map(u=>E.on(u,(...p)=>$.current?.[u]?.(...p)));return ()=>S.forEach(u=>u())},[R,e]),useEffect(()=>{if(qt.has(e))return;qt.add(e);let E={id:e,appId:d,label:e,eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:r,mode:"direct",sharedKeys:n?Object.keys(n):[],eventNames:o?Object.keys(o):[],propsShape:"",callbackNames:[]};fetch(`${s}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify(E)}).catch(()=>{});},[e,s,a,r,d]);let M=i?.id||null;useEffect(()=>{if(i?.bundleUrl,P.current,x.current,!i?.bundleUrl||!M){return}let E=`${s}${i.bundleUrl.replace("bundle.js","component.js")}`,S=`__fork_animated_${e}`,u=sessionStorage.getItem(S),p=f(e),g=!p&&u!==M;if(p&&M&&sessionStorage.setItem(S,M),g&&x.current){let D=Jt(x.current);v.current=D,y.current=true,`${e}${D.length}`;}window.__FORK_REACT__=ht__default,window.__FORK_REACT_DOM__=Or,window.__FORK_REACT_JSX__=Br;let I=Date.now(),z=`${s}${i.bundleUrl.replace("bundle.js","component.css")}?t=${I}`,Y=document.createElement("link");Y.rel="stylesheet",Y.href=z,Y.dataset.forkSlot=e,document.head.appendChild(Y);let H=document.createElement("script");return H.src=E+"?t="+I,H.onload=()=>{let D=window.__FORK_EXPORT__;if(D?.default){if(x.current&&v.current&&y.current){let V=x.current.getBoundingClientRect(),N=x.current.cloneNode(true);N.style.position="fixed",N.style.top=`${V.top}px`,N.style.left=`${V.left}px`,N.style.width=`${V.width}px`,N.style.height=`${V.height}px`,N.style.flex="none",N.style.minHeight="auto",N.style.zIndex="9998",N.style.pointerEvents="none",N.style.overflow="hidden";let Q=getComputedStyle(x.current).backgroundColor;N.style.backgroundColor=Q&&Q!=="rgba(0, 0, 0, 0)"&&Q!=="transparent"?Q:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(N);let ee=x.current.querySelectorAll("*"),ie=N.querySelectorAll("*");for(let q=0;q<ee.length;q++)ee[q].scrollTop!==0&&(ie[q].scrollTop=ee[q].scrollTop),ee[q].scrollLeft!==0&&(ie[q].scrollLeft=ee[q].scrollLeft);h.current=N;}F(()=>D.default),P.current=M;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},H.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(H),()=>{H.remove(),Y.remove(),C.current&&(clearTimeout(C.current),C.current=null),h.current&&(h.current.remove(),h.current=null);}},[M,s,e]),useEffect(()=>{if(!y.current||!c||!x.current){`${e}${y.current}`,x.current;return}let E=v.current;if(!E){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!x.current)return;let S=Jt(x.current),u=on(E,S),p=sn(E,S),g=h.current;if(`${e}${u.length}${p.length}`,p.length>0&&g){let I=an(p);C.current=setTimeout(()=>{C.current=null;let z=400;g.animate([{opacity:1},{opacity:0}],{duration:z,fill:"forwards"}),I.animate([{opacity:1},{opacity:0}],{duration:z,fill:"forwards"}),setTimeout(()=>{g.remove(),I.remove(),h.current=null,u.length>0&&(Xt(u));},z);},3500);}else g&&(g.remove(),h.current=null),u.length>0&&(Xt(u));v.current=null,y.current=false,M&&(sessionStorage.setItem(`__fork_animated_${e}`,M),`${e}`);});});},[c]);let w={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!i||i.status!=="complete"||!i.bundleUrl)return jsx("div",{ref:x,style:w,children:t});if(!c)return jsx("div",{ref:x,style:w,children:t});let l=t?.props??{};return jsx(mt,{slotId:e,resetKey:M,fallback:jsx("div",{ref:x,style:w,children:t}),children:jsx(cn,{component:c,containerRef:x,wrapperStyle:w,hostProps:l})})}var er=new Set;function fn(e){return `{ ${Object.entries(e).map(([r,n])=>n==null?`${r}: unknown`:Array.isArray(n)?`${r}: ${n.length>0?typeof n[0]:"unknown"}[]`:`${r}: ${typeof n}`).join("; ")} }`}function tr(e,t=new Set){return Children.forEach(e,r=>{if(!isValidElement(r))return;let n=r.props;for(let[o,i]of Object.entries(n))typeof i=="function"&&/^on[A-Z]/.test(o)&&t.add(o);n.children&&tr(n.children,t);}),t}function pn({slotId:e,props:t,children:r,allowedFetches:n,githubRepo:o,callbacks:i,mode:s="iframe",shared:a,events:d}){if(yt(r,e),s==="direct")return jsx(Zt,{slotId:e,githubRepo:o,shared:a,events:d,children:r});let f=Ne(e),{baseUrl:c,apiKey:F,appId:P}=G(),x=useRef(null),v=useRef(false),y=useRef(null),h=useRef(i);h.current=i;let C=useRef(t);C.current=t;let R=useRef(n);R.current=n,useEffect(()=>{if(typeof process<"u")return;let w=tr(r),k=new Set(i?Object.keys(i):[]),l=[...w].filter(E=>!k.has(E));l.length>0&&console.error(`[ForkSlot:${e}] Missing bridged callbacks! The following callback props are used by children but not passed to ForkSlot's \`callbacks\` prop:
2
- `+l.map(E=>` - ${E}`).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(()=>{er.has(e)||(er.add(e),fetch(`${c}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${F}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:P,label:e,propsShape:t?fn(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:o,callbackNames:i?Object.keys(i):[],mode:s||"iframe"})}).catch(()=>{}));},[e,c,F,o,P]);let T=useCallback(w=>{let k=x.current;if(k?.contentWindow&&v.current){let l=h.current?Object.keys(h.current):[];k.contentWindow.postMessage({type:"slot:props",props:w,callbackNames:l},"*"),y.current=null;}else y.current=w;},[]),$=useCallback((w,k)=>{let l=R.current;return !l||l.length===0?false:l.some(E=>{let[S,u]=E.split(" "),p=k.split("?")[0];return w.toUpperCase()===S.toUpperCase()&&p.startsWith(u)})},[]);if(useEffect(()=>{if(!f?.bundleUrl)return;let w=async k=>{if(k.source===x.current?.contentWindow){if(k.data?.type==="slot:ready")v.current=true,x.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:R.current||[]},"*"),R.current,y.current?T(y.current):T(C.current||{});else if(k.data?.type==="slot:event"){let l=k.data.event;l?.navigate&&(window.location.hash=l.navigate);}else if(k.data?.type==="slot:clipboard-write")navigator.clipboard.writeText(k.data.text).catch(l=>{console.warn(`[ForkSlot:${e}] clipboard write failed:`,l.message);});else if(k.data?.type==="slot:callback"){let{name:l,args:E}=k.data,S=h.current?.[l];S?(S(...E||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${l}`);}else if(k.data?.type==="slot:fetch"){let{id:l,method:E,url:S,body:u}=k.data,p=x.current?.contentWindow;if(!p)return;let g=E||"GET";if(!$(g,S)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${l}: ${g} ${S} \u2014 not in allowedFetches`),p.postMessage({type:"slot:fetch-response",id:l,error:`Fetch not allowed: ${g} ${S}`},"*");return}try{let I={method:g};u&&g!=="GET"&&(I.headers={"Content-Type":"application/json"},I.body=JSON.stringify(u));let z=await fetch(S,I),Y=await z.json();`${e}${l}${z.status}`,p.postMessage({type:"slot:fetch-response",id:l,data:Y,status:z.status},"*");}catch(I){console.error(`[ForkSlot:${e}] fetch #${l} failed:`,I.message),p.postMessage({type:"slot:fetch-response",id:l,error:I.message},"*");}}}};return window.addEventListener("message",w),()=>{window.removeEventListener("message",w),v.current=false;}},[f?.bundleUrl,e,T,$]),useEffect(()=>{f?.bundleUrl&&v.current&&T(t||{});},[t,f?.bundleUrl,T]),!f||f.status!=="complete"||!f.bundleUrl)return `${e}${f?.status||"none"}${f?.bundleUrl||"none"}`,jsx(Fragment,{children:r});`${e}${f.bundleUrl}`;let M=`${c}${f.bundleUrl.replace("/bundle.js","/host")}`;return jsx("iframe",{ref:x,src:M,sandbox:"allow-scripts allow-same-origin allow-forms allow-clipboard-write",title:`Forked ${e}`,style:{width:"100%",border:"none",flex:1,minHeight:0}})}function je({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 bt({onClick:e}){let[t,r]=useState(false),[n,o]=useState(false),i=t?48:40;return jsx("button",{onClick:e,onMouseEnter:()=>r(true),onMouseLeave:()=>{r(false),o(false);},onMouseDown:()=>o(true),onMouseUp:()=>o(false),style:{position:"fixed",bottom:24,right:24,zIndex:40,width:i,height:i,borderRadius:"50%",backgroundColor:t?"rgba(255, 255, 255, 1)":"rgba(255, 255, 255, 0.3)",border:t?"1px solid rgba(156, 163, 175, 1)":"1px solid rgba(156, 163, 175, 0.3)",display:"flex",alignItems:"center",justifyContent:"center",color:t?"#1c4587":"rgba(28, 69, 135, 0.5)",boxShadow:t?"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1)":"0 1px 2px 0 rgba(0, 0, 0, 0.05)",transform:n?"scale(0.95)":"scale(1)",transition:"all 300ms",cursor:"pointer",padding:0,margin:0,outline:"none",boxSizing:"border-box"},title:"Fork this app",children:jsx(je,{style:{width:24,height:24}})})}var xn={status:Loader2,agent_message:MessageSquare,tool_use:Wrench,build_start:Package,build_complete:Check,build_error:AlertCircle,complete:Sparkles,error:AlertCircle},Fn={status:"#60a5fa",agent_message:"#a0a0a0",tool_use:"#fbbf24",build_start:"#c084fc",build_complete:"#6b7280",build_error:"#f87171",complete:"#6b7280",error:"#f87171"},Rn={read:FileSearch,write:Pencil,search:FileSearch,shell:Terminal,build:Package},En={read:"#60a5fa",write:"#fbbf24",search:"#60a5fa",shell:"#a78bfa",build:"#c084fc"};function vt(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 cr({events:e}){let t=useRef(null);return useEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight);},[e]),jsxs(Fragment,{children:[jsx("style",{children:`
1
+ import*as xt from'react';import xt__default,{createContext,useSyncExternalStore,useState,useRef,useEffect,useCallback,startTransition,Children,useContext,isValidElement}from'react';import*as Xr from'react-dom';import {createPortal}from'react-dom';import*as Yr from'react/jsx-runtime';import {jsx,Fragment,jsxs}from'react/jsx-runtime';import*as Zr from'react/jsx-dev-runtime';import {ChevronDown,Check,PictureInPicture,PictureInPicture2,X,User,Undo2,RotateCcw,ArrowUp,Loader2,AlertCircle,Sparkles,Package,Wrench,MessageSquare,Code,Terminal,FileSearch,Pencil}from'lucide-react';var me="__FORK_SHARED__";function ft(){var t,r,n,o;let e=globalThis;return e[me]||(e[me]={}),(t=e[me]).react||(t.react=xt),(r=e[me])["react-dom"]||(r["react-dom"]=Xr),(n=e[me])["react/jsx-runtime"]||(n["react/jsx-runtime"]=Yr),(o=e[me])["react/jsx-dev-runtime"]||(o["react/jsx-dev-runtime"]=Zr),e[me]}function pt(e){return Object.assign(ft(),e)}var Qr="__fork_preview_session__";function ze(e){return `${Qr}${e}`}var H={apiKey:null,session:null},gt=new Set;function We(){for(let e of gt)try{e();}catch(t){console.error("[fork-preview] subscriber threw",t);}}function Jt(e){let t=Date.parse(e.expires_at);return Number.isFinite(t)?t<=Date.now():true}function en(e){if(typeof window>"u")return null;try{let t=window.sessionStorage.getItem(ze(e));if(!t)return null;let r=JSON.parse(t);return !r||typeof r!="object"||typeof r.preview_session_id!="string"?null:Jt(r)?(window.sessionStorage.removeItem(ze(e)),null):r}catch{return null}}function mt(e,t){if(!(typeof window>"u"))try{t?window.sessionStorage.setItem(ze(e),JSON.stringify(t)):window.sessionStorage.removeItem(ze(e));}catch{}}function Ee(e){H.apiKey!==e&&(H.apiKey=e,H.session=en(e),We());}function he(){return H.session?Jt(H.session)?(ht(null),null):H.session:null}function ht(e){H.session=e,H.apiKey&&mt(H.apiKey,e),We();}function _e(e){H.session&&H.session.fork_id!==e&&(H.session={...H.session,fork_id:e},H.apiKey&&mt(H.apiKey,H.session),We());}function yt(e,t){H.session&&(H.session.container_id===e&&H.session.container_name===t||(H.session={...H.session,container_id:e,container_name:t??H.session.container_name??H.session.target_user_id,fork_id:null},H.apiKey&&mt(H.apiKey,H.session),We()));}function kt(e){return gt.add(e),()=>{gt.delete(e);}}var qt="__fork_preview";function Xt(){if(typeof window>"u")return null;let e=window.location.hash;if(!e||e.length<2)return null;let r=new URLSearchParams(e.slice(1)).get(qt);return typeof r=="string"&&r.length>0?r:null}function bt(e){if(typeof window>"u")return false;try{if(window.sessionStorage.getItem(`__fork_preview_session__${e}`))return !0}catch{}return Zt()!==null}function Yt(){if(typeof window>"u")return;let e=window.location.hash;if(!e||e.length<2)return;let t=new URLSearchParams(e.slice(1));t.delete(qt);let r=t.toString(),n=r?`#${r}`:"";try{window.history.replaceState(null,"",window.location.pathname+window.location.search+n);}catch{}}var ye=null;function Zt(){if(ye)return ye;let e=Xt();return e?(ye=e,Yt(),ye):null}async function wt(e,t){Ee(e);let r=he();if(r)return ye=null,r;let n=ye??Xt();if(ye=null,!n)return null;Yt();try{let o=await fetch(`${t}/api/v1/preview/activate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({token:n})});if(!o.ok){let a=await o.json().catch(()=>({}));return console.warn(`[fork-preview] activate failed (${o.status}): ${a.error??"unknown"}`),null}let i=await o.json(),s={preview_session_id:i.preview_session_id,tenant_id:i.tenant_id,app_id:i.app_id,target:i.target,target_user_id:i.target_user_id,operator_id:i.operator_id,container_id:i.container_id??null,container_name:i.container_name??i.target_user_id,fork_id:i.fork_id??null,expires_at:i.expires_at};return ht(s),s}catch(o){return console.warn("[fork-preview] activate threw",o),null}}function rn(){return he()}function nn(){return null}function Ke(){return useSyncExternalStore(kt,rn,nn)}function G(){let e=he();if(!e)return {};let t={"X-Fork-Preview-Session":e.preview_session_id};return e.fork_id&&(t["X-Fork-Preview-Fork-Id"]=e.fork_id),t}async function Ge(e){let t=new URLSearchParams({app:e.appId,user:e.userId});e.containerId&&t.set("containerId",e.containerId);let r=`${e.baseUrl}/api/v1/manifest?${t.toString()}`,n={Authorization:`Bearer ${e.apiKey}`,"X-Fork-App-Id":e.appId,"X-Fork-User-Id":e.userId,...e.extraHeaders??{}};e.userHash&&(n["X-Fork-User-Hash"]=e.userHash),e.previous?.etag&&(n["If-None-Match"]=e.previous.etag);let o=await fetch(r,{headers:n,signal:e.signal});if(o.status===304)return null;if(!o.ok)throw new Error(`manifest ${o.status} ${o.statusText}`);let i=await o.json(),s={};for(let[a,f]of Object.entries(i.modules)){let p=f.moduleUrl??f.bundleUrl??null,d=f.legacyModuleUrl??f.legacyBundleUrl??null;s[a]={forkId:f.forkId,moduleUrl:p,legacyModuleUrl:d,bundleUrl:f.bundleUrl??p,legacyBundleUrl:f.legacyBundleUrl??d,cssUrls:f.cssUrls??[],integrity:f.integrity,metadata:f.metadata,buildId:f.buildId,updatedAt:f.updatedAt};}return {containerId:i.containerId,slots:i.slots,modules:s,generatedAt:i.generatedAt,etag:o.headers.get("ETag")??void 0}}var on="fork:manifest:v1";function vt(e,t,r){return `${on}:${e}:${t}:${r}`}function sn(e,t,r){if(typeof window>"u")return null;try{let n=window.localStorage.getItem(vt(e,t,r));return n?JSON.parse(n):null}catch{return null}}function an(e,t,r,n){if(!(typeof window>"u"))try{window.localStorage.setItem(vt(e,t,r),JSON.stringify(n));}catch{}}function ln(e,t,r){if(!(typeof window>"u"))try{window.localStorage.removeItem(vt(e,t,r));}catch{}}function cn(e,t){if(!e||!t)return e!==t;if(e.containerId!==t.containerId)return true;let r=Object.entries(e.slots),n=Object.entries(t.slots);if(r.length!==n.length)return true;for(let[s,a]of r){let f=t.slots[s];if(!f||f.forkId!==a.forkId||f.buildId!==a.buildId)return true}let o=Object.entries(e.modules),i=Object.entries(t.modules);if(o.length!==i.length)return true;for(let[s,a]of o){let f=t.modules[s];if(!f||f.forkId!==a.forkId||f.buildId!==a.buildId)return true}return false}var tr=createContext(null);function Ae(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function fn(e,t){let r={};for(let[n,o]of Object.entries(t.boundaries||{}))r[n]={...o,moduleUrl:Ae(e,o.moduleUrl),cssUrls:Array.isArray(o.cssUrls)?o.cssUrls.map(i=>Ae(e,i)):[]};return r}function Qt(e,t,r,n){let o={};for(let[i,s]of Object.entries(t.slots)){let a=s.bundleUrl??s.legacyBundleUrl;a&&(o[i]={id:s.forkId,userId:r,prompt:"",status:"complete",slotId:i,appId:n,bundleUrl:Ae(e,a),createdAt:s.updatedAt,completedAt:s.updatedAt});}return o}function er(e,t){let r={};for(let[n,o]of Object.entries(t.modules)){let i=o.moduleUrl??o.legacyModuleUrl??o.bundleUrl??"";i&&(r[n]={id:o.forkId,boundaryId:n,moduleUrl:Ae(e,i),cssUrls:(o.cssUrls??[]).map(s=>Ae(e,s)),integrity:o.integrity,metadata:o.metadata,createdAt:o.updatedAt});}return r}function pn(e){let{apiKey:t,baseUrl:r,children:n,appId:o,shared:i}=e,s="userId"in e?e.userId:void 0,a="authUrl"in e?e.authUrl:void 0,[f]=useState(()=>(Ee(t),bt(t))),[p,d]=useState({}),[S,P]=useState(s?{userId:s,userHash:void 0}:null),[R,x]=useState(!!s||f),[y,h]=useState({}),[T,_]=useState(!o),[M,$]=useState(0),[I,v]=useState(null),k=useRef(new Map),l=useRef(new Map),[A,F]=useState(0),u=useRef(new Set),g=useRef(new Map),m=useRef(void 0);ft(),useEffect(()=>{return wt(t,r).then(()=>{}),()=>{}},[]);let L=Ke();i&&m.current!==i&&(pt(i),m.current=i),useEffect(()=>{a&&(f||(x(false),fetch(a,{credentials:"include"}).then(E=>{if(!E.ok)throw new Error(`Auth endpoint returned ${E.status}`);return E.json()}).then(E=>{if(!E.userId||typeof E.userId!="string")throw new Error("authUrl response must include userId");P({userId:E.userId,userHash:E.userHash});}).catch(E=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",E.message);}).finally(()=>{x(true);})));},[a,f]),useEffect(()=>{!a&&s&&(P({userId:s,userHash:void 0}),x(true));},[s,a]);let W=S?.userId??"",ee=S?.userHash,N=L?L.target_user_id:W,z=L?void 0:ee,J=!!o,D=useCallback(async()=>{if(!J){v(null),h({}),_(true),$(w=>w+1);return}if(!R){_(false);return}if(!N||!o){v(null),h({}),_(true),$(w=>w+1);return}if(_(false),!L){try{let w=await Ge({baseUrl:r,apiKey:t,appId:o,userId:N,userHash:z});w&&(v(w.containerId),d(Qt(r,w,N,o)),h(er(r,w)));}catch(w){console.error("[ForkProvider] Failed to fetch fork manifest:",w.message),v(null),d({}),h({});}finally{$(w=>w+1),_(true);}return}if(v(L.container_id??null),L.container_id){try{let w=await Ge({baseUrl:r,apiKey:t,appId:o,userId:N,containerId:L.container_id,extraHeaders:G()});w&&(d(Qt(r,w,N,o)),h(er(r,w)));}catch(w){console.error("[ForkProvider] Failed to fetch preview container manifest:",w.message),d({}),h({});}finally{$(w=>w+1),_(true);}return}let E=new URLSearchParams({appId:o,userId:N});z&&E.set("userHash",z);try{let w=await fetch(`${r}/api/v1/boundaries/manifest?${E.toString()}`,{headers:{Authorization:`Bearer ${t}`,...G()}});if(!w.ok)throw new Error(`${w.status}`);let U=await w.json();h(fn(r,U));}catch(w){console.error("[ForkProvider] Failed to fetch module override manifest:",w.message),h({});}finally{$(w=>w+1),_(true);}},[t,o,r,R,J,z,N,L?.preview_session_id,L?.fork_id,L?.container_id]);useEffect(()=>{if(!N||o&&(!L||L.container_id))return;let E=new URLSearchParams({userId:N});z&&E.set("userHash",z),fetch(`${r}/api/v1/forks/active?${E.toString()}`,{headers:{Authorization:`Bearer ${t}`,...G()}}).then(w=>{if(!w.ok)throw new Error(`${w.status}`);return w.json()}).then(w=>{w&&typeof w=="object"&&d(w);}).catch(()=>{});},[t,o,N,z,r,L?.preview_session_id,L?.fork_id]),useEffect(()=>{D();},[D]);let te=useCallback((E,w)=>{d(U=>({...U,[E]:w}));},[]),ne=useCallback(E=>{d(w=>{let U={...w};return delete U[E],U});},[]),ue=useCallback(E=>{u.current.add(E);},[]),q=useCallback(E=>u.current.has(E)?(u.current.delete(E),true):false,[]),it=useCallback((E,w)=>{g.current.set(E,w);},[]),Ie=useCallback((E,w)=>g.current.get(E)!==w?false:(g.current.delete(E),true),[]),Fe=useCallback(E=>{if(!o)return;let w=JSON.stringify(E);k.current.get(E.id)===w||l.current.get(E.id)?.signature===w||(l.current.set(E.id,{boundary:E,signature:w}),F(K=>K+1));},[o]);useEffect(()=>{if(!o||l.current.size===0)return;let E=setTimeout(()=>{let w=Array.from(l.current.values());w.length!==0&&fetch(`${r}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:o,boundaries:w.map(U=>U.boundary)})}).then(U=>{if(!U.ok)throw new Error(`${U.status}`)}).then(()=>{for(let U of w)l.current.get(U.boundary.id)?.signature===U.signature&&(l.current.delete(U.boundary.id),k.current.set(U.boundary.id,U.signature));}).catch(U=>{console.error("[ForkProvider] Failed to register module boundaries:",U.message);});},50);return ()=>{clearTimeout(E);}},[t,o,r,A]);let ie=useCallback(E=>y[E],[y]),X=useCallback(async()=>{if(!N)throw new Error("Reset requires a resolved user identity.");let E=new URLSearchParams({userId:N});z&&E.set("userHash",z);let w=await fetch(`${r}/api/v1/forks/all?${E.toString()}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`,...G()}});if(!w.ok){let K=await w.json().catch(()=>({}));throw new Error(K.error||`API error: ${w.status}`)}let U=await w.json().catch(()=>({}));d({}),h({}),_(true),$(K=>K+1),u.current.clear(),g.current.clear();try{for(let K=sessionStorage.length-1;K>=0;K-=1){let ae=sessionStorage.key(K);ae&&ae.startsWith("__fork_animated_")&&sessionStorage.removeItem(ae);}}catch{}return U},[t,r,z,N]);return jsx(tr.Provider,{value:{apiKey:t,userId:N,userHash:z,baseUrl:r,appId:o,forks:p,moduleOverridesEnabled:J,moduleManifestReady:T,moduleManifestVersion:M,currentContainerId:I,previewSession:L,setSlotFork:te,clearSlotFork:ne,skipAnimationForSlot:ue,shouldSkipAnimation:q,queueBoundaryAnimation:it,consumeBoundaryAnimation:Ie,registerBoundary:Fe,getBoundaryOverride:ie,refreshModuleManifest:D,resetAllForks:X},children:n})}function V(){let e=useContext(tr);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function Ve(e){return V().forks[e]}var Ce=class{constructor(t){this.values=new Map;this.snapshots=new Map;this.listeners=new Map;this.eventHandlers=new Map;this.slotId=t,window.__FORK_BRIDGE__||(window.__FORK_BRIDGE__={}),window.__FORK_BRIDGE__[t]=this;}set(t,r){let n=this.values.get(t);if(Object.is(n,r))return;if(n!==void 0&&r!==null&&n!==null&&typeof n=="object"&&typeof r=="object")try{if(JSON.stringify(n)===JSON.stringify(r))return}catch{}this.values.set(t,r),this.snapshots.set(t,r);let o=this.listeners.get(t);o&&o.forEach(i=>i());}get(t){return this.values.get(t)}getSnapshot(t){return this.snapshots.get(t)}subscribe(t,r){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(r),()=>{this.listeners.get(t)?.delete(r);}}useValue(t){let r=window.__FORK_REACT__;return r?.useSyncExternalStore?r.useSyncExternalStore(n=>this.subscribe(t,n),()=>this.getSnapshot(t)):(console.warn("[ForkBridge] React.useSyncExternalStore not available, returning static value"),this.values.get(t))}emit(t,...r){let n=this.eventHandlers.get(t);n&&n.forEach(o=>o(...r));}on(t,r){return this.eventHandlers.has(t)||this.eventHandlers.set(t,new Set),this.eventHandlers.get(t).add(r),()=>{this.eventHandlers.get(t)?.delete(r);}}destroy(){this.listeners.clear(),this.eventHandlers.clear(),this.values.clear(),this.snapshots.clear();let t=window.__FORK_BRIDGE__;t&&delete t[this.slotId];}};function Ft(e,t){let r;try{r=Children.only(e);}catch{let o=Children.count(e);throw new Error(`<ForkSlot slotId="${t}"> must wrap exactly one React component, got ${o} children. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`)}let n=r.type;if(typeof n=="string")throw new Error(`<ForkSlot slotId="${t}"> child must be a React component (function or class), not an HTML element <${n}>. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`);if(typeof n=="symbol")throw new Error(`<ForkSlot slotId="${t}"> child must be a single React component, not a fragment or special React element. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`);return r}var nr=new Set;function or(e){let t=[],r=e.querySelectorAll("*");for(let n of r){if(!(n instanceof HTMLElement))continue;let o=n.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(n.tagName))continue;let i=getComputedStyle(n),s=parseFloat(i.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:s});}return t}function kn(e,t){let r=[];for(let n of t)if(!e.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)&&!r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom)){for(let s=r.length-1;s>=0;s--){let a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function bn(e,t){let r=[];for(let n of e)if(!t.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)&&!r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom)){for(let s=r.length-1;s>=0;s--){let a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function ir(e,t,r,n,o){return o=Math.max(0,Math.min(o,r/2,n/2)),o===0?`M ${e} ${t} L ${e+r} ${t} L ${e+r} ${t+n} L ${e} ${t+n} Z`:[`M ${e+o} ${t}`,`L ${e+r-o} ${t}`,`A ${o} ${o} 0 0 1 ${e+r} ${t+o}`,`L ${e+r} ${t+n-o}`,`A ${o} ${o} 0 0 1 ${e+r-o} ${t+n}`,`L ${e+o} ${t+n}`,`A ${o} ${o} 0 0 1 ${e} ${t+n-o}`,`L ${e} ${t+o}`,`A ${o} ${o} 0 0 1 ${e+o} ${t}`,"Z"].join(" ")}function sr(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-highlights","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");n.appendChild(o);let i=[];for(let d=0;d<e.length;d++){let{rect:S,borderRadius:P}=e[d],R=S.left-.5,x=S.top-.5,y=S.width+1,h=S.height+1,T=Math.min(P+.5,y/2,h/2),_=ir(R,x,y,h,T),M=`__fork-glow-${d}`,$=document.createElementNS(t,"filter");$.setAttribute("id",M),$.setAttribute("x","-100%"),$.setAttribute("y","-100%"),$.setAttribute("width","300%"),$.setAttribute("height","300%");let I=document.createElementNS(t,"feGaussianBlur");I.setAttribute("in","SourceGraphic"),I.setAttribute("stdDeviation","8"),$.appendChild(I),o.appendChild($);let v=`__fork-mask-${d}`,k=document.createElementNS(t,"mask");k.setAttribute("id",v),k.setAttribute("maskUnits","userSpaceOnUse"),k.setAttribute("x",String(R-200)),k.setAttribute("y",String(x-200)),k.setAttribute("width",String(y+400)),k.setAttribute("height",String(h+400));let l=document.createElementNS(t,"rect");l.setAttribute("x",String(R-200)),l.setAttribute("y",String(x-200)),l.setAttribute("width",String(y+400)),l.setAttribute("height",String(h+400)),l.setAttribute("fill","white"),k.appendChild(l);let A=document.createElementNS(t,"path");A.setAttribute("d",_),A.setAttribute("fill","black"),k.appendChild(A),o.appendChild(k);let F=document.createElementNS(t,"g");F.setAttribute("mask",`url(#${v})`),F.setAttribute("opacity","0");let u=document.createElementNS(t,"g");u.setAttribute("filter",`url(#${M})`);let g=document.createElementNS(t,"path");g.setAttribute("d",_),g.setAttribute("fill","none"),g.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),g.setAttribute("stroke-width","6"),g.setAttribute("stroke-linecap","round"),u.appendChild(g),F.appendChild(u),n.appendChild(F);let m=document.createElementNS(t,"path");m.setAttribute("d",_),m.setAttribute("fill","none"),m.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),m.setAttribute("stroke-width","2"),m.setAttribute("stroke-linecap","round"),m.setAttribute("opacity","0"),n.appendChild(m),i.push(g,m),g.__group=F;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let d=0;d<i.length;d+=2){let S=i[d],P=i[d+1],R=S.__group,x=P.getTotalLength(),y=S.getTotalLength();if(x<=0)continue;let h=x*.35;P.setAttribute("stroke-dasharray",`${h} ${x-h}`),P.setAttribute("stroke-dashoffset","0"),s.push(P.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*x,opacity:.92,offset:.06},{strokeDashoffset:-2*x,opacity:.92,offset:.92},{strokeDashoffset:-2.25*x,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let T=y*.35;S.setAttribute("stroke-dasharray",`${T} ${y-T}`),S.setAttribute("stroke-dashoffset","0"),s.push(S.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*y,offset:.06},{strokeDashoffset:-2*y,offset:.92},{strokeDashoffset:-2.25*y,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(R.animate([{opacity:0,offset:0},{opacity:.92,offset:.06},{opacity:.92,offset:.92},{opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));}let a=false,f=()=>{if(a)return;a=true,clearTimeout(p);for(let S of s)try{S.cancel();}catch{}let d=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});d.onfinish=()=>r.remove(),window.removeEventListener("click",f);},p=setTimeout(f,14500);return setTimeout(()=>{a||window.addEventListener("click",f);},500),f}function wn(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-removed","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs"),i=document.createElementNS(t,"filter");i.setAttribute("id","__fork-removed-shadow"),i.setAttribute("x","-10%"),i.setAttribute("y","-10%"),i.setAttribute("width","120%"),i.setAttribute("height","120%");let s=document.createElementNS(t,"feDropShadow");s.setAttribute("dx","0"),s.setAttribute("dy","1"),s.setAttribute("stdDeviation","2"),s.setAttribute("flood-color","rgba(0,0,0,0.15)"),i.appendChild(s),o.appendChild(i),n.appendChild(o);for(let{rect:a,borderRadius:f}of e){let p=a.left,d=a.top,S=a.width,P=a.height,R=Math.min(f,S/2,P/2),x=ir(p,d,S,P,R),y=document.createElementNS(t,"path");y.setAttribute("d",x),y.setAttribute("fill","none"),y.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),y.setAttribute("stroke-width","1.5"),y.setAttribute("stroke-dasharray","8 4"),y.setAttribute("stroke-linecap","round"),y.setAttribute("filter","url(#__fork-removed-shadow)"),y.setAttribute("opacity","0"),n.appendChild(y),y.animate([{opacity:0,offset:0},{opacity:.6,offset:.08},{opacity:.05,offset:.45},{opacity:.6,offset:.85},{opacity:.05,offset:1}],{duration:5e3,easing:"ease-in-out",fill:"forwards"});}return r.appendChild(n),document.body.appendChild(r),r}function vn(e,t){if(e===t)return true;let r=Object.keys(e);if(r.length!==Object.keys(t).length)return false;for(let n of r)if(!Object.is(e[n],t[n]))return false;return true}var Sn=xt__default.memo(function({component:t,containerRef:r,wrapperStyle:n,hostProps:o}){return jsx("div",{ref:r,style:n,children:jsx(t,{...o})})},(e,t)=>e.component===t.component&&vn(e.hostProps,t.hostProps)),St=class extends xt__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 ar({slotId:e,children:t,githubRepo:r,shared:n,events:o}){Ft(t,e);let i=Ve(e),{baseUrl:s,apiKey:a,appId:f,shouldSkipAnimation:p}=V(),[d,S]=useState(null),P=useRef(null),R=useRef(null),x=useRef(null),y=useRef(false),h=useRef(null),T=useRef(null),_=!!(n||o),M=useRef(null);_&&!M.current&&(M.current=new Ce(e));let $=useRef(o);if($.current=o,useEffect(()=>{if(_)return ()=>{M.current?.destroy(),M.current=null;}},[_,e]),_&&M.current&&n)for(let[A,F]of Object.entries(n))M.current.set(A,F);useEffect(()=>{if(!_)return;M.current||(M.current=new Ce(e));let A=M.current,F=Object.keys($.current||{}).map(u=>A.on(u,(...g)=>$.current?.[u]?.(...g)));return ()=>F.forEach(u=>u())},[_,e]),useEffect(()=>{if(nr.has(e))return;nr.add(e);let A={id:e,appId:f,label:e,eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:r,mode:"direct",sharedKeys:n?Object.keys(n):[],eventNames:o?Object.keys(o):[],propsShape:"",callbackNames:[]};fetch(`${s}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify(A)}).catch(()=>{});},[e,s,a,r,f]);let I=i?.id||null;useEffect(()=>{if(i?.bundleUrl,P.current,R.current,!i?.bundleUrl||!I){return}let A=`${s}${i.bundleUrl.replace("bundle.js","component.js")}`,F=`__fork_animated_${e}`,u=sessionStorage.getItem(F),g=p(e),m=!g&&u!==I;if(g&&I&&sessionStorage.setItem(F,I),m&&R.current){let z=or(R.current);x.current=z,y.current=true,`${e}${z.length}`;}window.__FORK_REACT__=xt__default,window.__FORK_REACT_DOM__=Xr,window.__FORK_REACT_JSX__=Yr;let L=Date.now(),W=`${s}${i.bundleUrl.replace("bundle.js","component.css")}?t=${L}`,ee=document.createElement("link");ee.rel="stylesheet",ee.href=W,ee.dataset.forkSlot=e,document.head.appendChild(ee);let N=document.createElement("script");return N.src=A+"?t="+L,N.onload=()=>{let z=window.__FORK_EXPORT__;if(z?.default){if(R.current&&x.current&&y.current){let J=R.current.getBoundingClientRect(),D=R.current.cloneNode(true);D.style.position="fixed",D.style.top=`${J.top}px`,D.style.left=`${J.left}px`,D.style.width=`${J.width}px`,D.style.height=`${J.height}px`,D.style.flex="none",D.style.minHeight="auto",D.style.zIndex="9998",D.style.pointerEvents="none",D.style.overflow="hidden";let te=getComputedStyle(R.current).backgroundColor;D.style.backgroundColor=te&&te!=="rgba(0, 0, 0, 0)"&&te!=="transparent"?te:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(D);let ne=R.current.querySelectorAll("*"),ue=D.querySelectorAll("*");for(let q=0;q<ne.length;q++)ne[q].scrollTop!==0&&(ue[q].scrollTop=ne[q].scrollTop),ne[q].scrollLeft!==0&&(ue[q].scrollLeft=ne[q].scrollLeft);h.current=D;}S(()=>z.default),P.current=I;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},N.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(N),()=>{N.remove(),ee.remove(),T.current&&(clearTimeout(T.current),T.current=null),h.current&&(h.current.remove(),h.current=null);}},[I,s,e]),useEffect(()=>{if(!y.current||!d||!R.current){`${e}${y.current}`,R.current;return}let A=x.current;if(!A){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!R.current)return;let F=or(R.current),u=kn(A,F),g=bn(A,F),m=h.current;if(`${e}${u.length}${g.length}`,g.length>0&&m){let L=wn(g);T.current=setTimeout(()=>{T.current=null;let W=400;m.animate([{opacity:1},{opacity:0}],{duration:W,fill:"forwards"}),L.animate([{opacity:1},{opacity:0}],{duration:W,fill:"forwards"}),setTimeout(()=>{m.remove(),L.remove(),h.current=null,u.length>0&&(sr(u));},W);},3500);}else m&&(m.remove(),h.current=null),u.length>0&&(sr(u));x.current=null,y.current=false,I&&(sessionStorage.setItem(`__fork_animated_${e}`,I),`${e}`);});});},[d]);let v={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!i||i.status!=="complete"||!i.bundleUrl)return jsx("div",{ref:R,style:v,children:t});if(!d)return jsx("div",{ref:R,style:v,children:t});let l=t?.props??{};return jsx(St,{slotId:e,resetKey:I,fallback:jsx("div",{ref:R,style:v,children:t}),children:jsx(Sn,{component:d,containerRef:R,wrapperStyle:v,hostProps:l})})}var cr=new Set;function Rn(e){return `{ ${Object.entries(e).map(([r,n])=>n==null?`${r}: unknown`:Array.isArray(n)?`${r}: ${n.length>0?typeof n[0]:"unknown"}[]`:`${r}: ${typeof n}`).join("; ")} }`}function dr(e,t=new Set){return Children.forEach(e,r=>{if(!isValidElement(r))return;let n=r.props;for(let[o,i]of Object.entries(n))typeof i=="function"&&/^on[A-Z]/.test(o)&&t.add(o);n.children&&dr(n.children,t);}),t}function En({slotId:e,props:t,children:r,allowedFetches:n,githubRepo:o,callbacks:i,mode:s="iframe",shared:a,events:f}){if(Ft(r,e),s==="direct")return jsx(ar,{slotId:e,githubRepo:o,shared:a,events:f,children:r});let p=Ve(e),{baseUrl:d,apiKey:S,appId:P}=V(),R=useRef(null),x=useRef(false),y=useRef(null),h=useRef(i);h.current=i;let T=useRef(t);T.current=t;let _=useRef(n);_.current=n,useEffect(()=>{if(typeof process<"u")return;let v=dr(r),k=new Set(i?Object.keys(i):[]),l=[...v].filter(A=>!k.has(A));l.length>0&&console.error(`[ForkSlot:${e}] Missing bridged callbacks! The following callback props are used by children but not passed to ForkSlot's \`callbacks\` prop:
2
+ `+l.map(A=>` - ${A}`).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(()=>{cr.has(e)||(cr.add(e),fetch(`${d}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${S}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:P,label:e,propsShape:t?Rn(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:o,callbackNames:i?Object.keys(i):[],mode:s||"iframe"})}).catch(()=>{}));},[e,d,S,o,P]);let M=useCallback(v=>{let k=R.current;if(k?.contentWindow&&x.current){let l=h.current?Object.keys(h.current):[];k.contentWindow.postMessage({type:"slot:props",props:v,callbackNames:l},"*"),y.current=null;}else y.current=v;},[]),$=useCallback((v,k)=>{let l=_.current;return !l||l.length===0?false:l.some(A=>{let[F,u]=A.split(" "),g=k.split("?")[0];return v.toUpperCase()===F.toUpperCase()&&g.startsWith(u)})},[]);if(useEffect(()=>{if(!p?.bundleUrl)return;let v=async k=>{if(k.source===R.current?.contentWindow){if(k.data?.type==="slot:ready")x.current=true,R.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:_.current||[]},"*"),_.current,y.current?M(y.current):M(T.current||{});else if(k.data?.type==="slot:event"){let l=k.data.event;l?.navigate&&(window.location.hash=l.navigate);}else if(k.data?.type==="slot:clipboard-write")navigator.clipboard.writeText(k.data.text).catch(l=>{console.warn(`[ForkSlot:${e}] clipboard write failed:`,l.message);});else if(k.data?.type==="slot:callback"){let{name:l,args:A}=k.data,F=h.current?.[l];F?(F(...A||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${l}`);}else if(k.data?.type==="slot:fetch"){let{id:l,method:A,url:F,body:u}=k.data,g=R.current?.contentWindow;if(!g)return;let m=A||"GET";if(!$(m,F)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${l}: ${m} ${F} \u2014 not in allowedFetches`),g.postMessage({type:"slot:fetch-response",id:l,error:`Fetch not allowed: ${m} ${F}`},"*");return}try{let L={method:m};u&&m!=="GET"&&(L.headers={"Content-Type":"application/json"},L.body=JSON.stringify(u));let W=await fetch(F,L),ee=await W.json();`${e}${l}${W.status}`,g.postMessage({type:"slot:fetch-response",id:l,data:ee,status:W.status},"*");}catch(L){console.error(`[ForkSlot:${e}] fetch #${l} failed:`,L.message),g.postMessage({type:"slot:fetch-response",id:l,error:L.message},"*");}}}};return window.addEventListener("message",v),()=>{window.removeEventListener("message",v),x.current=false;}},[p?.bundleUrl,e,M,$]),useEffect(()=>{p?.bundleUrl&&x.current&&M(t||{});},[t,p?.bundleUrl,M]),!p||p.status!=="complete"||!p.bundleUrl)return `${e}${p?.status||"none"}${p?.bundleUrl||"none"}`,jsx(Fragment,{children:r});`${e}${p.bundleUrl}`;let I=`${d}${p.bundleUrl.replace("/bundle.js","/host")}`;return jsx("iframe",{ref:R,src:I,sandbox:"allow-scripts allow-same-origin allow-forms allow-clipboard-write",title:`Forked ${e}`,style:{width:"100%",border:"none",flex:1,minHeight:0}})}function qe({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 Et({onClick:e}){let[t,r]=useState(false),[n,o]=useState(false),i=t?48:40;return jsx("button",{onClick:e,onMouseEnter:()=>r(true),onMouseLeave:()=>{r(false),o(false);},onMouseDown:()=>o(true),onMouseUp:()=>o(false),style:{position:"fixed",bottom:24,right:24,zIndex:40,width:i,height:i,borderRadius:"50%",backgroundColor:t?"rgba(255, 255, 255, 1)":"rgba(255, 255, 255, 0.3)",border:t?"1px solid rgba(156, 163, 175, 1)":"1px solid rgba(156, 163, 175, 0.3)",display:"flex",alignItems:"center",justifyContent:"center",color:t?"#1c4587":"rgba(28, 69, 135, 0.5)",boxShadow:t?"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1)":"0 1px 2px 0 rgba(0, 0, 0, 0.05)",transform:n?"scale(0.95)":"scale(1)",transition:"all 300ms",cursor:"pointer",padding:0,margin:0,outline:"none",boxSizing:"border-box"},title:"Fork this app",children:jsx(qe,{style:{width:24,height:24}})})}var On={status:Loader2,agent_message:MessageSquare,tool_use:Wrench,build_start:Package,build_complete:Check,build_error:AlertCircle,complete:Sparkles,error:AlertCircle},Un={status:"#60a5fa",agent_message:"#a0a0a0",tool_use:"#fbbf24",build_start:"#c084fc",build_complete:"#6b7280",build_error:"#f87171",complete:"#6b7280",error:"#f87171"},Bn={read:FileSearch,write:Pencil,search:FileSearch,shell:Terminal,build:Package},Hn={read:"#60a5fa",write:"#fbbf24",search:"#60a5fa",shell:"#a78bfa",build:"#c084fc"};function $t(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 kr({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 ht from'react';import ht__default,{createContext,useSyncExternalStore,
18
18
  .__fork-stream::-webkit-scrollbar-thumb:hover {
19
19
  background: rgba(255, 255, 255, 0.3);
20
20
  }
21
- `}),jsxs("div",{className:"__fork-stream",ref:t,style:{scrollbarWidth:"thin",scrollbarColor:"rgba(255, 255, 255, 0.15) transparent",backgroundColor:"#1a1a2e",borderRadius:"8px",padding:"12px",fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:"11px",maxHeight:"300px",overflowY:"auto",boxSizing:"border-box"},children:[e.length===0&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"#6b7280",fontSize:"11px"},children:[jsx(Loader2,{style:{width:"12px",height:"12px",animation:"__fork-spin 1s linear infinite",flexShrink:0}}),"Connecting to agent..."]}),e.map((r,n)=>{let o=n===e.length-1,i=r.type==="complete"||r.type==="error"||r.type==="build_complete"||r.type==="build_error",s=o&&!i&&(r.type==="status"||r.type==="tool_use"||r.type==="build_start"),a=xn[r.type]||Code,d=Fn[r.type]||"#9ca3af";if(r.type==="tool_use"){let f=String(r.data.category||"");a=Rn[f]||Wrench,d=En[f]||"#fbbf24";}return s?a=Loader2:!o&&r.type==="status"&&(a=Check,d="#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:d,...s?{animation:"__fork-spin 1s linear infinite"}:{}}}),jsx("span",{style:{color:o&&!i?"#d1d5db":"#6b7280",wordBreak:"break-all"},children:vt(r)})]},n)})]})]})}var pr=35,In="Working on Feature",Ln="Built Custom Feature",gr=360,Ke=350;function Un(e){return e.length<=pr?e:e.slice(0,pr-3).trimEnd()+"..."}function On({events:e}){let[t,r]=useState("Setting up environment..."),[n,o]=useState(true),i=useRef(t),s=useRef(false);return useEffect(()=>{if(!s.current){for(let d of e)if(d.type==="status"&&String(d.data.message||"").includes("Agent started")){s.current=true;break}}let a="Setting up environment...";if(s.current)for(let d=e.length-1;d>=0;d--){let f=e[d];if(f.type==="tool_use"||f.type==="build_start"||f.type==="build_complete"){a=Un(vt(f));break}}if(a!==i.current){o(false);let d=setTimeout(()=>{r(a),i.current=a,o(true);},200);return ()=>clearTimeout(d)}},[e]),jsx("span",{style:{fontSize:11,color:"#d1d5db",fontWeight:500,opacity:n?1:0,transition:"opacity 0.2s ease",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},children:t})}function Bn({children:e}){let[t,r]=useState(null);return useEffect(()=>{if(typeof document>"u")return;let n=document.createElement("div");n.setAttribute("data-fork-panel-host",""),n.style.cssText="all: initial;",document.body.appendChild(n);let o=n.attachShadow({mode:"open"});return r(o),()=>{n.remove();}},[]),t?createPortal(e,t):null}function Ge({state:e,fork:t,events:r,error:n,slotId:o,targetId:i,targetLabel:s,historyMode:a="slot",onSubmit:d,onUndo:f,onClose:c,baseUrl:F,apiKey:P,userId:x,userHash:v,appId:y,embedded:h=false}){let[C,R]=useState(""),[T,$]=useState([]),[M,w]=useState(false),[k,l]=useState(false),[E,S]=useState(false),[u,p]=useState(false),[g,I]=useState(false),[z,Y]=useState(false),[H,D]=useState(false),[V,N]=useState(false),[Q,ee]=useState(false),[ie,q]=useState(null),[Qe,_e]=useState(false),[ke,be]=useState([]),[J,_]=useState(null),[b,O]=useState(false),[W,ae]=useState(false),[$r,Ct]=useState(false),[_r,Tt]=useState(null),[ge,Mt]=useState(null),et=useRef(null),Ae=useRef(null),{resetAllForks:Ar,previewSession:Pe,currentContainerId:Pr}=G(),Ce=Pe?.container_id??Pr,It=!!Pe,ne=ge!==null,Lt=useRef(c);useEffect(()=>{Lt.current=c;});let tt=useRef(null),Te=useRef(false),Ut=typeof window<"u"&&"documentPictureInPicture"in window,Cr=async()=>{if(!(!Ut||ne))try{let m=await window.documentPictureInPicture.requestWindow({width:gr,height:640});m.document.body.style.margin="0",m.document.body.style.padding="0",m.document.body.style.height="100vh",m.document.body.style.overflow="hidden",m.document.body.style.background="#ffffff";try{let L=document.adoptedStyleSheets??[];L.length>0&&(m.document.adoptedStyleSheets=[...L]);}catch{}m.addEventListener("pagehide",()=>{tt.current=null,Mt(null),Te.current||Lt.current(),Te.current=!1;},{once:!0}),tt.current=m,Mt(m);}catch(m){console.warn("[Fork] PiP open failed:",m);}},Tr=()=>{ge&&(Te.current=true,ge.close());};useEffect(()=>()=>{Te.current=true,tt.current?.close();},[]);let oe=i??o??"",Me=(s||oe).replace(/[-_]+/g," ").replace(/\b\w/g,m=>m.toUpperCase()),rt=useRef(""),Ie=h?true:k&&!E,Mr=r.find(m=>{let L=m.data;return m.type==="status"&&L.summary})?.data?.summary||t?.summary||In,ce=r.find(m=>{let L=m.data;return (m.type==="status"||m.type==="complete")&&typeof L?.estimateMinutes=="number"})?.data?.estimateMinutes??t?.estimateMinutes;useEffect(()=>{if(a==="none"){w(true);return}if(!F||!P||!x||!oe||M||!b)return;let m=new URLSearchParams({userId:x});if(v&&m.set("userHash",v),J&&m.set("containerId",J),a==="slot")m.set("slotId",oe);else if(a==="boundary"){if(!y){w(true);return}m.set("boundaryId",oe),m.set("appId",y);}fetch(`${F}/api/v1/forks/history?${m.toString()}`,{headers:{Authorization:`Bearer ${P}`}}).then(L=>L.ok?L.json():[]).then(L=>{let U=[];for(let Ue of L)Ue.role==="user"?U.push({type:"user",text:Ue.content}):U.push({type:"applied",text:Ue.content});$(U),w(true);}).catch(()=>w(true));},[P,y,F,M,a,oe,v,x,J,b]),useEffect(()=>{e==="complete"&&N(false);},[e]),useEffect(()=>{if(h&&a==="none"){be([]),_(null),O(true);return}Ce?(be([{id:Ce,name:It?Pe?.container_name||"Preview container":"Primary container",createdAt:""}]),_(Ce)):(be([]),_(null)),O(true);},[Ce,h,a,It,Pe?.container_name]);let Le=useRef(void 0);useEffect(()=>{if(b){if(Le.current===void 0){Le.current=J;return}Le.current!==J&&(Le.current=J,$([]),w(false));}},[J,b]);let nt=useRef(null);useEffect(()=>{if(!W)return;let m=U=>{nt.current&&(nt.current.contains(U.target)||ae(false));},L=U=>{U.key==="Escape"&&ae(false);};return document.addEventListener("mousedown",m,true),document.addEventListener("keydown",L,true),()=>{document.removeEventListener("mousedown",m,true),document.removeEventListener("keydown",L,true);}},[W]),useEffect(()=>{if(h)return;let m=requestAnimationFrame(()=>l(true));return ()=>cancelAnimationFrame(m)},[h]),useEffect(()=>{let m=h||ne;if((m||Ie)&&(e==="prompting"||e==="complete")){let L=setTimeout(()=>et.current?.focus(),m?100:Ke+100);return ()=>clearTimeout(L)}},[Ie,h,ne,e]),useEffect(()=>{if(e==="complete"&&rt.current){let L=r.find(U=>U.type==="complete")?.data?.summary||t?.summary||Ln;$(U=>U[U.length-1]?.type==="applied"?U:[...U,{type:"applied",text:L}]),R(""),setTimeout(()=>et.current?.focus(),200);}},[e,Me,r,t?.summary]),useEffect(()=>{Ae.current&&(Ae.current.scrollTop=Ae.current.scrollHeight);},[T,e]);let Ot=()=>{C.trim()&&(rt.current=C.trim(),$(m=>[...m,{type:"user",text:C.trim()}]),d(C.trim(),oe,J),R(""));},Ir=async()=>{if(!(!f||Q||!oe)){ee(true);try{let m=await f(oe);$(L=>{let U=[...L];return U.length>=2&&U[U.length-1]?.type==="applied"?U.splice(-2,2):U.length>=1&&U[U.length-1]?.type==="applied"&&U.splice(-1,1),U}),m?.removed&&$([]);}catch{}finally{ee(false);}}},ot=()=>{if(h){c();return}if(ne){ge?.close();return}S(true),l(false),setTimeout(()=>c(),Ke);},Lr=h||ne?{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:gr,maxWidth:"100vw",background:"#ffffff",boxShadow:Ie?"-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:Ie?"translateX(0)":"translateX(100%)",transition:`transform ${Ke}ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow ${Ke}ms ease`,display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'},st=jsxs(Fragment,{children:[jsx("style",{children:`
21
+ `}),jsxs("div",{className:"__fork-stream",ref:t,style:{scrollbarWidth:"thin",scrollbarColor:"rgba(255, 255, 255, 0.15) transparent",backgroundColor:"#1a1a2e",borderRadius:"8px",padding:"12px",fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:"11px",maxHeight:"300px",overflowY:"auto",boxSizing:"border-box"},children:[e.length===0&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"#6b7280",fontSize:"11px"},children:[jsx(Loader2,{style:{width:"12px",height:"12px",animation:"__fork-spin 1s linear infinite",flexShrink:0}}),"Connecting to agent..."]}),e.map((r,n)=>{let o=n===e.length-1,i=r.type==="complete"||r.type==="error"||r.type==="build_complete"||r.type==="build_error",s=o&&!i&&(r.type==="status"||r.type==="tool_use"||r.type==="build_start"),a=On[r.type]||Code,f=Un[r.type]||"#9ca3af";if(r.type==="tool_use"){let p=String(r.data.category||"");a=Bn[p]||Wrench,f=Hn[p]||"#fbbf24";}return s?a=Loader2:!o&&r.type==="status"&&(a=Check,f="#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:f,...s?{animation:"__fork-spin 1s linear infinite"}:{}}}),jsx("span",{style:{color:o&&!i?"#d1d5db":"#6b7280",wordBreak:"break-all"},children:$t(r)})]},n)})]})]})}var Sr=35,Vn="Working on Feature",Jn="Built Custom Feature",xr=360,Ze=350;function qn(e){return e.length<=Sr?e:e.slice(0,Sr-3).trimEnd()+"..."}function Xn({events:e}){let[t,r]=useState("Setting up environment..."),[n,o]=useState(true),i=useRef(t),s=useRef(false);return useEffect(()=>{if(!s.current){for(let f of e)if(f.type==="status"&&String(f.data.message||"").includes("Agent started")){s.current=true;break}}let a="Setting up environment...";if(s.current)for(let f=e.length-1;f>=0;f--){let p=e[f];if(p.type==="tool_use"||p.type==="build_start"||p.type==="build_complete"){a=qn($t(p));break}}if(a!==i.current){o(false);let f=setTimeout(()=>{r(a),i.current=a,o(true);},200);return ()=>clearTimeout(f)}},[e]),jsx("span",{style:{fontSize:11,color:"#d1d5db",fontWeight:500,opacity:n?1:0,transition:"opacity 0.2s ease",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},children:t})}function Yn({children:e}){let[t,r]=useState(null);return useEffect(()=>{if(typeof document>"u")return;let n=document.createElement("div");n.setAttribute("data-fork-panel-host",""),n.style.cssText="all: initial;",document.body.appendChild(n);let o=n.attachShadow({mode:"open"});return r(o),()=>{n.remove();}},[]),t?createPortal(e,t):null}function Qe({state:e,fork:t,events:r,error:n,slotId:o,targetId:i,targetLabel:s,historyMode:a="slot",onSubmit:f,onUndo:p,onClose:d,baseUrl:S,apiKey:P,userId:R,userHash:x,appId:y,embedded:h=false}){let[T,_]=useState(""),[M,$]=useState([]),[I,v]=useState(false),[k,l]=useState(false),[A,F]=useState(false),[u,g]=useState(false),[m,L]=useState(false),[W,ee]=useState(false),[N,z]=useState(false),[J,D]=useState(false),[te,ne]=useState(false),[ue,q]=useState(null),[it,Ie]=useState(false),[Fe,ie]=useState([]),[X$1,E]=useState(null),[w,U]=useState(false),[K,ae]=useState(false),[Or,Bt]=useState(false),[Ur,Ht]=useState(null),[re,Le]=useState(null),[Br,Nt]=useState(false),[Dt,be]=useState(null),[Hr,Re]=useState(false),[we,jt]=useState(null),at=useRef(null),Oe=useRef(null),{resetAllForks:Nr,previewSession:Y,currentContainerId:Dr}=V(),pe=Y?.container_id??Dr,Ue=!!(Y&&Hr),le=we!==null,zt=useRef(d);useEffect(()=>{zt.current=d;});let lt=useRef(null),Be=useRef(false),Wt=typeof window<"u"&&"documentPictureInPicture"in window,jr=async()=>{if(!(!Wt||le))try{let c=await window.documentPictureInPicture.requestWindow({width:xr,height:640});c.document.body.style.margin="0",c.document.body.style.padding="0",c.document.body.style.height="100vh",c.document.body.style.overflow="hidden",c.document.body.style.background="#ffffff";try{let b=document.adoptedStyleSheets??[];b.length>0&&(c.document.adoptedStyleSheets=[...b]);}catch{}c.addEventListener("pagehide",()=>{lt.current=null,jt(null),Be.current||zt.current(),Be.current=!1;},{once:!0}),lt.current=c,jt(c);}catch(c){console.warn("[Fork] PiP open failed:",c);}},zr=()=>{we&&(Be.current=true,we.close());};useEffect(()=>()=>{Be.current=true,lt.current?.close();},[]);let ce=i??o??"",He=(s||ce).replace(/[-_]+/g," ").replace(/\b\w/g,c=>c.toUpperCase()),ct=useRef(""),Ne=h?true:k&&!A,Wr=r.find(c=>{let b=c.data;return c.type==="status"&&b.summary})?.data?.summary||t?.summary||Vn,ge=r.find(c=>{let b=c.data;return (c.type==="status"||c.type==="complete")&&typeof b?.estimateMinutes=="number"})?.data?.estimateMinutes??t?.estimateMinutes;useEffect(()=>{if(a==="none"){v(true);return}if(!S||!P||!R||!ce||I||!w)return;let c=new URLSearchParams({userId:R});if(x&&c.set("userHash",x),X$1&&c.set("containerId",X$1),a==="slot")c.set("slotId",ce);else if(a==="boundary"){if(!y){v(true);return}c.set("boundaryId",ce),c.set("appId",y);}fetch(`${S}/api/v1/forks/history?${c.toString()}`,{headers:{Authorization:`Bearer ${P}`}}).then(b=>b.ok?b.json():[]).then(b=>{let O=[];for(let Z of b)Z.role==="user"?O.push({type:"user",text:Z.content}):O.push({type:"applied",text:Z.content});$(O),v(true);}).catch(()=>v(true));},[P,y,S,I,a,ce,x,R,X$1,w]),useEffect(()=>{e==="complete"&&D(false);},[e]),useEffect(()=>{if(h&&a==="none"){ie([]),E(null),U(true),Re(false);return}if(Y){let c=false;return U(false),Re(false),be(null),fetch(`${S}/api/v1/preview/${encodeURIComponent(Y.preview_session_id)}/containers`,{headers:{Authorization:`Bearer ${P}`,...G()}}).then(b=>{if(!b.ok)throw new Error(`${b.status}`);return b.json()}).then(b=>{c||(ie(b.containers),E(b.currentContainerId??Y.container_id??null),Re(true));}).catch(b=>{c||(Re(false),be(b instanceof Error?b.message:String(b)),pe?(ie([{id:pe,name:Y.container_name||"Primary container",createdAt:"",hasAccess:true,isPrimary:true}]),E(pe)):(ie([]),E(null)));}).finally(()=>{c||U(true);}),()=>{c=true;}}pe?(ie([{id:pe,name:"Primary container",createdAt:""}]),E(pe)):(ie([]),E(null)),U(true),Re(false);},[P,pe,S,h,a,Y?.container_id,Y?.container_name,Y?.preview_session_id]);let De=useRef(void 0);useEffect(()=>{if(w){if(De.current===void 0){De.current=X$1;return}De.current!==X$1&&(De.current=X$1,$([]),v(false));}},[X$1,w]);let je=useRef(null);useEffect(()=>{if(!K)return;let c=O=>{if(!je.current)return;let Z=typeof O.composedPath=="function"?O.composedPath():[];je.current.contains(O.target)||Z.includes(je.current)||ae(false);},b=O=>{O.key==="Escape"&&ae(false);};return document.addEventListener("mousedown",c,true),document.addEventListener("keydown",b,true),()=>{document.removeEventListener("mousedown",c,true),document.removeEventListener("keydown",b,true);}},[K]),useEffect(()=>{if(h)return;let c=requestAnimationFrame(()=>l(true));return ()=>cancelAnimationFrame(c)},[h]),useEffect(()=>{let c=h||le;if((c||Ne)&&(e==="prompting"||e==="complete")){let b=setTimeout(()=>at.current?.focus(),c?100:Ze+100);return ()=>clearTimeout(b)}},[Ne,h,le,e]),useEffect(()=>{if(e==="complete"&&ct.current){let b=r.find(O=>O.type==="complete")?.data?.summary||t?.summary||Jn;$(O=>O[O.length-1]?.type==="applied"?O:[...O,{type:"applied",text:b}]),_(""),setTimeout(()=>at.current?.focus(),200);}},[e,He,r,t?.summary]),useEffect(()=>{Oe.current&&(Oe.current.scrollTop=Oe.current.scrollHeight);},[M,e]);let Kt=()=>{T.trim()&&(ct.current=T.trim(),$(c=>[...c,{type:"user",text:T.trim()}]),f(T.trim(),ce,X$1),_(""));},Gt=c=>{yt(c.session.containerId,c.session.containerName),E(c.session.containerId),ie(b=>{let O=b.filter(Z=>Z.id!==c.container.id);return [{...c.container,isPrimary:true,hasAccess:true},...O.map(Z=>({...Z,isPrimary:false}))]}),$([]),v(false);},Kr=async c=>{if(!(!Y||!Ue||re)){Le(c),be(null);try{let b=await fetch(`${S}/api/v1/preview/${encodeURIComponent(Y.preview_session_id)}/containers/${encodeURIComponent(c)}/primary`,{method:"POST",headers:{Authorization:`Bearer ${P}`,...G()}});if(!b.ok){let O=await b.json().catch(()=>({}));throw new Error(O.error||`API error: ${b.status}`)}Gt(await b.json()),ae(!1);}catch(b){be(b instanceof Error?b.message:String(b));}finally{Le(null);}}},Gr=async()=>{if(!Y||!Ue||re)return;let c=window.prompt("Container name","New container");if(!(!c||!c.trim())){Le("__new__"),be(null);try{let b=await fetch(`${S}/api/v1/preview/${encodeURIComponent(Y.preview_session_id)}/containers`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${P}`,...G()},body:JSON.stringify({name:c.trim()})});if(!b.ok){let O=await b.json().catch(()=>({}));throw new Error(O.error||`API error: ${b.status}`)}Gt(await b.json()),ae(!1);}catch(b){be(b instanceof Error?b.message:String(b));}finally{Le(null);}}},Vr=async()=>{if(!(!p||te||!ce)){ne(true);try{let c=await p(ce);$(b=>{let O=[...b];return O.length>=2&&O[O.length-1]?.type==="applied"?O.splice(-2,2):O.length>=1&&O[O.length-1]?.type==="applied"&&O.splice(-1,1),O}),c?.removed&&$([]);}catch{}finally{ne(false);}}},dt=()=>{if(h){d();return}if(le){we?.close();return}F(true),l(false),setTimeout(()=>d(),Ze);},Jr=h||le?{position:"relative",width:"100%",height:"100%",background:"#ffffff",display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'}:{position:"fixed",top:0,right:0,bottom:0,zIndex:2147483e3,width:xr,maxWidth:"100vw",background:"#ffffff",boxShadow:Ne?"-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:Ne?"translateX(0)":"translateX(100%)",transition:`transform ${Ze}ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow ${Ze}ms ease`,display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'},Vt=Fe.find(c=>c.id===X$1)?.name??(w?`Fork ${He}`:"Loading..."),ut=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 ht from'react';import ht__default,{createContext,useSyncExternalStore,
40
40
  scrollbar-width: thin;
41
41
  scrollbar-color: rgba(0, 0, 0, 0.12) transparent;
42
42
  }
43
- `}),jsxs("div",{className:"__fork-panel",style:Lr,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(je,{style:{width:16,height:16,color:"#1c4587",cursor:"pointer",flexShrink:0},onDoubleClick:async m=>{if(m.stopPropagation(),!Qe&&confirm("Reset all forks? This will remove all forked components.")){_e(true);try{let L=await Ar();`${L?.deleted??0}`,$([]),R(""),N(!1),ot();}catch(L){console.error("[Fork] Reset failed:",L);}finally{_e(false);}}}}),e==="running"?jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:Mr}):ke.length===0?jsxs("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:["Fork ",Me]}):jsxs("div",{ref:nt,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[jsxs("button",{type:"button",onClick:()=>{ae(m=>!m);},onMouseEnter:()=>Ct(true),onMouseLeave:()=>Ct(false),"aria-haspopup":"menu","aria-expanded":W,style:{display:"inline-flex",alignItems:"center",gap:4,padding:"3px 6px",border:"1px solid transparent",borderRadius:6,background:$r||W?"#f3f4f6":"transparent",fontSize:13,fontWeight:600,color:"#111827",fontFamily:"inherit",cursor:"pointer",maxWidth:180,minWidth:0,transition:"background-color 0.12s"},children:[jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:ke.find(m=>m.id===J)?.name??(b?`Fork ${Me}`:"Loading\u2026")}),jsx(ChevronDown,{style:{width:12,height:12,color:"#6b7280",flexShrink:0,transform:W?"rotate(180deg)":void 0,transition:"transform 0.15s"}})]}),W&&jsx("div",{role:"menu",style:{position:"absolute",top:"calc(100% + 4px)",left:0,minWidth:200,maxWidth:260,background:"#ffffff",border:"1px solid #e5e7eb",borderRadius:8,boxShadow:"0 4px 12px rgba(0,0,0,0.08), 0 1px 3px rgba(0,0,0,0.06)",padding:4,zIndex:2147483001},children:ke.map(m=>{let L=m.id===J,U=_r===m.id;return jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>Tt(m.id),onMouseLeave:()=>Tt(null),onClick:()=>{ae(false),m.id!==J&&_(m.id);},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:U?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:"pointer",textAlign:"left",fontWeight:L?600:400},children:[jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:L&&jsx(Check,{style:{width:12,height:12}})}),jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:m.name})]},m.id)})})]}),e==="running"&&jsx("span",{title:ce?`Estimated ~${ce} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:ce?"#1c4587":"#9ca3af",backgroundColor:ce?"rgba(28, 69, 135, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:ce?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:ce?`~${ce}m`:"~ m"}),e==="complete"&&jsx("div",{style:{height:6,width:6,backgroundColor:"#1c4587",borderRadius:"50%",flexShrink:0}})]}),!h&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[Ut&&jsx("button",{onClick:ne?Tr:Cr,onMouseEnter:()=>I(true),onMouseLeave:()=>I(false),title:ne?"Redock to sidebar":"Pop out into window",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:ne?jsx(PictureInPicture,{style:{width:16,height:16}}):jsx(PictureInPicture2,{style:{width:16,height:16}})}),jsx("button",{onClick:ot,onMouseEnter:()=>p(true),onMouseLeave:()=>p(false),style:{padding:6,borderRadius:6,color:u?"#4b5563":"#9ca3af",backgroundColor:u?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:jsx(X,{style:{width:16,height:16}})})]})]}),jsxs("div",{ref:Ae,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[e==="prompting"&&T.length===0&&jsx("div",{style:{padding:"24px 20px",textAlign:"center"},children:jsx("p",{style:{fontSize:13,color:"#6b7280",marginBottom:14,lineHeight:1.625,margin:"0 0 14px 0"},children:"Describe the feature you want to build."})}),T.length>0&&jsx("div",{style:{padding:"16px 16px 0 16px"},children:T.map((m,L)=>jsx("div",{style:{marginBottom:L<T.length-1?10:0},children:m.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:m.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:m.text}),f&&L===T.length-1&&e!=="running"&&jsxs("button",{onClick:U=>{U.stopPropagation(),Ir();},onMouseEnter:()=>q(L),onMouseLeave:()=>q(null),disabled:Q,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:ie===L?"rgba(0,0,0,0.06)":"transparent",color:ie===L?"#6b7280":"#d1d5db",cursor:Q?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:Q?.4:1,flexShrink:0},children:[jsx(Undo2,{style:{width:12,height:12}}),ie===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:()=>N(!V),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(On,{events:r})]}),jsx("div",{style:{color:"#6b7280",flexShrink:0,marginLeft:8,transition:"transform 0.2s ease",transform:V?"rotate(180deg)":"rotate(0deg)"},children:jsx(ChevronDown,{style:{width:14,height:14}})})]}),jsx("div",{style:{maxHeight:V?320:0,opacity:V?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(cr,{events:r})})})]})}),e==="error"&&jsxs("div",{style:{padding:"20px 16px",textAlign:"center"},children:[jsx("div",{style:{width:36,height:36,backgroundColor:"#fef2f2",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 10px auto"},children:jsx(X,{style:{width:18,height:18,color:"#ef4444"}})}),jsx("p",{style:{fontSize:12,color:"#6b7280",marginBottom:10,maxWidth:260,margin:"0 auto 10px auto"},children:n}),jsxs("button",{onClick:()=>{let m=t?.prompt||rt.current;m&&d(m,oe);},onMouseEnter:()=>D(true),onMouseLeave:()=>D(false),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,color:"#4f46e5",backgroundColor:H?"#e0e7ff":"#eef2ff",border:"none",cursor:"pointer",transition:"background-color 0.15s",fontFamily:"inherit"},children:[jsx(RotateCcw,{style:{width:12,height:12}})," Try Again"]})]})]}),e!=="running"&&jsx("div",{style:{padding:"8px 12px 12px 12px",borderTop:"1px solid rgba(229, 231, 235, 0.6)",flexShrink:0},children:jsxs("div",{style:{display:"flex",alignItems:"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:et,value:C,onChange:m=>{R(m.target.value),m.target.style.height="auto",m.target.style.height=Math.min(m.target.scrollHeight,160)+"px";},onKeyDown:m=>{m.key==="Enter"&&!m.shiftKey&&(m.preventDefault(),Ot()),m.key==="Escape"&&!h&&ot();},placeholder:T.length>0?"Ask for another change...":`Describe your ideal ${Me.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:Ot,disabled:!C.trim(),onMouseEnter:()=>Y(true),onMouseLeave:()=>Y(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:C.trim()?1:.25,transform:z&&C.trim()?"scale(1.1)":"scale(1)",background:C.trim()?"#1c4587":"rgba(0,0,0,0.12)",border:"none",cursor:C.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:jsx(ArrowUp,{style:{width:13,height:13}})})]})})]})]});return h?st:ne&&ge?createPortal(st,ge.document.body):jsx(Bn,{children:st})}function hr(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 St(e){let{apiKey:t,userId:r,userHash:n,baseUrl:o,appId:i,previewSession:s,refreshModuleManifest:a,queueBoundaryAnimation:d}=G(),[f,c]=useState("idle"),[F,P]=useState(null),[x,v]=useState([]),[y,h]=useState(null),C=useRef(null),R=useCallback(()=>{c("prompting"),v([]),h(null),P(null);},[]),T=useCallback(()=>{c("idle"),C.current&&(C.current.close(),C.current=null);},[]);useEffect(()=>{s&&s.target.kind==="module"&&s.target.id===e&&c(w=>w==="idle"?"prompting":w);},[s?.preview_session_id,s?.target.id,e]);let $=useCallback(async(w,k)=>{try{if(!i)throw new Error("ForkProvider requires appId for module boundary prompts.");c("running"),v([]),h(null);let l;if(s){let u=await fetch(`${o}/api/v1/preview/${encodeURIComponent(s.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...Z()},body:JSON.stringify({prompt:w,...s.fork_id?{fork_id:s.fork_id}:{}})});if(!u.ok){let I=await u.json().catch(()=>({}));throw new Error(I.error||`API error: ${u.status}`)}let p=await u.json();ve(p.fork_id),l=await(await fetch(`${o}/api/v1/forks/${p.fork_id}`,{headers:{Authorization:`Bearer ${t}`,...Z()}})).json();}else {let u={userId:r,prompt:w,boundaryId:e,appId:i};k&&(u.containerId=k),n&&(u.userHash=n);let p=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(u)});if(!p.ok){let g=await p.json().catch(()=>({}));throw new Error(g.error||`API error: ${p.status}`)}l=await p.json();}P(l);let E=new URLSearchParams({key:t});n&&(E.set("userId",r),E.set("userHash",n));let S=new EventSource(`${o}/api/v1/forks/${l.id}/events?${E.toString()}`);C.current=S,S.onmessage=u=>{try{let p=JSON.parse(u.data);if(v(g=>[...g,p]),p.type==="complete"){let g=p.data;d(e,l.id),a().catch(()=>{}).finally(()=>{let I={...l,status:"complete",moduleUrl:g.moduleUrl,cssUrls:g.cssUrls,summary:g.summary,completedAt:new Date().toISOString()};P(I),c("complete"),S.close();});}else if(p.type==="error"){let g=p.data;h(g.error||"Unknown error"),c("error"),S.close();}}catch{}},S.onerror=()=>{fetch(`${o}/api/v1/forks/${l.id}`,{headers:{Authorization:`Bearer ${t}`}}).then(u=>u.json()).then(u=>{P(u),u.status==="complete"?(d(e,u.id),a().catch(()=>{}),c("complete")):u.status==="error"&&(h(u.error||"Fork generation failed"),c("error"));}).catch(()=>{h("Connection lost"),c("error");}),S.close();};}catch(l){h(l.message),c("error");}},[t,i,o,e,s,d,a,n,r]),M=useCallback(async()=>{try{if(!i)throw new Error("ForkProvider requires appId for boundary undo.");let w={userId:r,boundaryId:e,appId:i};n&&(w.userHash=n);let k=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(w)});if(!k.ok){let E=await k.json().catch(()=>({}));throw new Error(E.error||`API error: ${k.status}`)}let l=await k.json();return await a().catch(()=>{}),l.removed?(P(null),c("prompting")):l.fork&&(P(l.fork),c("complete")),l}catch(w){throw h(w.message),w}},[t,i,o,e,a,n,r]);return {state:f,fork:F,events:x,error:y,open:R,close:T,startFork:$,undoFork:M}}function yr(e){let{state:t,fork:r,events:n,error:o,open:i,close:s,startFork:a,undoFork:d}=St(e);return {state:t,fork:r,events:n,error:o,isOpen:t!=="idle",open:i,close:s,submit:a,undo:d}}function xt(){let{apiKey:e,userId:t,userHash:r,baseUrl:n,previewSession:o,setSlotFork:i,clearSlotFork:s,skipAnimationForSlot:a}=G(),[d,f]=useState("idle"),[c,F]=useState(null),[P,x]=useState([]),[v,y]=useState(null),h=useRef(null),C=useCallback(()=>{f("prompting"),x([]),y(null),F(null);},[]),R=useCallback(()=>{f("idle"),h.current&&(h.current.close(),h.current=null);},[]);useEffect(()=>{o&&o.target.kind==="slot"&&f(M=>M==="idle"?"prompting":M);},[o?.preview_session_id,o?.target.kind]);let T=useCallback(async(M,w,k)=>{try{f("running"),x([]),y(null);let l;if(o){let u=await fetch(`${n}/api/v1/preview/${encodeURIComponent(o.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...Z()},body:JSON.stringify({prompt:M,...o.fork_id?{fork_id:o.fork_id}:{}})});if(!u.ok){let I=await u.json().catch(()=>({}));throw new Error(I.error||`API error: ${u.status}`)}let p=await u.json();ve(p.fork_id),l=await(await fetch(`${n}/api/v1/forks/${p.fork_id}`,{headers:{Authorization:`Bearer ${e}`,...Z()}})).json();}else {let u={userId:t,prompt:M};w&&(u.slotId=w),k&&(u.containerId=k),r&&(u.userHash=r);let p=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(u)});if(!p.ok){let g=await p.json().catch(()=>({}));throw new Error(g.error||`API error: ${p.status}`)}l=await p.json();}F(l);let E=new URLSearchParams({key:e});r&&(E.set("userId",t),E.set("userHash",r));let S=new EventSource(`${n}/api/v1/forks/${l.id}/events?${E.toString()}`);h.current=S,S.onmessage=u=>{try{let p=JSON.parse(u.data);if(x(g=>[...g,p]),p.type==="complete"){let g=p.data,I={...l,status:"complete",bundleUrl:g.bundleUrl,summary:g.summary,completedAt:new Date().toISOString()};F(I),f("complete"),w&&g.bundleUrl&&i(w,I),S.close();}else if(p.type==="error"){let g=p.data;y(g.error||"Unknown error"),f("error"),S.close();}}catch{}},S.onerror=()=>{fetch(`${n}/api/v1/forks/${l.id}`,{headers:{Authorization:`Bearer ${e}`}}).then(u=>u.json()).then(u=>{F(u),u.status==="complete"?(f("complete"),w&&u.bundleUrl&&i(w,u)):u.status==="error"&&(y(u.error||"Fork generation failed"),f("error"));}).catch(()=>{y("Connection lost"),f("error");}),S.close();};}catch(l){y(l.message),f("error");}},[e,t,r,n,o,i]),$=useCallback(async M=>{try{let w={userId:t,slotId:M};r&&(w.userHash=r);let k=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(w)});if(!k.ok){let E=await k.json().catch(()=>({}));throw new Error(E.error||`API error: ${k.status}`)}let l=await k.json();return a(M),l.removed?(s(M),F(null),f("prompting")):l.fork&&(i(M,l.fork),F(l.fork)),l}catch(w){throw y(w.message),w}},[e,t,r,n,s,i]);return {state:d,fork:c,events:P,error:v,open:C,close:R,startFork:T,undoFork:$}}function kr(){let{state:e,fork:t,events:r,error:n,open:o,close:i,startFork:s,undoFork:a}=xt();return {state:e,fork:t,events:r,error:n,isOpen:e!=="idle",open:o,close:i,submit:s,undo:a}}function Ft(e){let t=hr(e),r=kr(),n=yr(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:i,userId:s,userHash:a,appId:d}=G(),f=t.type==="slot"?r:n,c=t.type==="slot"?"slot":"boundary",F=t.id,P=t.title,x=useCallback((y,h,C)=>t.type==="slot"?r.submit(y,h??t.id,C):n.submit(y,C),[n,r,t]),v=useCallback(y=>t.type==="slot"?r.undo(y??t.id):n.undo(),[n,r,t]);return {...f,target:t,targetId:F,targetLabel:P,historyMode:c,submit:x,undo:v,buttonProps:{onClick:f.open},panelProps:{state:f.state,fork:f.fork,events:f.events,error:f.error,...t.type==="slot"?{slotId:F,targetLabel:P,historyMode:c}:{targetId:F,targetLabel:P,historyMode:c},onSubmit:x,onUndo:v,onClose:f.close,baseUrl:o,apiKey:i,userId:s,userHash:a,appId:d}}}function $e(e){let{embedded:t}=e,r=Ft(e);return t?jsx(Ge,{...r.panelProps,embedded:true}):r.isOpen?jsx(Ge,{...r.panelProps}):jsx(bt,{...r.buttonProps})}function Wn({boundaryId:e,title:t}){return jsx($e,{boundaryId:e,title:t})}function Et(e){let t=Array.from(e.children).filter(n=>n instanceof HTMLElement);return t.length===1?t[0]:getComputedStyle(e).display==="contents"?null:e}function wr(e){let t=e.getBoundingClientRect(),r=e.cloneNode(true);r.style.position="fixed",r.style.top=`${t.top}px`,r.style.left=`${t.left}px`,r.style.width=`${t.width}px`,r.style.height=`${t.height}px`,r.style.flex="none",r.style.minHeight="auto",r.style.zIndex="9998",r.style.pointerEvents="none",r.style.overflow="hidden";let n=getComputedStyle(e).backgroundColor;r.style.backgroundColor=n&&n!=="rgba(0, 0, 0, 0)"&&n!=="transparent"?n:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(r);let o=e.querySelectorAll("*"),i=r.querySelectorAll("*");for(let s=0;s<o.length;s+=1)o[s].scrollTop!==0&&(i[s].scrollTop=o[s].scrollTop),o[s].scrollLeft!==0&&(i[s].scrollLeft=o[s].scrollLeft);return r}function $t(e){let t=[],r=e.querySelectorAll("*");for(let n of r){if(!(n instanceof HTMLElement))continue;let o=n.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(n.tagName))continue;let i=getComputedStyle(n),s=parseFloat(i.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:s});}return t}function vr(e,t){let r=[];for(let n of t)if(!(e.find(s=>s.tag===n.tag&&s.className===n.className&&Math.abs(s.rect.top-n.rect.top)<20&&Math.abs(s.rect.left-n.rect.left)<20)||r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom))){for(let s=r.length-1;s>=0;s-=1){let a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Sr(e,t){let r=[];for(let n of e)if(!(t.find(s=>s.tag===n.tag&&s.className===n.className&&Math.abs(s.rect.top-n.rect.top)<20&&Math.abs(s.rect.left-n.rect.left)<20)||r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom))){for(let s=r.length-1;s>=0;s-=1){let a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function xr(e,t,r,n,o){let i=Math.max(0,Math.min(o,r/2,n/2));return i===0?`M ${e} ${t} L ${e+r} ${t} L ${e+r} ${t+n} L ${e} ${t+n} Z`:[`M ${e+i} ${t}`,`L ${e+r-i} ${t}`,`A ${i} ${i} 0 0 1 ${e+r} ${t+i}`,`L ${e+r} ${t+n-i}`,`A ${i} ${i} 0 0 1 ${e+r-i} ${t+n}`,`L ${e+i} ${t+n}`,`A ${i} ${i} 0 0 1 ${e} ${t+n-i}`,`L ${e} ${t+i}`,`A ${i} ${i} 0 0 1 ${e+i} ${t}`,"Z"].join(" ")}function _t(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-highlights","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");n.appendChild(o);let i=[];for(let c=0;c<e.length;c+=1){let{rect:F,borderRadius:P}=e[c],x=F.left-.5,v=F.top-.5,y=F.width+1,h=F.height+1,C=Math.min(P+.5,y/2,h/2),R=xr(x,v,y,h,C),T=`__fork-glow-${c}`,$=document.createElementNS(t,"filter");$.setAttribute("id",T),$.setAttribute("x","-100%"),$.setAttribute("y","-100%"),$.setAttribute("width","300%"),$.setAttribute("height","300%");let M=document.createElementNS(t,"feGaussianBlur");M.setAttribute("in","SourceGraphic"),M.setAttribute("stdDeviation","8"),$.appendChild(M),o.appendChild($);let w=`__fork-mask-${c}`,k=document.createElementNS(t,"mask");k.setAttribute("id",w),k.setAttribute("maskUnits","userSpaceOnUse"),k.setAttribute("x",String(x-200)),k.setAttribute("y",String(v-200)),k.setAttribute("width",String(y+400)),k.setAttribute("height",String(h+400));let l=document.createElementNS(t,"rect");l.setAttribute("x",String(x-200)),l.setAttribute("y",String(v-200)),l.setAttribute("width",String(y+400)),l.setAttribute("height",String(h+400)),l.setAttribute("fill","white"),k.appendChild(l);let E=document.createElementNS(t,"path");E.setAttribute("d",R),E.setAttribute("fill","black"),k.appendChild(E),o.appendChild(k);let S=document.createElementNS(t,"g");S.setAttribute("mask",`url(#${w})`),S.setAttribute("opacity","0");let u=document.createElementNS(t,"g");u.setAttribute("filter",`url(#${T})`);let p=document.createElementNS(t,"path");p.setAttribute("d",R),p.setAttribute("fill","none"),p.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),p.setAttribute("stroke-width","6"),p.setAttribute("stroke-linecap","round"),u.appendChild(p),S.appendChild(u),n.appendChild(S);let g=document.createElementNS(t,"path");g.setAttribute("d",R),g.setAttribute("fill","none"),g.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),g.setAttribute("stroke-width","2"),g.setAttribute("stroke-linecap","round"),g.setAttribute("opacity","0"),n.appendChild(g),i.push(p,g),p.__group=S;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let c=0;c<i.length;c+=2){let F=i[c],P=i[c+1],x=F.__group;if(!x)continue;let v=P.getTotalLength(),y=F.getTotalLength();if(v<=0)continue;let h=v*.35;P.setAttribute("stroke-dasharray",`${h} ${v-h}`),P.setAttribute("stroke-dashoffset","0"),s.push(P.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*v,opacity:.92,offset:.06},{strokeDashoffset:-2*v,opacity:.92,offset:.92},{strokeDashoffset:-2.25*v,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let C=y*.35;F.setAttribute("stroke-dasharray",`${C} ${y-C}`),F.setAttribute("stroke-dashoffset","0"),s.push(F.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*y,offset:.06},{strokeDashoffset:-2*y,offset:.92},{strokeDashoffset:-2.25*y,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(x.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,d=()=>{if(a)return;a=true,clearTimeout(f);for(let F of s)try{F.cancel();}catch{}let c=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});c.onfinish=()=>r.remove(),window.removeEventListener("click",d);},f=setTimeout(d,14500);return setTimeout(()=>{a||window.addEventListener("click",d);},500),d}function Fr(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-removed","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs"),i=document.createElementNS(t,"filter");i.setAttribute("id","__fork-removed-shadow"),i.setAttribute("x","-10%"),i.setAttribute("y","-10%"),i.setAttribute("width","120%"),i.setAttribute("height","120%");let s=document.createElementNS(t,"feDropShadow");s.setAttribute("dx","0"),s.setAttribute("dy","1"),s.setAttribute("stdDeviation","2"),s.setAttribute("flood-color","rgba(0,0,0,0.15)"),i.appendChild(s),o.appendChild(i),n.appendChild(o);for(let{rect:a,borderRadius:d}of e){let f=document.createElementNS(t,"path");f.setAttribute("d",xr(a.left,a.top,a.width,a.height,d)),f.setAttribute("fill","none"),f.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),f.setAttribute("stroke-width","1.5"),f.setAttribute("stroke-dasharray","8 4"),f.setAttribute("stroke-linecap","round"),f.setAttribute("filter","url(#__fork-removed-shadow)"),f.setAttribute("opacity","0"),n.appendChild(f),f.animate([{opacity:0,offset:0},{opacity:.6,offset:.08},{opacity:.05,offset:.45},{opacity:.6,offset:.85},{opacity:.05,offset:1}],{duration:5e3,easing:"ease-in-out",fill:"forwards"});}return r.appendChild(n),document.body.appendChild(r),r}var Ze=new Map,At=new Map;function Vn(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function Er(e,t){let r=(t?e[t]:void 0)??e.default;if(typeof r!="function"){let n=t||"default";throw new Error(`Fork boundary module is missing a React component export: ${n}`)}return r}function qn(e){if(!e||typeof document>"u")return Promise.resolve();let t=Ze.get(e);if(t)return t;let r=document.querySelector(`link[data-fork-override-href="${e}"]`);if(r instanceof HTMLLinkElement){let o=r.sheet?Promise.resolve():new Promise((i,s)=>{let a=()=>{r.removeEventListener("load",a),r.removeEventListener("error",d),i();},d=()=>{r.removeEventListener("load",a),r.removeEventListener("error",d),s(new Error(`Failed to load boundary stylesheet: ${e}`));};r.addEventListener("load",a,{once:true}),r.addEventListener("error",d,{once:true});});return Ze.set(e,o),o}let n=new Promise((o,i)=>{let s=document.createElement("link");s.rel="stylesheet",s.href=e,s.setAttribute("data-fork-override-href",e),s.onload=()=>o(),s.onerror=()=>{s.remove(),i(new Error(`Failed to load boundary stylesheet: ${e}`));},document.head.appendChild(s);}).catch(o=>{throw Ze.delete(e),o});return Ze.set(e,n),n}function Jn(e){let t=At.get(e);if(t)return t;let r=import(e).catch(n=>{throw At.delete(e),n});return At.set(e,r),r}async function Xn(e,t,r){if(e)try{await Promise.all(e.cssUrls.map(i=>qn(i)));let o=await Jn(e.moduleUrl);return Er(o,r)}catch(o){console.error(`[Fork] Failed to load override for boundary "${e.boundaryId}", falling back to original module.`,o);}let n=await t();return Er(n,r)}function Yn(e){function t(r){let{appId:n,moduleOverridesEnabled:o,moduleManifestReady:i,moduleManifestVersion:s,registerBoundary:a,getBoundaryOverride:d,consumeBoundaryAnimation:f}=G(),[c,F]=useState(null),[P,x]=useState(null),v=useRef(null),y=useRef(null),h=useRef(null),C=useRef(false),R=useRef(null),T=useRef(null),$=d(e.id),M=$?`override:${$.id}`:"original",w=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if(useEffect(()=>()=>{T.current&&(clearTimeout(T.current),T.current=null),R.current&&(R.current.remove(),R.current=null);},[]),useEffect(()=>{a({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[n,a,e.id,e.exportName,w]),useEffect(()=>{if(o&&!i&&!c||y.current===M&&c)return;let k=false;return x(null),Xn($,e.original,e.exportName).then(l=>{if(!k){if($?.id&&f(e.id,$.id)&&v.current){let E=Et(v.current);if(E){let S=$t(E);S.length>0&&(h.current=S,C.current=true,T.current&&(clearTimeout(T.current),T.current=null),R.current&&R.current.remove(),R.current=wr(E));}}y.current=M,startTransition(()=>{F(()=>l);});}}).catch(l=>{k||x(Vn(l));}),()=>{k=true;}},[f,M,o,i,s,$?.id,$?.moduleUrl,$?.integrity,$?.cssUrls.join("|"),e.exportName,e.original,c]),useEffect(()=>{if(!C.current||!c||!v.current)return;let k=false;return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(k||!v.current)return;let l=h.current,E=Et(v.current);if(h.current=null,C.current=false,!l||!E){R.current&&(R.current.remove(),R.current=null);return}let S=$t(E),u=vr(l,S),p=Sr(l,S),g=R.current;if(p.length>0&&g){let I=Fr(p);T.current=setTimeout(()=>{T.current=null;let z=400;g.animate([{opacity:1},{opacity:0}],{duration:z,fill:"forwards"}),I.animate([{opacity:1},{opacity:0}],{duration:z,fill:"forwards"}),setTimeout(()=>{g.remove(),I.remove(),R.current===g&&(R.current=null),u.length>0&&_t(u);},z);},3500);}else g&&(g.remove(),R.current===g&&(R.current=null)),u.length>0&&_t(u);});}),()=>{k=true;}},[c]),P)throw P;return c?jsx("div",{ref:v,style:{display:"contents"},children:jsx(c,{...r})}):jsx(Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function Qn({slotId:e,title:t,slotLabel:r}){return jsx($e,{slotId:e,title:t,slotLabel:r})}
44
- export{Wn as ForkBoundaryUI,bt as ForkButton,$e as ForkChatInterface,Ge as ForkPanel,Qr as ForkProvider,pn as ForkSlot,Qn as ForkUI,qr as clearCachedManifest,Yn as forkable,He as loadManifest,Jr as manifestDiffers,Gr as readCachedManifest,at as registerForkShared,St as useBoundaryFork,xt as useFork,Ft as useForkChatPanel,Be as usePreviewSession,Vr as writeCachedManifest};
43
+ `}),jsxs("div",{className:"__fork-panel",style:Jr,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(qe,{style:{width:16,height:16,color:"#1c4587",cursor:"pointer",flexShrink:0},onDoubleClick:async c=>{if(c.stopPropagation(),!it&&confirm("Reset all forks? This will remove all forked components.")){Ie(true);try{let b=await Nr();`${b?.deleted??0}`,$([]),_(""),D(!1),dt();}catch(b){console.error("[Fork] Reset failed:",b);}finally{Ie(false);}}}}),e==="running"?jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:Wr}):Fe.length===0&&!Ue?jsxs("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:["Fork ",He]}):Ue?jsxs("div",{ref:je,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[jsxs("button",{type:"button",onClick:()=>{ae(c=>!c);},onMouseEnter:()=>Bt(true),onMouseLeave:()=>Bt(false),"aria-haspopup":"menu","aria-expanded":K,style:{display:"inline-flex",alignItems:"center",gap:4,padding:"3px 6px",border:"1px solid transparent",borderRadius:6,background:Or||K?"#f3f4f6":"transparent",fontSize:13,fontWeight:600,color:"#111827",fontFamily:"inherit",cursor:"pointer",maxWidth:180,minWidth:0,transition:"background-color 0.12s"},children:[jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:Vt}),jsx(ChevronDown,{style:{width:12,height:12,color:"#6b7280",flexShrink:0,transform:K?"rotate(180deg)":void 0,transition:"transform 0.15s"}})]}),K&&jsxs("div",{role:"menu",style:{position:"absolute",top:"calc(100% + 4px)",left:0,minWidth:200,maxWidth:260,background:"#ffffff",border:"1px solid #e5e7eb",borderRadius:8,boxShadow:"0 4px 12px rgba(0,0,0,0.08), 0 1px 3px rgba(0,0,0,0.06)",padding:4,zIndex:2147483001},children:[Fe.map(c=>{let b=c.id===X$1,O=Ur===c.id,Z=re===c.id;return jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>Ht(c.id),onMouseLeave:()=>Ht(null),onClick:()=>{c.id!==X$1&&Kr(c.id);},disabled:!!re,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:O?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:re?"default":"pointer",textAlign:"left",fontWeight:b?600:400,opacity:re&&!Z?.55:1},children:[jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:b&&jsx(Check,{style:{width:12,height:12}})}),jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Z?"Switching...":c.name})]},c.id)}),jsx("div",{style:{height:1,background:"#e5e7eb",margin:"4px 0"}}),jsx("button",{type:"button",role:"menuitem",onMouseEnter:()=>Nt(true),onMouseLeave:()=>Nt(false),onClick:()=>{Gr();},disabled:!!re,style:{display:"flex",alignItems:"center",width:"100%",padding:"6px 8px",border:"none",background:Br?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:re?"default":"pointer",textAlign:"left",opacity:re&&re!=="__new__"?.55:1},children:re==="__new__"?"Creating...":"+ New container"}),Dt&&jsx("div",{style:{padding:"6px 8px",fontSize:11,lineHeight:1.35,color:"#b91c1c"},children:Dt})]})]}):jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:Vt}),e==="running"&&jsx("span",{title:ge?`Estimated ~${ge} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:ge?"#1c4587":"#9ca3af",backgroundColor:ge?"rgba(28, 69, 135, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:ge?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:ge?`~${ge}m`:"~ m"}),e==="complete"&&jsx("div",{style:{height:6,width:6,backgroundColor:"#1c4587",borderRadius:"50%",flexShrink:0}})]}),!h&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[Wt&&jsx("button",{onClick:le?zr:jr,onMouseEnter:()=>L(true),onMouseLeave:()=>L(false),title:le?"Redock to sidebar":"Pop out into window",style:{padding:6,borderRadius:6,color:m?"#4b5563":"#9ca3af",backgroundColor:m?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:le?jsx(PictureInPicture,{style:{width:16,height:16}}):jsx(PictureInPicture2,{style:{width:16,height:16}})}),jsx("button",{onClick:dt,onMouseEnter:()=>g(true),onMouseLeave:()=>g(false),style:{padding:6,borderRadius:6,color:u?"#4b5563":"#9ca3af",backgroundColor:u?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:jsx(X,{style:{width:16,height:16}})})]})]}),jsxs("div",{ref:Oe,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[e==="prompting"&&M.length===0&&jsx("div",{style:{padding:"24px 20px",textAlign:"center"},children:jsx("p",{style:{fontSize:13,color:"#6b7280",marginBottom:14,lineHeight:1.625,margin:"0 0 14px 0"},children:"Describe the feature you want to build."})}),M.length>0&&jsx("div",{style:{padding:"16px 16px 0 16px"},children:M.map((c,b)=>jsx("div",{style:{marginBottom:b<M.length-1?10:0},children:c.type==="user"?jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexDirection:"row-reverse"},children:[jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:jsx(User,{style:{width:13,height:13,color:"#6b7280"}})}),jsx("div",{style:{backgroundColor:"#f3f4f6",borderRadius:"12px 4px 12px 12px",padding:"8px 12px",fontSize:13,color:"#374151",lineHeight:1.5,maxWidth:"75%"},children:c.text})]}):jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#f0fdf4",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:jsx(Check,{style:{width:13,height:13,color:"#9ca3af"}})}),jsxs("div",{style:{backgroundColor:"#f9fafb",borderRadius:"4px 12px 12px 12px",padding:"8px 12px",fontSize:13,color:"#6b7280",fontWeight:500,display:"flex",alignItems:"center",gap:6,maxWidth:"75%"},children:[jsx("span",{style:{flex:1},children:c.text}),p&&b===M.length-1&&e!=="running"&&jsxs("button",{onClick:O=>{O.stopPropagation(),Vr();},onMouseEnter:()=>q(b),onMouseLeave:()=>q(null),disabled:te,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:ue===b?"rgba(0,0,0,0.06)":"transparent",color:ue===b?"#6b7280":"#d1d5db",cursor:te?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:te?.4:1,flexShrink:0},children:[jsx(Undo2,{style:{width:12,height:12}}),ue===b&&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"})]})]})]})},b))}),e==="running"&&jsx("div",{style:{padding:16},children:jsxs("div",{onClick:()=>D(!J),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(Xn,{events:r})]}),jsx("div",{style:{color:"#6b7280",flexShrink:0,marginLeft:8,transition:"transform 0.2s ease",transform:J?"rotate(180deg)":"rotate(0deg)"},children:jsx(ChevronDown,{style:{width:14,height:14}})})]}),jsx("div",{style:{maxHeight:J?320:0,opacity:J?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(kr,{events:r})})})]})}),e==="error"&&jsxs("div",{style:{padding:"20px 16px",textAlign:"center"},children:[jsx("div",{style:{width:36,height:36,backgroundColor:"#fef2f2",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 10px auto"},children:jsx(X,{style:{width:18,height:18,color:"#ef4444"}})}),jsx("p",{style:{fontSize:12,color:"#6b7280",marginBottom:10,maxWidth:260,margin:"0 auto 10px auto"},children:n}),jsxs("button",{onClick:()=>{let c=t?.prompt||ct.current;c&&f(c,ce);},onMouseEnter:()=>z(true),onMouseLeave:()=>z(false),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,color:"#4f46e5",backgroundColor:N?"#e0e7ff":"#eef2ff",border:"none",cursor:"pointer",transition:"background-color 0.15s",fontFamily:"inherit"},children:[jsx(RotateCcw,{style:{width:12,height:12}})," Try Again"]})]})]}),e!=="running"&&jsx("div",{style:{padding:"8px 12px 12px 12px",borderTop:"1px solid rgba(229, 231, 235, 0.6)",flexShrink:0},children:jsxs("div",{style:{display:"flex",alignItems:"flex-end",gap:6,borderRadius:12,padding:"8px 8px 8px 12px",background:"rgba(0, 0, 0, 0.04)",border:"1px solid rgba(0, 0, 0, 0.06)"},children:[jsx("textarea",{ref:at,value:T,onChange:c=>{_(c.target.value),c.target.style.height="auto",c.target.style.height=Math.min(c.target.scrollHeight,160)+"px";},onKeyDown:c=>{c.key==="Enter"&&!c.shiftKey&&(c.preventDefault(),Kt()),c.key==="Escape"&&!h&&dt();},placeholder:M.length>0?"Ask for another change...":`Describe your ideal ${He.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:Kt,disabled:!T.trim(),onMouseEnter:()=>ee(true),onMouseLeave:()=>ee(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:T.trim()?1:.25,transform:W&&T.trim()?"scale(1.1)":"scale(1)",background:T.trim()?"#1c4587":"rgba(0,0,0,0.12)",border:"none",cursor:T.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:jsx(ArrowUp,{style:{width:13,height:13}})})]})})]})]});return h?ut:le&&we?createPortal(ut,we.document.body):jsx(Yn,{children:ut})}function Rr(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 At(e){let{apiKey:t,userId:r,userHash:n,baseUrl:o,appId:i,previewSession:s,refreshModuleManifest:a,queueBoundaryAnimation:f}=V(),[p,d]=useState("idle"),[S,P]=useState(null),[R,x]=useState([]),[y,h]=useState(null),T=useRef(null),_=useCallback(()=>{d("prompting"),x([]),h(null),P(null);},[]),M=useCallback(()=>{d("idle"),T.current&&(T.current.close(),T.current=null);},[]);useEffect(()=>{s&&s.target.kind==="module"&&s.target.id===e&&d(v=>v==="idle"?"prompting":v);},[s?.preview_session_id,s?.target.id,e]);let $=useCallback(async(v,k)=>{try{if(!i)throw new Error("ForkProvider requires appId for module boundary prompts.");d("running"),x([]),h(null);let l;if(s){let u=await fetch(`${o}/api/v1/preview/${encodeURIComponent(s.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...G()},body:JSON.stringify({prompt:v,...s.fork_id?{fork_id:s.fork_id}:{}})});if(!u.ok){let L=await u.json().catch(()=>({}));throw new Error(L.error||`API error: ${u.status}`)}let g=await u.json();_e(g.fork_id),l=await(await fetch(`${o}/api/v1/forks/${g.fork_id}`,{headers:{Authorization:`Bearer ${t}`,...G()}})).json();}else {let u={userId:r,prompt:v,boundaryId:e,appId:i};k&&(u.containerId=k),n&&(u.userHash=n);let g=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(u)});if(!g.ok){let m=await g.json().catch(()=>({}));throw new Error(m.error||`API error: ${g.status}`)}l=await g.json();}P(l);let A=new URLSearchParams({key:t});n&&(A.set("userId",r),A.set("userHash",n));let F=new EventSource(`${o}/api/v1/forks/${l.id}/events?${A.toString()}`);T.current=F,F.onmessage=u=>{try{let g=JSON.parse(u.data);if(x(m=>[...m,g]),g.type==="complete"){let m=g.data;f(e,l.id),a().catch(()=>{}).finally(()=>{let L={...l,status:"complete",moduleUrl:m.moduleUrl,cssUrls:m.cssUrls,summary:m.summary,completedAt:new Date().toISOString()};P(L),d("complete"),F.close();});}else if(g.type==="error"){let m=g.data;h(m.error||"Unknown error"),d("error"),F.close();}}catch{}},F.onerror=()=>{fetch(`${o}/api/v1/forks/${l.id}`,{headers:{Authorization:`Bearer ${t}`}}).then(u=>u.json()).then(u=>{P(u),u.status==="complete"?(f(e,u.id),a().catch(()=>{}),d("complete")):u.status==="error"&&(h(u.error||"Fork generation failed"),d("error"));}).catch(()=>{h("Connection lost"),d("error");}),F.close();};}catch(l){h(l.message),d("error");}},[t,i,o,e,s,f,a,n,r]),I=useCallback(async()=>{try{if(!i)throw new Error("ForkProvider requires appId for boundary undo.");let v={userId:r,boundaryId:e,appId:i};n&&(v.userHash=n);let k=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(v)});if(!k.ok){let A=await k.json().catch(()=>({}));throw new Error(A.error||`API error: ${k.status}`)}let l=await k.json();return await a().catch(()=>{}),l.removed?(P(null),d("prompting")):l.fork&&(P(l.fork),d("complete")),l}catch(v){throw h(v.message),v}},[t,i,o,e,a,n,r]);return {state:p,fork:S,events:R,error:y,open:_,close:M,startFork:$,undoFork:I}}function Er(e){let{state:t,fork:r,events:n,error:o,open:i,close:s,startFork:a,undoFork:f}=At(e);return {state:t,fork:r,events:n,error:o,isOpen:t!=="idle",open:i,close:s,submit:a,undo:f}}function Ct(){let{apiKey:e,userId:t,userHash:r,baseUrl:n,previewSession:o,setSlotFork:i,clearSlotFork:s,skipAnimationForSlot:a}=V(),[f,p]=useState("idle"),[d,S]=useState(null),[P,R]=useState([]),[x,y]=useState(null),h=useRef(null),T=useCallback(()=>{p("prompting"),R([]),y(null),S(null);},[]),_=useCallback(()=>{p("idle"),h.current&&(h.current.close(),h.current=null);},[]);useEffect(()=>{o&&o.target.kind==="slot"&&p(I=>I==="idle"?"prompting":I);},[o?.preview_session_id,o?.target.kind]);let M=useCallback(async(I,v,k)=>{try{p("running"),R([]),y(null);let l;if(o){let u=await fetch(`${n}/api/v1/preview/${encodeURIComponent(o.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...G()},body:JSON.stringify({prompt:I,...o.fork_id?{fork_id:o.fork_id}:{}})});if(!u.ok){let L=await u.json().catch(()=>({}));throw new Error(L.error||`API error: ${u.status}`)}let g=await u.json();_e(g.fork_id),l=await(await fetch(`${n}/api/v1/forks/${g.fork_id}`,{headers:{Authorization:`Bearer ${e}`,...G()}})).json();}else {let u={userId:t,prompt:I};v&&(u.slotId=v),k&&(u.containerId=k),r&&(u.userHash=r);let g=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(u)});if(!g.ok){let m=await g.json().catch(()=>({}));throw new Error(m.error||`API error: ${g.status}`)}l=await g.json();}S(l);let A=new URLSearchParams({key:e});r&&(A.set("userId",t),A.set("userHash",r));let F=new EventSource(`${n}/api/v1/forks/${l.id}/events?${A.toString()}`);h.current=F,F.onmessage=u=>{try{let g=JSON.parse(u.data);if(R(m=>[...m,g]),g.type==="complete"){let m=g.data,L={...l,status:"complete",bundleUrl:m.bundleUrl,summary:m.summary,completedAt:new Date().toISOString()};S(L),p("complete"),v&&m.bundleUrl&&i(v,L),F.close();}else if(g.type==="error"){let m=g.data;y(m.error||"Unknown error"),p("error"),F.close();}}catch{}},F.onerror=()=>{fetch(`${n}/api/v1/forks/${l.id}`,{headers:{Authorization:`Bearer ${e}`}}).then(u=>u.json()).then(u=>{S(u),u.status==="complete"?(p("complete"),v&&u.bundleUrl&&i(v,u)):u.status==="error"&&(y(u.error||"Fork generation failed"),p("error"));}).catch(()=>{y("Connection lost"),p("error");}),F.close();};}catch(l){y(l.message),p("error");}},[e,t,r,n,o,i]),$=useCallback(async I=>{try{let v={userId:t,slotId:I};r&&(v.userHash=r);let k=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(v)});if(!k.ok){let A=await k.json().catch(()=>({}));throw new Error(A.error||`API error: ${k.status}`)}let l=await k.json();return a(I),l.removed?(s(I),S(null),p("prompting")):l.fork&&(i(I,l.fork),S(l.fork)),l}catch(v){throw y(v.message),v}},[e,t,r,n,s,i]);return {state:f,fork:d,events:P,error:x,open:T,close:_,startFork:M,undoFork:$}}function _r(){let{state:e,fork:t,events:r,error:n,open:o,close:i,startFork:s,undoFork:a}=Ct();return {state:e,fork:t,events:r,error:n,isOpen:e!=="idle",open:o,close:i,submit:s,undo:a}}function Pt(e){let t=Rr(e),r=_r(),n=Er(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:i,userId:s,userHash:a,appId:f}=V(),p=t.type==="slot"?r:n,d=t.type==="slot"?"slot":"boundary",S=t.id,P=t.title,R=useCallback((y,h,T)=>t.type==="slot"?r.submit(y,h??t.id,T):n.submit(y,T),[n,r,t]),x=useCallback(y=>t.type==="slot"?r.undo(y??t.id):n.undo(),[n,r,t]);return {...p,target:t,targetId:S,targetLabel:P,historyMode:d,submit:R,undo:x,buttonProps:{onClick:p.open},panelProps:{state:p.state,fork:p.fork,events:p.events,error:p.error,...t.type==="slot"?{slotId:S,targetLabel:P,historyMode:d}:{targetId:S,targetLabel:P,historyMode:d},onSubmit:R,onUndo:x,onClose:p.close,baseUrl:o,apiKey:i,userId:s,userHash:a,appId:f}}}function Me(e){let{embedded:t}=e,r=Pt(e);return t?jsx(Qe,{...r.panelProps,embedded:true}):r.isOpen?jsx(Qe,{...r.panelProps}):jsx(Et,{...r.buttonProps})}function no({boundaryId:e,title:t}){return jsx(Me,{boundaryId:e,title:t})}function Mt(e){let t=Array.from(e.children).filter(n=>n instanceof HTMLElement);return t.length===1?t[0]:getComputedStyle(e).display==="contents"?null:e}function Ar(e){let t=e.getBoundingClientRect(),r=e.cloneNode(true);r.style.position="fixed",r.style.top=`${t.top}px`,r.style.left=`${t.left}px`,r.style.width=`${t.width}px`,r.style.height=`${t.height}px`,r.style.flex="none",r.style.minHeight="auto",r.style.zIndex="9998",r.style.pointerEvents="none",r.style.overflow="hidden";let n=getComputedStyle(e).backgroundColor;r.style.backgroundColor=n&&n!=="rgba(0, 0, 0, 0)"&&n!=="transparent"?n:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(r);let o=e.querySelectorAll("*"),i=r.querySelectorAll("*");for(let s=0;s<o.length;s+=1)o[s].scrollTop!==0&&(i[s].scrollTop=o[s].scrollTop),o[s].scrollLeft!==0&&(i[s].scrollLeft=o[s].scrollLeft);return r}function It(e){let t=[],r=e.querySelectorAll("*");for(let n of r){if(!(n instanceof HTMLElement))continue;let o=n.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(n.tagName))continue;let i=getComputedStyle(n),s=parseFloat(i.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:s});}return t}function Cr(e,t){let r=[];for(let n of t)if(!(e.find(s=>s.tag===n.tag&&s.className===n.className&&Math.abs(s.rect.top-n.rect.top)<20&&Math.abs(s.rect.left-n.rect.left)<20)||r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom))){for(let s=r.length-1;s>=0;s-=1){let a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Pr(e,t){let r=[];for(let n of e)if(!(t.find(s=>s.tag===n.tag&&s.className===n.className&&Math.abs(s.rect.top-n.rect.top)<20&&Math.abs(s.rect.left-n.rect.left)<20)||r.some(s=>n.rect.top>=s.rect.top&&n.rect.left>=s.rect.left&&n.rect.right<=s.rect.right&&n.rect.bottom<=s.rect.bottom))){for(let s=r.length-1;s>=0;s-=1){let a=r[s];a.rect.top>=n.rect.top&&a.rect.left>=n.rect.left&&a.rect.right<=n.rect.right&&a.rect.bottom<=n.rect.bottom&&r.splice(s,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Tr(e,t,r,n,o){let i=Math.max(0,Math.min(o,r/2,n/2));return i===0?`M ${e} ${t} L ${e+r} ${t} L ${e+r} ${t+n} L ${e} ${t+n} Z`:[`M ${e+i} ${t}`,`L ${e+r-i} ${t}`,`A ${i} ${i} 0 0 1 ${e+r} ${t+i}`,`L ${e+r} ${t+n-i}`,`A ${i} ${i} 0 0 1 ${e+r-i} ${t+n}`,`L ${e+i} ${t+n}`,`A ${i} ${i} 0 0 1 ${e} ${t+n-i}`,`L ${e} ${t+i}`,`A ${i} ${i} 0 0 1 ${e+i} ${t}`,"Z"].join(" ")}function Lt(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-highlights","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");n.appendChild(o);let i=[];for(let d=0;d<e.length;d+=1){let{rect:S,borderRadius:P}=e[d],R=S.left-.5,x=S.top-.5,y=S.width+1,h=S.height+1,T=Math.min(P+.5,y/2,h/2),_=Tr(R,x,y,h,T),M=`__fork-glow-${d}`,$=document.createElementNS(t,"filter");$.setAttribute("id",M),$.setAttribute("x","-100%"),$.setAttribute("y","-100%"),$.setAttribute("width","300%"),$.setAttribute("height","300%");let I=document.createElementNS(t,"feGaussianBlur");I.setAttribute("in","SourceGraphic"),I.setAttribute("stdDeviation","8"),$.appendChild(I),o.appendChild($);let v=`__fork-mask-${d}`,k=document.createElementNS(t,"mask");k.setAttribute("id",v),k.setAttribute("maskUnits","userSpaceOnUse"),k.setAttribute("x",String(R-200)),k.setAttribute("y",String(x-200)),k.setAttribute("width",String(y+400)),k.setAttribute("height",String(h+400));let l=document.createElementNS(t,"rect");l.setAttribute("x",String(R-200)),l.setAttribute("y",String(x-200)),l.setAttribute("width",String(y+400)),l.setAttribute("height",String(h+400)),l.setAttribute("fill","white"),k.appendChild(l);let A=document.createElementNS(t,"path");A.setAttribute("d",_),A.setAttribute("fill","black"),k.appendChild(A),o.appendChild(k);let F=document.createElementNS(t,"g");F.setAttribute("mask",`url(#${v})`),F.setAttribute("opacity","0");let u=document.createElementNS(t,"g");u.setAttribute("filter",`url(#${M})`);let g=document.createElementNS(t,"path");g.setAttribute("d",_),g.setAttribute("fill","none"),g.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),g.setAttribute("stroke-width","6"),g.setAttribute("stroke-linecap","round"),u.appendChild(g),F.appendChild(u),n.appendChild(F);let m=document.createElementNS(t,"path");m.setAttribute("d",_),m.setAttribute("fill","none"),m.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),m.setAttribute("stroke-width","2"),m.setAttribute("stroke-linecap","round"),m.setAttribute("opacity","0"),n.appendChild(m),i.push(g,m),g.__group=F;}r.appendChild(n),document.body.appendChild(r);let s=[];for(let d=0;d<i.length;d+=2){let S=i[d],P=i[d+1],R=S.__group;if(!R)continue;let x=P.getTotalLength(),y=S.getTotalLength();if(x<=0)continue;let h=x*.35;P.setAttribute("stroke-dasharray",`${h} ${x-h}`),P.setAttribute("stroke-dashoffset","0"),s.push(P.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*x,opacity:.92,offset:.06},{strokeDashoffset:-2*x,opacity:.92,offset:.92},{strokeDashoffset:-2.25*x,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let T=y*.35;S.setAttribute("stroke-dasharray",`${T} ${y-T}`),S.setAttribute("stroke-dashoffset","0"),s.push(S.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*y,offset:.06},{strokeDashoffset:-2*y,offset:.92},{strokeDashoffset:-2.25*y,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),s.push(R.animate([{opacity:0,offset:0},{opacity:.92,offset:.06},{opacity:.92,offset:.92},{opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));}let a=false,f=()=>{if(a)return;a=true,clearTimeout(p);for(let S of s)try{S.cancel();}catch{}let d=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});d.onfinish=()=>r.remove(),window.removeEventListener("click",f);},p=setTimeout(f,14500);return setTimeout(()=>{a||window.addEventListener("click",f);},500),f}function Mr(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-removed","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs"),i=document.createElementNS(t,"filter");i.setAttribute("id","__fork-removed-shadow"),i.setAttribute("x","-10%"),i.setAttribute("y","-10%"),i.setAttribute("width","120%"),i.setAttribute("height","120%");let s=document.createElementNS(t,"feDropShadow");s.setAttribute("dx","0"),s.setAttribute("dy","1"),s.setAttribute("stdDeviation","2"),s.setAttribute("flood-color","rgba(0,0,0,0.15)"),i.appendChild(s),o.appendChild(i),n.appendChild(o);for(let{rect:a,borderRadius:f}of e){let p=document.createElementNS(t,"path");p.setAttribute("d",Tr(a.left,a.top,a.width,a.height,f)),p.setAttribute("fill","none"),p.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),p.setAttribute("stroke-width","1.5"),p.setAttribute("stroke-dasharray","8 4"),p.setAttribute("stroke-linecap","round"),p.setAttribute("filter","url(#__fork-removed-shadow)"),p.setAttribute("opacity","0"),n.appendChild(p),p.animate([{opacity:0,offset:0},{opacity:.6,offset:.08},{opacity:.05,offset:.45},{opacity:.6,offset:.85},{opacity:.05,offset:1}],{duration:5e3,easing:"ease-in-out",fill:"forwards"});}return r.appendChild(n),document.body.appendChild(r),r}var st=new Map,Ot=new Map;function io(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function Lr(e,t){let r=(t?e[t]:void 0)??e.default;if(typeof r!="function"){let n=t||"default";throw new Error(`Fork boundary module is missing a React component export: ${n}`)}return r}function ao(e){if(!e||typeof document>"u")return Promise.resolve();let t=st.get(e);if(t)return t;let r=document.querySelector(`link[data-fork-override-href="${e}"]`);if(r instanceof HTMLLinkElement){let o=r.sheet?Promise.resolve():new Promise((i,s)=>{let a=()=>{r.removeEventListener("load",a),r.removeEventListener("error",f),i();},f=()=>{r.removeEventListener("load",a),r.removeEventListener("error",f),s(new Error(`Failed to load boundary stylesheet: ${e}`));};r.addEventListener("load",a,{once:true}),r.addEventListener("error",f,{once:true});});return st.set(e,o),o}let n=new Promise((o,i)=>{let s=document.createElement("link");s.rel="stylesheet",s.href=e,s.setAttribute("data-fork-override-href",e),s.onload=()=>o(),s.onerror=()=>{s.remove(),i(new Error(`Failed to load boundary stylesheet: ${e}`));},document.head.appendChild(s);}).catch(o=>{throw st.delete(e),o});return st.set(e,n),n}function lo(e){let t=Ot.get(e);if(t)return t;let r=import(e).catch(n=>{throw Ot.delete(e),n});return Ot.set(e,r),r}async function co(e,t,r){if(e)try{await Promise.all(e.cssUrls.map(i=>ao(i)));let o=await lo(e.moduleUrl);return Lr(o,r)}catch(o){console.error(`[Fork] Failed to load override for boundary "${e.boundaryId}", falling back to original module.`,o);}let n=await t();return Lr(n,r)}function uo(e){function t(r){let{appId:n,moduleOverridesEnabled:o,moduleManifestReady:i,moduleManifestVersion:s,registerBoundary:a,getBoundaryOverride:f,consumeBoundaryAnimation:p}=V(),[d,S]=useState(null),[P,R]=useState(null),x=useRef(null),y=useRef(null),h=useRef(null),T=useRef(false),_=useRef(null),M=useRef(null),$=f(e.id),I=$?`override:${$.id}`:"original",v=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if(useEffect(()=>()=>{M.current&&(clearTimeout(M.current),M.current=null),_.current&&(_.current.remove(),_.current=null);},[]),useEffect(()=>{a({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[n,a,e.id,e.exportName,v]),useEffect(()=>{if(o&&!i&&!d||y.current===I&&d)return;let k=false;return R(null),co($,e.original,e.exportName).then(l=>{if(!k){if($?.id&&p(e.id,$.id)&&x.current){let A=Mt(x.current);if(A){let F=It(A);F.length>0&&(h.current=F,T.current=true,M.current&&(clearTimeout(M.current),M.current=null),_.current&&_.current.remove(),_.current=Ar(A));}}y.current=I,startTransition(()=>{S(()=>l);});}}).catch(l=>{k||R(io(l));}),()=>{k=true;}},[p,I,o,i,s,$?.id,$?.moduleUrl,$?.integrity,$?.cssUrls.join("|"),e.exportName,e.original,d]),useEffect(()=>{if(!T.current||!d||!x.current)return;let k=false;return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(k||!x.current)return;let l=h.current,A=Mt(x.current);if(h.current=null,T.current=false,!l||!A){_.current&&(_.current.remove(),_.current=null);return}let F=It(A),u=Cr(l,F),g=Pr(l,F),m=_.current;if(g.length>0&&m){let L=Mr(g);M.current=setTimeout(()=>{M.current=null;let W=400;m.animate([{opacity:1},{opacity:0}],{duration:W,fill:"forwards"}),L.animate([{opacity:1},{opacity:0}],{duration:W,fill:"forwards"}),setTimeout(()=>{m.remove(),L.remove(),_.current===m&&(_.current=null),u.length>0&&Lt(u);},W);},3500);}else m&&(m.remove(),_.current===m&&(_.current=null)),u.length>0&&Lt(u);});}),()=>{k=true;}},[d]),P)throw P;return d?jsx("div",{ref:x,style:{display:"contents"},children:jsx(d,{...r})}):jsx(Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function po({slotId:e,title:t,slotLabel:r}){return jsx(Me,{slotId:e,title:t,slotLabel:r})}
44
+ export{no as ForkBoundaryUI,Et as ForkButton,Me as ForkChatInterface,Qe as ForkPanel,pn as ForkProvider,En as ForkSlot,po as ForkUI,ln as clearCachedManifest,uo as forkable,Ge as loadManifest,cn as manifestDiffers,sn as readCachedManifest,pt as registerForkShared,At as useBoundaryFork,Ct as useFork,Pt as useForkChatPanel,Ke as usePreviewSession,an as writeCachedManifest};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fork-api/chat-sdk",
3
- "version": "0.1.134",
3
+ "version": "0.1.136",
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",