@fork-api/chat-sdk 0.1.174 → 0.1.175
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +7 -8
- package/dist/index.d.cts +18 -44
- package/dist/index.d.ts +18 -44
- package/dist/index.js +7 -8
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
'use strict';var Fr=require('react'),vo=require('react-dom'),So=require('react/jsx-runtime'),Fo=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 Fr__namespace=/*#__PURE__*/_interopNamespace(Fr);var vo__namespace=/*#__PURE__*/_interopNamespace(vo);var So__namespace=/*#__PURE__*/_interopNamespace(So);var Fo__namespace=/*#__PURE__*/_interopNamespace(Fo);var Xe="__FORK_SHARED__";function ur(){var t,r,n,o;let e=globalThis;return e[Xe]||(e[Xe]={}),(t=e[Xe]).react||(t.react=Fr__namespace),(r=e[Xe])["react-dom"]||(r["react-dom"]=vo__namespace),(n=e[Xe])["react/jsx-runtime"]||(n["react/jsx-runtime"]=So__namespace),(o=e[Xe])["react/jsx-dev-runtime"]||(o["react/jsx-dev-runtime"]=Fo__namespace),e[Xe]}function dr(e){return Object.assign(ur(),e)}var xo="__fork_preview_session__";function Dt(e){return `${xo}${e}`}var se={apiKey:null,session:null},fr=new Set;function jt(){for(let e of fr)try{e();}catch(t){console.error("[fork-preview] subscriber threw",t);}}function on(e){let t=Date.parse(e.expires_at);return Number.isFinite(t)?t<=Date.now():true}function Ao(e){if(typeof window>"u")return null;try{let t=window.sessionStorage.getItem(Dt(e));if(!t)return null;let r=JSON.parse(t);return !r||typeof r!="object"||typeof r.preview_session_id!="string"?null:on(r)?(window.sessionStorage.removeItem(Dt(e)),null):r}catch{return null}}function pr(e,t){if(!(typeof window>"u"))try{t?window.sessionStorage.setItem(Dt(e),JSON.stringify(t)):window.sessionStorage.removeItem(Dt(e));}catch{}}function ct(e){se.apiKey!==e&&(se.apiKey=e,se.session=Ao(e),jt());}function Ne(){return se.session?on(se.session)?(Kt(null),null):se.session:null}function Kt(e){se.session=e,se.apiKey&&pr(se.apiKey,e),jt();}function mt(e){se.session&&se.session.fork_id!==e&&(se.session={...se.session,fork_id:e},se.apiKey&&pr(se.apiKey,se.session),jt());}function Ge(e,t){se.session&&(se.session.container_id===e&&se.session.container_name===t||(se.session={...se.session,container_id:e,container_name:t??se.session.container_name??"Fork",fork_id:null},se.apiKey&&pr(se.apiKey,se.session),jt()));}function gr(e){return fr.add(e),()=>{fr.delete(e);}}var sn="__fork_preview";function an(){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(sn);return typeof r=="string"&&r.length>0?r:null}function hr(e){if(typeof window>"u")return false;try{let t=window.sessionStorage.getItem(`__fork_preview_session__${e}`);if(t){let r=JSON.parse(t),n=typeof r?.expires_at=="string"?Date.parse(r.expires_at):NaN;if(Number.isFinite(n)&&n>Date.now())return !0;window.sessionStorage.removeItem(`__fork_preview_session__${e}`);}}catch{}return cn()!==null}function ln(){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(sn);let r=t.toString(),n=r?`#${r}`:"";try{window.history.replaceState(null,"",window.location.pathname+window.location.search+n);}catch{}}var Ye=null,mr=null,ht=null;function cn(){if(Ye)return Ye;let e=an();return e?(Ye=e,ln(),Ye):null}async function yr(e,t){ct(e);let r=Ne();if(r)return Ye=null,r;let n=Ye??an();if(Ye=null,!n)return null;ln();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 s=await o.json(),i={preview_session_id:s.preview_session_id,tenant_id:s.tenant_id,app_id:s.app_id,target:s.target,operator_id:s.operator_id,container_id:s.container_id??null,container_name:s.container_name??"Fork",fork_id:s.fork_id??null,expires_at:s.expires_at};return Kt(i),i}catch(o){return console.warn("[fork-preview] activate threw",o),null}}async function kr(e,t,r){ct(e);let n=Ne();if(n)return n;if(!r.appId||!r.userId||!r.userHash)return null;let o=[e,t,r.appId,r.userId].join(`
|
|
2
|
-
`);return ht&&mr===o||(mr=o,ht=(async()=>{try{let s=await fetch(`${t}/api/v1/preview/auto-activate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,"X-Fork-User-Id":r.userId,"X-Fork-User-Hash":r.userHash},body:JSON.stringify({appId:r.appId})});if(s.status===204)return null;if(!s.ok){let c=await s.json().catch(()=>({}));return console.warn(`[fork-preview] auto admin activate failed (${s.status}): ${c.error??"unknown"}`),null}let i=await s.json(),a={preview_session_id:i.preview_session_id,tenant_id:i.tenant_id,app_id:i.app_id,target:i.target,operator_id:i.operator_id,container_id:i.container_id??null,container_name:i.container_name??"Fork",fork_id:i.fork_id??null,expires_at:i.expires_at};return Kt(a),a}catch(s){return console.warn("[fork-preview] auto admin activate threw",s),null}finally{mr=null,ht=null;}})()),ht}function Ro(){return Ne()}function _o(){return null}function zt(){return Fr.useSyncExternalStore(gr,Ro,_o)}function ne(){let e=Ne();if(!e)return {};let t={"X-Fork-Preview-Session":e.preview_session_id};return e.fork_id&&(t["X-Fork-Preview-Fork-Id"]=e.fork_id),t}async function Wt(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 s=await o.json(),i={};for(let[a,c]of Object.entries(s.modules)){let y=c.moduleUrl??c.bundleUrl??null,S=c.legacyModuleUrl??c.legacyBundleUrl??null;i[a]={forkId:c.forkId,moduleUrl:y,legacyModuleUrl:S,bundleUrl:c.bundleUrl??y,legacyBundleUrl:c.legacyBundleUrl??S,cssUrls:c.cssUrls??[],integrity:c.integrity,metadata:c.metadata,highlightHint:c.highlightHint,buildId:c.buildId,updatedAt:c.updatedAt};}return {containerId:s.containerId,forksPaused:!!s.forksPaused,slots:s.slots,modules:i,generatedAt:s.generatedAt,etag:o.headers.get("ETag")??void 0}}var Eo="fork:manifest:v1";function br(e,t,r){return `${Eo}:${e}:${t}:${r}`}function Co(e,t,r){if(typeof window>"u")return null;try{let n=window.localStorage.getItem(br(e,t,r));return n?JSON.parse(n):null}catch{return null}}function Po(e,t,r,n){if(!(typeof window>"u"))try{window.localStorage.setItem(br(e,t,r),JSON.stringify(n));}catch{}}function $o(e,t,r){if(!(typeof window>"u"))try{window.localStorage.removeItem(br(e,t,r));}catch{}}function To(e,t){if(!e||!t)return e!==t;if(e.containerId!==t.containerId||!!e.forksPaused!=!!t.forksPaused)return true;let r=Object.entries(e.slots),n=Object.entries(t.slots);if(r.length!==n.length)return true;for(let[i,a]of r){let c=t.slots[i];if(!c||c.forkId!==a.forkId||c.buildId!==a.buildId)return true}let o=Object.entries(e.modules),s=Object.entries(t.modules);if(o.length!==s.length)return true;for(let[i,a]of o){let c=t.modules[i];if(!c||c.forkId!==a.forkId||c.buildId!==a.buildId)return true}return false}var mn=Fr.createContext(null),Ho=12e3,Oo=45e3,un="fork:activity:v1",Uo=new Set(["pending","running","building"]),Bo="Setting up environment";function _e(e){return Uo.has(e)}function No(e,t){return t?.targetId?t:e.boundaryId?{targetKind:"module",targetId:e.boundaryId}:e.slotId?{targetKind:"slot",targetId:e.slotId}:null}function Do(e,t){let r=No(e,t);if(!r)return null;let n=new Date().toISOString();return {id:e.id,status:e.status,targetKind:r.targetKind,targetId:r.targetId,summary:e.summary??null,estimateMinutes:e.estimateMinutes??null,createdAt:e.createdAt||n,updatedAt:e.completedAt||n,completedAt:e.completedAt??null}}function dn(e){return {id:e.id,status:e.status,targetKind:e.targetKind,targetId:e.targetId,summary:e.summary??null,estimateMinutes:e.estimateMinutes??null,promptCount:e.promptCount,messageCount:e.messageCount,isActive:e.isActive,createdAt:e.createdAt,updatedAt:e.updatedAt,completedAt:e.completedAt??null}}function Jt(e,t){let r=typeof t.summary=="string"&&t.summary.trim()?t.summary.trim():void 0,n=typeof e?.summary=="string"&&e.summary.trim()?e.summary.trim():void 0,o=typeof t.estimateMinutes=="number"&&Number.isFinite(t.estimateMinutes)?t.estimateMinutes:void 0,s=typeof e?.estimateMinutes=="number"&&Number.isFinite(e.estimateMinutes)?e.estimateMinutes:void 0;return {...e,...t,summary:r??n??null,estimateMinutes:o??s??null,latestMessage:t.latestMessage??e?.latestMessage??null,unread:t.unread??e?.unread??false}}function yt(e){return `${e.id}:${e.completedAt||e.updatedAt}`}function Qe(e){if(typeof window>"u")return new Set;try{let t=window.localStorage.getItem(e);if(!t)return new Set;let r=JSON.parse(t);return Array.isArray(r)?new Set(r.filter(n=>typeof n=="string")):new Set}catch{return new Set}}function Ze(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify([...t].slice(-200)));}catch{}}var jo="fork:previewPaused:v1";function wr(e,t,r,n){return `${jo}:${e}:${t}:${r}:${n}`}function Ko(e){if(typeof window>"u")return false;try{return window.localStorage.getItem(e)==="1"}catch{return false}}function fn(e,t){if(!(typeof window>"u"))try{t?window.localStorage.setItem(e,"1"):window.localStorage.removeItem(e);}catch{}}function zo(e){if(e.estimateMinutes)return `~${e.estimateMinutes}m`}function Wo(e){let t=e.data&&typeof e.data=="object"?e.data:{};if(e.type==="status"){let r=typeof t.status=="string"?t.status:"running",n=typeof t.summary=="string"?t.summary:void 0;return {status:r,latestMessage:_e(r)?"Building":void 0,summary:n,estimateMinutes:typeof t.estimateMinutes=="number"?t.estimateMinutes:void 0,updatedAt:e.timestamp}}return e.type==="tool_use"?{status:"running",latestMessage:"Building",updatedAt:e.timestamp}:e.type==="build_start"?{status:"building",latestMessage:"Building",updatedAt:e.timestamp}:e.type==="build_complete"?{status:"building",latestMessage:"Building",updatedAt:e.timestamp}:e.type==="complete"?{status:"complete",summary:typeof t.summary=="string"?t.summary:void 0,estimateMinutes:typeof t.estimateMinutes=="number"?t.estimateMinutes:void 0,latestMessage:"Fork ready",completedAt:e.timestamp,updatedAt:e.timestamp}:e.type==="error"||e.type==="build_error"?{status:"error",latestMessage:typeof t.error=="string"?t.error:typeof t.message=="string"?t.message:"Fork failed",updatedAt:e.timestamp}:{updatedAt:e.timestamp}}function Jo(e){let t=e.filter(o=>_e(o.status)),r=e.filter(o=>o.status==="complete"&&o.unread),n=[...e].sort((o,s)=>Date.parse(s.updatedAt)-Date.parse(o.updatedAt))[0]??null;if(t.length>1)return {state:"running",label:`${t.length} forks running`,count:t.length,runningCount:t.length,unreadCompletedCount:r.length,latest:t[0]};if(t.length===1){let o=t[0],s=!!(typeof o.summary=="string"&&o.summary.trim());return {state:"running",label:s?o.summary.trim():Bo,detail:s?zo(o):void 0,count:1,runningCount:1,unreadCompletedCount:r.length,latest:o}}if(r.length>1)return {state:"complete",label:`${r.length} forks ready`,count:r.length,runningCount:0,unreadCompletedCount:r.length,latest:r[0]};if(r.length===1){let o=r[0];return {state:"complete",label:o.summary||"Fork ready",count:1,runningCount:0,unreadCompletedCount:1,latest:o}}return {state:n?.status==="error"?"error":"idle",label:"Fork",count:0,runningCount:0,unreadCompletedCount:0,latest:n}}function kt(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function Vo(e,t){let r={};for(let[n,o]of Object.entries(t.boundaries||{}))r[n]={...o,moduleUrl:kt(e,o.moduleUrl),cssUrls:Array.isArray(o.cssUrls)?o.cssUrls.map(s=>kt(e,s)):[]};return r}function pn(e,t,r,n){let o={};for(let[s,i]of Object.entries(t.slots)){let a=i.bundleUrl??i.legacyBundleUrl;a&&(o[s]={id:i.forkId,userId:r,prompt:"",status:"complete",slotId:s,appId:n,bundleUrl:kt(e,a),revealPending:i.revealPending===true,createdAt:i.updatedAt,completedAt:i.updatedAt});}return o}function gn(e,t){let r={};for(let[n,o]of Object.entries(t.modules)){let s=o.moduleUrl??o.legacyModuleUrl??o.bundleUrl??"";s&&(r[n]={id:o.forkId,boundaryId:n,moduleUrl:kt(e,s),cssUrls:(o.cssUrls??[]).map(i=>kt(e,i)),integrity:o.integrity,metadata:o.metadata,highlightHint:o.highlightHint,createdAt:o.updatedAt});}return r}function qo(e){let{apiKey:t,baseUrl:r,children:n,appId:o,shared:s}=e,i="userId"in e?e.userId:void 0,a="userHash"in e?e.userHash:void 0,c="authUrl"in e?e.authUrl:void 0,[y]=Fr.useState(()=>(ct(t),hr(t))),[S,u]=Fr.useState({}),[m,I]=Fr.useState(i?{userId:i,userHash:a}:null),[v,f]=Fr.useState(!!i||y),[E,$]=Fr.useState({}),[F,h]=Fr.useState(!o),[N,D]=Fr.useState(0),[U,O]=Fr.useState(null),[C,M]=Fr.useState(false),[j,k]=Fr.useState([]),[d,w]=Fr.useState(()=>typeof document>"u"?true:document.visibilityState!=="hidden"),H=Fr.useRef(new Map),R=Fr.useRef(new Map),[A,b]=Fr.useState(0),P=Fr.useRef(new Set),G=Fr.useRef(new Map),te=Fr.useRef(void 0),z=Fr.useRef(new Map),Q=Fr.useRef([]),J=Fr.useRef(new Set),ie=Fr.useRef(false);ur(),Fr.useEffect(()=>{return yr(t,r).then(()=>{}),()=>{}},[]);let L=zt();Fr.useEffect(()=>{y||L||!o||!m?.userHash||kr(t,r,{appId:o,userId:m.userId,userHash:m.userHash});},[t,o,m?.userHash,m?.userId,r,y,L?.preview_session_id]),s&&te.current!==s&&(dr(s),te.current=s),Fr.useEffect(()=>{c&&(y||(f(false),fetch(c,{credentials:"include"}).then(p=>{if(!p.ok)throw new Error(`Auth endpoint returned ${p.status}`);return p.json()}).then(p=>{if(!p.userId||typeof p.userId!="string")throw new Error("authUrl response must include userId");I({userId:p.userId,userHash:typeof p.userHash=="string"?p.userHash:void 0});}).catch(p=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",p.message);}).finally(()=>{f(true);})));},[c,y]),Fr.useEffect(()=>{!c&&i&&(I({userId:i,userHash:a}),f(true));},[i,a,c]);let xe=m?.userId??"",Ae=m?.userHash,K=L?"":xe,V=L?void 0:Ae,he=!!o,fe=Fr.useCallback(async()=>{if(!he){O(null),M(false),$({}),h(true),D(g=>g+1);return}if(!v){h(false);return}if(!L&&!K||!o){O(null),M(false),$({}),h(true),D(g=>g+1);return}if(h(false),!L){try{let g=await Wt({baseUrl:r,apiKey:t,appId:o,userId:K,userHash:V});g&&(O(g.containerId),M(!!g.forksPaused),u(pn(r,g,K,o)),$(gn(r,g)));}catch(g){console.error("[ForkProvider] Failed to fetch fork manifest:",g.message),O(null),M(false),u({}),$({});}finally{D(g=>g+1),h(true);}return}if(O(L.container_id??null),L.container_id){let g=wr(t,o,L.operator_id,L.container_id);if(Ko(g)){M(true),u({}),$({}),D(x=>x+1),h(true);return}M(false);try{let x=await Wt({baseUrl:r,apiKey:t,appId:o,userId:K,containerId:L.container_id,extraHeaders:ne()});x&&(u(pn(r,x,K,o)),$(gn(r,x)));}catch(x){console.error("[ForkProvider] Failed to fetch preview container manifest:",x.message),u({}),$({});}finally{D(x=>x+1),h(true);}return}M(false);let p=new URLSearchParams({appId:o,userId:K});V&&p.set("userHash",V);try{let g=await fetch(`${r}/api/v1/boundaries/manifest?${p.toString()}`,{headers:{Authorization:`Bearer ${t}`,...ne()}});if(!g.ok)throw new Error(`${g.status}`);let x=await g.json();$(Vo(r,x));}catch(g){console.error("[ForkProvider] Failed to fetch module override manifest:",g.message),$({});}finally{D(g=>g+1),h(true);}},[t,o,r,v,he,V,K,L?.preview_session_id,L?.fork_id,L?.container_id]);Fr.useEffect(()=>{if(!K||o&&(!L||L.container_id))return;let p=new URLSearchParams({userId:K});V&&p.set("userHash",V),fetch(`${r}/api/v1/forks/active?${p.toString()}`,{headers:{Authorization:`Bearer ${t}`,...ne()}}).then(g=>{if(!g.ok)throw new Error(`${g.status}`);return g.json()}).then(g=>{g&&typeof g=="object"&&u(g);}).catch(()=>{});},[t,o,K,V,r,L?.preview_session_id,L?.fork_id]),Fr.useEffect(()=>{fe();},[fe]);let ze=Fr.useCallback(async p=>{if(o){if(L){if(!L.container_id)return;fn(wr(t,o,L.operator_id,L.container_id),p),M(p),p?(u({}),$({}),D(g=>g+1)):await fe();return}if(K){M(p),p&&(u({}),$({}),D(g=>g+1));try{let g=await fetch(`${r}/api/v1/containers/primary/paused`,{method:"PUT",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json","X-Fork-App-Id":o},body:JSON.stringify({appId:o,paused:p,userId:K,userHash:V})});if(!g.ok)throw new Error(`${g.status}`);p||await fe();}catch(g){console.error("[ForkProvider] Failed to persist fork pause state:",g?.message??g),fe().catch(()=>{});}}}},[t,o,r,fe,L,V,K]),rt=Fr.useCallback((p,g)=>{u(x=>({...x,[p]:g}));},[]),Pe=Fr.useCallback(p=>{u(g=>{let x={...g};return delete x[p],x});},[]),We=Fr.useCallback(p=>{P.current.add(p);},[]),ir=Fr.useCallback(p=>P.current.has(p)?(P.current.delete(p),true):false,[]),Tt=Fr.useCallback(p=>{if(p.slotId&&u(x=>{let W=x[p.slotId];return !W||W.id!==p.id||!W.revealPending?x:{...x,[p.slotId]:{...W,revealPending:false}}}),L||!K)return;let g={Authorization:`Bearer ${t}`,"Content-Type":"application/json","X-Fork-User-Id":K};V&&(g["X-Fork-User-Hash"]=V),fetch(`${r}/api/v1/forks/reveals`,{method:"POST",headers:g,body:JSON.stringify({forkId:p.id,userId:K,userHash:V})}).catch(()=>{});},[t,r,L,V,K]),Je=Fr.useCallback((p,g)=>{G.current.set(p,g);},[]),Mt=Fr.useCallback((p,g)=>G.current.get(p)!==g?false:(G.current.delete(p),true),[]),pe=Fr.useCallback(p=>{if(!o)return;let g=JSON.stringify(p);H.current.get(p.id)===g||R.current.get(p.id)?.signature===g||(R.current.set(p.id,{boundary:p,signature:g}),b(W=>W+1));},[o]);Fr.useEffect(()=>{if(!o||R.current.size===0)return;let p=setTimeout(()=>{let g=Array.from(R.current.values());g.length!==0&&fetch(`${r}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:o,boundaries:g.map(x=>x.boundary)})}).then(x=>{if(!x.ok)throw new Error(`${x.status}`)}).then(()=>{for(let x of g)R.current.get(x.boundary.id)?.signature===x.signature&&(R.current.delete(x.boundary.id),H.current.set(x.boundary.id,x.signature));}).catch(x=>{console.error("[ForkProvider] Failed to register module boundaries:",x.message);});},50);return ()=>{clearTimeout(p);}},[t,o,r,A]);let nt=Fr.useCallback(p=>E[p],[E]),ar=L?`preview:${L.preview_session_id}`:K,dt=`${t}:${o||"no-app"}:${U||"no-container"}:${ar||"anonymous"}`,ft=L?`op:${L.operator_id}`:K,ot=`${t}:${o||"no-app"}:${ft||"anonymous"}`,ke=`${un}:seen:${dt}`,ue=`${un}:tracked:${dt}`;Fr.useEffect(()=>{Q.current=j;},[j]);let st=Fr.useCallback(()=>{let p={Authorization:`Bearer ${t}`,...ne()};return o&&(p["X-Fork-App-Id"]=o),!L&&K&&(p["X-Fork-User-Id"]=K),!L&&V&&(p["X-Fork-User-Hash"]=V),p},[t,o,L,V,K]);Fr.useEffect(()=>{if(typeof window>"u")return;let p=window.__FORK_RUNTIME__,g={dataFetch:async(x,W,ee="POST")=>{if(!o||!U)throw new Error("Fork data is unavailable until appId and containerId are resolved");let q=typeof x=="string"&&x.startsWith("/")?x:`/${String(x||"")}`,re=q.startsWith("/api/v1/data")?q:`/api/v1/data${q}`,le=ee.toUpperCase(),ye=new URL(`${r}${re}`),ge={Authorization:`Bearer ${t}`,"Content-Type":"application/json","X-Fork-App-Id":o,...ne()};!L&&K&&(ge["X-Fork-User-Id"]=K),!L&&V&&(ge["X-Fork-User-Hash"]=V);let X={method:le,headers:ge};le==="GET"?(ye.searchParams.set("appId",o),ye.searchParams.set("containerId",U)):X.body=JSON.stringify({appId:o,containerId:U,...W&&typeof W=="object"?W:{}});let ce=await fetch(ye.toString(),X),oe=await ce.json().catch(()=>({}));if(!ce.ok)throw new Error(typeof oe?.error=="string"?oe.error:`Fork data API ${ce.status}`);return oe}};return window.__FORK_RUNTIME__=g,()=>{window.__FORK_RUNTIME__===g&&(window.__FORK_RUNTIME__=p);}},[t,o,r,U,L,V,K]);let $e=Fr.useCallback(async()=>{if(!U)return;let p=new URLSearchParams({container_id:U}),g=await fetch(`${r}/api/v1/forks?${p.toString()}`,{headers:st()}).catch(()=>null);if(!g||!g.ok)return;let x=await g.json().catch(()=>({})),W=Array.isArray(x.forks)?x.forks:[],ee=Qe(ke),q=Qe(ue),re=false,le=new Map(Q.current.map(ge=>[ge.id,ge])),ye=[];for(let ge of W){let X=dn(ge);_e(X.status)&&!q.has(X.id)&&(q.add(X.id),re=true);let ce=le.get(X.id),oe=ce?_e(ce.status):false,Ie=yt(X);X.status==="complete"&&(q.has(X.id)||oe)&&!ee.has(Ie)&&!J.current.has(Ie)&&!ce?.unread&&(ie.current||q.has(X.id)||oe)&&(J.current.add(Ie),ye.push(X));}if(k(ge=>{let X=new Map(ge.map(ae=>[ae.id,ae])),ce=new Set,oe=new Map;for(let ae of W){let ve=dn(ae);ce.add(ve.id);let Be=X.get(ve.id),Ce=Be?_e(Be.status):false,it=yt(ve),Fe=ve.status==="complete"&&(q.has(ve.id)||Ce)&&!ee.has(it),Ht=Jt(Be,{...ve,unread:Fe});oe.set(ve.id,Ht);}for(let ae of ge)ce.has(ae.id)||(_e(ae.status)||ae.unread)&&oe.set(ae.id,ae);let Ie=[...oe.values()].sort((ae,ve)=>Date.parse(ve.updatedAt)-Date.parse(ae.updatedAt));return Q.current=Ie,Ie}),re&&Ze(ue,q),ye.length>0){for(let ge of ye)ge.targetKind==="module"&&Je(ge.targetId,ge.id);fe().catch(()=>{});}ie.current=true;},[ke,ue,r,st,U,fe,Je]),Te=Fr.useCallback((p,g)=>{let x=Do(p,g);if(!x)return;let W=p.containerId??p._containerId;if(W&&!U&&O(W),_e(x.status)){let re=Qe(ue);re.has(x.id)||(re.add(x.id),Ze(ue,re)),M(false),L?.container_id&&o&&fn(wr(t,o,L.operator_id,L.container_id),false);}let ee=new Map(Q.current.map(re=>[re.id,re]));ee.set(x.id,Jt(ee.get(x.id),x));let q=[...ee.values()].sort((re,le)=>Date.parse(le.updatedAt)-Date.parse(re.updatedAt));Q.current=q,k(q);},[ue,t,o,U,L]),pt=Fr.useCallback((p,g)=>{let x=Wo(g),W=Qe(ke),ee=Qe(ue),q=Q.current.find(ce=>ce.id===p),re=q?_e(q.status):false;x.status&&_e(x.status)&&!ee.has(p)&&(ee.add(p),Ze(ue,ee));let le=q?Jt(q,{...q,...x}):null,ye=le?yt(le):null,ge=!!(le&&le.status==="complete"&&(ee.has(p)||re)&&ye&&!W.has(ye)&&!J.current.has(ye)&&!q?.unread),X=g.type==="complete"&&q?.targetKind==="module"?q.targetId:null;if(k(ce=>{let oe=ce.find(Ce=>Ce.id===p);if(!oe)return ce;let Ie=Jt(oe,{...oe,...x}),ae=Ie.status==="complete"&&(ee.has(p)||_e(oe.status))&&!W.has(yt(Ie)),ve={...Ie,unread:ae},Be=ce.map(Ce=>Ce.id===p?ve:Ce).sort((Ce,it)=>Date.parse(it.updatedAt)-Date.parse(Ce.updatedAt));return Q.current=Be,Be}),ge&&le&&ye&&J.current.add(ye),g.type==="complete"){let ce=g.data&&typeof g.data=="object"?g.data:{},oe=typeof ce.boundaryId=="string"?ce.boundaryId:X;oe&&Je(oe,p),fe().catch(()=>{});}},[ke,ue,fe,Je]),Ve=Fr.useCallback(p=>{let g=Qe(ke),x=Qe(ue),W=false,ee=false;for(let q of Q.current){if(q.status!=="complete"||p&&q.id!==p)continue;let re=yt(q);g.has(re)||(g.add(re),W=true),x.delete(q.id)&&(ee=true);}k(q=>{let re=q.map(le=>le.status!=="complete"||p&&le.id!==p?le:{...le,unread:false});return Q.current=re,re}),W&&Ze(ke,g),ee&&Ze(ue,x);},[ke,ue]);Fr.useEffect(()=>{ie.current=false,J.current.clear(),k([]);for(let p of z.current.values())p.close();z.current.clear(),U&&$e();},[U,$e]),Fr.useEffect(()=>{if(typeof document>"u")return;let p=()=>{let g=document.visibilityState!=="hidden";w(g),g&&U&&$e();};return document.addEventListener("visibilitychange",p),window.addEventListener("focus",p),window.addEventListener("online",p),()=>{document.removeEventListener("visibilitychange",p),window.removeEventListener("focus",p),window.removeEventListener("online",p);}},[U,$e]),Fr.useEffect(()=>{let p=j.filter(W=>_e(W.status));if(!U||p.length===0)return;let g=d?Ho:Oo,x=window.setInterval(()=>{$e();},g);return ()=>window.clearInterval(x)},[U,d,j,$e]),Fr.useEffect(()=>{for(let p of z.current.values())p.close();z.current.clear();},[t,r,L?.preview_session_id,V,K]),Fr.useEffect(()=>{let p=new Set(j.filter(g=>_e(g.status)).map(g=>g.id));for(let[g,x]of z.current.entries())p.has(g)||(x.close(),z.current.delete(g));for(let g of p){if(z.current.has(g))continue;let x=new URLSearchParams({key:t});L?(x.set("previewSessionId",L.preview_session_id),x.set("previewForkId",g)):K&&x.set("userId",K),V&&x.set("userHash",V);let W=new EventSource(`${r}/api/v1/forks/${g}/events?${x.toString()}`);W.onmessage=ee=>{try{pt(g,JSON.parse(ee.data));}catch{}},W.onerror=()=>{W.close(),z.current.delete(g);},z.current.set(g,W);}},[t,r,j,L,pt,V,K]),Fr.useEffect(()=>()=>{for(let p of z.current.values())p.close();z.current.clear();},[]);let Ue=Jo(j),Lt=Fr.useCallback(async()=>{if(!K)throw new Error("Reset requires a resolved user identity.");let p=new URLSearchParams({userId:K});V&&p.set("userHash",V);let g={Authorization:`Bearer ${t}`,...ne()};o&&(g["X-Fork-App-Id"]=o);let x=await fetch(`${r}/api/v1/forks/all?${p.toString()}`,{method:"DELETE",headers:g});if(!x.ok){let ee=await x.json().catch(()=>({}));throw new Error(ee.error||`API error: ${x.status}`)}let W=await x.json().catch(()=>({}));return u({}),$({}),h(true),D(ee=>ee+1),k([]),J.current.clear(),Ze(ke,new Set),Ze(ue,new Set),P.current.clear(),G.current.clear(),W},[ke,ue,t,o,r,V,K]);return So.jsx(mn.Provider,{value:{apiKey:t,userId:K,userHash:V,baseUrl:r,appId:o,forks:S,moduleOverridesEnabled:he,moduleManifestReady:F,moduleManifestVersion:N,currentContainerId:U,forksPaused:C,setForksPaused:ze,forkActivities:j,activitySummary:Ue,previewSession:L,trackForkActivity:Te,recordForkActivityEvent:pt,markForkActivitySeen:Ve,refreshForkActivities:$e,setSlotFork:rt,clearSlotFork:Pe,skipAnimationForSlot:We,shouldSkipAnimation:ir,markRevealSeen:Tt,queueBoundaryAnimation:Je,consumeBoundaryAnimation:Mt,registerBoundary:pe,getBoundaryOverride:nt,refreshModuleManifest:fe,resetAllForks:Lt,highlightScope:ot},children:n})}function we(){let e=Fr.useContext(mn);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function Vt(e){return we().forks[e]}var bt=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(s=>s());}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];}};var vr=new Set;function xr(e,t){let r;try{r=Fr.Children.only(e);}catch{let o=Fr.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 yn=new Set;function kn(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 s=getComputedStyle(n),i=parseFloat(s.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:i});}return t}function Zo(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(i=>n.rect.top>=i.rect.top&&n.rect.left>=i.rect.left&&n.rect.right<=i.rect.right&&n.rect.bottom<=i.rect.bottom)){for(let i=r.length-1;i>=0;i--){let a=r[i];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(i,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function es(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(i=>n.rect.top>=i.rect.top&&n.rect.left>=i.rect.left&&n.rect.right<=i.rect.right&&n.rect.bottom<=i.rect.bottom)){for(let i=r.length-1;i>=0;i--){let a=r[i];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(i,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function wn(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 bn(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 s=[];for(let S=0;S<e.length;S++){let{rect:u,borderRadius:m}=e[S],I=u.left-.5,v=u.top-.5,f=u.width+1,E=u.height+1,$=Math.min(m+.5,f/2,E/2),F=wn(I,v,f,E,$),h=`__fork-glow-${S}`,N=document.createElementNS(t,"filter");N.setAttribute("id",h),N.setAttribute("x","-100%"),N.setAttribute("y","-100%"),N.setAttribute("width","300%"),N.setAttribute("height","300%");let D=document.createElementNS(t,"feGaussianBlur");D.setAttribute("in","SourceGraphic"),D.setAttribute("stdDeviation","8"),N.appendChild(D),o.appendChild(N);let U=`__fork-mask-${S}`,O=document.createElementNS(t,"mask");O.setAttribute("id",U),O.setAttribute("maskUnits","userSpaceOnUse"),O.setAttribute("x",String(I-200)),O.setAttribute("y",String(v-200)),O.setAttribute("width",String(f+400)),O.setAttribute("height",String(E+400));let C=document.createElementNS(t,"rect");C.setAttribute("x",String(I-200)),C.setAttribute("y",String(v-200)),C.setAttribute("width",String(f+400)),C.setAttribute("height",String(E+400)),C.setAttribute("fill","white"),O.appendChild(C);let M=document.createElementNS(t,"path");M.setAttribute("d",F),M.setAttribute("fill","black"),O.appendChild(M),o.appendChild(O);let j=document.createElementNS(t,"g");j.setAttribute("mask",`url(#${U})`),j.setAttribute("opacity","0");let k=document.createElementNS(t,"g");k.setAttribute("filter",`url(#${h})`);let d=document.createElementNS(t,"path");d.setAttribute("d",F),d.setAttribute("fill","none"),d.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),d.setAttribute("stroke-width","6"),d.setAttribute("stroke-linecap","round"),k.appendChild(d),j.appendChild(k),n.appendChild(j);let w=document.createElementNS(t,"path");w.setAttribute("d",F),w.setAttribute("fill","none"),w.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),w.setAttribute("stroke-width","2"),w.setAttribute("stroke-linecap","round"),w.setAttribute("opacity","0"),n.appendChild(w),s.push(d,w),d.__group=j;}r.appendChild(n),document.body.appendChild(r);let i=[];for(let S=0;S<s.length;S+=2){let u=s[S],m=s[S+1],I=u.__group,v=m.getTotalLength(),f=u.getTotalLength();if(v<=0)continue;let E=v*.35;m.setAttribute("stroke-dasharray",`${E} ${v-E}`),m.setAttribute("stroke-dashoffset","0"),i.push(m.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 $=f*.35;u.setAttribute("stroke-dasharray",`${$} ${f-$}`),u.setAttribute("stroke-dashoffset","0"),i.push(u.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*f,offset:.06},{strokeDashoffset:-2*f,offset:.92},{strokeDashoffset:-2.25*f,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),i.push(I.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,c=()=>{if(a)return;a=true,clearTimeout(y);for(let u of i)try{u.cancel();}catch{}let S=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});S.onfinish=()=>r.remove(),window.removeEventListener("click",c);},y=setTimeout(c,14500);return setTimeout(()=>{a||window.addEventListener("click",c);},500),c}function ts(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"),s=document.createElementNS(t,"filter");s.setAttribute("id","__fork-removed-shadow"),s.setAttribute("x","-10%"),s.setAttribute("y","-10%"),s.setAttribute("width","120%"),s.setAttribute("height","120%");let i=document.createElementNS(t,"feDropShadow");i.setAttribute("dx","0"),i.setAttribute("dy","1"),i.setAttribute("stdDeviation","2"),i.setAttribute("flood-color","rgba(0,0,0,0.15)"),s.appendChild(i),o.appendChild(s),n.appendChild(o);for(let{rect:a,borderRadius:c}of e){let y=a.left,S=a.top,u=a.width,m=a.height,I=Math.min(c,u/2,m/2),v=wn(y,S,u,m,I),f=document.createElementNS(t,"path");f.setAttribute("d",v),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}function rs(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 ns=Fr__namespace.default.memo(function({component:t,containerRef:r,wrapperStyle:n,hostProps:o}){return So.jsx("div",{ref:r,style:n,children:So.jsx(t,{...o})})},(e,t)=>e.component===t.component&&rs(e.hostProps,t.hostProps)),Sr=class extends Fr__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 vn({slotId:e,children:t,githubRepo:r,shared:n,events:o,entityBindings:s}){xr(t,e);let i=Vt(e),{baseUrl:a,apiKey:c,appId:y,shouldSkipAnimation:S,markRevealSeen:u}=we(),[m,I]=Fr.useState(null),v=Fr.useRef(null),f=Fr.useRef(null),E=Fr.useRef(null),$=Fr.useRef(false),F=Fr.useRef(null),h=Fr.useRef(null),N=!!(n||o),D=Fr.useRef(null);N&&!D.current&&(D.current=new bt(e));let U=Fr.useRef(o);if(U.current=o,Fr.useEffect(()=>{if(N)return ()=>{D.current?.destroy(),D.current=null;}},[N,e]),N&&D.current&&n)for(let[k,d]of Object.entries(n))D.current.set(k,d);Fr.useEffect(()=>{if(!N)return;D.current||(D.current=new bt(e));let k=D.current,d=Object.keys(U.current||{}).map(w=>k.on(w,(...H)=>U.current?.[w]?.(...H)));return ()=>d.forEach(w=>w())},[N,e]),Fr.useEffect(()=>{if(yn.has(e))return;yn.add(e);let k={id:e,appId:y,label:e,eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:r,mode:"direct",sharedKeys:n?Object.keys(n):[],eventNames:o?Object.keys(o):[],propsShape:"",callbackNames:[],entityBindings:s||{}};fetch(`${a}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json"},body:JSON.stringify(k)}).catch(()=>{});},[e,a,c,r,y,s]);let O=i?.id||null;Fr.useEffect(()=>{if(i?.bundleUrl,v.current,f.current,!i?.bundleUrl||!O){return}let k=`${a}${i.bundleUrl.replace("bundle.js","component.js")}`,d=i.revealPending===true&&!vr.has(O),w=S(e),H=!w&&d;if(i.revealPending,w&&d&&(vr.add(O),u(i)),H&&f.current){let G=kn(f.current);E.current=G,$.current=true,`${e}${G.length}`;}window.__FORK_REACT__=Fr__namespace.default,window.__FORK_REACT_DOM__=vo__namespace,window.__FORK_REACT_JSX__=So__namespace;let R=Date.now(),A=`${a}${i.bundleUrl.replace("bundle.js","component.css")}?t=${R}`,b=document.createElement("link");b.rel="stylesheet",b.href=A,b.dataset.forkSlot=e,document.head.appendChild(b);let P=document.createElement("script");return P.src=k+"?t="+R,P.onload=()=>{let G=window.__FORK_EXPORT__;if(G?.default){if(f.current&&E.current&&$.current){let te=f.current.getBoundingClientRect(),z=f.current.cloneNode(true);z.setAttribute("data-fork-clone-overlay","true"),z.style.position="fixed",z.style.top=`${te.top}px`,z.style.left=`${te.left}px`,z.style.width=`${te.width}px`,z.style.height=`${te.height}px`,z.style.flex="none",z.style.minHeight="auto",z.style.zIndex="9998",z.style.pointerEvents="none",z.style.overflow="hidden";let Q=getComputedStyle(f.current).backgroundColor;z.style.backgroundColor=Q&&Q!=="rgba(0, 0, 0, 0)"&&Q!=="transparent"?Q:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(z);let J=f.current.querySelectorAll("*"),ie=z.querySelectorAll("*");for(let L=0;L<J.length;L++)J[L].scrollTop!==0&&(ie[L].scrollTop=J[L].scrollTop),J[L].scrollLeft!==0&&(ie[L].scrollLeft=J[L].scrollLeft);F.current=z;}I(()=>G.default),v.current=O;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},P.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(P),()=>{P.remove(),b.remove(),h.current&&(clearTimeout(h.current),h.current=null),F.current&&(F.current.remove(),F.current=null);}},[O,a,e]),Fr.useEffect(()=>{if(!$.current||!m||!f.current){`${e}${$.current}`,f.current;return}let k=E.current;if(!k){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!f.current)return;let d=kn(f.current),w=Zo(k,d),H=es(k,d),R=F.current;if(`${e}${w.length}${H.length}`,H.length>0&&R){let A=ts(H);h.current=setTimeout(()=>{h.current=null;let b=400;R.animate([{opacity:1},{opacity:0}],{duration:b,fill:"forwards"}),A.animate([{opacity:1},{opacity:0}],{duration:b,fill:"forwards"}),setTimeout(()=>{R.remove(),A.remove(),F.current=null,w.length>0&&(bn(w));},b);},3500);}else R&&(R.remove(),F.current=null),w.length>0&&(bn(w));E.current=null,$.current=false,i&&O&&(vr.add(O),u(i),`${e}`);});});},[m]);let C={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!i||i.status!=="complete"||!i.bundleUrl)return So.jsx("div",{ref:f,style:C,children:t});if(!m)return So.jsx("div",{ref:f,style:C,children:t});let j=t?.props??{};return So.jsx(Sr,{slotId:e,resetKey:O,fallback:So.jsx("div",{ref:f,style:C,children:t}),children:So.jsx(ns,{component:m,containerRef:f,wrapperStyle:C,hostProps:j})})}var Fn=new Set;function is(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 xn(e,t=new Set){return Fr.Children.forEach(e,r=>{if(!Fr.isValidElement(r))return;let n=r.props;for(let[o,s]of Object.entries(n))typeof s=="function"&&/^on[A-Z]/.test(o)&&t.add(o);n.children&&xn(n.children,t);}),t}function as({slotId:e,props:t,children:r,allowedFetches:n,entityBindings:o,githubRepo:s,callbacks:i,mode:a="iframe",shared:c,events:y}){if(xr(r,e),a==="direct")return So.jsx(vn,{slotId:e,githubRepo:s,shared:c,events:y,entityBindings:o,children:r});let S=Vt(e),{baseUrl:u,apiKey:m,appId:I,userId:v,userHash:f,currentContainerId:E,previewSession:$}=we(),F=Fr.useRef(null),h=Fr.useRef(false),N=Fr.useRef(null),D=Fr.useRef(i);D.current=i;let U=Fr.useRef(t);U.current=t;let O=Fr.useRef(n);O.current=n,Fr.useEffect(()=>{if(typeof process<"u")return;let k=xn(r),d=new Set(i?Object.keys(i):[]),w=[...k].filter(H=>!d.has(H));w.length>0&&console.error(`[ForkSlot:${e}] Missing bridged callbacks! The following callback props are used by children but not passed to ForkSlot's \`callbacks\` prop:
|
|
3
|
-
`+w.map(H=>` - ${H}`).join(`
|
|
4
|
-
`)+"\n\nThe forked component will not be able to call these. Add them to the `callbacks` prop of <ForkSlot>.");},[e,r,i]),Fr.useEffect(()=>{Fn.has(e)||(Fn.add(e),fetch(`${u}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${m}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:I,label:e,propsShape:t?is(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:s,callbackNames:i?Object.keys(i):[],mode:a||"iframe",entityBindings:o||{}})}).catch(()=>{}));},[e,u,m,s,I,o]);let C=Fr.useCallback(k=>{let d=F.current;if(d?.contentWindow&&h.current){let w=D.current?Object.keys(D.current):[];d.contentWindow.postMessage({type:"slot:props",props:k,callbackNames:w},"*"),N.current=null;}else N.current=k;},[]),M=Fr.useCallback((k,d)=>{let w=O.current;return !w||w.length===0?false:w.some(H=>{let[R,A]=H.split(" "),b=d.split("?")[0];return k.toUpperCase()===R.toUpperCase()&&b.startsWith(A)})},[]);if(Fr.useEffect(()=>{if(!S?.bundleUrl)return;let k=async d=>{if(d.source===F.current?.contentWindow){if(d.data?.type==="slot:ready")h.current=true,F.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:O.current||[]},"*"),O.current,N.current?C(N.current):C(U.current||{});else if(d.data?.type==="slot:event"){let w=d.data.event;w?.navigate&&(window.location.hash=w.navigate);}else if(d.data?.type==="slot:clipboard-write")navigator.clipboard.writeText(d.data.text).catch(w=>{console.warn(`[ForkSlot:${e}] clipboard write failed:`,w.message);});else if(d.data?.type==="slot:callback"){let{name:w,args:H}=d.data,R=D.current?.[w];R?(R(...H||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${w}`);}else if(d.data?.type==="slot:fetch"){let{id:w,method:H,url:R,body:A}=d.data,b=F.current?.contentWindow;if(!b)return;let P=H||"GET";if(!M(P,R)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${w}: ${P} ${R} \u2014 not in allowedFetches`),b.postMessage({type:"slot:fetch-response",id:w,error:`Fetch not allowed: ${P} ${R}`},"*");return}try{let G={method:P};A&&P!=="GET"&&(G.headers={"Content-Type":"application/json"},G.body=JSON.stringify(A));let te=await fetch(R,G),z=await te.json();`${e}${w}${te.status}`,b.postMessage({type:"slot:fetch-response",id:w,data:z,status:te.status},"*");}catch(G){console.error(`[ForkSlot:${e}] fetch #${w} failed:`,G.message),b.postMessage({type:"slot:fetch-response",id:w,error:G.message},"*");}}else if(d.data?.type==="slot:fork-data"){let{id:w,path:H,method:R,body:A}=d.data,b=F.current?.contentWindow;if(!b)return;if(!E||!I){b.postMessage({type:"slot:fork-data-response",id:w,error:"Fork data is unavailable until appId and containerId are resolved"},"*");return}let P=typeof H=="string"&&H.startsWith("/")?H:`/${String(H||"")}`,G=P.startsWith("/api/v1/data")?P:`/api/v1/data${P}`;try{let te={Authorization:`Bearer ${m}`,"Content-Type":"application/json","X-Fork-App-Id":I,...ne()};!$&&v&&(te["X-Fork-User-Id"]=v),!$&&f&&(te["X-Fork-User-Hash"]=f);let z=typeof R=="string"?R.toUpperCase():"POST",Q=new URL(`${u}${G}`),J={method:z,headers:te};z==="GET"?(Q.searchParams.set("appId",I),Q.searchParams.set("containerId",E)):J.body=JSON.stringify({appId:I,containerId:E,...A&&typeof A=="object"?A:{}});let ie=await fetch(Q.toString(),J),L=await ie.json().catch(()=>({}));if(!ie.ok){let xe=typeof L?.error=="string"?L.error:`Fork data API ${ie.status}`;b.postMessage({type:"slot:fork-data-response",id:w,error:xe,status:ie.status},"*");return}b.postMessage({type:"slot:fork-data-response",id:w,data:L,status:ie.status},"*");}catch(te){b.postMessage({type:"slot:fork-data-response",id:w,error:te.message},"*");}}}};return window.addEventListener("message",k),()=>{window.removeEventListener("message",k),h.current=false;}},[S?.bundleUrl,e,C,M,E,I,m,u,$,f,v]),Fr.useEffect(()=>{S?.bundleUrl&&h.current&&C(t||{});},[t,S?.bundleUrl,C]),!S||S.status!=="complete"||!S.bundleUrl)return `${e}${S?.status||"none"}${S?.bundleUrl||"none"}`,So.jsx(So.Fragment,{children:r});`${e}${S.bundleUrl}`;let j=`${u}${S.bundleUrl.replace("/bundle.js","/host")}`;return So.jsx("iframe",{ref:F,src:j,sandbox:"allow-scripts allow-same-origin allow-forms allow-clipboard-write",title:`Forked ${e}`,style:{width:"100%",border:"none",flex:1,minHeight:0}})}function Xt({style:e={width:20,height:20},...t}){return So.jsxs("svg",{viewBox:"320 95 270 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:e,...t,children:[So.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"}),So.jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M387.096 174.735v188"}),So.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"}),So.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"}),So.jsx("path",{fill:"currentColor",stroke:"currentColor",strokeWidth:"1",strokeLinejoin:"round",d:"M527.117 162.547L570.487 134.368Q577.196 130.009 577.624 137.997L580.39 189.69Q580.818 197.678 573.69 194.047L527.536 170.538Q520.408 166.907 527.117 162.547Z"})]})}var fs=5600,Ir=2147483002;function ps(e){return !e||e.state!=="complete"||!e.latest?null:`${e.latest.id}:${e.latest.completedAt??e.latest.updatedAt}`}function gs(){return typeof document>"u"?false:!!document.querySelector("[data-fork-clone-overlay], [data-fork-removed], [data-fork-highlights]")}function Rr(e,t){let r=Math.min(e.length,t?26:34)*7.4,n=t?Math.min(t.length,24)*6.8+10:0;return Math.round(Math.min(390,Math.max(116,56+r+n)))}function ms(e,t=false){return e?.state==="complete"&&e.unreadCompletedCount>0?e.unreadCompletedCount>1?`${e.unreadCompletedCount} forks ready`:`${e.label} ready`:t?"Fork update ready":void 0}function _r({onClick:e,hasNotification:t=false,activity:r}){let[n,o]=Fr.useState(false),[s,i]=Fr.useState(false),[a,c]=Fr.useState(null),[y,S]=Fr.useState(null),[u,m]=Fr.useState(null),I=Fr.useRef(0),v=n?48:40,f=ps(r),E=!!(f&&r?.state==="complete"&&r.unreadCompletedCount>0),$=E?f:y?.key??null,F=!!(r&&r.state==="running"&&r.runningCount>0),h=!!($&&$!==a&&(E||y)),N=F||h,D=E?r?.label:y?.label,U=h?"Built":r?.label??"Fork this app",O=h?D:r?.detail,C=Rr(r?.label??"Fork this app",r?.detail),M=Rr(U,O),j=h?Math.min(420,Math.max(326,M,y?.width??0,I.current+40)):M,k=h?46:40,d=N?[U,O].filter(Boolean).join(" "):ms(r,t)??"Fork this app",w=N?`${U}:${O??""}`:"idle",H=(t||r?.state==="complete"&&r.unreadCompletedCount>0)&&!N;Fr.useEffect(()=>{if(typeof document>"u")return;let J=document.createElement("div");return J.setAttribute("data-fork-button-host","true"),J.style.position="relative",J.style.zIndex=String(Ir),document.body.appendChild(J),m(J),()=>{J.remove(),m(null);}},[]),Fr.useEffect(()=>{F&&(I.current=C);},[C,F]),Fr.useEffect(()=>{!E||!f||!r?.label||S(J=>{if(J?.key===f)return J;let ie=Math.min(420,Math.max(326,Rr("Built",r.label),I.current+40));return {key:f,label:r.label,width:ie,startedAt:Date.now()}});},[r?.label,f,E]),Fr.useEffect(()=>{r?.state==="complete"&&r.unreadCompletedCount===0&&S(null);},[r?.state,r?.unreadCompletedCount]),Fr.useEffect(()=>{if(!$||!h||$===a)return;let J,ie=y?.key===$?y.startedAt:Date.now(),L=()=>{if(Date.now()-ie>=fs&&!gs()){c($);return}J=window.setTimeout(L,250);};return J=window.setTimeout(L,250),()=>{J!==void 0&&window.clearTimeout(J);}},[$,a,y?.key,y?.startedAt,h]);let R=N?{position:"fixed",bottom:24,right:24,zIndex:Ir,width:`min(${j}px, calc(100vw - 32px))`,height:k,minWidth:0,maxWidth:"calc(100vw - 32px)",borderRadius:h?12:999,backgroundColor:n?"#ffffff":"rgba(255, 255, 255, 0.92)",border:"1px solid rgba(148, 163, 184, 0.42)",display:"inline-flex",alignItems:"center",justifyContent:h?"flex-start":"center",gap:h?10:8,color:"#111827",boxShadow:n?"0 12px 24px -16px rgba(15, 23, 42, 0.45), 0 4px 10px -6px rgba(15, 23, 42, 0.25)":"0 10px 20px -18px rgba(15, 23, 42, 0.35), 0 2px 7px -5px rgba(15, 23, 42, 0.18)",transform:s?"scale(0.98)":"scale(1)",transition:"width 320ms cubic-bezier(0.16, 1, 0.3, 1), height 320ms cubic-bezier(0.16, 1, 0.3, 1), border-radius 320ms cubic-bezier(0.16, 1, 0.3, 1), transform 180ms ease, box-shadow 180ms ease, background-color 180ms ease, border-color 180ms ease",cursor:"pointer",padding:h?"0 16px 0 14px":"0 13px 0 11px",margin:0,outline:"none",boxSizing:"border-box",fontFamily:'Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif'}:{position:"fixed",bottom:24,right:24,zIndex:Ir,width:v,height:v,borderRadius:"50%",backgroundColor:n?"rgba(255, 255, 255, 1)":"rgba(255, 255, 255, 0.3)",border:n?"1px solid rgba(156, 163, 175, 1)":"1px solid rgba(156, 163, 175, 0.3)",display:"flex",alignItems:"center",justifyContent:"center",color:n?"#111827":"rgba(17, 24, 39, 0.5)",boxShadow:n?"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1)":"0 1px 2px 0 rgba(0, 0, 0, 0.05)",transform:s?"scale(0.95)":"scale(1)",transition:"width 320ms cubic-bezier(0.16, 1, 0.3, 1), height 320ms cubic-bezier(0.16, 1, 0.3, 1), border-radius 320ms cubic-bezier(0.16, 1, 0.3, 1), transform 180ms ease, box-shadow 180ms ease, background-color 180ms ease, border-color 180ms ease, color 180ms ease",cursor:"pointer",padding:0,margin:0,outline:"none",boxSizing:"border-box"},A={minWidth:0,maxWidth:F?286:h?82:O?116:238,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13,fontWeight:650,lineHeight:"16px",letterSpacing:0},b={minWidth:0,maxWidth:h?278:void 0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flexShrink:h?1:0,color:"#64748b",fontSize:F?13:12,fontWeight:650,lineHeight:"16px",letterSpacing:0},P={minWidth:0,flex:h?1:void 0,display:"inline-flex",alignItems:"center",justifyContent:h?"flex-start":void 0,gap:8,animation:"__forkButtonTextSwap 220ms ease-out"},G={width:8,height:8,borderRadius:"50%",backgroundColor:r?.state==="complete"?"#16a34a":"#ef4444",boxShadow:r?.state==="complete"?"0 0 0 3px rgba(22, 163, 74, 0.14)":"none",animation:h?"__forkButtonBuiltDot 420ms ease-out":void 0,flexShrink:0},Q=So.jsxs(So.Fragment,{children:[So.jsx("style",{children:`
|
|
1
|
+
'use strict';var cr=require('react'),Zn=require('react-dom'),eo=require('react/jsx-runtime'),to=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 cr__namespace=/*#__PURE__*/_interopNamespace(cr);var Zn__namespace=/*#__PURE__*/_interopNamespace(Zn);var eo__namespace=/*#__PURE__*/_interopNamespace(eo);var to__namespace=/*#__PURE__*/_interopNamespace(to);var qe="__FORK_SHARED__";function er(){var t,r,n,o;let e=globalThis;return e[qe]||(e[qe]={}),(t=e[qe]).react||(t.react=cr__namespace),(r=e[qe])["react-dom"]||(r["react-dom"]=Zn__namespace),(n=e[qe])["react/jsx-runtime"]||(n["react/jsx-runtime"]=eo__namespace),(o=e[qe])["react/jsx-dev-runtime"]||(o["react/jsx-dev-runtime"]=to__namespace),e[qe]}function tr(e){return Object.assign(er(),e)}var jr=false,rr=null,nr=null;function zr(e,t,r){jr=e,rr=t,nr=r;}function ie(){if(!jr)return {};let e={};return rr&&(e["X-Fork-App-Id"]=rr),nr&&(e["X-Fork-Container-Id"]=nr),e}async function or(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 s=await o.json(),i={};for(let[a,d]of Object.entries(s.modules)){let b=d.moduleUrl??d.bundleUrl??null,m=d.legacyModuleUrl??d.legacyBundleUrl??null;i[a]={forkId:d.forkId,moduleUrl:b,legacyModuleUrl:m,bundleUrl:d.bundleUrl??b,legacyBundleUrl:d.legacyBundleUrl??m,cssUrls:d.cssUrls??[],integrity:d.integrity,metadata:d.metadata,highlightHint:d.highlightHint,buildId:d.buildId,updatedAt:d.updatedAt};}return {containerId:s.containerId,forksPaused:!!s.forksPaused,slots:s.slots,modules:i,generatedAt:s.generatedAt,etag:o.headers.get("ETag")??void 0}}var ro="fork:manifest:v1";function sr(e,t,r){return `${ro}:${e}:${t}:${r}`}function no(e,t,r){if(typeof window>"u")return null;try{let n=window.localStorage.getItem(sr(e,t,r));return n?JSON.parse(n):null}catch{return null}}function oo(e,t,r,n){if(!(typeof window>"u"))try{window.localStorage.setItem(sr(e,t,r),JSON.stringify(n));}catch{}}function so(e,t,r){if(!(typeof window>"u"))try{window.localStorage.removeItem(sr(e,t,r));}catch{}}function io(e,t){if(!e||!t)return e!==t;if(e.containerId!==t.containerId||!!e.forksPaused!=!!t.forksPaused)return true;let r=Object.entries(e.slots),n=Object.entries(t.slots);if(r.length!==n.length)return true;for(let[i,a]of r){let d=t.slots[i];if(!d||d.forkId!==a.forkId||d.buildId!==a.buildId)return true}let o=Object.entries(e.modules),s=Object.entries(t.modules);if(o.length!==s.length)return true;for(let[i,a]of o){let d=t.modules[i];if(!d||d.forkId!==a.forkId||d.buildId!==a.buildId)return true}return false}var Pt={isAdmin:false,actingUserId:null,containerId:null,containerName:null,containers:[]},Jr=cr.createContext(null),co=12e3,uo=45e3,Wr="fork:activity:v1",fo=new Set(["pending","running","building"]),po="Setting up environment";function Ce(e){return fo.has(e)}function go(e,t){return t?.targetId?t:e.boundaryId?{targetKind:"module",targetId:e.boundaryId}:e.slotId?{targetKind:"slot",targetId:e.slotId}:null}function mo(e,t){let r=go(e,t);if(!r)return null;let n=new Date().toISOString();return {id:e.id,status:e.status,targetKind:r.targetKind,targetId:r.targetId,summary:e.summary??null,estimateMinutes:e.estimateMinutes??null,createdAt:e.createdAt||n,updatedAt:e.completedAt||n,completedAt:e.completedAt??null}}function Vr(e){return {id:e.id,status:e.status,targetKind:e.targetKind,targetId:e.targetId,summary:e.summary??null,estimateMinutes:e.estimateMinutes??null,promptCount:e.promptCount,messageCount:e.messageCount,isActive:e.isActive,createdAt:e.createdAt,updatedAt:e.updatedAt,completedAt:e.completedAt??null}}function _t(e,t){let r=typeof t.summary=="string"&&t.summary.trim()?t.summary.trim():void 0,n=typeof e?.summary=="string"&&e.summary.trim()?e.summary.trim():void 0,o=typeof t.estimateMinutes=="number"&&Number.isFinite(t.estimateMinutes)?t.estimateMinutes:void 0,s=typeof e?.estimateMinutes=="number"&&Number.isFinite(e.estimateMinutes)?e.estimateMinutes:void 0;return {...e,...t,summary:r??n??null,estimateMinutes:o??s??null,latestMessage:t.latestMessage??e?.latestMessage??null,unread:t.unread??e?.unread??false}}function ct(e){return `${e.id}:${e.completedAt||e.updatedAt}`}function Xe(e){if(typeof window>"u")return new Set;try{let t=window.localStorage.getItem(e);if(!t)return new Set;let r=JSON.parse(t);return Array.isArray(r)?new Set(r.filter(n=>typeof n=="string")):new Set}catch{return new Set}}function Ge(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify([...t].slice(-200)));}catch{}}function ho(e){if(e.estimateMinutes)return `~${e.estimateMinutes}m`}function yo(e){let t=e.data&&typeof e.data=="object"?e.data:{};if(e.type==="status"){let r=typeof t.status=="string"?t.status:"running",n=typeof t.summary=="string"?t.summary:void 0;return {status:r,latestMessage:Ce(r)?"Building":void 0,summary:n,estimateMinutes:typeof t.estimateMinutes=="number"?t.estimateMinutes:void 0,updatedAt:e.timestamp}}return e.type==="tool_use"?{status:"running",latestMessage:"Building",updatedAt:e.timestamp}:e.type==="build_start"?{status:"building",latestMessage:"Building",updatedAt:e.timestamp}:e.type==="build_complete"?{status:"building",latestMessage:"Building",updatedAt:e.timestamp}:e.type==="complete"?{status:"complete",summary:typeof t.summary=="string"?t.summary:void 0,estimateMinutes:typeof t.estimateMinutes=="number"?t.estimateMinutes:void 0,latestMessage:"Fork ready",completedAt:e.timestamp,updatedAt:e.timestamp}:e.type==="error"||e.type==="build_error"?{status:"error",latestMessage:typeof t.error=="string"?t.error:typeof t.message=="string"?t.message:"Fork failed",updatedAt:e.timestamp}:{updatedAt:e.timestamp}}function ko(e){let t=e.filter(o=>Ce(o.status)),r=e.filter(o=>o.status==="complete"&&o.unread),n=[...e].sort((o,s)=>Date.parse(s.updatedAt)-Date.parse(o.updatedAt))[0]??null;if(t.length>1)return {state:"running",label:`${t.length} forks running`,count:t.length,runningCount:t.length,unreadCompletedCount:r.length,latest:t[0]};if(t.length===1){let o=t[0],s=!!(typeof o.summary=="string"&&o.summary.trim());return {state:"running",label:s?o.summary.trim():po,detail:s?ho(o):void 0,count:1,runningCount:1,unreadCompletedCount:r.length,latest:o}}if(r.length>1)return {state:"complete",label:`${r.length} forks ready`,count:r.length,runningCount:0,unreadCompletedCount:r.length,latest:r[0]};if(r.length===1){let o=r[0];return {state:"complete",label:o.summary||"Fork ready",count:1,runningCount:0,unreadCompletedCount:1,latest:o}}return {state:n?.status==="error"?"error":"idle",label:"Fork",count:0,runningCount:0,unreadCompletedCount:0,latest:n}}function ir(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function bo(e,t,r,n){let o={};for(let[s,i]of Object.entries(t.slots)){let a=i.bundleUrl??i.legacyBundleUrl;a&&(o[s]={id:i.forkId,userId:r,prompt:"",status:"complete",slotId:s,appId:n,bundleUrl:ir(e,a),revealPending:i.revealPending===true,createdAt:i.updatedAt,completedAt:i.updatedAt});}return o}function wo(e,t){let r={};for(let[n,o]of Object.entries(t.modules)){let s=o.moduleUrl??o.legacyModuleUrl??o.bundleUrl??"";s&&(r[n]={id:o.forkId,boundaryId:n,moduleUrl:ir(e,s),cssUrls:(o.cssUrls??[]).map(i=>ir(e,i)),integrity:o.integrity,metadata:o.metadata,highlightHint:o.highlightHint,createdAt:o.updatedAt});}return r}function vo(e){let{apiKey:t,baseUrl:r,children:n,appId:o,shared:s}=e,i="userId"in e?e.userId:void 0,a="userHash"in e?e.userHash:void 0,d="authUrl"in e?e.authUrl:void 0,[b,m]=cr.useState({}),[f,w]=cr.useState(i?{userId:i,userHash:a}:null),[A,h]=cr.useState(!!i),[l,C]=cr.useState(Pt),[_,k]=cr.useState(false),[v,L]=cr.useState({}),[D,B]=cr.useState(!o),[U,R]=cr.useState(0),[$,O]=cr.useState(null),[y,u]=cr.useState(false),[F,T]=cr.useState([]),[M,I]=cr.useState(()=>typeof document>"u"?true:document.visibilityState!=="hidden"),S=cr.useRef(new Map),H=cr.useRef(new Map),[Y,ae]=cr.useState(0),Q=cr.useRef(new Set),re=cr.useRef(new Map),V=cr.useRef(void 0),Z=cr.useRef(new Map),q=cr.useRef([]),ke=cr.useRef(new Set),Se=cr.useRef(false);er(),cr.useEffect(()=>{if(!o||!f?.userHash||!f.userId){C(Pt);return}let g=false,p=new URLSearchParams({app:o});return fetch(`${r}/api/v1/admin/containers?${p.toString()}`,{headers:{Authorization:`Bearer ${t}`,"X-Fork-App-Id":o,"X-Fork-User-Id":f.userId,"X-Fork-User-Hash":f.userHash}}).then(async x=>x.status===403||!x.ok?null:x.json()).then(x=>{if(g)return;if(!x){C(Pt);return}let K=Array.isArray(x.containers)?x.containers:[],J=x.currentContainerId??null,z=K.find(te=>te.id===J)?.name??null;C({isAdmin:true,actingUserId:typeof x.actingUserId=="string"?x.actingUserId:null,containerId:J,containerName:z,containers:K});}).catch(()=>{g||C(Pt);}),()=>{g=true;}},[t,o,f?.userHash,f?.userId,r]),cr.useEffect(()=>{zr(l.isAdmin,o??null,l.containerId);},[l.isAdmin,l.containerId,o]);let Ue=cr.useCallback((g,p)=>{C(x=>{if(!x.isAdmin)return x;let K=p??x.containers.find(J=>J.id===g)?.name??null;return {...x,containerId:g,containerName:K}}),k(false);},[]);s&&V.current!==s&&(tr(s),V.current=s),cr.useEffect(()=>{d&&(h(false),fetch(d,{credentials:"include"}).then(g=>{if(!g.ok)throw new Error(`Auth endpoint returned ${g.status}`);return g.json()}).then(g=>{if(!g.userId||typeof g.userId!="string")throw new Error("authUrl response must include userId");w({userId:g.userId,userHash:typeof g.userHash=="string"?g.userHash:void 0});}).catch(g=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",g.message);}).finally(()=>{h(true);}));},[d]),cr.useEffect(()=>{!d&&i&&(w({userId:i,userHash:a}),h(true));},[i,a,d]);let W=f?.userId??"",j=f?.userHash,Te=!!o,me=cr.useCallback(async()=>{if(!Te){O(null),u(false),L({}),B(true),R(p=>p+1);return}if(!A){B(false);return}if(!W||!o){O(null),u(false),m({}),L({}),B(true),R(p=>p+1);return}B(false);let g=l.isAdmin?l.containerId:null;if(l.isAdmin&&_){u(true),m({}),L({}),R(p=>p+1),B(true);return}try{let p=await or({baseUrl:r,apiKey:t,appId:o,userId:W,userHash:j,containerId:g??void 0});p&&(O(p.containerId),u(l.isAdmin?!1:!!p.forksPaused),m(bo(r,p,W,o)),L(wo(r,p)));}catch(p){console.error("[ForkProvider] Failed to fetch fork manifest:",p.message),O(null),u(false),m({}),L({});}finally{R(p=>p+1),B(true);}},[t,o,r,A,Te,j,W,l.isAdmin,l.containerId,_]);cr.useEffect(()=>{if(!W||o)return;let g=new URLSearchParams({userId:W});j&&g.set("userHash",j),fetch(`${r}/api/v1/forks/active?${g.toString()}`,{headers:{Authorization:`Bearer ${t}`,...ie()}}).then(p=>{if(!p.ok)throw new Error(`${p.status}`);return p.json()}).then(p=>{p&&typeof p=="object"&&m(p);}).catch(()=>{});},[t,o,W,j,r]),cr.useEffect(()=>{me();},[me]);let it=cr.useCallback(async g=>{if(o){if(l.isAdmin){k(g),u(g),g?(m({}),L({}),R(p=>p+1)):await me();return}if(W){u(g),g&&(m({}),L({}),R(p=>p+1));try{let p=await fetch(`${r}/api/v1/containers/primary/paused`,{method:"PUT",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json","X-Fork-App-Id":o},body:JSON.stringify({appId:o,paused:g,userId:W,userHash:j})});if(!p.ok)throw new Error(`${p.status}`);g||await me();}catch(p){console.error("[ForkProvider] Failed to persist fork pause state:",p?.message??p),me().catch(()=>{});}}}},[t,o,r,me,l.isAdmin,j,W]),$e=cr.useCallback((g,p)=>{m(x=>({...x,[g]:p}));},[]),ze=cr.useCallback(g=>{m(p=>{let x={...p};return delete x[g],x});},[]),qt=cr.useCallback(g=>{Q.current.add(g);},[]),xt=cr.useCallback(g=>Q.current.has(g)?(Q.current.delete(g),true):false,[]),Xt=cr.useCallback(g=>{if(g.slotId&&m(x=>{let K=x[g.slotId];return !K||K.id!==g.id||!K.revealPending?x:{...x,[g.slotId]:{...K,revealPending:false}}}),l.isAdmin||!W)return;let p={Authorization:`Bearer ${t}`,"Content-Type":"application/json","X-Fork-User-Id":W};j&&(p["X-Fork-User-Hash"]=j),fetch(`${r}/api/v1/forks/reveals`,{method:"POST",headers:p,body:JSON.stringify({forkId:g.id,userId:W,userHash:j})}).catch(()=>{});},[t,r,l.isAdmin,j,W]),Oe=cr.useCallback((g,p)=>{re.current.set(g,p);},[]),ue=cr.useCallback((g,p)=>re.current.get(g)!==p?false:(re.current.delete(g),true),[]),Ze=cr.useCallback(g=>{if(!o)return;let p=JSON.stringify(g);S.current.get(g.id)===p||H.current.get(g.id)?.signature===p||(H.current.set(g.id,{boundary:g,signature:p}),ae(K=>K+1));},[o]);cr.useEffect(()=>{if(!o||H.current.size===0)return;let g=setTimeout(()=>{let p=Array.from(H.current.values());p.length!==0&&fetch(`${r}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:o,boundaries:p.map(x=>x.boundary)})}).then(x=>{if(!x.ok)throw new Error(`${x.status}`)}).then(()=>{for(let x of p)H.current.get(x.boundary.id)?.signature===x.signature&&(H.current.delete(x.boundary.id),S.current.set(x.boundary.id,x.signature));}).catch(x=>{console.error("[ForkProvider] Failed to register module boundaries:",x.message);});},50);return ()=>{clearTimeout(g);}},[t,o,r,Y]);let Gt=cr.useCallback(g=>v[g],[v]),At=l.isAdmin?`admin:${l.actingUserId??"op"}`:W,et=`${t}:${o||"no-app"}:${$||"no-container"}:${At||"anonymous"}`,tt=l.isAdmin?`op:${l.actingUserId??"op"}`:W,Me=`${t}:${o||"no-app"}:${tt||"anonymous"}`,be=`${Wr}:seen:${et}`,fe=`${Wr}:tracked:${et}`;cr.useEffect(()=>{q.current=F;},[F]);let at=cr.useCallback(()=>{let g={Authorization:`Bearer ${t}`,...ie()};return o&&(g["X-Fork-App-Id"]=o),W&&(g["X-Fork-User-Id"]=W),j&&(g["X-Fork-User-Hash"]=j),g},[t,o,j,W]);cr.useEffect(()=>{if(typeof window>"u")return;let g=window.__FORK_RUNTIME__,p={dataFetch:async(x,K,J="POST")=>{if(!o||!$)throw new Error("Fork data is unavailable until appId and containerId are resolved");let z=typeof x=="string"&&x.startsWith("/")?x:`/${String(x||"")}`,te=z.startsWith("/api/v1/data")?z:`/api/v1/data${z}`,oe=J.toUpperCase(),we=new URL(`${r}${te}`),ee={Authorization:`Bearer ${t}`,"Content-Type":"application/json","X-Fork-App-Id":o,...ie()};W&&(ee["X-Fork-User-Id"]=W),j&&(ee["X-Fork-User-Hash"]=j);let pe={method:oe,headers:ee};oe==="GET"?(we.searchParams.set("appId",o),we.searchParams.set("containerId",$)):pe.body=JSON.stringify({appId:o,containerId:$,...K&&typeof K=="object"?K:{}});let se=await fetch(we.toString(),pe),ne=await se.json().catch(()=>({}));if(!se.ok)throw new Error(typeof ne?.error=="string"?ne.error:`Fork data API ${se.status}`);return ne}};return window.__FORK_RUNTIME__=p,()=>{window.__FORK_RUNTIME__===p&&(window.__FORK_RUNTIME__=g);}},[t,o,r,$,j,W]);let Fe=cr.useCallback(async()=>{if(!$)return;let g=new URLSearchParams({container_id:$}),p=await fetch(`${r}/api/v1/forks?${g.toString()}`,{headers:at()}).catch(()=>null);if(!p||!p.ok)return;let x=await p.json().catch(()=>({})),K=Array.isArray(x.forks)?x.forks:[],J=Xe(be),z=Xe(fe),te=false,oe=new Map(q.current.map(ee=>[ee.id,ee])),we=[];for(let ee of K){let pe=Vr(ee);Ce(pe.status)&&!z.has(pe.id)&&(z.add(pe.id),te=true);let se=oe.get(pe.id),ne=se?Ce(se.status):false,Ie=ct(pe);pe.status==="complete"&&(z.has(pe.id)||ne)&&!J.has(Ie)&&!ke.current.has(Ie)&&!se?.unread&&(Se.current||z.has(pe.id)||ne)&&(ke.current.add(Ie),we.push(pe));}if(T(ee=>{let pe=new Map(ee.map(le=>[le.id,le])),se=new Set,ne=new Map;for(let le of K){let ye=Vr(le);se.add(ye.id);let Be=pe.get(ye.id),Ee=Be?Ce(Be.status):false,rt=ct(ye),xe=ye.status==="complete"&&(z.has(ye.id)||Ee)&&!J.has(rt),Ct=_t(Be,{...ye,unread:xe});ne.set(ye.id,Ct);}for(let le of ee)se.has(le.id)||(Ce(le.status)||le.unread)&&ne.set(le.id,le);let Ie=[...ne.values()].sort((le,ye)=>Date.parse(ye.updatedAt)-Date.parse(le.updatedAt));return q.current=Ie,Ie}),te&&Ge(fe,z),we.length>0){for(let ee of we)ee.targetKind==="module"&&Oe(ee.targetId,ee.id);me().catch(()=>{});}Se.current=true;},[be,fe,r,at,$,me,Oe]),Yt=cr.useCallback((g,p)=>{let x=mo(g,p);if(!x)return;let K=g.containerId??g._containerId;if(K&&!$&&O(K),Ce(x.status)){let te=Xe(fe);te.has(x.id)||(te.add(x.id),Ge(fe,te)),u(false),l.isAdmin&&k(false);}let J=new Map(q.current.map(te=>[te.id,te]));J.set(x.id,_t(J.get(x.id),x));let z=[...J.values()].sort((te,oe)=>Date.parse(oe.updatedAt)-Date.parse(te.updatedAt));q.current=z,T(z);},[fe,t,o,$,l.isAdmin]),We=cr.useCallback((g,p)=>{let x=yo(p),K=Xe(be),J=Xe(fe),z=q.current.find(se=>se.id===g),te=z?Ce(z.status):false;x.status&&Ce(x.status)&&!J.has(g)&&(J.add(g),Ge(fe,J));let oe=z?_t(z,{...z,...x}):null,we=oe?ct(oe):null,ee=!!(oe&&oe.status==="complete"&&(J.has(g)||te)&&we&&!K.has(we)&&!ke.current.has(we)&&!z?.unread),pe=p.type==="complete"&&z?.targetKind==="module"?z.targetId:null;if(T(se=>{let ne=se.find(Ee=>Ee.id===g);if(!ne)return se;let Ie=_t(ne,{...ne,...x}),le=Ie.status==="complete"&&(J.has(g)||Ce(ne.status))&&!K.has(ct(Ie)),ye={...Ie,unread:le},Be=se.map(Ee=>Ee.id===g?ye:Ee).sort((Ee,rt)=>Date.parse(rt.updatedAt)-Date.parse(Ee.updatedAt));return q.current=Be,Be}),ee&&oe&&we&&ke.current.add(we),p.type==="complete"){let se=p.data&&typeof p.data=="object"?p.data:{},ne=typeof se.boundaryId=="string"?se.boundaryId:pe;ne&&Oe(ne,g),me().catch(()=>{});}},[be,fe,me,Oe]),Ne=cr.useCallback(g=>{let p=Xe(be),x=Xe(fe),K=false,J=false;for(let z of q.current){if(z.status!=="complete"||g&&z.id!==g)continue;let te=ct(z);p.has(te)||(p.add(te),K=true),x.delete(z.id)&&(J=true);}T(z=>{let te=z.map(oe=>oe.status!=="complete"||g&&oe.id!==g?oe:{...oe,unread:false});return q.current=te,te}),K&&Ge(be,p),J&&Ge(fe,x);},[be,fe]);cr.useEffect(()=>{Se.current=false,ke.current.clear(),T([]);for(let g of Z.current.values())g.close();Z.current.clear(),$&&Fe();},[$,Fe]),cr.useEffect(()=>{if(typeof document>"u")return;let g=()=>{let p=document.visibilityState!=="hidden";I(p),p&&$&&Fe();};return document.addEventListener("visibilitychange",g),window.addEventListener("focus",g),window.addEventListener("online",g),()=>{document.removeEventListener("visibilitychange",g),window.removeEventListener("focus",g),window.removeEventListener("online",g);}},[$,Fe]),cr.useEffect(()=>{let g=F.filter(K=>Ce(K.status));if(!$||g.length===0)return;let p=M?co:uo,x=window.setInterval(()=>{Fe();},p);return ()=>window.clearInterval(x)},[$,M,F,Fe]),cr.useEffect(()=>{for(let g of Z.current.values())g.close();Z.current.clear();},[t,r,l.containerId,j,W]),cr.useEffect(()=>{let g=new Set(F.filter(p=>Ce(p.status)).map(p=>p.id));for(let[p,x]of Z.current.entries())g.has(p)||(x.close(),Z.current.delete(p));for(let p of g){if(Z.current.has(p))continue;let x=new URLSearchParams({key:t});W&&x.set("userId",W),j&&x.set("userHash",j),l.isAdmin&&l.containerId&&x.set("containerId",l.containerId);let K=new EventSource(`${r}/api/v1/forks/${p}/events?${x.toString()}`);K.onmessage=J=>{try{We(p,JSON.parse(J.data));}catch{}},K.onerror=()=>{K.close(),Z.current.delete(p);},Z.current.set(p,K);}},[t,r,F,l.isAdmin,l.containerId,We,j,W]),cr.useEffect(()=>()=>{for(let g of Z.current.values())g.close();Z.current.clear();},[]);let It=ko(F),Ve=cr.useCallback(async()=>{if(!W)throw new Error("Reset requires a resolved user identity.");let g=new URLSearchParams({userId:W});j&&g.set("userHash",j);let p={Authorization:`Bearer ${t}`,...ie()};o&&(p["X-Fork-App-Id"]=o);let x=await fetch(`${r}/api/v1/forks/all?${g.toString()}`,{method:"DELETE",headers:p});if(!x.ok){let J=await x.json().catch(()=>({}));throw new Error(J.error||`API error: ${x.status}`)}let K=await x.json().catch(()=>({}));return m({}),L({}),B(true),R(J=>J+1),T([]),ke.current.clear(),Ge(be,new Set),Ge(fe,new Set),Q.current.clear(),re.current.clear(),K},[be,fe,t,o,r,j,W]);return eo.jsx(Jr.Provider,{value:{apiKey:t,userId:W,userHash:j,baseUrl:r,appId:o,forks:b,moduleOverridesEnabled:Te,moduleManifestReady:D,moduleManifestVersion:U,currentContainerId:$,forksPaused:y,setForksPaused:it,forkActivities:F,activitySummary:It,adminContext:l,setAdminContainer:Ue,trackForkActivity:Yt,recordForkActivityEvent:We,markForkActivitySeen:Ne,refreshForkActivities:Fe,setSlotFork:$e,clearSlotFork:ze,skipAnimationForSlot:qt,shouldSkipAnimation:xt,markRevealSeen:Xt,queueBoundaryAnimation:Oe,consumeBoundaryAnimation:ue,registerBoundary:Ze,getBoundaryOverride:Gt,refreshModuleManifest:me,resetAllForks:Ve,highlightScope:Me},children:n})}function he(){let e=cr.useContext(Jr);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function Lt(e){return he().forks[e]}var ut=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(s=>s());}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];}};var ar=new Set;function ur(e,t){let r;try{r=cr.Children.only(e);}catch{let o=cr.Children.count(e);throw new Error(`<ForkSlot slotId="${t}"> must wrap exactly one React component, got ${o} children. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`)}let n=r.type;if(typeof n=="string")throw new Error(`<ForkSlot slotId="${t}"> child must be a React component (function or class), not an HTML element <${n}>. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`);if(typeof n=="symbol")throw new Error(`<ForkSlot slotId="${t}"> child must be a single React component, not a fragment or special React element. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`);return r}var Xr=new Set;function Gr(e){let t=[],r=e.querySelectorAll("*");for(let n of r){if(!(n instanceof HTMLElement))continue;let o=n.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(n.tagName))continue;let s=getComputedStyle(n),i=parseFloat(s.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:i});}return t}function Io(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(i=>n.rect.top>=i.rect.top&&n.rect.left>=i.rect.left&&n.rect.right<=i.rect.right&&n.rect.bottom<=i.rect.bottom)){for(let i=r.length-1;i>=0;i--){let a=r[i];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(i,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Co(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(i=>n.rect.top>=i.rect.top&&n.rect.left>=i.rect.left&&n.rect.right<=i.rect.right&&n.rect.bottom<=i.rect.bottom)){for(let i=r.length-1;i>=0;i--){let a=r[i];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(i,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Qr(e,t,r,n,o){return o=Math.max(0,Math.min(o,r/2,n/2)),o===0?`M ${e} ${t} L ${e+r} ${t} L ${e+r} ${t+n} L ${e} ${t+n} Z`:[`M ${e+o} ${t}`,`L ${e+r-o} ${t}`,`A ${o} ${o} 0 0 1 ${e+r} ${t+o}`,`L ${e+r} ${t+n-o}`,`A ${o} ${o} 0 0 1 ${e+r-o} ${t+n}`,`L ${e+o} ${t+n}`,`A ${o} ${o} 0 0 1 ${e} ${t+n-o}`,`L ${e} ${t+o}`,`A ${o} ${o} 0 0 1 ${e+o} ${t}`,"Z"].join(" ")}function Yr(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-highlights","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");n.appendChild(o);let s=[];for(let m=0;m<e.length;m++){let{rect:f,borderRadius:w}=e[m],A=f.left-.5,h=f.top-.5,l=f.width+1,C=f.height+1,_=Math.min(w+.5,l/2,C/2),k=Qr(A,h,l,C,_),v=`__fork-glow-${m}`,L=document.createElementNS(t,"filter");L.setAttribute("id",v),L.setAttribute("x","-100%"),L.setAttribute("y","-100%"),L.setAttribute("width","300%"),L.setAttribute("height","300%");let D=document.createElementNS(t,"feGaussianBlur");D.setAttribute("in","SourceGraphic"),D.setAttribute("stdDeviation","8"),L.appendChild(D),o.appendChild(L);let B=`__fork-mask-${m}`,U=document.createElementNS(t,"mask");U.setAttribute("id",B),U.setAttribute("maskUnits","userSpaceOnUse"),U.setAttribute("x",String(A-200)),U.setAttribute("y",String(h-200)),U.setAttribute("width",String(l+400)),U.setAttribute("height",String(C+400));let R=document.createElementNS(t,"rect");R.setAttribute("x",String(A-200)),R.setAttribute("y",String(h-200)),R.setAttribute("width",String(l+400)),R.setAttribute("height",String(C+400)),R.setAttribute("fill","white"),U.appendChild(R);let $=document.createElementNS(t,"path");$.setAttribute("d",k),$.setAttribute("fill","black"),U.appendChild($),o.appendChild(U);let O=document.createElementNS(t,"g");O.setAttribute("mask",`url(#${B})`),O.setAttribute("opacity","0");let y=document.createElementNS(t,"g");y.setAttribute("filter",`url(#${v})`);let u=document.createElementNS(t,"path");u.setAttribute("d",k),u.setAttribute("fill","none"),u.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),u.setAttribute("stroke-width","6"),u.setAttribute("stroke-linecap","round"),y.appendChild(u),O.appendChild(y),n.appendChild(O);let F=document.createElementNS(t,"path");F.setAttribute("d",k),F.setAttribute("fill","none"),F.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),F.setAttribute("stroke-width","2"),F.setAttribute("stroke-linecap","round"),F.setAttribute("opacity","0"),n.appendChild(F),s.push(u,F),u.__group=O;}r.appendChild(n),document.body.appendChild(r);let i=[];for(let m=0;m<s.length;m+=2){let f=s[m],w=s[m+1],A=f.__group,h=w.getTotalLength(),l=f.getTotalLength();if(h<=0)continue;let C=h*.35;w.setAttribute("stroke-dasharray",`${C} ${h-C}`),w.setAttribute("stroke-dashoffset","0"),i.push(w.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*h,opacity:.92,offset:.06},{strokeDashoffset:-2*h,opacity:.92,offset:.92},{strokeDashoffset:-2.25*h,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let _=l*.35;f.setAttribute("stroke-dasharray",`${_} ${l-_}`),f.setAttribute("stroke-dashoffset","0"),i.push(f.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*l,offset:.06},{strokeDashoffset:-2*l,offset:.92},{strokeDashoffset:-2.25*l,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),i.push(A.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(b);for(let f of i)try{f.cancel();}catch{}let m=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});m.onfinish=()=>r.remove(),window.removeEventListener("click",d);},b=setTimeout(d,14500);return setTimeout(()=>{a||window.addEventListener("click",d);},500),d}function Ro(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"),s=document.createElementNS(t,"filter");s.setAttribute("id","__fork-removed-shadow"),s.setAttribute("x","-10%"),s.setAttribute("y","-10%"),s.setAttribute("width","120%"),s.setAttribute("height","120%");let i=document.createElementNS(t,"feDropShadow");i.setAttribute("dx","0"),i.setAttribute("dy","1"),i.setAttribute("stdDeviation","2"),i.setAttribute("flood-color","rgba(0,0,0,0.15)"),s.appendChild(i),o.appendChild(s),n.appendChild(o);for(let{rect:a,borderRadius:d}of e){let b=a.left,m=a.top,f=a.width,w=a.height,A=Math.min(d,f/2,w/2),h=Qr(b,m,f,w,A),l=document.createElementNS(t,"path");l.setAttribute("d",h),l.setAttribute("fill","none"),l.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),l.setAttribute("stroke-width","1.5"),l.setAttribute("stroke-dasharray","8 4"),l.setAttribute("stroke-linecap","round"),l.setAttribute("filter","url(#__fork-removed-shadow)"),l.setAttribute("opacity","0"),n.appendChild(l),l.animate([{opacity:0,offset:0},{opacity:.6,offset:.08},{opacity:.05,offset:.45},{opacity:.6,offset:.85},{opacity:.05,offset:1}],{duration:5e3,easing:"ease-in-out",fill:"forwards"});}return r.appendChild(n),document.body.appendChild(r),r}function Eo(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 $o=cr__namespace.default.memo(function({component:t,containerRef:r,wrapperStyle:n,hostProps:o}){return eo.jsx("div",{ref:r,style:n,children:eo.jsx(t,{...o})})},(e,t)=>e.component===t.component&&Eo(e.hostProps,t.hostProps)),lr=class extends cr__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 Zr({slotId:e,children:t,githubRepo:r,shared:n,events:o,entityBindings:s}){ur(t,e);let i=Lt(e),{baseUrl:a,apiKey:d,appId:b,shouldSkipAnimation:m,markRevealSeen:f}=he(),[w,A]=cr.useState(null),h=cr.useRef(null),l=cr.useRef(null),C=cr.useRef(null),_=cr.useRef(false),k=cr.useRef(null),v=cr.useRef(null),L=!!(n||o),D=cr.useRef(null);L&&!D.current&&(D.current=new ut(e));let B=cr.useRef(o);if(B.current=o,cr.useEffect(()=>{if(L)return ()=>{D.current?.destroy(),D.current=null;}},[L,e]),L&&D.current&&n)for(let[y,u]of Object.entries(n))D.current.set(y,u);cr.useEffect(()=>{if(!L)return;D.current||(D.current=new ut(e));let y=D.current,u=Object.keys(B.current||{}).map(F=>y.on(F,(...T)=>B.current?.[F]?.(...T)));return ()=>u.forEach(F=>F())},[L,e]),cr.useEffect(()=>{if(Xr.has(e))return;Xr.add(e);let y={id:e,appId:b,label:e,eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:r,mode:"direct",sharedKeys:n?Object.keys(n):[],eventNames:o?Object.keys(o):[],propsShape:"",callbackNames:[],entityBindings:s||{}};fetch(`${a}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${d}`,"Content-Type":"application/json"},body:JSON.stringify(y)}).catch(()=>{});},[e,a,d,r,b,s]);let U=i?.id||null;cr.useEffect(()=>{if(i?.bundleUrl,h.current,l.current,!i?.bundleUrl||!U){return}let y=`${a}${i.bundleUrl.replace("bundle.js","component.js")}`,u=i.revealPending===true&&!ar.has(U),F=m(e),T=!F&&u;if(i.revealPending,F&&u&&(ar.add(U),f(i)),T&&l.current){let Y=Gr(l.current);C.current=Y,_.current=true,`${e}${Y.length}`;}window.__FORK_REACT__=cr__namespace.default,window.__FORK_REACT_DOM__=Zn__namespace,window.__FORK_REACT_JSX__=eo__namespace;let M=Date.now(),I=`${a}${i.bundleUrl.replace("bundle.js","component.css")}?t=${M}`,S=document.createElement("link");S.rel="stylesheet",S.href=I,S.dataset.forkSlot=e,document.head.appendChild(S);let H=document.createElement("script");return H.src=y+"?t="+M,H.onload=()=>{let Y=window.__FORK_EXPORT__;if(Y?.default){if(l.current&&C.current&&_.current){let ae=l.current.getBoundingClientRect(),Q=l.current.cloneNode(true);Q.setAttribute("data-fork-clone-overlay","true"),Q.style.position="fixed",Q.style.top=`${ae.top}px`,Q.style.left=`${ae.left}px`,Q.style.width=`${ae.width}px`,Q.style.height=`${ae.height}px`,Q.style.flex="none",Q.style.minHeight="auto",Q.style.zIndex="9998",Q.style.pointerEvents="none",Q.style.overflow="hidden";let re=getComputedStyle(l.current).backgroundColor;Q.style.backgroundColor=re&&re!=="rgba(0, 0, 0, 0)"&&re!=="transparent"?re:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(Q);let V=l.current.querySelectorAll("*"),Z=Q.querySelectorAll("*");for(let q=0;q<V.length;q++)V[q].scrollTop!==0&&(Z[q].scrollTop=V[q].scrollTop),V[q].scrollLeft!==0&&(Z[q].scrollLeft=V[q].scrollLeft);k.current=Q;}A(()=>Y.default),h.current=U;}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(),S.remove(),v.current&&(clearTimeout(v.current),v.current=null),k.current&&(k.current.remove(),k.current=null);}},[U,a,e]),cr.useEffect(()=>{if(!_.current||!w||!l.current){`${e}${_.current}`,l.current;return}let y=C.current;if(!y){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!l.current)return;let u=Gr(l.current),F=Io(y,u),T=Co(y,u),M=k.current;if(`${e}${F.length}${T.length}`,T.length>0&&M){let I=Ro(T);v.current=setTimeout(()=>{v.current=null;let S=400;M.animate([{opacity:1},{opacity:0}],{duration:S,fill:"forwards"}),I.animate([{opacity:1},{opacity:0}],{duration:S,fill:"forwards"}),setTimeout(()=>{M.remove(),I.remove(),k.current=null,F.length>0&&(Yr(F));},S);},3500);}else M&&(M.remove(),k.current=null),F.length>0&&(Yr(F));C.current=null,_.current=false,i&&U&&(ar.add(U),f(i),`${e}`);});});},[w]);let R={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!i||i.status!=="complete"||!i.bundleUrl)return eo.jsx("div",{ref:l,style:R,children:t});if(!w)return eo.jsx("div",{ref:l,style:R,children:t});let O=t?.props??{};return eo.jsx(lr,{slotId:e,resetKey:U,fallback:eo.jsx("div",{ref:l,style:R,children:t}),children:eo.jsx($o,{component:w,containerRef:l,wrapperStyle:R,hostProps:O})})}var tn=new Set;function Po(e){return `{ ${Object.entries(e).map(([r,n])=>n==null?`${r}: unknown`:Array.isArray(n)?`${r}: ${n.length>0?typeof n[0]:"unknown"}[]`:`${r}: ${typeof n}`).join("; ")} }`}function rn(e,t=new Set){return cr.Children.forEach(e,r=>{if(!cr.isValidElement(r))return;let n=r.props;for(let[o,s]of Object.entries(n))typeof s=="function"&&/^on[A-Z]/.test(o)&&t.add(o);n.children&&rn(n.children,t);}),t}function _o({slotId:e,props:t,children:r,allowedFetches:n,entityBindings:o,githubRepo:s,callbacks:i,mode:a="iframe",shared:d,events:b}){if(ur(r,e),a==="direct")return eo.jsx(Zr,{slotId:e,githubRepo:s,shared:d,events:b,entityBindings:o,children:r});let m=Lt(e),{baseUrl:f,apiKey:w,appId:A,userId:h,userHash:l,currentContainerId:C}=he(),_=cr.useRef(null),k=cr.useRef(false),v=cr.useRef(null),L=cr.useRef(i);L.current=i;let D=cr.useRef(t);D.current=t;let B=cr.useRef(n);B.current=n,cr.useEffect(()=>{if(typeof process<"u")return;let O=rn(r),y=new Set(i?Object.keys(i):[]),u=[...O].filter(F=>!y.has(F));u.length>0&&console.error(`[ForkSlot:${e}] Missing bridged callbacks! The following callback props are used by children but not passed to ForkSlot's \`callbacks\` prop:
|
|
2
|
+
`+u.map(F=>` - ${F}`).join(`
|
|
3
|
+
`)+"\n\nThe forked component will not be able to call these. Add them to the `callbacks` prop of <ForkSlot>.");},[e,r,i]),cr.useEffect(()=>{tn.has(e)||(tn.add(e),fetch(`${f}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${w}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:A,label:e,propsShape:t?Po(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:s,callbackNames:i?Object.keys(i):[],mode:a||"iframe",entityBindings:o||{}})}).catch(()=>{}));},[e,f,w,s,A,o]);let U=cr.useCallback(O=>{let y=_.current;if(y?.contentWindow&&k.current){let u=L.current?Object.keys(L.current):[];y.contentWindow.postMessage({type:"slot:props",props:O,callbackNames:u},"*"),v.current=null;}else v.current=O;},[]),R=cr.useCallback((O,y)=>{let u=B.current;return !u||u.length===0?false:u.some(F=>{let[T,M]=F.split(" "),I=y.split("?")[0];return O.toUpperCase()===T.toUpperCase()&&I.startsWith(M)})},[]);if(cr.useEffect(()=>{if(!m?.bundleUrl)return;let O=async y=>{if(y.source===_.current?.contentWindow){if(y.data?.type==="slot:ready")k.current=true,_.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:B.current||[]},"*"),B.current,v.current?U(v.current):U(D.current||{});else if(y.data?.type==="slot:event"){let u=y.data.event;u?.navigate&&(window.location.hash=u.navigate);}else if(y.data?.type==="slot:clipboard-write")navigator.clipboard.writeText(y.data.text).catch(u=>{console.warn(`[ForkSlot:${e}] clipboard write failed:`,u.message);});else if(y.data?.type==="slot:callback"){let{name:u,args:F}=y.data,T=L.current?.[u];T?(T(...F||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${u}`);}else if(y.data?.type==="slot:fetch"){let{id:u,method:F,url:T,body:M}=y.data,I=_.current?.contentWindow;if(!I)return;let S=F||"GET";if(!R(S,T)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${u}: ${S} ${T} \u2014 not in allowedFetches`),I.postMessage({type:"slot:fetch-response",id:u,error:`Fetch not allowed: ${S} ${T}`},"*");return}try{let H={method:S};M&&S!=="GET"&&(H.headers={"Content-Type":"application/json"},H.body=JSON.stringify(M));let Y=await fetch(T,H),ae=await Y.json();`${e}${u}${Y.status}`,I.postMessage({type:"slot:fetch-response",id:u,data:ae,status:Y.status},"*");}catch(H){console.error(`[ForkSlot:${e}] fetch #${u} failed:`,H.message),I.postMessage({type:"slot:fetch-response",id:u,error:H.message},"*");}}else if(y.data?.type==="slot:fork-data"){let{id:u,path:F,method:T,body:M}=y.data,I=_.current?.contentWindow;if(!I)return;if(!C||!A){I.postMessage({type:"slot:fork-data-response",id:u,error:"Fork data is unavailable until appId and containerId are resolved"},"*");return}let S=typeof F=="string"&&F.startsWith("/")?F:`/${String(F||"")}`,H=S.startsWith("/api/v1/data")?S:`/api/v1/data${S}`;try{let Y={Authorization:`Bearer ${w}`,"Content-Type":"application/json","X-Fork-App-Id":A,...ie()};h&&(Y["X-Fork-User-Id"]=h),l&&(Y["X-Fork-User-Hash"]=l);let ae=typeof T=="string"?T.toUpperCase():"POST",Q=new URL(`${f}${H}`),re={method:ae,headers:Y};ae==="GET"?(Q.searchParams.set("appId",A),Q.searchParams.set("containerId",C)):re.body=JSON.stringify({appId:A,containerId:C,...M&&typeof M=="object"?M:{}});let V=await fetch(Q.toString(),re),Z=await V.json().catch(()=>({}));if(!V.ok){let q=typeof Z?.error=="string"?Z.error:`Fork data API ${V.status}`;I.postMessage({type:"slot:fork-data-response",id:u,error:q,status:V.status},"*");return}I.postMessage({type:"slot:fork-data-response",id:u,data:Z,status:V.status},"*");}catch(Y){I.postMessage({type:"slot:fork-data-response",id:u,error:Y.message},"*");}}}};return window.addEventListener("message",O),()=>{window.removeEventListener("message",O),k.current=false;}},[m?.bundleUrl,e,U,R,C,A,w,f,l,h]),cr.useEffect(()=>{m?.bundleUrl&&k.current&&U(t||{});},[t,m?.bundleUrl,U]),!m||m.status!=="complete"||!m.bundleUrl)return `${e}${m?.status||"none"}${m?.bundleUrl||"none"}`,eo.jsx(eo.Fragment,{children:r});`${e}${m.bundleUrl}`;let $=`${f}${m.bundleUrl.replace("/bundle.js","/host")}`;return eo.jsx("iframe",{ref:_,src:$,sandbox:"allow-scripts allow-same-origin allow-forms allow-clipboard-write",title:`Forked ${e}`,style:{width:"100%",border:"none",flex:1,minHeight:0}})}function Ut({style:e={width:20,height:20},...t}){return eo.jsxs("svg",{viewBox:"320 95 270 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:e,...t,children:[eo.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"}),eo.jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M387.096 174.735v188"}),eo.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"}),eo.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"}),eo.jsx("path",{fill:"currentColor",stroke:"currentColor",strokeWidth:"1",strokeLinejoin:"round",d:"M527.117 162.547L570.487 134.368Q577.196 130.009 577.624 137.997L580.39 189.69Q580.818 197.678 573.69 194.047L527.536 170.538Q520.408 166.907 527.117 162.547Z"})]})}var No=5600,fr=2147483002;function Bo(e){return !e||e.state!=="complete"||!e.latest?null:`${e.latest.id}:${e.latest.completedAt??e.latest.updatedAt}`}function Do(){return typeof document>"u"?false:!!document.querySelector("[data-fork-clone-overlay], [data-fork-removed], [data-fork-highlights]")}function pr(e,t){let r=Math.min(e.length,t?26:34)*7.4,n=t?Math.min(t.length,24)*6.8+10:0;return Math.round(Math.min(390,Math.max(116,56+r+n)))}function Ko(e,t=false){return e?.state==="complete"&&e.unreadCompletedCount>0?e.unreadCompletedCount>1?`${e.unreadCompletedCount} forks ready`:`${e.label} ready`:t?"Fork update ready":void 0}function gr({onClick:e,hasNotification:t=false,activity:r}){let[n,o]=cr.useState(false),[s,i]=cr.useState(false),[a,d]=cr.useState(null),[b,m]=cr.useState(null),[f,w]=cr.useState(null),A=cr.useRef(0),h=n?48:40,l=Bo(r),C=!!(l&&r?.state==="complete"&&r.unreadCompletedCount>0),_=C?l:b?.key??null,k=!!(r&&r.state==="running"&&r.runningCount>0),v=!!(_&&_!==a&&(C||b)),L=k||v,D=C?r?.label:b?.label,B=v?"Built":r?.label??"Fork this app",U=v?D:r?.detail,R=pr(r?.label??"Fork this app",r?.detail),$=pr(B,U),O=v?Math.min(420,Math.max(326,$,b?.width??0,A.current+40)):$,y=v?46:40,u=L?[B,U].filter(Boolean).join(" "):Ko(r,t)??"Fork this app",F=L?`${B}:${U??""}`:"idle",T=(t||r?.state==="complete"&&r.unreadCompletedCount>0)&&!L;cr.useEffect(()=>{if(typeof document>"u")return;let V=document.createElement("div");return V.setAttribute("data-fork-button-host","true"),V.style.position="relative",V.style.zIndex=String(fr),document.body.appendChild(V),w(V),()=>{V.remove(),w(null);}},[]),cr.useEffect(()=>{k&&(A.current=R);},[R,k]),cr.useEffect(()=>{!C||!l||!r?.label||m(V=>{if(V?.key===l)return V;let Z=Math.min(420,Math.max(326,pr("Built",r.label),A.current+40));return {key:l,label:r.label,width:Z,startedAt:Date.now()}});},[r?.label,l,C]),cr.useEffect(()=>{r?.state==="complete"&&r.unreadCompletedCount===0&&m(null);},[r?.state,r?.unreadCompletedCount]),cr.useEffect(()=>{if(!_||!v||_===a)return;let V,Z=b?.key===_?b.startedAt:Date.now(),q=()=>{if(Date.now()-Z>=No&&!Do()){d(_);return}V=window.setTimeout(q,250);};return V=window.setTimeout(q,250),()=>{V!==void 0&&window.clearTimeout(V);}},[_,a,b?.key,b?.startedAt,v]);let M=L?{position:"fixed",bottom:24,right:24,zIndex:fr,width:`min(${O}px, calc(100vw - 32px))`,height:y,minWidth:0,maxWidth:"calc(100vw - 32px)",borderRadius:v?12:999,backgroundColor:n?"#ffffff":"rgba(255, 255, 255, 0.92)",border:"1px solid rgba(148, 163, 184, 0.42)",display:"inline-flex",alignItems:"center",justifyContent:v?"flex-start":"center",gap:v?10:8,color:"#111827",boxShadow:n?"0 12px 24px -16px rgba(15, 23, 42, 0.45), 0 4px 10px -6px rgba(15, 23, 42, 0.25)":"0 10px 20px -18px rgba(15, 23, 42, 0.35), 0 2px 7px -5px rgba(15, 23, 42, 0.18)",transform:s?"scale(0.98)":"scale(1)",transition:"width 320ms cubic-bezier(0.16, 1, 0.3, 1), height 320ms cubic-bezier(0.16, 1, 0.3, 1), border-radius 320ms cubic-bezier(0.16, 1, 0.3, 1), transform 180ms ease, box-shadow 180ms ease, background-color 180ms ease, border-color 180ms ease",cursor:"pointer",padding:v?"0 16px 0 14px":"0 13px 0 11px",margin:0,outline:"none",boxSizing:"border-box",fontFamily:'Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif'}:{position:"fixed",bottom:24,right:24,zIndex:fr,width:h,height:h,borderRadius:"50%",backgroundColor:n?"rgba(255, 255, 255, 1)":"rgba(255, 255, 255, 0.3)",border:n?"1px solid rgba(156, 163, 175, 1)":"1px solid rgba(156, 163, 175, 0.3)",display:"flex",alignItems:"center",justifyContent:"center",color:n?"#111827":"rgba(17, 24, 39, 0.5)",boxShadow:n?"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1)":"0 1px 2px 0 rgba(0, 0, 0, 0.05)",transform:s?"scale(0.95)":"scale(1)",transition:"width 320ms cubic-bezier(0.16, 1, 0.3, 1), height 320ms cubic-bezier(0.16, 1, 0.3, 1), border-radius 320ms cubic-bezier(0.16, 1, 0.3, 1), transform 180ms ease, box-shadow 180ms ease, background-color 180ms ease, border-color 180ms ease, color 180ms ease",cursor:"pointer",padding:0,margin:0,outline:"none",boxSizing:"border-box"},I={minWidth:0,maxWidth:k?286:v?82:U?116:238,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13,fontWeight:650,lineHeight:"16px",letterSpacing:0},S={minWidth:0,maxWidth:v?278:void 0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flexShrink:v?1:0,color:"#64748b",fontSize:k?13:12,fontWeight:650,lineHeight:"16px",letterSpacing:0},H={minWidth:0,flex:v?1:void 0,display:"inline-flex",alignItems:"center",justifyContent:v?"flex-start":void 0,gap:8,animation:"__forkButtonTextSwap 220ms ease-out"},Y={width:8,height:8,borderRadius:"50%",backgroundColor:r?.state==="complete"?"#16a34a":"#ef4444",boxShadow:r?.state==="complete"?"0 0 0 3px rgba(22, 163, 74, 0.14)":"none",animation:v?"__forkButtonBuiltDot 420ms ease-out":void 0,flexShrink:0},re=eo.jsxs(eo.Fragment,{children:[eo.jsx("style",{children:`
|
|
5
4
|
@keyframes __forkButtonSpin { to { transform: rotate(360deg); } }
|
|
6
5
|
@keyframes __forkButtonTextSwap {
|
|
7
6
|
from { opacity: 0; transform: translateY(2px); }
|
|
@@ -16,7 +15,7 @@
|
|
|
16
15
|
70% { opacity: 1; transform: scale(1.18); }
|
|
17
16
|
100% { opacity: 1; transform: scale(1); }
|
|
18
17
|
}
|
|
19
|
-
`}),
|
|
18
|
+
`}),eo.jsxs("button",{onClick:e,onMouseEnter:()=>o(true),onMouseLeave:()=>{o(false),i(false);},onMouseDown:()=>i(true),onMouseUp:()=>i(false),style:M,title:u,"aria-label":u,children:[L&&r?eo.jsxs(eo.Fragment,{children:[k?eo.jsx("span",{"aria-hidden":true,style:{width:14,height:14,borderRadius:"50%",border:"2px solid rgba(17, 24, 39, 0.18)",borderTopColor:"#111827",animation:"__forkButtonSpin 780ms linear infinite",flexShrink:0,boxSizing:"border-box"}}):eo.jsx("span",{"aria-hidden":true,style:Y}),eo.jsxs("span",{style:H,children:[eo.jsx("span",{style:I,children:B}),U&&eo.jsx("span",{style:S,children:U})]},F)]}):eo.jsx(Ut,{style:{width:24,height:24,animation:"__forkButtonLogoIn 220ms ease-out"}}),T&&eo.jsx("span",{"aria-hidden":true,style:{position:"absolute",top:2,right:2,width:10,height:10,borderRadius:"50%",backgroundColor:"#111827",border:"2px solid #ffffff",boxSizing:"border-box",pointerEvents:"none"}})]})]});return f?Zn.createPortal(re,f):re}var Go={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},Yo={status:"#60a5fa",agent_message:"#a0a0a0",tool_use:"#fbbf24",build_start:"#c084fc",build_complete:"#6b7280",build_error:"#f87171",complete:"#6b7280",error:"#f87171"},Qo={read:lucideReact.FileSearch,write:lucideReact.Pencil,search:lucideReact.FileSearch,shell:lucideReact.Terminal,build:lucideReact.Package},Zo={read:"#60a5fa",write:"#fbbf24",search:"#60a5fa",shell:"#a78bfa",build:"#c084fc"};function hr(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 un({events:e}){let t=cr.useRef(null);return cr.useEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight);},[e]),eo.jsxs(eo.Fragment,{children:[eo.jsx("style",{children:`
|
|
20
19
|
@keyframes __fork-spin {
|
|
21
20
|
from { transform: rotate(0deg); }
|
|
22
21
|
to { transform: rotate(360deg); }
|
|
@@ -34,7 +33,7 @@
|
|
|
34
33
|
.__fork-stream::-webkit-scrollbar-thumb:hover {
|
|
35
34
|
background: rgba(255, 255, 255, 0.3);
|
|
36
35
|
}
|
|
37
|
-
`}),So.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&&So.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"#6b7280",fontSize:"11px"},children:[So.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,s=r.type==="complete"||r.type==="error"||r.type==="build_complete"||r.type==="build_error",i=o&&!s&&(r.type==="status"||r.type==="tool_use"||r.type==="build_start"),a=Fs[r.type]||lucideReact.Code,c=xs[r.type]||"#9ca3af";if(r.type==="tool_use"){let y=String(r.data.category||"");a=As[y]||lucideReact.Wrench,c=Is[y]||"#fbbf24";}return i?a=lucideReact.Loader2:!o&&r.type==="status"&&(a=lucideReact.Check,c="#4ade80"),So.jsxs("div",{style:{display:"flex",gap:"6px",marginBottom:"6px",lineHeight:1.625},children:[So.jsx(a,{style:{width:"12px",height:"12px",marginTop:"2px",flexShrink:0,color:c,...i?{animation:"__fork-spin 1s linear infinite"}:{}}}),So.jsx("span",{style:{color:o&&!s?"#d1d5db":"#6b7280",wordBreak:"break-all"},children:Cr(r)})]},n)})]})]})}var Mn=35,Ls="Setting up environment",Hs="Built Custom Feature",Ln=360,xt=380;function Os(e){let t=Date.parse(e);if(Number.isNaN(t))return "";let r=Math.max(1,Math.round((Date.now()-t)/1e3));if(r<60)return `${r}s`;let n=Math.round(r/60);if(n<60)return `${n}m`;let o=Math.round(n/60);return o<24?`${o}h`:`${Math.round(o/24)}d`}function Us(e){return e.length<=Mn?e:e.slice(0,Mn-3).trimEnd()+"..."}function Bs({events:e}){let[t,r]=Fr.useState("Setting up environment..."),[n,o]=Fr.useState(true),s=Fr.useRef(t),i=Fr.useRef(false);return Fr.useEffect(()=>{if(!i.current){for(let c of e)if(c.type==="status"&&String(c.data.message||"").includes("Agent started")){i.current=true;break}}let a="Setting up environment...";if(i.current)for(let c=e.length-1;c>=0;c--){let y=e[c];if(y.type==="tool_use"||y.type==="build_start"||y.type==="build_complete"){a=Us(Cr(y));break}}if(a!==s.current){o(false);let c=setTimeout(()=>{r(a),s.current=a,o(true);},200);return ()=>clearTimeout(c)}},[e]),So.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 Ns({children:e}){let[t,r]=Fr.useState(null);return Fr.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?vo.createPortal(e,t):null}function Zt({state:e,fork:t,events:r,error:n,slotId:o,targetId:s,targetLabel:i,historyMode:a="slot",onSubmit:c,onUndo:y,onClose:S,baseUrl:u,apiKey:m,userId:I,userHash:v,appId:f,embedded:E=false,completeVariant:$="bubble"}){let[F,h]=Fr.useState(""),[N,D]=Fr.useState([]),[U,O]=Fr.useState(false),[C,M]=Fr.useState(false),[j,k]=Fr.useState(false),[d,w]=Fr.useState(false),[H,R]=Fr.useState(false),[A,b]=Fr.useState(false),[P,G]=Fr.useState(false),[te,z]=Fr.useState(false),[Q,J]=Fr.useState(false),[ie,L]=Fr.useState(null),[xe,Ae]=Fr.useState(false),[K,V]=Fr.useState([]),[he,fe]=Fr.useState(null),[ze,rt]=Fr.useState(false),[Pe,We]=Fr.useState(false),[ir,Tt]=Fr.useState(false),[Je,Mt]=Fr.useState(null),[pe,nt]=Fr.useState(null),[ar,dt]=Fr.useState(false),[ft,ot]=Fr.useState(false),[ke,ue]=Fr.useState(""),st=Fr.useRef(null),[$e,Te]=Fr.useState(null),[pt,Ve]=Fr.useState(false),[Ue,Lt]=Fr.useState(null),[p,g]=Fr.useState([]),[x,W]=Fr.useState(null),[ee,q]=Fr.useState(false),re=Fr.useRef(false),le=Fr.useRef(null),ye=Fr.useRef(null),{resetAllForks:ge,previewSession:X,currentContainerId:ce,forksPaused:oe,setForksPaused:Ie}=we(),ae=X?.container_id??ce,ve=!!(X&&pt),Be=!!(X?.container_id??ce),[Ce,it]=Fr.useState(false),Fe=Ue!==null,Ht=Fr.useRef(S);Fr.useEffect(()=>{Ht.current=S;});let lr=Fr.useRef(null),Ot=Fr.useRef(false),Xr=typeof window<"u"&&"documentPictureInPicture"in window,po=async()=>{if(!(!Xr||Fe))try{let l=await window.documentPictureInPicture.requestWindow({width:Ln,height:640});l.document.body.style.margin="0",l.document.body.style.padding="0",l.document.body.style.height="100vh",l.document.body.style.overflow="hidden",l.document.body.style.background="#ffffff";try{let _=document.adoptedStyleSheets??[];_.length>0&&(l.document.adoptedStyleSheets=[..._]);}catch{}l.addEventListener("pagehide",()=>{lr.current=null,Lt(null),Ot.current||Ht.current(),Ot.current=!1;},{once:!0}),lr.current=l,Lt(l);}catch(l){console.warn("[Fork] PiP open failed:",l);}},go=()=>{Ue&&(Ot.current=true,Ue.close());};Fr.useEffect(()=>()=>{Ot.current=true,lr.current?.close();},[]);let at=s??o??"",mo=(i||at).replace(/[-_]+/g," ").replace(/\b\w/g,l=>l.toUpperCase()),Ut=Fr.useRef(""),Gr=()=>{let l={Authorization:`Bearer ${m}`,...ne()};return f&&(l["X-Fork-App-Id"]=f),!X&&I&&(l["X-Fork-User-Id"]=I),!X&&v&&(l["X-Fork-User-Hash"]=v),l},lt=E?true:C&&!j,ho=r.find(l=>{let _=l.data;return l.type==="status"&&_.summary})?.data?.summary||t?.summary||Ls,qe=r.find(l=>{let _=l.data;return (l.type==="status"||l.type==="complete")&&typeof _?.estimateMinutes=="number"})?.data?.estimateMinutes??t?.estimateMinutes;Fr.useEffect(()=>{if(a==="none"){O(true);return}if(!u||!m)return;if(!x){D([]),O(true);return}let l=new AbortController;return fetch(`${u}/api/v1/forks/${encodeURIComponent(x)}/messages`,{headers:Gr(),signal:l.signal}).then(_=>_.ok?_.json():[]).then(_=>{if(l.signal.aborted)return;let B=[];for(let me of _){let Me=me.forkId??x;me.role==="user"?B.push({type:"user",text:me.content,forkId:Me}):B.push({type:"applied",text:me.content,forkId:Me});}D(B),O(true);}).catch(()=>{l.signal.aborted||O(true);}),()=>{l.abort();}},[m,f,u,a,x,X?.fork_id,X?.preview_session_id,v,I,t?.id,t?.completedAt]),Fr.useEffect(()=>{if(a==="none"||!u||!m||!ze)return;if(!he){g([]);return}let l=new AbortController,_=new URLSearchParams({container_id:he});return fetch(`${u}/api/v1/forks?${_.toString()}`,{headers:Gr(),signal:l.signal}).then(B=>B.ok?B.json():{forks:[]}).then(B=>{l.signal.aborted||g(B.forks??[]);}).catch(()=>{}),()=>{l.abort();}},[m,f,u,a,he,ze,t?.id,t?.completedAt,X?.fork_id,X?.preview_session_id,v,I]),Fr.useEffect(()=>{e==="complete"&&z(false);},[e]);let Yr=p.some(l=>l.status==="pending"||l.status==="running"||l.status==="building");Fr.useEffect(()=>{if(!Yr||!u||!m||!he)return;let l=new URLSearchParams({container_id:he}),_={Authorization:`Bearer ${m}`,...ne()};f&&(_["X-Fork-App-Id"]=f);let me=setInterval(async()=>{try{let Me=await fetch(`${u}/api/v1/forks?${l.toString()}`,{headers:_});if(!Me.ok)return;let bo=await Me.json();g(bo.forks??[]);}catch{}},3e3);return ()=>clearInterval(me)},[Yr,u,m,f,he]),Fr.useEffect(()=>{if(E&&a==="none"){V([]),fe(null),rt(true),Ve(false);return}if(X){let l=false;return rt(false),Ve(false),Te(null),fetch(`${u}/api/v1/preview/${encodeURIComponent(X.preview_session_id)}/containers`,{headers:{Authorization:`Bearer ${m}`,...ne()}}).then(_=>{if(!_.ok)throw new Error(`${_.status}`);return _.json()}).then(_=>{l||(V(_.containers),fe(_.currentContainerId??X.container_id??null),Ve(true));}).catch(_=>{l||(Ve(false),Te(_ instanceof Error?_.message:String(_)),ae?(V([{id:ae,name:X.container_name||"Primary container",createdAt:"",hasAccess:true,isPrimary:true}]),fe(ae)):(V([]),fe(null)));}).finally(()=>{l||rt(true);}),()=>{l=true;}}ae?(V([{id:ae,name:"Primary container",createdAt:""}]),fe(ae)):(V([]),fe(null)),rt(true),Ve(false);},[m,ae,u,E,a,X?.container_id,X?.container_name,X?.preview_session_id]);let Bt=Fr.useRef(void 0);Fr.useEffect(()=>{if(ze){if(Bt.current===void 0){Bt.current=he;return}Bt.current!==he&&(Bt.current=he,D([]),O(false));}},[he,ze]);let Nt=Fr.useRef(null);Fr.useEffect(()=>{if(!Pe)return;let l=B=>{if(!Nt.current)return;let me=typeof B.composedPath=="function"?B.composedPath():[];Nt.current.contains(B.target)||me.includes(Nt.current)||We(false);},_=B=>{B.key==="Escape"&&We(false);};return document.addEventListener("mousedown",l,true),document.addEventListener("keydown",_,true),()=>{document.removeEventListener("mousedown",l,true),document.removeEventListener("keydown",_,true);}},[Pe]),Fr.useEffect(()=>{if(E||!lt||j||Fe)return;let l=_=>{(typeof _.composedPath=="function"?_.composedPath():[]).some(Me=>Me instanceof Element&&Me.hasAttribute("data-fork-panel-host"))||(k(true),M(false),setTimeout(()=>S(),xt));};return document.addEventListener("mousedown",l,true),()=>{document.removeEventListener("mousedown",l,true);}},[E,lt,j,Fe,S]),Fr.useEffect(()=>{Pe||(ot(false),ue(""));},[Pe]),Fr.useEffect(()=>{ft&&(st.current?.focus(),st.current?.select());},[ft]),Fr.useEffect(()=>{if(E)return;let l=requestAnimationFrame(()=>M(true));return ()=>cancelAnimationFrame(l)},[E]),Fr.useEffect(()=>{let l=E||Fe;if((l||lt)&&(e==="prompting"||e==="complete")){let _=setTimeout(()=>le.current?.focus(),l?100:xt+100);return ()=>clearTimeout(_)}},[lt,E,Fe,e]),Fr.useEffect(()=>{if(e==="complete"&&Ut.current){let _=r.find(B=>B.type==="complete")?.data?.summary||t?.summary||Hs;D(B=>B[B.length-1]?.type==="applied"?B:[...B,{type:"applied",text:_}]),h(""),setTimeout(()=>le.current?.focus(),200);}},[e,mo,r,t?.summary]),Fr.useEffect(()=>{ye.current&&(ye.current.scrollTop=ye.current.scrollHeight);},[N,e]);let Qr=()=>{if(F.trim()){Ut.current=F.trim();let l={},_=ee||!x;_?(l.forceNew=true,re.current=true,ee||q(true)):l.forkId=x,_||D(B=>[...B,{type:"user",text:F.trim(),forkId:x}]),c(F.trim(),at,he,l),h("");}};Fr.useEffect(()=>{if(re.current){if(e==="error"){re.current=false;return}t?.id&&(W(t.id),q(false),re.current=false);}},[t?.id,e]),Fr.useEffect(()=>{t?.id&&(re.current||e!=="running"&&e!=="complete"||(W(l=>l??t.id),q(false)));},[t?.id,e]);let Zr=l=>{Ge(l.session.containerId,l.session.containerName),fe(l.session.containerId),V(_=>{let B=_.filter(me=>me.id!==l.container.id);return [{...l.container,isPrimary:true,hasAccess:true},...B.map(me=>({...me,isPrimary:false}))]}),W(null),q(false),re.current=false,D([]),O(false),Ut.current="";},yo=async l=>{if(!(!X||!ve||pe)){nt(l),Te(null);try{let _=await fetch(`${u}/api/v1/preview/${encodeURIComponent(X.preview_session_id)}/containers/${encodeURIComponent(l)}/primary`,{method:"POST",headers:{Authorization:`Bearer ${m}`,...ne()}});if(!_.ok){let B=await _.json().catch(()=>({}));throw new Error(B.error||`API error: ${_.status}`)}Zr(await _.json()),We(!1);}catch(_){Te(_ instanceof Error?_.message:String(_));}finally{nt(null);}}},en=async l=>{if(!X||!ve||pe)return;let _=l.trim();if(_){nt("__new__"),Te(null);try{let B=await fetch(`${u}/api/v1/preview/${encodeURIComponent(X.preview_session_id)}/containers`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${m}`,...ne()},body:JSON.stringify({name:_})});if(!B.ok){let me=await B.json().catch(()=>({}));throw new Error(me.error||`API error: ${B.status}`)}Zr(await B.json()),ot(!1),ue(""),We(!1);}catch(B){Te(B instanceof Error?B.message:String(B));}finally{nt(null);}}},tn=async()=>{if(!(!y||Q||!at)){J(true);try{let l=await y(at);D(_=>{let B=[..._];return B.length>=2&&B[B.length-1]?.type==="applied"?B.splice(-2,2):B.length>=1&&B[B.length-1]?.type==="applied"&&B.splice(-1,1),B}),l?.removed&&D([]);}catch{}finally{J(false);}}},rn=()=>{if(E){S();return}if(Fe){Ue?.close();return}k(true),M(false),setTimeout(()=>S(),xt);},ko=E||Fe?{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:Ln,maxWidth:"100vw",background:"#ffffff",boxShadow:lt?"-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:lt?"translateX(0)":"translateX(100%)",transition:`transform ${xt}ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow ${xt}ms ease`,display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'},nn=K.find(l=>l.id===he)?.name??(ze?"Fork":"Loading..."),gt=ee?[]:x?N.filter(l=>l.forkId===x||l.forkId==null):N,cr=So.jsxs(So.Fragment,{children:[So.jsx("style",{children:`
|
|
36
|
+
`}),eo.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&&eo.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"#6b7280",fontSize:"11px"},children:[eo.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,s=r.type==="complete"||r.type==="error"||r.type==="build_complete"||r.type==="build_error",i=o&&!s&&(r.type==="status"||r.type==="tool_use"||r.type==="build_start"),a=Go[r.type]||lucideReact.Code,d=Yo[r.type]||"#9ca3af";if(r.type==="tool_use"){let b=String(r.data.category||"");a=Qo[b]||lucideReact.Wrench,d=Zo[b]||"#fbbf24";}return i?a=lucideReact.Loader2:!o&&r.type==="status"&&(a=lucideReact.Check,d="#4ade80"),eo.jsxs("div",{style:{display:"flex",gap:"6px",marginBottom:"6px",lineHeight:1.625},children:[eo.jsx(a,{style:{width:"12px",height:"12px",marginTop:"2px",flexShrink:0,color:d,...i?{animation:"__fork-spin 1s linear infinite"}:{}}}),eo.jsx("span",{style:{color:o&&!s?"#d1d5db":"#6b7280",wordBreak:"break-all"},children:hr(r)})]},n)})]})]})}var pn=35,ls="Setting up environment",cs="Built Custom Feature",gn=360,mt=380;function us(e){let t=Date.parse(e);if(Number.isNaN(t))return "";let r=Math.max(1,Math.round((Date.now()-t)/1e3));if(r<60)return `${r}s`;let n=Math.round(r/60);if(n<60)return `${n}m`;let o=Math.round(n/60);return o<24?`${o}h`:`${Math.round(o/24)}d`}function ds(e){return e.length<=pn?e:e.slice(0,pn-3).trimEnd()+"..."}function fs({events:e}){let[t,r]=cr.useState("Setting up environment..."),[n,o]=cr.useState(true),s=cr.useRef(t),i=cr.useRef(false);return cr.useEffect(()=>{if(!i.current){for(let d of e)if(d.type==="status"&&String(d.data.message||"").includes("Agent started")){i.current=true;break}}let a="Setting up environment...";if(i.current)for(let d=e.length-1;d>=0;d--){let b=e[d];if(b.type==="tool_use"||b.type==="build_start"||b.type==="build_complete"){a=ds(hr(b));break}}if(a!==s.current){o(false);let d=setTimeout(()=>{r(a),s.current=a,o(true);},200);return ()=>clearTimeout(d)}},[e]),eo.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 ps({children:e}){let[t,r]=cr.useState(null);return cr.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?Zn.createPortal(e,t):null}function Dt({state:e,fork:t,events:r,error:n,slotId:o,targetId:s,targetLabel:i,historyMode:a="slot",onSubmit:d,onUndo:b,onClose:m,baseUrl:f,apiKey:w,userId:A,userHash:h,appId:l,embedded:C=false,completeVariant:_="bubble"}){let[k,v]=cr.useState(""),[L,D]=cr.useState([]),[B,U]=cr.useState(false),[R,$]=cr.useState(false),[O,y]=cr.useState(false),[u,F]=cr.useState(false),[T,M]=cr.useState(false),[I,S]=cr.useState(false),[H,Y]=cr.useState(false),[ae,Q]=cr.useState(false),[re,V]=cr.useState(false),[Z,q]=cr.useState(null),[ke,Se]=cr.useState(false),[Ue,W]=cr.useState([]),[j,Te]=cr.useState(null),[me,it]=cr.useState(false),[$e,ze]=cr.useState(false),[qt,xt]=cr.useState(false),[Xt,Oe]=cr.useState(null),[ue,Ze]=cr.useState(null),[Gt,At]=cr.useState(false),[et,tt]=cr.useState(false),[Me,be]=cr.useState(""),fe=cr.useRef(null),[at,Fe]=cr.useState(null),[Yt,We]=cr.useState(false),[Ne,It]=cr.useState(null),[Ve,g]=cr.useState([]),[p,x]=cr.useState(null),[K,J]=cr.useState(false),z=cr.useRef(false),te=cr.useRef(null),oe=cr.useRef(null),{resetAllForks:we,adminContext:ee,setAdminContainer:pe,currentContainerId:se,forksPaused:ne,setForksPaused:Ie}=he(),le=ee.containerId??se,ye=!!(ee.isAdmin&&Yt),Be=!!(ee.containerId??se),[Ee,rt]=cr.useState(false),xe=Ne!==null,Ct=cr.useRef(m);cr.useEffect(()=>{Ct.current=m;});let Qt=cr.useRef(null),Rt=cr.useRef(false),Lr=typeof window<"u"&&"documentPictureInPicture"in window,Wn=async()=>{if(!(!Lr||xe))try{let c=await window.documentPictureInPicture.requestWindow({width:gn,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 P=document.adoptedStyleSheets??[];P.length>0&&(c.document.adoptedStyleSheets=[...P]);}catch{}c.addEventListener("pagehide",()=>{Qt.current=null,It(null),Rt.current||Ct.current(),Rt.current=!1;},{once:!0}),Qt.current=c,It(c);}catch(c){console.warn("[Fork] PiP open failed:",c);}},Vn=()=>{Ne&&(Rt.current=true,Ne.close());};cr.useEffect(()=>()=>{Rt.current=true,Qt.current?.close();},[]);let nt=s??o??"",Jn=(i||nt).replace(/[-_]+/g," ").replace(/\b\w/g,c=>c.toUpperCase()),Et=cr.useRef(""),$t=()=>{let c={Authorization:`Bearer ${w}`,...ie()};return l&&(c["X-Fork-App-Id"]=l),A&&(c["X-Fork-User-Id"]=A),h&&(c["X-Fork-User-Hash"]=h),c},ot=C?true:R&&!O,qn=r.find(c=>{let P=c.data;return c.type==="status"&&P.summary})?.data?.summary||t?.summary||ls,Je=r.find(c=>{let P=c.data;return (c.type==="status"||c.type==="complete")&&typeof P?.estimateMinutes=="number"})?.data?.estimateMinutes??t?.estimateMinutes;cr.useEffect(()=>{if(a==="none"){U(true);return}if(!f||!w)return;if(!p){D([]),U(true);return}let c=new AbortController;return fetch(`${f}/api/v1/forks/${encodeURIComponent(p)}/messages`,{headers:$t(),signal:c.signal}).then(P=>P.ok?P.json():[]).then(P=>{if(c.signal.aborted)return;let N=[];for(let de of P){let Pe=de.forkId??p;de.role==="user"?N.push({type:"user",text:de.content,forkId:Pe}):N.push({type:"applied",text:de.content,forkId:Pe});}D(N),U(true);}).catch(()=>{c.signal.aborted||U(true);}),()=>{c.abort();}},[w,l,f,a,p,ee.containerId,h,A,t?.id,t?.completedAt]),cr.useEffect(()=>{if(a==="none"||!f||!w||!me)return;if(!j){g([]);return}let c=new AbortController,P=new URLSearchParams({container_id:j});return fetch(`${f}/api/v1/forks?${P.toString()}`,{headers:$t(),signal:c.signal}).then(N=>N.ok?N.json():{forks:[]}).then(N=>{c.signal.aborted||g(N.forks??[]);}).catch(()=>{}),()=>{c.abort();}},[w,l,f,a,j,me,t?.id,t?.completedAt,ee.containerId,h,A]),cr.useEffect(()=>{e==="complete"&&Q(false);},[e]);let Hr=Ve.some(c=>c.status==="pending"||c.status==="running"||c.status==="building");cr.useEffect(()=>{if(!Hr||!f||!w||!j)return;let c=new URLSearchParams({container_id:j}),P={Authorization:`Bearer ${w}`,...ie()};l&&(P["X-Fork-App-Id"]=l);let de=setInterval(async()=>{try{let Pe=await fetch(`${f}/api/v1/forks?${c.toString()}`,{headers:P});if(!Pe.ok)return;let Yn=await Pe.json();g(Yn.forks??[]);}catch{}},3e3);return ()=>clearInterval(de)},[Hr,f,w,l,j]),cr.useEffect(()=>{if(C&&a==="none"){W([]),Te(null),it(true),We(false);return}if(ee.isAdmin){Fe(null),W(ee.containers.map(c=>({id:c.id,name:c.name,createdAt:"",hasAccess:true,isPrimary:c.isPrimary}))),Te(ee.containerId??null),We(true),it(true);return}le?(W([{id:le,name:"Primary container",createdAt:""}]),Te(le)):(W([]),Te(null)),it(true),We(false);},[w,le,f,C,a,ee.isAdmin,ee.containerId,ee.containers]);let Tt=cr.useRef(void 0);cr.useEffect(()=>{if(me){if(Tt.current===void 0){Tt.current=j;return}Tt.current!==j&&(Tt.current=j,D([]),U(false));}},[j,me]);let Mt=cr.useRef(null);cr.useEffect(()=>{if(!$e)return;let c=N=>{if(!Mt.current)return;let de=typeof N.composedPath=="function"?N.composedPath():[];Mt.current.contains(N.target)||de.includes(Mt.current)||ze(false);},P=N=>{N.key==="Escape"&&ze(false);};return document.addEventListener("mousedown",c,true),document.addEventListener("keydown",P,true),()=>{document.removeEventListener("mousedown",c,true),document.removeEventListener("keydown",P,true);}},[$e]),cr.useEffect(()=>{if(C||!ot||O||xe)return;let c=P=>{(typeof P.composedPath=="function"?P.composedPath():[]).some(Pe=>Pe instanceof Element&&Pe.hasAttribute("data-fork-panel-host"))||(y(true),$(false),setTimeout(()=>m(),mt));};return document.addEventListener("mousedown",c,true),()=>{document.removeEventListener("mousedown",c,true);}},[C,ot,O,xe,m]),cr.useEffect(()=>{$e||(tt(false),be(""));},[$e]),cr.useEffect(()=>{et&&(fe.current?.focus(),fe.current?.select());},[et]),cr.useEffect(()=>{if(C)return;let c=requestAnimationFrame(()=>$(true));return ()=>cancelAnimationFrame(c)},[C]),cr.useEffect(()=>{let c=C||xe;if((c||ot)&&(e==="prompting"||e==="complete")){let P=setTimeout(()=>te.current?.focus(),c?100:mt+100);return ()=>clearTimeout(P)}},[ot,C,xe,e]),cr.useEffect(()=>{if(e==="complete"&&Et.current){let P=r.find(N=>N.type==="complete")?.data?.summary||t?.summary||cs;D(N=>N[N.length-1]?.type==="applied"?N:[...N,{type:"applied",text:P}]),v(""),setTimeout(()=>te.current?.focus(),200);}},[e,Jn,r,t?.summary]),cr.useEffect(()=>{oe.current&&(oe.current.scrollTop=oe.current.scrollHeight);},[L,e]);let Ur=()=>{if(k.trim()){Et.current=k.trim();let c={},P=K||!p;P?(c.forceNew=true,z.current=true,K||J(true)):c.forkId=p,P||D(N=>[...N,{type:"user",text:k.trim(),forkId:p}]),d(k.trim(),nt,j,c),v("");}};cr.useEffect(()=>{if(z.current){if(e==="error"){z.current=false;return}t?.id&&(x(t.id),J(false),z.current=false);}},[t?.id,e]),cr.useEffect(()=>{t?.id&&(z.current||e!=="running"&&e!=="complete"||(x(c=>c??t.id),J(false)));},[t?.id,e]);let Or=c=>{pe(c.container.id,c.container.name),Te(c.container.id),W(P=>{let N=P.filter(de=>de.id!==c.container.id);return [{...c.container,isPrimary:true,hasAccess:true},...N.map(de=>({...de,isPrimary:false}))]}),x(null),J(false),z.current=false,D([]),U(false),Et.current="";},Xn=async c=>{if(!(!ye||ue)){Ze(c),Fe(null);try{let P=await fetch(`${f}/api/v1/admin/containers/${encodeURIComponent(c)}/primary`,{method:"POST",headers:$t()});if(!P.ok){let N=await P.json().catch(()=>({}));throw new Error(N.error||`API error: ${P.status}`)}Or(await P.json()),ze(!1);}catch(P){Fe(P instanceof Error?P.message:String(P));}finally{Ze(null);}}},Nr=async c=>{if(!ye||ue)return;let P=c.trim();if(P){Ze("__new__"),Fe(null);try{let N=await fetch(`${f}/api/v1/admin/containers`,{method:"POST",headers:{...$t(),"Content-Type":"application/json"},body:JSON.stringify({name:P})});if(!N.ok){let de=await N.json().catch(()=>({}));throw new Error(de.error||`API error: ${N.status}`)}Or(await N.json()),tt(!1),be(""),ze(!1);}catch(N){Fe(N instanceof Error?N.message:String(N));}finally{Ze(null);}}},Br=async()=>{if(!(!b||re||!nt)){V(true);try{let c=await b(nt);D(P=>{let N=[...P];return N.length>=2&&N[N.length-1]?.type==="applied"?N.splice(-2,2):N.length>=1&&N[N.length-1]?.type==="applied"&&N.splice(-1,1),N}),c?.removed&&D([]);}catch{}finally{V(false);}}},Dr=()=>{if(C){m();return}if(xe){Ne?.close();return}y(true),$(false),setTimeout(()=>m(),mt);},Gn=C||xe?{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:gn,maxWidth:"100vw",background:"#ffffff",boxShadow:ot?"-12px 0 32px -16px rgba(0, 0, 0, 0.18), -2px 0 8px -2px rgba(0, 0, 0, 0.06)":"none",borderLeft:"1px solid rgba(0, 0, 0, 0.08)",transform:ot?"translateX(0)":"translateX(100%)",transition:`transform ${mt}ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow ${mt}ms ease`,display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'},Kr=Ue.find(c=>c.id===j)?.name??(me?"Fork":"Loading..."),lt=K?[]:p?L.filter(c=>c.forkId===p||c.forkId==null):L,Zt=eo.jsxs(eo.Fragment,{children:[eo.jsx("style",{children:`
|
|
38
37
|
@keyframes __fork-pulse {
|
|
39
38
|
0%, 100% { opacity: 1; }
|
|
40
39
|
50% { opacity: 0.5; }
|
|
@@ -56,9 +55,9 @@
|
|
|
56
55
|
scrollbar-width: thin;
|
|
57
56
|
scrollbar-color: rgba(0, 0, 0, 0.12) transparent;
|
|
58
57
|
}
|
|
59
|
-
`}),So.jsxs("div",{className:"__fork-panel",style:ko,children:[So.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:[So.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:[So.jsx("span",{onDoubleClick:async l=>{if(l.stopPropagation(),!xe&&confirm("Kill all forks in this container?")){Ae(true);try{let _=await ge();`${_?.deleted??0}`,g([]),W(null),q(!1),h("");}catch(_){console.error("[Fork] Reset failed:",_);}finally{Ae(false);}}},style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:4,margin:-4,cursor:"pointer",flexShrink:0},children:So.jsx(Xt,{style:{width:16,height:16,color:"#111827",pointerEvents:"none"}})}),e==="running"?So.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:ho}):K.length===0&&!ve?So.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:"Fork"}):ve?So.jsxs("div",{ref:Nt,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[So.jsxs("button",{type:"button",onClick:()=>{We(l=>!l);},onMouseEnter:()=>Tt(true),onMouseLeave:()=>Tt(false),"aria-haspopup":"menu","aria-expanded":Pe,style:{display:"inline-flex",alignItems:"center",gap:4,padding:"3px 6px",border:"1px solid transparent",borderRadius:6,background:ir||Pe?"#f3f4f6":"transparent",fontSize:13,fontWeight:600,color:"#111827",fontFamily:"inherit",cursor:"pointer",maxWidth:180,minWidth:0,transition:"background-color 0.12s"},children:[So.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:nn}),So.jsx(lucideReact.ChevronDown,{style:{width:12,height:12,color:"#6b7280",flexShrink:0,transform:Pe?"rotate(180deg)":void 0,transition:"transform 0.15s"}})]}),Pe&&So.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:[K.map(l=>{let _=l.id===he,B=Je===l.id,me=pe===l.id;return So.jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>Mt(l.id),onMouseLeave:()=>Mt(null),onClick:()=>{l.id!==he&&yo(l.id);},disabled:!!pe,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:B?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:pe?"default":"pointer",textAlign:"left",fontWeight:_?600:400,opacity:pe&&!me?.55:1},children:[So.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:_&&So.jsx(lucideReact.Check,{style:{width:12,height:12}})}),So.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:me?"Switching...":l.name})]},l.id)}),So.jsx("div",{style:{height:1,background:"#e5e7eb",margin:"4px 0"}}),ft?So.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"4px 4px"},children:[So.jsx("input",{ref:st,type:"text",value:ke,placeholder:"Container name",disabled:pe==="__new__",onChange:l=>ue(l.target.value),onKeyDown:l=>{l.key==="Enter"?(l.preventDefault(),en(ke)):l.key==="Escape"&&(l.preventDefault(),l.stopPropagation(),ot(false),ue(""));},style:{flex:1,minWidth:0,padding:"5px 8px",border:"1px solid #d1d5db",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",background:"#ffffff",outline:"none"},onFocus:l=>{l.currentTarget.style.borderColor="#111827",l.currentTarget.style.boxShadow="0 0 0 2px rgba(17,24,39,0.15)";},onBlur:l=>{l.currentTarget.style.borderColor="#d1d5db",l.currentTarget.style.boxShadow="none";}}),So.jsx("button",{type:"button",onClick:()=>{en(ke);},disabled:!ke.trim()||pe==="__new__",title:"Create",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:26,height:26,border:"none",borderRadius:4,background:!ke.trim()||pe==="__new__"?"#e5e7eb":"#111827",color:!ke.trim()||pe==="__new__"?"#9ca3af":"#ffffff",cursor:!ke.trim()||pe==="__new__"?"default":"pointer",flexShrink:0},children:pe==="__new__"?So.jsx("span",{style:{width:10,height:10,border:"1.5px solid currentColor",borderTopColor:"transparent",borderRadius:"50%",animation:"__fork-spin 0.7s linear infinite"}}):So.jsx(lucideReact.Check,{style:{width:12,height:12}})})]}):So.jsx("button",{type:"button",role:"menuitem",onMouseEnter:()=>dt(true),onMouseLeave:()=>dt(false),onClick:()=>{pe||(Te(null),ue(""),ot(true));},disabled:!!pe,style:{display:"flex",alignItems:"center",width:"100%",padding:"6px 8px",border:"none",background:ar?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:pe?"default":"pointer",textAlign:"left",opacity:pe&&pe!=="__new__"?.55:1},children:"+ New container"}),$e&&So.jsx("div",{style:{padding:"6px 8px",fontSize:11,lineHeight:1.35,color:"#b91c1c"},children:$e})]})]}):So.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:nn}),e==="running"&&So.jsx("span",{title:qe?`Estimated ~${qe} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:qe?"#111827":"#9ca3af",backgroundColor:qe?"rgba(17, 24, 39, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:qe?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:qe?`~${qe}m`:"~ m"})]}),So.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[Be&&So.jsx("button",{type:"button",role:"switch","aria-checked":!oe,"aria-label":oe?"Turn Fork back on":"Turn Fork off",title:oe?"Fork is off \u2014 you're seeing the original app. Turn it back on. Only affects you.":"Turn Fork off to see the original app. Only affects you.",onClick:()=>{Ie(!oe);},onMouseEnter:()=>it(true),onMouseLeave:()=>it(false),style:{position:"relative",width:26,height:15,borderRadius:999,border:"none",padding:0,marginRight:6,flexShrink:0,cursor:"pointer",backgroundColor:oe?Ce?"#9ca3af":"#d1d5db":Ce?"#374151":"#111827",transition:"background-color 0.18s ease",outline:"none",boxSizing:"border-box"},children:So.jsx("span",{"aria-hidden":true,style:{position:"absolute",top:2,left:oe?2:13,width:11,height:11,borderRadius:"50%",backgroundColor:"#ffffff",boxShadow:"0 1px 2px rgba(15, 23, 42, 0.25)",transition:"left 0.18s cubic-bezier(0.16, 1, 0.3, 1)"}})}),!E&&So.jsxs(So.Fragment,{children:[Xr&&So.jsx("button",{onClick:Fe?go:po,onMouseEnter:()=>R(true),onMouseLeave:()=>R(false),title:Fe?"Redock to sidebar":"Pop out into window",style:{padding:6,borderRadius:6,color:H?"#4b5563":"#9ca3af",backgroundColor:H?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:Fe?So.jsx(lucideReact.PictureInPicture,{style:{width:16,height:16}}):So.jsx(lucideReact.PictureInPicture2,{style:{width:16,height:16}})}),So.jsx("button",{onClick:rn,onMouseEnter:()=>w(true),onMouseLeave:()=>w(false),style:{padding:6,borderRadius:6,color:d?"#4b5563":"#9ca3af",backgroundColor:d?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:So.jsx(lucideReact.X,{style:{width:16,height:16}})})]})]})]}),So.jsxs("div",{ref:ye,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[(x||ee)&&So.jsxs("div",{style:{padding:"10px 12px 6px 12px",display:"flex",alignItems:"center",gap:8,borderBottom:"1px solid #f3f4f6"},children:[So.jsx("button",{onClick:()=>{W(null),q(false),re.current=false;},style:{fontSize:12,color:"#374151",background:"transparent",border:"none",padding:"2px 4px",cursor:"pointer",display:"inline-flex",alignItems:"center",gap:4},title:"Back to all forks",children:"\u2190 All forks"}),(()=>{let _=(x?p.find(B=>B.id===x)?.targetId:null)??at;return _?So.jsxs("span",{style:{fontSize:11,color:"#9ca3af",fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, "Liberation Mono", "Courier New", monospace',whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1},title:`Forking ${_}`,children:["Forking ",So.jsx("span",{style:{color:"#6b7280"},children:_})]}):null})()]}),!x&&!ee&&So.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[So.jsx("div",{style:{padding:"12px 16px 10px 16px",borderBottom:"1px solid #f3f4f6"},children:So.jsx("span",{style:{fontSize:12,fontWeight:600,color:"#111827"},children:"Forks"})}),p.length===0&&So.jsx("div",{style:{padding:"24px 20px",textAlign:"center",fontSize:13,color:"#6b7280"},children:"No forks yet. Describe a feature below to start one."}),p.length>0&&So.jsx("div",{style:{display:"flex",flexDirection:"column"},children:p.map(l=>{let _=l.summary||"Untitled fork";return So.jsxs("button",{onClick:()=>{q(false),W(l.id);},style:{textAlign:"left",padding:"10px 16px",background:"#ffffff",border:"none",borderBottom:"1px solid #f3f4f6",cursor:"pointer",display:"flex",flexDirection:"column",gap:2},onMouseEnter:B=>B.currentTarget.style.background="#fafafa",onMouseLeave:B=>B.currentTarget.style.background="#ffffff",children:[So.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[So.jsx("span",{style:{fontSize:13,fontWeight:500,color:"#111827",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1},children:_}),So.jsx("span",{style:{fontSize:11,color:"#9ca3af",flexShrink:0},children:Os(l.updatedAt)})]}),So.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:11,color:"#6b7280"},children:[So.jsx("span",{style:{fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, "Liberation Mono", "Courier New", monospace',whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:l.targetId}),So.jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),So.jsxs("span",{children:[l.promptCount," prompt",l.promptCount===1?"":"s"]}),l.status==="running"||l.status==="building"?So.jsxs(So.Fragment,{children:[So.jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),So.jsx("span",{style:{color:"#111827"},children:"running"})]}):null]})]},l.id)})})]}),x&>.length>0&&So.jsx("div",{style:{padding:"16px 16px 0 16px"},children:gt.map((l,_)=>So.jsx("div",{style:{marginBottom:_<gt.length-1?10:0},children:l.type==="user"?So.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexDirection:"row-reverse"},children:[So.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:So.jsx(lucideReact.User,{style:{width:13,height:13,color:"#6b7280"}})}),So.jsx("div",{style:{backgroundColor:"#f3f4f6",borderRadius:"12px 4px 12px 12px",padding:"8px 12px",fontSize:13,color:"#374151",lineHeight:1.5,maxWidth:"75%"},children:l.text})]}):$==="item"&&_===gt.length-1?So.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:12,padding:12,borderRadius:8,border:"1px solid #e4e4e7",background:"#ffffff"},children:[So.jsx("div",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,flexShrink:0,borderRadius:6,background:"#f4f4f5",color:"#0a0a0a"},children:So.jsx(lucideReact.BadgeCheck,{style:{width:16,height:16}})}),So.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,flex:1,minWidth:0},children:[So.jsx("div",{style:{fontSize:13,fontWeight:500,color:"#0a0a0a",lineHeight:1.3},children:"Feature applied"}),So.jsx("div",{style:{fontSize:13,color:"#71717a",lineHeight:1.4},children:l.text})]}),y&&e!=="running"&&So.jsx("button",{onClick:B=>{B.stopPropagation(),tn();},disabled:Q,style:{padding:"4px 10px",fontSize:12,fontWeight:500,borderRadius:6,border:"1px solid #e4e4e7",background:"#ffffff",color:"#0a0a0a",cursor:Q?"default":"pointer",opacity:Q?.4:1,height:28,flexShrink:0},children:"Undo"})]}):So.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[So.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#f0fdf4",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:So.jsx(lucideReact.Check,{style:{width:13,height:13,color:"#9ca3af"}})}),So.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:[So.jsx("span",{style:{flex:1},children:l.text}),y&&_===gt.length-1&&e!=="running"&&So.jsxs("button",{onClick:B=>{B.stopPropagation(),tn();},onMouseEnter:()=>L(_),onMouseLeave:()=>L(null),disabled:Q,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:ie===_?"rgba(0,0,0,0.06)":"transparent",color:ie===_?"#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:[So.jsx(lucideReact.Undo2,{style:{width:12,height:12}}),ie===_&&So.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"})]})]})]})},_))}),e==="running"&&(x||ee)&&So.jsx("div",{style:{padding:16},children:So.jsxs("div",{onClick:()=>z(!te),style:{backgroundColor:"#1a1a2e",borderRadius:12,overflow:"hidden",cursor:"pointer",transition:"all 0.3s cubic-bezier(0.22, 1, 0.36, 1)"},children:[So.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px"},children:[So.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[So.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:So.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),So.jsx(Bs,{events:r})]}),So.jsx("div",{style:{color:"#6b7280",flexShrink:0,marginLeft:8,transition:"transform 0.2s ease",transform:te?"rotate(180deg)":"rotate(0deg)"},children:So.jsx(lucideReact.ChevronDown,{style:{width:14,height:14}})})]}),So.jsx("div",{style:{maxHeight:te?320:0,opacity:te?1:0,transition:"max-height 0.35s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.25s ease",overflow:"hidden"},children:So.jsx("div",{style:{borderTop:"1px solid rgba(255,255,255,0.08)",maxHeight:320,overflowY:"auto"},children:So.jsx(Pn,{events:r})})})]})}),e==="error"&&(x||ee)&&So.jsxs("div",{style:{padding:"20px 16px",textAlign:"center"},children:[So.jsx("div",{style:{width:36,height:36,backgroundColor:"#fef2f2",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 10px auto"},children:So.jsx(lucideReact.X,{style:{width:18,height:18,color:"#ef4444"}})}),So.jsx("p",{style:{fontSize:12,color:"#6b7280",marginBottom:10,maxWidth:260,margin:"0 auto 10px auto"},children:n}),So.jsxs("button",{onClick:()=>{let l=t?.prompt||Ut.current;l&&c(l,at);},onMouseEnter:()=>G(true),onMouseLeave:()=>G(false),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,color:"#111827",backgroundColor:P?"#e5e7eb":"#f3f4f6",border:"none",cursor:"pointer",transition:"background-color 0.15s",fontFamily:"inherit"},children:[So.jsx(lucideReact.RotateCcw,{style:{width:12,height:12}})," Try Again"]})]})]}),e!=="running"&&So.jsx("div",{style:{padding:"8px 12px 12px 12px",borderTop:"1px solid rgba(229, 231, 235, 0.6)",flexShrink:0},children:So.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,borderRadius:12,padding:"8px 8px 8px 12px",background:"rgba(0, 0, 0, 0.04)",border:"1px solid rgba(0, 0, 0, 0.06)"},children:[So.jsx("textarea",{ref:le,value:F,onChange:l=>{h(l.target.value),l.target.style.height="auto",l.target.style.height=Math.min(l.target.scrollHeight,160)+"px";},onKeyDown:l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),Qr()),l.key==="Escape"&&!E&&rn();},placeholder:x?"Iterate on this feature...":"Start building a new Fork...",rows:1,style:{flex:1,backgroundColor:"transparent",fontSize:13,color:"#111827",border:"none",outline:"none",padding:"0 4px 0 0",fontFamily:"inherit",resize:"none",lineHeight:1.5,maxHeight:160,overflow:"auto"}}),So.jsx("button",{onClick:Qr,disabled:!F.trim(),onMouseEnter:()=>b(true),onMouseLeave:()=>b(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:F.trim()?1:.25,transform:A&&F.trim()?"scale(1.1)":"scale(1)",background:F.trim()?"#111827":"rgba(0,0,0,0.12)",border:"none",cursor:F.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:So.jsx(lucideReact.ArrowUp,{style:{width:13,height:13}})})]})})]})]});return E?cr:Fe&&Ue?vo.createPortal(cr,Ue.document.body):So.jsx(Ns,{children:cr})}function On(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 Tr(e){let{apiKey:t,userId:r,userHash:n,baseUrl:o,appId:s,previewSession:i,refreshModuleManifest:a,queueBoundaryAnimation:c,trackForkActivity:y,recordForkActivityEvent:S}=we(),[u,m]=Fr.useState("idle"),[I,v]=Fr.useState(null),[f,E]=Fr.useState([]),[$,F]=Fr.useState(null),h=Fr.useRef(null),N=Fr.useCallback(()=>{m("prompting"),E([]),F(null),v(null);},[]),D=Fr.useCallback(()=>{m("idle"),h.current&&(h.current.close(),h.current=null);},[]);Fr.useEffect(()=>{i&&i.target.kind==="module"&&i.target.id===e&&m(M=>M==="idle"?"prompting":M);},[i?.preview_session_id,i?.target.id,e]);let U=Fr.useCallback(async(M,j,k)=>{try{if(!s)throw new Error("ForkProvider requires appId for module boundary prompts.");m("running"),E([]),F(null),v(null);let d;if(i){let R=k?.forkId??i.fork_id??void 0,A=await fetch(`${o}/api/v1/preview/${encodeURIComponent(i.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...ne()},body:JSON.stringify({prompt:M,...e?{boundary_id:e}:{},...R&&!k?.forceNew?{fork_id:R}:{},...k?.forceNew?{force_new:!0}:{}})});if(!A.ok){let G=await A.json().catch(()=>({}));throw new Error(G.error||`API error: ${A.status}`)}let b=await A.json();b.container_id&&Ge(b.container_id,b.container_name),mt(b.fork_id),d=await(await fetch(`${o}/api/v1/forks/${b.fork_id}`,{headers:{Authorization:`Bearer ${t}`,...ne()}})).json();}else if(k?.forkId){let R={prompt:M};r&&(R.userId=r),n&&(R.userHash=n);let A=await fetch(`${o}/api/v1/forks/${encodeURIComponent(k.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(R)});if(!A.ok){let b=await A.json().catch(()=>({}));throw new Error(b.error||`API error: ${A.status}`)}d=await A.json();}else {let R={userId:r,prompt:M,boundaryId:e,appId:s};j&&(R.containerId=j),n&&(R.userHash=n),k?.forceNew&&(R.force_new=!0);let A=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(R)});if(!A.ok){let b=await A.json().catch(()=>({}));throw new Error(b.error||`API error: ${A.status}`)}d=await A.json();}v(d),y(d,{targetKind:"module",targetId:e});let w=new URLSearchParams({key:t});i?(w.set("previewSessionId",i.preview_session_id),w.set("previewForkId",d.id)):r&&w.set("userId",r),n&&w.set("userHash",n);let H=new EventSource(`${o}/api/v1/forks/${d.id}/events?${w.toString()}`);h.current=H,H.onmessage=R=>{try{let A=JSON.parse(R.data);if(S(d.id,A),E(b=>[...b,A]),A.type==="complete"){let b=A.data;c(e,d.id),a().catch(()=>{}).finally(()=>{let P={...d,status:"complete",moduleUrl:b.moduleUrl,cssUrls:b.cssUrls,summary:b.summary,completedAt:new Date().toISOString()};v(P),m("complete"),H.close();});}else if(A.type==="error"){let b=A.data;F(b.error||"Unknown error"),m("error"),H.close();}}catch{}},H.onerror=()=>{let R={Authorization:`Bearer ${t}`,...ne()};!i&&r&&(R["X-Fork-User-Id"]=r),!i&&n&&(R["X-Fork-User-Hash"]=n),fetch(`${o}/api/v1/forks/${d.id}`,{headers:R}).then(A=>A.json()).then(A=>{v(A),A.status==="complete"?(c(e,A.id),a().catch(()=>{}),m("complete")):A.status==="error"&&(F(A.error||"Fork generation failed"),m("error"));}).catch(()=>{F("Connection lost"),m("error");}),H.close();};}catch(d){F(d.message),m("error");}},[t,s,o,e,i,c,a,S,y,n,r]),O=Fr.useCallback(async M=>{try{let j={Authorization:`Bearer ${t}`,...ne()};!i&&r&&(j["X-Fork-User-Id"]=r),!i&&n&&(j["X-Fork-User-Hash"]=n);let k=await fetch(`${o}/api/v1/forks/${M}`,{headers:j});if(!k.ok)return;let d=await k.json(),w=d.boundaryId??e;if(y(d,{targetKind:"module",targetId:w}),d.status==="complete"){m("complete"),v(d),F(null),E([]);return}if(d.status==="error"){m("error"),v(d),F(d.error||"Fork generation failed"),E([]);return}if(d.status!=="pending"&&d.status!=="running"&&d.status!=="building")return;m("running"),v(d),F(null),E([]);let H=new URLSearchParams({key:t});i?(H.set("previewSessionId",i.preview_session_id),H.set("previewForkId",d.id)):r&&H.set("userId",r),n&&H.set("userHash",n);let R=new EventSource(`${o}/api/v1/forks/${d.id}/events?${H.toString()}`);h.current&&h.current.close(),h.current=R,R.onmessage=A=>{try{let b=JSON.parse(A.data);if(S(d.id,b),E(P=>[...P,b]),b.type==="complete"){let P=b.data;c(e,d.id),a().catch(()=>{}).finally(()=>{let G={...d,status:"complete",moduleUrl:P.moduleUrl,cssUrls:P.cssUrls,summary:P.summary,completedAt:new Date().toISOString()};v(G),m("complete"),R.close();});}else if(b.type==="error"){let P=b.data;F(P.error||"Unknown error"),m("error"),R.close();}}catch{}},R.onerror=()=>{R.close();};}catch{}},[t,o,e,i,c,S,a,y,n,r]),C=Fr.useCallback(async()=>{try{if(!s)throw new Error("ForkProvider requires appId for boundary undo.");let M={userId:r,boundaryId:e,appId:s};n&&(M.userHash=n);let j=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(M)});if(!j.ok){let d=await j.json().catch(()=>({}));throw new Error(d.error||`API error: ${j.status}`)}let k=await j.json();return await a().catch(()=>{}),k.removed?(v(null),m("prompting")):k.fork&&(v(k.fork),m("complete")),k}catch(M){throw F(M.message),M}},[t,s,o,e,a,n,r]);return {state:u,fork:I,events:f,error:$,open:N,close:D,startFork:U,undoFork:C,adoptRunningFork:O}}var zs=0;function Nn(e){let{state:t,fork:r,events:n,error:o,open:s,close:i,startFork:a,undoFork:c,adoptRunningFork:y}=Tr(e),[S,u]=Fr.useState(false),m=Fr.useRef(null),I=Fr.useRef(t),v=Fr.useCallback(()=>{m.current!==null&&(clearTimeout(m.current),m.current=null);},[]),f=Fr.useCallback(()=>{v(),u(true),s();},[v,s]),E=Fr.useCallback(()=>{v(),u(false),i();},[v,i]),$=Fr.useCallback(async F=>{v(),u(true),await y(F);},[y,v]);return Fr.useEffect(()=>{let F=I.current;I.current=t,t==="complete"&&F==="running"&&S&&(v(),m.current=setTimeout(()=>{m.current=null,u(false),i();},zs)),(t==="running"||t==="prompting")&&v();},[t,S,v,i]),Fr.useEffect(()=>v,[v]),{state:t,fork:r,events:n,error:o,isOpen:S,open:f,close:E,submit:a,undo:c,adoptRunningFork:$}}function Mr(){let{apiKey:e,userId:t,userHash:r,baseUrl:n,previewSession:o,setSlotFork:s,clearSlotFork:i,skipAnimationForSlot:a,trackForkActivity:c,recordForkActivityEvent:y}=we(),[S,u]=Fr.useState("idle"),[m,I]=Fr.useState(null),[v,f]=Fr.useState([]),[E,$]=Fr.useState(null),F=Fr.useRef(null),h=Fr.useCallback(()=>{u("prompting"),f([]),$(null),I(null);},[]),N=Fr.useCallback(()=>{u("idle"),F.current&&(F.current.close(),F.current=null);},[]);Fr.useEffect(()=>{o&&o.target.kind==="slot"&&u(C=>C==="idle"?"prompting":C);},[o?.preview_session_id,o?.target.kind]);let D=Fr.useCallback(async(C,M,j,k)=>{try{u("running"),f([]),$(null),I(null);let d;if(o){let A=k?.forkId??o.fork_id??void 0,b=await fetch(`${n}/api/v1/preview/${encodeURIComponent(o.preview_session_id)}/author`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...ne()},body:JSON.stringify({prompt:C,...M?{slot_id:M}:{},...A&&!k?.forceNew?{fork_id:A}:{},...k?.forceNew?{force_new:!0}:{}})});if(!b.ok){let te=await b.json().catch(()=>({}));throw new Error(te.error||`API error: ${b.status}`)}let P=await b.json();P.container_id&&Ge(P.container_id,P.container_name),mt(P.fork_id),d=await(await fetch(`${n}/api/v1/forks/${P.fork_id}`,{headers:{Authorization:`Bearer ${e}`,...ne()}})).json();}else if(k?.forkId){let A={prompt:C};t&&(A.userId=t),r&&(A.userHash=r);let b=await fetch(`${n}/api/v1/forks/${encodeURIComponent(k.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(A)});if(!b.ok){let P=await b.json().catch(()=>({}));throw new Error(P.error||`API error: ${b.status}`)}d=await b.json();}else {let A={userId:t,prompt:C};M&&(A.slotId=M),j&&(A.containerId=j),r&&(A.userHash=r),k?.forceNew&&(A.force_new=!0);let b=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(A)});if(!b.ok){let P=await b.json().catch(()=>({}));throw new Error(P.error||`API error: ${b.status}`)}d=await b.json();}I(d);let w=M??d.slotId;w&&c(d,{targetKind:"slot",targetId:w});let H=new URLSearchParams({key:e});o?(H.set("previewSessionId",o.preview_session_id),H.set("previewForkId",d.id)):t&&H.set("userId",t),r&&H.set("userHash",r);let R=new EventSource(`${n}/api/v1/forks/${d.id}/events?${H.toString()}`);F.current=R,R.onmessage=A=>{try{let b=JSON.parse(A.data);if(y(d.id,b),f(P=>[...P,b]),b.type==="complete"){let P=b.data,G={...d,status:"complete",bundleUrl:P.bundleUrl,summary:P.summary,revealPending:!0,completedAt:new Date().toISOString()};I(G),u("complete"),M&&P.bundleUrl&&s(M,G),R.close();}else if(b.type==="error"){let P=b.data;$(P.error||"Unknown error"),u("error"),R.close();}}catch{}},R.onerror=()=>{let A={Authorization:`Bearer ${e}`,...ne()};!o&&t&&(A["X-Fork-User-Id"]=t),!o&&r&&(A["X-Fork-User-Hash"]=r),fetch(`${n}/api/v1/forks/${d.id}`,{headers:A}).then(b=>b.json()).then(b=>{I(b),b.status==="complete"?(u("complete"),M&&b.bundleUrl&&s(M,{...b,revealPending:!0})):b.status==="error"&&($(b.error||"Fork generation failed"),u("error"));}).catch(()=>{$("Connection lost"),u("error");}),R.close();};}catch(d){$(d.message),u("error");}},[e,n,o,y,s,c,r,t]),U=Fr.useCallback(async C=>{try{let M={Authorization:`Bearer ${e}`,...ne()};!o&&t&&(M["X-Fork-User-Id"]=t),!o&&r&&(M["X-Fork-User-Hash"]=r);let j=await fetch(`${n}/api/v1/forks/${C}`,{headers:M});if(!j.ok)return;let k=await j.json();if(k.slotId&&c(k,{targetKind:"slot",targetId:k.slotId}),k.status==="complete"){u("complete"),I(k),$(null),f([]);return}if(k.status==="error"){u("error"),I(k),$(k.error||"Fork generation failed"),f([]);return}if(k.status!=="pending"&&k.status!=="running"&&k.status!=="building")return;u("running"),I(k),$(null),f([]);let d=new URLSearchParams({key:e});o?(d.set("previewSessionId",o.preview_session_id),d.set("previewForkId",k.id)):t&&d.set("userId",t),r&&d.set("userHash",r);let w=new EventSource(`${n}/api/v1/forks/${k.id}/events?${d.toString()}`);F.current&&F.current.close(),F.current=w;let H=k.slotId;w.onmessage=R=>{try{let A=JSON.parse(R.data);if(y(k.id,A),f(b=>[...b,A]),A.type==="complete"){let b=A.data,P={...k,status:"complete",bundleUrl:b.bundleUrl,summary:b.summary,revealPending:!0,completedAt:new Date().toISOString()};I(P),u("complete"),H&&b.bundleUrl&&s(H,P),w.close();}else if(A.type==="error"){let b=A.data;$(b.error||"Unknown error"),u("error"),w.close();}}catch{}},w.onerror=()=>{w.close();};}catch{}},[e,n,o,y,s,c,r,t]),O=Fr.useCallback(async C=>{try{let M={userId:t,slotId:C};r&&(M.userHash=r);let j=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(M)});if(!j.ok){let d=await j.json().catch(()=>({}));throw new Error(d.error||`API error: ${j.status}`)}let k=await j.json();return a(C),k.removed?(i(C),I(null),u("prompting")):k.fork&&(s(C,k.fork),I(k.fork)),k}catch(M){throw $(M.message),M}},[e,t,r,n,i,s]);return {state:S,fork:m,events:v,error:E,open:h,close:N,startFork:D,undoFork:O,adoptRunningFork:U}}var qs=0;function Kn(){let{state:e,fork:t,events:r,error:n,open:o,close:s,startFork:i,undoFork:a,adoptRunningFork:c}=Mr(),[y,S]=Fr.useState(false),u=Fr.useRef(null),m=Fr.useRef(e),I=Fr.useCallback(()=>{u.current!==null&&(clearTimeout(u.current),u.current=null);},[]),v=Fr.useCallback(()=>{I(),S(true),o();},[I,o]),f=Fr.useCallback(()=>{I(),S(false),s();},[I,s]),E=Fr.useCallback(async $=>{I(),S(true),await c($);},[c,I]);return Fr.useEffect(()=>{let $=m.current;m.current=e,e==="complete"&&$==="running"&&y&&(I(),u.current=setTimeout(()=>{u.current=null,S(false),s();},qs)),(e==="running"||e==="prompting")&&I();},[e,y,I,s]),Fr.useEffect(()=>I,[I]),{state:e,fork:t,events:r,error:n,isOpen:y,open:v,close:f,submit:i,undo:a,adoptRunningFork:E}}var Xs=new Set(["pending","running","building"]);function Hr(e){let t=On(e),r=Kn(),n=Nn(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:s,userId:i,userHash:a,appId:c,activitySummary:y,forkActivities:S,markForkActivitySeen:u}=we(),m=t.type==="slot"?r:n,I=t.type==="slot"?"slot":"boundary",v=t.id,f=t.title,E=t.type==="slot"?"slot":"module",$=S.find(U=>U.targetKind===E&&U.targetId===t.id&&Xs.has(U.status)),F=S.find(U=>U.targetKind===E&&U.targetId===t.id&&U.status==="complete"&&U.unread),h=Fr.useCallback(()=>{u();let U=$??F;if(U){m.adoptRunningFork(U.id);return}m.open();},[m,u,$,F]),N=Fr.useCallback((U,O,C,M)=>t.type==="slot"?r.submit(U,O??t.id,C,M):n.submit(U,C,M),[n,r,t]),D=Fr.useCallback(U=>t.type==="slot"?r.undo(U??t.id):n.undo(),[n,r,t]);return {...m,open:h,target:t,targetId:v,targetLabel:f,historyMode:I,submit:N,undo:D,buttonProps:{onClick:h,hasNotification:y.unreadCompletedCount>0,activity:y},panelProps:{state:m.state,fork:m.fork,events:m.events,error:m.error,...t.type==="slot"?{slotId:v,targetLabel:f,historyMode:I}:{targetId:v,targetLabel:f,historyMode:I},onSubmit:N,onUndo:D,onClose:m.close,baseUrl:o,apiKey:s,userId:i,userHash:a,appId:c}}}function Rt(e){let{embedded:t,completeVariant:r}=e,n=Hr(e);return t?So.jsx(Zt,{...n.panelProps,embedded:true,completeVariant:r}):n.isOpen?So.jsx(Zt,{...n.panelProps,completeVariant:r}):So.jsx(_r,{...n.buttonProps})}function Gs({boundaryId:e,title:t}){return So.jsx(Rt,{boundaryId:e,title:t})}function Ur(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 zn(e){let t=e.getBoundingClientRect(),r=e.cloneNode(true);r.setAttribute("data-fork-clone-overlay","true"),r.style.position="fixed",r.style.top=`${t.top}px`,r.style.left=`${t.left}px`,r.style.width=`${t.width}px`,r.style.height=`${t.height}px`,r.style.flex="none",r.style.minHeight="auto",r.style.zIndex="9998",r.style.pointerEvents="none",r.style.overflow="hidden";let n=getComputedStyle(e).backgroundColor;r.style.backgroundColor=n&&n!=="rgba(0, 0, 0, 0)"&&n!=="transparent"?n:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(r);let o=e.querySelectorAll("*"),s=r.querySelectorAll("*");for(let i=0;i<o.length;i+=1)o[i].scrollTop!==0&&(s[i].scrollTop=o[i].scrollTop),o[i].scrollLeft!==0&&(s[i].scrollLeft=o[i].scrollLeft);return r}function Br(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 s=getComputedStyle(n),i=parseFloat(s.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:i});}return t}function Wn(e,t){let r=[];for(let n of t)if(!(e.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)||r.some(i=>n.rect.top>=i.rect.top&&n.rect.left>=i.rect.left&&n.rect.right<=i.rect.right&&n.rect.bottom<=i.rect.bottom))){for(let i=r.length-1;i>=0;i-=1){let a=r[i];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(i,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Jn(e,t){let r=[];for(let n of e)if(!(t.find(i=>i.tag===n.tag&&i.className===n.className&&Math.abs(i.rect.top-n.rect.top)<20&&Math.abs(i.rect.left-n.rect.left)<20)||r.some(i=>n.rect.top>=i.rect.top&&n.rect.left>=i.rect.left&&n.rect.right<=i.rect.right&&n.rect.bottom<=i.rect.bottom))){for(let i=r.length-1;i>=0;i-=1){let a=r[i];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(i,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Vn(e,t,r,n,o){let s=Math.max(0,Math.min(o,r/2,n/2));return s===0?`M ${e} ${t} L ${e+r} ${t} L ${e+r} ${t+n} L ${e} ${t+n} Z`:[`M ${e+s} ${t}`,`L ${e+r-s} ${t}`,`A ${s} ${s} 0 0 1 ${e+r} ${t+s}`,`L ${e+r} ${t+n-s}`,`A ${s} ${s} 0 0 1 ${e+r-s} ${t+n}`,`L ${e+s} ${t+n}`,`A ${s} ${s} 0 0 1 ${e} ${t+n-s}`,`L ${e} ${t+s}`,`A ${s} ${s} 0 0 1 ${e+s} ${t}`,"Z"].join(" ")}function Nr(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 s=[];for(let S=0;S<e.length;S+=1){let{rect:u,borderRadius:m}=e[S],I=u.left-.5,v=u.top-.5,f=u.width+1,E=u.height+1,$=Math.min(m+.5,f/2,E/2),F=Vn(I,v,f,E,$),h=`__fork-glow-${S}`,N=document.createElementNS(t,"filter");N.setAttribute("id",h),N.setAttribute("x","-100%"),N.setAttribute("y","-100%"),N.setAttribute("width","300%"),N.setAttribute("height","300%");let D=document.createElementNS(t,"feGaussianBlur");D.setAttribute("in","SourceGraphic"),D.setAttribute("stdDeviation","8"),N.appendChild(D),o.appendChild(N);let U=`__fork-mask-${S}`,O=document.createElementNS(t,"mask");O.setAttribute("id",U),O.setAttribute("maskUnits","userSpaceOnUse"),O.setAttribute("x",String(I-200)),O.setAttribute("y",String(v-200)),O.setAttribute("width",String(f+400)),O.setAttribute("height",String(E+400));let C=document.createElementNS(t,"rect");C.setAttribute("x",String(I-200)),C.setAttribute("y",String(v-200)),C.setAttribute("width",String(f+400)),C.setAttribute("height",String(E+400)),C.setAttribute("fill","white"),O.appendChild(C);let M=document.createElementNS(t,"path");M.setAttribute("d",F),M.setAttribute("fill","black"),O.appendChild(M),o.appendChild(O);let j=document.createElementNS(t,"g");j.setAttribute("mask",`url(#${U})`),j.setAttribute("opacity","0");let k=document.createElementNS(t,"g");k.setAttribute("filter",`url(#${h})`);let d=document.createElementNS(t,"path");d.setAttribute("d",F),d.setAttribute("fill","none"),d.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),d.setAttribute("stroke-width","6"),d.setAttribute("stroke-linecap","round"),k.appendChild(d),j.appendChild(k),n.appendChild(j);let w=document.createElementNS(t,"path");w.setAttribute("d",F),w.setAttribute("fill","none"),w.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),w.setAttribute("stroke-width","2"),w.setAttribute("stroke-linecap","round"),w.setAttribute("opacity","0"),n.appendChild(w),s.push(d,w),d.__group=j;}r.appendChild(n),document.body.appendChild(r);let i=[];for(let S=0;S<s.length;S+=2){let u=s[S],m=s[S+1],I=u.__group;if(!I)continue;let v=m.getTotalLength(),f=u.getTotalLength();if(v<=0)continue;let E=v*.35;m.setAttribute("stroke-dasharray",`${E} ${v-E}`),m.setAttribute("stroke-dashoffset","0"),i.push(m.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 $=f*.35;u.setAttribute("stroke-dasharray",`${$} ${f-$}`),u.setAttribute("stroke-dashoffset","0"),i.push(u.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*f,offset:.06},{strokeDashoffset:-2*f,offset:.92},{strokeDashoffset:-2.25*f,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),i.push(I.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,c=()=>{if(a)return;a=true,clearTimeout(y);for(let u of i)try{u.cancel();}catch{}let S=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});S.onfinish=()=>r.remove(),window.removeEventListener("click",c);},y=setTimeout(c,14500);return setTimeout(()=>{a||window.addEventListener("click",c);},500),c}function qn(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"),s=document.createElementNS(t,"filter");s.setAttribute("id","__fork-removed-shadow"),s.setAttribute("x","-10%"),s.setAttribute("y","-10%"),s.setAttribute("width","120%"),s.setAttribute("height","120%");let i=document.createElementNS(t,"feDropShadow");i.setAttribute("dx","0"),i.setAttribute("dy","1"),i.setAttribute("stdDeviation","2"),i.setAttribute("flood-color","rgba(0,0,0,0.15)"),s.appendChild(i),o.appendChild(s),n.appendChild(o);for(let{rect:a,borderRadius:c}of e){let y=document.createElementNS(t,"path");y.setAttribute("d",Vn(a.left,a.top,a.width,a.height,c)),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 Yn(e,t){if(Qs(t.selector))return Gn(e,t);let n=Gn(e,t);if(n)return n;try{let s=document.querySelector(t.selector);if(s instanceof HTMLElement&&s!==e&&e.contains(s))return s}catch{}if(Xn(t.selector))try{let s=e.querySelector(t.selector);if(s instanceof HTMLElement&&s!==e)return s}catch{}if(t.textHint){let s=t.textHint.trim();if(s){let i=jr(e,S=>S===s);if(i)return i;let a=s.toLowerCase(),c=jr(e,S=>S.toLowerCase()===a);if(c)return c;let y=jr(e,S=>S.toLowerCase().includes(a));if(y)return y}}let o=Zs(t.selector);if(o&&o!==t.selector&&Xn(o))try{let s=e.querySelector(o);if(s instanceof HTMLElement&&s!==e)return s}catch{}return null}function Xn(e){let t=e.split(/\s+|>|~|\+/),r=t[t.length-1]??"";return /[#\[]|:not\(|:nth-/.test(r)}function Gn(e,t){let r=Array.from(e.querySelectorAll("[data-fork-new]"));if(r.length===0)return null;let n=Dr(t.label),o=Dr(t.textHint);return r.find(i=>{let a=Dr(i.getAttribute("data-fork-new"));return !!a&&(a===n||a===o)})??null}function Qs(e){return e.trim()==="[data-fork-new]"}function Dr(e){return e?.trim().replace(/\s+/g," ").toLowerCase()||null}function Zs(e){return e.replace(/\[class[\*~|^$]?=("[^"]*"|'[^']*'|[^\]]+)\]/g,"").replace(/\.[A-Za-z_][\w-]*/g,"").replace(/\s+/g," ").trim()}function jr(e,t){let r=null,n=1/0,o=e.querySelectorAll("*");for(let s of o){let i=s.textContent?.trim();if(!i||!t(i))continue;let a=s.getBoundingClientRect();if(a.width<4||a.height<4)continue;let c=a.width*a.height;c<n&&(r=s,n=c);}return r}var Kr=2147483600,ei=1600,ti=3e4,ri=300,je=10;function ni(e){let r=getComputedStyle(e).borderTopLeftRadius;if(!r)return 4;if(r.endsWith("%")){let i=parseFloat(r);if(!Number.isFinite(i)||i<=0)return 4;let a=e.getBoundingClientRect(),c=Math.min(a.width,a.height);return Math.max(4,i/100*c)}let n=parseFloat(r);if(!Number.isFinite(n)||n<=0)return 4;let o=e.getBoundingClientRect(),s=Math.min(o.width,o.height)/2;return n>=s?s:Math.min(n,16)}function oi(e,t,r,n){let s=window.innerWidth,i=window.innerHeight,a=e;a==="top"&&t.top<n+je+8?a="bottom":a==="bottom"&&i-t.bottom<n+je+8?a="top":a==="left"&&t.left<r+je+8?a="right":a==="right"&&s-t.right<r+je+8&&(a="left");let c=0,y=0;return a==="top"?(c=t.top-n-je,y=t.left+t.width/2-r/2):a==="bottom"?(c=t.bottom+je,y=t.left+t.width/2-r/2):a==="left"?(c=t.top+t.height/2-n/2,y=t.left-r-je):(c=t.top+t.height/2-n/2,y=t.right+je),y=Math.max(8,Math.min(y,s-r-8)),c=Math.max(8,Math.min(c,i-n-8)),{top:c,left:y,placement:a}}function si(e){let t=document.createElement("div");t.setAttribute("data-fork-highlight-outline","true"),t.style.cssText=["position:fixed","pointer-events:none",`z-index:${Kr}`,"border:1.5px solid rgba(59,130,246,0.85)","box-sizing:border-box","opacity:0","transition:opacity 200ms ease-out"].join(";");let r=document.createElement("div");r.setAttribute("data-fork-highlight-glow","true"),r.style.cssText=["position:fixed","pointer-events:none",`z-index:${Kr-1}`,"box-sizing:border-box","border:1px solid rgba(59,130,246,0.36)","box-shadow:0 0 0 4px rgba(59,130,246,0.16), 0 0 18px 2px rgba(59,130,246,0.31)","opacity:0","transition:opacity 200ms ease-out"].join(";");let n=document.createElement("div");return n.setAttribute("data-fork-highlight-tooltip","true"),n.style.cssText=["position:fixed","pointer-events:none",`z-index:${Kr+1}`,"padding:6px 10px","font:500 12px/1.2 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif","color:#ffffff","background:linear-gradient(135deg,#64748b,#475569)","border-radius:999px","box-shadow:0 4px 14px rgba(71,85,105,0.31),0 1px 2px rgba(0,0,0,0.1)","white-space:nowrap","opacity:0","transform:translateY(-2px)","transition:opacity 200ms ease-out, transform 200ms ease-out"].join(";"),n.textContent=`New: ${e}`,{outline:t,glow:r,tooltip:n}}function ii(){if(document.getElementById("__fork-highlight-keyframes"))return;let e=document.createElement("style");e.id="__fork-highlight-keyframes",e.textContent=`
|
|
58
|
+
`}),eo.jsxs("div",{className:"__fork-panel",style:Gn,children:[eo.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:[eo.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:[eo.jsx("span",{onDoubleClick:async c=>{if(c.stopPropagation(),!ke&&confirm("Kill all forks in this container?")){Se(true);try{let P=await we();`${P?.deleted??0}`,g([]),x(null),J(!1),v("");}catch(P){console.error("[Fork] Reset failed:",P);}finally{Se(false);}}},style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:4,margin:-4,cursor:"pointer",flexShrink:0},children:eo.jsx(Ut,{style:{width:16,height:16,color:"#111827",pointerEvents:"none"}})}),e==="running"?eo.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:qn}):Ue.length===0&&!ye?eo.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:"Fork"}):ye?eo.jsxs("div",{ref:Mt,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[eo.jsxs("button",{type:"button",onClick:()=>{ze(c=>!c);},onMouseEnter:()=>xt(true),onMouseLeave:()=>xt(false),"aria-haspopup":"menu","aria-expanded":$e,style:{display:"inline-flex",alignItems:"center",gap:4,padding:"3px 6px",border:"1px solid transparent",borderRadius:6,background:qt||$e?"#f3f4f6":"transparent",fontSize:13,fontWeight:600,color:"#111827",fontFamily:"inherit",cursor:"pointer",maxWidth:180,minWidth:0,transition:"background-color 0.12s"},children:[eo.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:Kr}),eo.jsx(lucideReact.ChevronDown,{style:{width:12,height:12,color:"#6b7280",flexShrink:0,transform:$e?"rotate(180deg)":void 0,transition:"transform 0.15s"}})]}),$e&&eo.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:[Ue.map(c=>{let P=c.id===j,N=Xt===c.id,de=ue===c.id;return eo.jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>Oe(c.id),onMouseLeave:()=>Oe(null),onClick:()=>{c.id!==j&&Xn(c.id);},disabled:!!ue,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:N?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:ue?"default":"pointer",textAlign:"left",fontWeight:P?600:400,opacity:ue&&!de?.55:1},children:[eo.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:P&&eo.jsx(lucideReact.Check,{style:{width:12,height:12}})}),eo.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:de?"Switching...":c.name})]},c.id)}),eo.jsx("div",{style:{height:1,background:"#e5e7eb",margin:"4px 0"}}),et?eo.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"4px 4px"},children:[eo.jsx("input",{ref:fe,type:"text",value:Me,placeholder:"Container name",disabled:ue==="__new__",onChange:c=>be(c.target.value),onKeyDown:c=>{c.key==="Enter"?(c.preventDefault(),Nr(Me)):c.key==="Escape"&&(c.preventDefault(),c.stopPropagation(),tt(false),be(""));},style:{flex:1,minWidth:0,padding:"5px 8px",border:"1px solid #d1d5db",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",background:"#ffffff",outline:"none"},onFocus:c=>{c.currentTarget.style.borderColor="#111827",c.currentTarget.style.boxShadow="0 0 0 2px rgba(17,24,39,0.15)";},onBlur:c=>{c.currentTarget.style.borderColor="#d1d5db",c.currentTarget.style.boxShadow="none";}}),eo.jsx("button",{type:"button",onClick:()=>{Nr(Me);},disabled:!Me.trim()||ue==="__new__",title:"Create",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:26,height:26,border:"none",borderRadius:4,background:!Me.trim()||ue==="__new__"?"#e5e7eb":"#111827",color:!Me.trim()||ue==="__new__"?"#9ca3af":"#ffffff",cursor:!Me.trim()||ue==="__new__"?"default":"pointer",flexShrink:0},children:ue==="__new__"?eo.jsx("span",{style:{width:10,height:10,border:"1.5px solid currentColor",borderTopColor:"transparent",borderRadius:"50%",animation:"__fork-spin 0.7s linear infinite"}}):eo.jsx(lucideReact.Check,{style:{width:12,height:12}})})]}):eo.jsx("button",{type:"button",role:"menuitem",onMouseEnter:()=>At(true),onMouseLeave:()=>At(false),onClick:()=>{ue||(Fe(null),be(""),tt(true));},disabled:!!ue,style:{display:"flex",alignItems:"center",width:"100%",padding:"6px 8px",border:"none",background:Gt?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:ue?"default":"pointer",textAlign:"left",opacity:ue&&ue!=="__new__"?.55:1},children:"+ New container"}),at&&eo.jsx("div",{style:{padding:"6px 8px",fontSize:11,lineHeight:1.35,color:"#b91c1c"},children:at})]})]}):eo.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:Kr}),e==="running"&&eo.jsx("span",{title:Je?`Estimated ~${Je} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:Je?"#111827":"#9ca3af",backgroundColor:Je?"rgba(17, 24, 39, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:Je?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:Je?`~${Je}m`:"~ m"})]}),eo.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[Be&&eo.jsx("button",{type:"button",role:"switch","aria-checked":!ne,"aria-label":ne?"Turn Fork back on":"Turn Fork off",title:ne?"Fork is off \u2014 you're seeing the original app. Turn it back on. Only affects you.":"Turn Fork off to see the original app. Only affects you.",onClick:()=>{Ie(!ne);},onMouseEnter:()=>rt(true),onMouseLeave:()=>rt(false),style:{position:"relative",width:26,height:15,borderRadius:999,border:"none",padding:0,marginRight:6,flexShrink:0,cursor:"pointer",backgroundColor:ne?Ee?"#9ca3af":"#d1d5db":Ee?"#374151":"#111827",transition:"background-color 0.18s ease",outline:"none",boxSizing:"border-box"},children:eo.jsx("span",{"aria-hidden":true,style:{position:"absolute",top:2,left:ne?2:13,width:11,height:11,borderRadius:"50%",backgroundColor:"#ffffff",boxShadow:"0 1px 2px rgba(15, 23, 42, 0.25)",transition:"left 0.18s cubic-bezier(0.16, 1, 0.3, 1)"}})}),!C&&eo.jsxs(eo.Fragment,{children:[Lr&&eo.jsx("button",{onClick:xe?Vn:Wn,onMouseEnter:()=>M(true),onMouseLeave:()=>M(false),title:xe?"Redock to sidebar":"Pop out into window",style:{padding:6,borderRadius:6,color:T?"#4b5563":"#9ca3af",backgroundColor:T?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:xe?eo.jsx(lucideReact.PictureInPicture,{style:{width:16,height:16}}):eo.jsx(lucideReact.PictureInPicture2,{style:{width:16,height:16}})}),eo.jsx("button",{onClick:Dr,onMouseEnter:()=>F(true),onMouseLeave:()=>F(false),style:{padding:6,borderRadius:6,color:u?"#4b5563":"#9ca3af",backgroundColor:u?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:eo.jsx(lucideReact.X,{style:{width:16,height:16}})})]})]})]}),eo.jsxs("div",{ref:oe,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[(p||K)&&eo.jsxs("div",{style:{padding:"10px 12px 6px 12px",display:"flex",alignItems:"center",gap:8,borderBottom:"1px solid #f3f4f6"},children:[eo.jsx("button",{onClick:()=>{x(null),J(false),z.current=false;},style:{fontSize:12,color:"#374151",background:"transparent",border:"none",padding:"2px 4px",cursor:"pointer",display:"inline-flex",alignItems:"center",gap:4},title:"Back to all forks",children:"\u2190 All forks"}),(()=>{let P=(p?Ve.find(N=>N.id===p)?.targetId:null)??nt;return P?eo.jsxs("span",{style:{fontSize:11,color:"#9ca3af",fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, "Liberation Mono", "Courier New", monospace',whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1},title:`Forking ${P}`,children:["Forking ",eo.jsx("span",{style:{color:"#6b7280"},children:P})]}):null})()]}),!p&&!K&&eo.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[eo.jsx("div",{style:{padding:"12px 16px 10px 16px",borderBottom:"1px solid #f3f4f6"},children:eo.jsx("span",{style:{fontSize:12,fontWeight:600,color:"#111827"},children:"Forks"})}),Ve.length===0&&eo.jsx("div",{style:{padding:"24px 20px",textAlign:"center",fontSize:13,color:"#6b7280"},children:"No forks yet. Describe a feature below to start one."}),Ve.length>0&&eo.jsx("div",{style:{display:"flex",flexDirection:"column"},children:Ve.map(c=>{let P=c.summary||"Untitled fork";return eo.jsxs("button",{onClick:()=>{J(false),x(c.id);},style:{textAlign:"left",padding:"10px 16px",background:"#ffffff",border:"none",borderBottom:"1px solid #f3f4f6",cursor:"pointer",display:"flex",flexDirection:"column",gap:2},onMouseEnter:N=>N.currentTarget.style.background="#fafafa",onMouseLeave:N=>N.currentTarget.style.background="#ffffff",children:[eo.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[eo.jsx("span",{style:{fontSize:13,fontWeight:500,color:"#111827",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1},children:P}),eo.jsx("span",{style:{fontSize:11,color:"#9ca3af",flexShrink:0},children:us(c.updatedAt)})]}),eo.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:11,color:"#6b7280"},children:[eo.jsx("span",{style:{fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, "Liberation Mono", "Courier New", monospace',whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:c.targetId}),eo.jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),eo.jsxs("span",{children:[c.promptCount," prompt",c.promptCount===1?"":"s"]}),c.status==="running"||c.status==="building"?eo.jsxs(eo.Fragment,{children:[eo.jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),eo.jsx("span",{style:{color:"#111827"},children:"running"})]}):null]})]},c.id)})})]}),p&<.length>0&&eo.jsx("div",{style:{padding:"16px 16px 0 16px"},children:lt.map((c,P)=>eo.jsx("div",{style:{marginBottom:P<lt.length-1?10:0},children:c.type==="user"?eo.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexDirection:"row-reverse"},children:[eo.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:eo.jsx(lucideReact.User,{style:{width:13,height:13,color:"#6b7280"}})}),eo.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})]}):_==="item"&&P===lt.length-1?eo.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:12,padding:12,borderRadius:8,border:"1px solid #e4e4e7",background:"#ffffff"},children:[eo.jsx("div",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,flexShrink:0,borderRadius:6,background:"#f4f4f5",color:"#0a0a0a"},children:eo.jsx(lucideReact.BadgeCheck,{style:{width:16,height:16}})}),eo.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,flex:1,minWidth:0},children:[eo.jsx("div",{style:{fontSize:13,fontWeight:500,color:"#0a0a0a",lineHeight:1.3},children:"Feature applied"}),eo.jsx("div",{style:{fontSize:13,color:"#71717a",lineHeight:1.4},children:c.text})]}),b&&e!=="running"&&eo.jsx("button",{onClick:N=>{N.stopPropagation(),Br();},disabled:re,style:{padding:"4px 10px",fontSize:12,fontWeight:500,borderRadius:6,border:"1px solid #e4e4e7",background:"#ffffff",color:"#0a0a0a",cursor:re?"default":"pointer",opacity:re?.4:1,height:28,flexShrink:0},children:"Undo"})]}):eo.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[eo.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#f0fdf4",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:eo.jsx(lucideReact.Check,{style:{width:13,height:13,color:"#9ca3af"}})}),eo.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:[eo.jsx("span",{style:{flex:1},children:c.text}),b&&P===lt.length-1&&e!=="running"&&eo.jsxs("button",{onClick:N=>{N.stopPropagation(),Br();},onMouseEnter:()=>q(P),onMouseLeave:()=>q(null),disabled:re,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:Z===P?"rgba(0,0,0,0.06)":"transparent",color:Z===P?"#6b7280":"#d1d5db",cursor:re?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:re?.4:1,flexShrink:0},children:[eo.jsx(lucideReact.Undo2,{style:{width:12,height:12}}),Z===P&&eo.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"})]})]})]})},P))}),e==="running"&&(p||K)&&eo.jsx("div",{style:{padding:16},children:eo.jsxs("div",{onClick:()=>Q(!ae),style:{backgroundColor:"#1a1a2e",borderRadius:12,overflow:"hidden",cursor:"pointer",transition:"all 0.3s cubic-bezier(0.22, 1, 0.36, 1)"},children:[eo.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px"},children:[eo.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[eo.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:eo.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),eo.jsx(fs,{events:r})]}),eo.jsx("div",{style:{color:"#6b7280",flexShrink:0,marginLeft:8,transition:"transform 0.2s ease",transform:ae?"rotate(180deg)":"rotate(0deg)"},children:eo.jsx(lucideReact.ChevronDown,{style:{width:14,height:14}})})]}),eo.jsx("div",{style:{maxHeight:ae?320:0,opacity:ae?1:0,transition:"max-height 0.35s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.25s ease",overflow:"hidden"},children:eo.jsx("div",{style:{borderTop:"1px solid rgba(255,255,255,0.08)",maxHeight:320,overflowY:"auto"},children:eo.jsx(un,{events:r})})})]})}),e==="error"&&(p||K)&&eo.jsxs("div",{style:{padding:"20px 16px",textAlign:"center"},children:[eo.jsx("div",{style:{width:36,height:36,backgroundColor:"#fef2f2",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 10px auto"},children:eo.jsx(lucideReact.X,{style:{width:18,height:18,color:"#ef4444"}})}),eo.jsx("p",{style:{fontSize:12,color:"#6b7280",marginBottom:10,maxWidth:260,margin:"0 auto 10px auto"},children:n}),eo.jsxs("button",{onClick:()=>{let c=t?.prompt||Et.current;c&&d(c,nt);},onMouseEnter:()=>Y(true),onMouseLeave:()=>Y(false),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,color:"#111827",backgroundColor:H?"#e5e7eb":"#f3f4f6",border:"none",cursor:"pointer",transition:"background-color 0.15s",fontFamily:"inherit"},children:[eo.jsx(lucideReact.RotateCcw,{style:{width:12,height:12}})," Try Again"]})]})]}),e!=="running"&&eo.jsx("div",{style:{padding:"8px 12px 12px 12px",borderTop:"1px solid rgba(229, 231, 235, 0.6)",flexShrink:0},children:eo.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,borderRadius:12,padding:"8px 8px 8px 12px",background:"rgba(0, 0, 0, 0.04)",border:"1px solid rgba(0, 0, 0, 0.06)"},children:[eo.jsx("textarea",{ref:te,value:k,onChange:c=>{v(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(),Ur()),c.key==="Escape"&&!C&&Dr();},placeholder:p?"Iterate on this feature...":"Start building a new Fork...",rows:1,style:{flex:1,backgroundColor:"transparent",fontSize:13,color:"#111827",border:"none",outline:"none",padding:"0 4px 0 0",fontFamily:"inherit",resize:"none",lineHeight:1.5,maxHeight:160,overflow:"auto"}}),eo.jsx("button",{onClick:Ur,disabled:!k.trim(),onMouseEnter:()=>S(true),onMouseLeave:()=>S(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:k.trim()?1:.25,transform:I&&k.trim()?"scale(1.1)":"scale(1)",background:k.trim()?"#111827":"rgba(0,0,0,0.12)",border:"none",cursor:k.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:eo.jsx(lucideReact.ArrowUp,{style:{width:13,height:13}})})]})})]})]});return C?Zt:xe&&Ne?Zn.createPortal(Zt,Ne.document.body):eo.jsx(ps,{children:Zt})}function hn(e){if("target"in e&&e.target)return e.target;if("boundaryId"in e&&e.boundaryId)return {type:"boundary",id:e.boundaryId,title:e.title};if("slotId"in e&&e.slotId)return {type:"slot",id:e.slotId,title:e.title??e.slotLabel};throw new Error("Fork chat target requires either target, slotId, or boundaryId.")}function br(e){let{apiKey:t,userId:r,userHash:n,baseUrl:o,appId:s,adminContext:i,refreshModuleManifest:a,queueBoundaryAnimation:d,trackForkActivity:b,recordForkActivityEvent:m}=he(),[f,w]=cr.useState("idle"),[A,h]=cr.useState(null),[l,C]=cr.useState([]),[_,k]=cr.useState(null),v=cr.useRef(null),L=cr.useCallback(()=>{w("prompting"),C([]),k(null),h(null);},[]),D=cr.useCallback(()=>{w("idle"),v.current&&(v.current.close(),v.current=null);},[]),B=cr.useCallback(async($,O,y)=>{try{if(!s)throw new Error("ForkProvider requires appId for module boundary prompts.");w("running"),C([]),k(null),h(null);let u;if(y?.forkId){let M={prompt:$};r&&(M.userId=r),n&&(M.userHash=n);let I=await fetch(`${o}/api/v1/forks/${encodeURIComponent(y.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...ie()},body:JSON.stringify(M)});if(!I.ok){let S=await I.json().catch(()=>({}));throw new Error(S.error||`API error: ${I.status}`)}u=await I.json();}else {let M={userId:r,prompt:$,boundaryId:e,appId:s};O?M.containerId=O:i.isAdmin&&i.containerId&&(M.containerId=i.containerId),n&&(M.userHash=n),y?.forceNew&&(M.force_new=!0);let I=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...ie()},body:JSON.stringify(M)});if(!I.ok){let S=await I.json().catch(()=>({}));throw new Error(S.error||`API error: ${I.status}`)}u=await I.json();}h(u),b(u,{targetKind:"module",targetId:e});let F=new URLSearchParams({key:t});r&&F.set("userId",r),n&&F.set("userHash",n),i.isAdmin&&i.containerId&&F.set("containerId",i.containerId);let T=new EventSource(`${o}/api/v1/forks/${u.id}/events?${F.toString()}`);v.current=T,T.onmessage=M=>{try{let I=JSON.parse(M.data);if(m(u.id,I),C(S=>[...S,I]),I.type==="complete"){let S=I.data;d(e,u.id),a().catch(()=>{}).finally(()=>{let H={...u,status:"complete",moduleUrl:S.moduleUrl,cssUrls:S.cssUrls,summary:S.summary,completedAt:new Date().toISOString()};h(H),w("complete"),T.close();});}else if(I.type==="error"){let S=I.data;k(S.error||"Unknown error"),w("error"),T.close();}}catch{}},T.onerror=()=>{let M={Authorization:`Bearer ${t}`,...ie()};r&&(M["X-Fork-User-Id"]=r),n&&(M["X-Fork-User-Hash"]=n),fetch(`${o}/api/v1/forks/${u.id}`,{headers:M}).then(I=>I.json()).then(I=>{h(I),I.status==="complete"?(d(e,I.id),a().catch(()=>{}),w("complete")):I.status==="error"&&(k(I.error||"Fork generation failed"),w("error"));}).catch(()=>{k("Connection lost"),w("error");}),T.close();};}catch(u){k(u.message),w("error");}},[i.containerId,i.isAdmin,t,s,o,e,d,a,m,b,n,r]),U=cr.useCallback(async $=>{try{let O={Authorization:`Bearer ${t}`,...ie()};r&&(O["X-Fork-User-Id"]=r),n&&(O["X-Fork-User-Hash"]=n);let y=await fetch(`${o}/api/v1/forks/${$}`,{headers:O});if(!y.ok)return;let u=await y.json(),F=u.boundaryId??e;if(b(u,{targetKind:"module",targetId:F}),u.status==="complete"){w("complete"),h(u),k(null),C([]);return}if(u.status==="error"){w("error"),h(u),k(u.error||"Fork generation failed"),C([]);return}if(u.status!=="pending"&&u.status!=="running"&&u.status!=="building")return;w("running"),h(u),k(null),C([]);let T=new URLSearchParams({key:t});r&&T.set("userId",r),n&&T.set("userHash",n),i.isAdmin&&i.containerId&&T.set("containerId",i.containerId);let M=new EventSource(`${o}/api/v1/forks/${u.id}/events?${T.toString()}`);v.current&&v.current.close(),v.current=M,M.onmessage=I=>{try{let S=JSON.parse(I.data);if(m(u.id,S),C(H=>[...H,S]),S.type==="complete"){let H=S.data;d(e,u.id),a().catch(()=>{}).finally(()=>{let Y={...u,status:"complete",moduleUrl:H.moduleUrl,cssUrls:H.cssUrls,summary:H.summary,completedAt:new Date().toISOString()};h(Y),w("complete"),M.close();});}else if(S.type==="error"){let H=S.data;k(H.error||"Unknown error"),w("error"),M.close();}}catch{}},M.onerror=()=>{M.close();};}catch{}},[i.containerId,i.isAdmin,t,o,e,d,m,a,b,n,r]),R=cr.useCallback(async()=>{try{if(!s)throw new Error("ForkProvider requires appId for boundary undo.");let $={userId:r,boundaryId:e,appId:s};n&&($.userHash=n);let O=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify($)});if(!O.ok){let u=await O.json().catch(()=>({}));throw new Error(u.error||`API error: ${O.status}`)}let y=await O.json();return await a().catch(()=>{}),y.removed?(h(null),w("prompting")):y.fork&&(h(y.fork),w("complete")),y}catch($){throw k($.message),$}},[t,s,o,e,a,n,r]);return {state:f,fork:A,events:l,error:_,open:L,close:D,startFork:B,undoFork:R,adoptRunningFork:U}}var hs=0;function bn(e){let{state:t,fork:r,events:n,error:o,open:s,close:i,startFork:a,undoFork:d,adoptRunningFork:b}=br(e),[m,f]=cr.useState(false),w=cr.useRef(null),A=cr.useRef(t),h=cr.useCallback(()=>{w.current!==null&&(clearTimeout(w.current),w.current=null);},[]),l=cr.useCallback(()=>{h(),f(true),s();},[h,s]),C=cr.useCallback(()=>{h(),f(false),i();},[h,i]),_=cr.useCallback(async k=>{h(),f(true),await b(k);},[b,h]);return cr.useEffect(()=>{let k=A.current;A.current=t,t==="complete"&&k==="running"&&m&&(h(),w.current=setTimeout(()=>{w.current=null,f(false),i();},hs)),(t==="running"||t==="prompting")&&h();},[t,m,h,i]),cr.useEffect(()=>h,[h]),{state:t,fork:r,events:n,error:o,isOpen:m,open:l,close:C,submit:a,undo:d,adoptRunningFork:_}}function wr(){let{apiKey:e,userId:t,userHash:r,baseUrl:n,adminContext:o,setSlotFork:s,clearSlotFork:i,skipAnimationForSlot:a,trackForkActivity:d,recordForkActivityEvent:b}=he(),[m,f]=cr.useState("idle"),[w,A]=cr.useState(null),[h,l]=cr.useState([]),[C,_]=cr.useState(null),k=cr.useRef(null),v=cr.useCallback(()=>{f("prompting"),l([]),_(null),A(null);},[]),L=cr.useCallback(()=>{f("idle"),k.current&&(k.current.close(),k.current=null);},[]),D=cr.useCallback(async(R,$,O,y)=>{try{f("running"),l([]),_(null),A(null);let u;if(y?.forkId){let I={prompt:R};t&&(I.userId=t),r&&(I.userHash=r);let S=await fetch(`${n}/api/v1/forks/${encodeURIComponent(y.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...ie()},body:JSON.stringify(I)});if(!S.ok){let H=await S.json().catch(()=>({}));throw new Error(H.error||`API error: ${S.status}`)}u=await S.json();}else {let I={userId:t,prompt:R};$&&(I.slotId=$),O?I.containerId=O:o.isAdmin&&o.containerId&&(I.containerId=o.containerId),r&&(I.userHash=r),y?.forceNew&&(I.force_new=!0);let S=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...ie()},body:JSON.stringify(I)});if(!S.ok){let H=await S.json().catch(()=>({}));throw new Error(H.error||`API error: ${S.status}`)}u=await S.json();}A(u);let F=$??u.slotId;F&&d(u,{targetKind:"slot",targetId:F});let T=new URLSearchParams({key:e});t&&T.set("userId",t),r&&T.set("userHash",r),o.isAdmin&&o.containerId&&T.set("containerId",o.containerId);let M=new EventSource(`${n}/api/v1/forks/${u.id}/events?${T.toString()}`);k.current=M,M.onmessage=I=>{try{let S=JSON.parse(I.data);if(b(u.id,S),l(H=>[...H,S]),S.type==="complete"){let H=S.data,Y={...u,status:"complete",bundleUrl:H.bundleUrl,summary:H.summary,revealPending:!0,completedAt:new Date().toISOString()};A(Y),f("complete"),$&&H.bundleUrl&&s($,Y),M.close();}else if(S.type==="error"){let H=S.data;_(H.error||"Unknown error"),f("error"),M.close();}}catch{}},M.onerror=()=>{let I={Authorization:`Bearer ${e}`,...ie()};t&&(I["X-Fork-User-Id"]=t),r&&(I["X-Fork-User-Hash"]=r),fetch(`${n}/api/v1/forks/${u.id}`,{headers:I}).then(S=>S.json()).then(S=>{A(S),S.status==="complete"?(f("complete"),$&&S.bundleUrl&&s($,{...S,revealPending:!0})):S.status==="error"&&(_(S.error||"Fork generation failed"),f("error"));}).catch(()=>{_("Connection lost"),f("error");}),M.close();};}catch(u){_(u.message),f("error");}},[o.containerId,o.isAdmin,e,n,b,s,d,r,t]),B=cr.useCallback(async R=>{try{let $={Authorization:`Bearer ${e}`,...ie()};t&&($["X-Fork-User-Id"]=t),r&&($["X-Fork-User-Hash"]=r);let O=await fetch(`${n}/api/v1/forks/${R}`,{headers:$});if(!O.ok)return;let y=await O.json();if(y.slotId&&d(y,{targetKind:"slot",targetId:y.slotId}),y.status==="complete"){f("complete"),A(y),_(null),l([]);return}if(y.status==="error"){f("error"),A(y),_(y.error||"Fork generation failed"),l([]);return}if(y.status!=="pending"&&y.status!=="running"&&y.status!=="building")return;f("running"),A(y),_(null),l([]);let u=new URLSearchParams({key:e});t&&u.set("userId",t),r&&u.set("userHash",r),o.isAdmin&&o.containerId&&u.set("containerId",o.containerId);let F=new EventSource(`${n}/api/v1/forks/${y.id}/events?${u.toString()}`);k.current&&k.current.close(),k.current=F;let T=y.slotId;F.onmessage=M=>{try{let I=JSON.parse(M.data);if(b(y.id,I),l(S=>[...S,I]),I.type==="complete"){let S=I.data,H={...y,status:"complete",bundleUrl:S.bundleUrl,summary:S.summary,revealPending:!0,completedAt:new Date().toISOString()};A(H),f("complete"),T&&S.bundleUrl&&s(T,H),F.close();}else if(I.type==="error"){let S=I.data;_(S.error||"Unknown error"),f("error"),F.close();}}catch{}},F.onerror=()=>{F.close();};}catch{}},[o.containerId,o.isAdmin,e,n,b,s,d,r,t]),U=cr.useCallback(async R=>{try{let $={userId:t,slotId:R};r&&($.userHash=r);let O=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify($)});if(!O.ok){let u=await O.json().catch(()=>({}));throw new Error(u.error||`API error: ${O.status}`)}let y=await O.json();return a(R),y.removed?(i(R),A(null),f("prompting")):y.fork&&(s(R,y.fork),A(y.fork)),y}catch($){throw _($.message),$}},[e,t,r,n,i,s]);return {state:m,fork:w,events:h,error:C,open:v,close:L,startFork:D,undoFork:U,adoptRunningFork:B}}var bs=0;function Sn(){let{state:e,fork:t,events:r,error:n,open:o,close:s,startFork:i,undoFork:a,adoptRunningFork:d}=wr(),[b,m]=cr.useState(false),f=cr.useRef(null),w=cr.useRef(e),A=cr.useCallback(()=>{f.current!==null&&(clearTimeout(f.current),f.current=null);},[]),h=cr.useCallback(()=>{A(),m(true),o();},[A,o]),l=cr.useCallback(()=>{A(),m(false),s();},[A,s]),C=cr.useCallback(async _=>{A(),m(true),await d(_);},[d,A]);return cr.useEffect(()=>{let _=w.current;w.current=e,e==="complete"&&_==="running"&&b&&(A(),f.current=setTimeout(()=>{f.current=null,m(false),s();},bs)),(e==="running"||e==="prompting")&&A();},[e,b,A,s]),cr.useEffect(()=>A,[A]),{state:e,fork:t,events:r,error:n,isOpen:b,open:h,close:l,submit:i,undo:a,adoptRunningFork:C}}var ws=new Set(["pending","running","building"]);function Sr(e){let t=hn(e),r=Sn(),n=bn(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:s,userId:i,userHash:a,appId:d,activitySummary:b,forkActivities:m,markForkActivitySeen:f}=he(),w=t.type==="slot"?r:n,A=t.type==="slot"?"slot":"boundary",h=t.id,l=t.title,C=t.type==="slot"?"slot":"module",_=m.find(B=>B.targetKind===C&&B.targetId===t.id&&ws.has(B.status)),k=m.find(B=>B.targetKind===C&&B.targetId===t.id&&B.status==="complete"&&B.unread),v=cr.useCallback(()=>{f();let B=_??k;if(B){w.adoptRunningFork(B.id);return}w.open();},[w,f,_,k]),L=cr.useCallback((B,U,R,$)=>t.type==="slot"?r.submit(B,U??t.id,R,$):n.submit(B,R,$),[n,r,t]),D=cr.useCallback(B=>t.type==="slot"?r.undo(B??t.id):n.undo(),[n,r,t]);return {...w,open:v,target:t,targetId:h,targetLabel:l,historyMode:A,submit:L,undo:D,buttonProps:{onClick:v,hasNotification:b.unreadCompletedCount>0,activity:b},panelProps:{state:w.state,fork:w.fork,events:w.events,error:w.error,...t.type==="slot"?{slotId:h,targetLabel:l,historyMode:A}:{targetId:h,targetLabel:l,historyMode:A},onSubmit:L,onUndo:D,onClose:w.close,baseUrl:o,apiKey:s,userId:i,userHash:a,appId:d}}}function kt(e){let{embedded:t,completeVariant:r}=e,n=Sr(e);return t?eo.jsx(Dt,{...n.panelProps,embedded:true,completeVariant:r}):n.isOpen?eo.jsx(Dt,{...n.panelProps,completeVariant:r}):eo.jsx(gr,{...n.buttonProps})}function vs({boundaryId:e,title:t}){return eo.jsx(kt,{boundaryId:e,title:t})}function xr(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 Fn(e){let t=e.getBoundingClientRect(),r=e.cloneNode(true);r.setAttribute("data-fork-clone-overlay","true"),r.style.position="fixed",r.style.top=`${t.top}px`,r.style.left=`${t.left}px`,r.style.width=`${t.width}px`,r.style.height=`${t.height}px`,r.style.flex="none",r.style.minHeight="auto",r.style.zIndex="9998",r.style.pointerEvents="none",r.style.overflow="hidden";let n=getComputedStyle(e).backgroundColor;r.style.backgroundColor=n&&n!=="rgba(0, 0, 0, 0)"&&n!=="transparent"?n:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(r);let o=e.querySelectorAll("*"),s=r.querySelectorAll("*");for(let i=0;i<o.length;i+=1)o[i].scrollTop!==0&&(s[i].scrollTop=o[i].scrollTop),o[i].scrollLeft!==0&&(s[i].scrollLeft=o[i].scrollLeft);return r}function Ar(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 s=getComputedStyle(n),i=parseFloat(s.borderTopLeftRadius)||0;t.push({tag:n.tagName,className:n.className||"",text:(n.textContent||"").slice(0,50).trim(),rect:o,borderRadius:i});}return t}function xn(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(i=>n.rect.top>=i.rect.top&&n.rect.left>=i.rect.left&&n.rect.right<=i.rect.right&&n.rect.bottom<=i.rect.bottom))){for(let i=r.length-1;i>=0;i-=1){let a=r[i];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(i,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function An(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(i=>n.rect.top>=i.rect.top&&n.rect.left>=i.rect.left&&n.rect.right<=i.rect.right&&n.rect.bottom<=i.rect.bottom))){for(let i=r.length-1;i>=0;i-=1){let a=r[i];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(i,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function In(e,t,r,n,o){let s=Math.max(0,Math.min(o,r/2,n/2));return s===0?`M ${e} ${t} L ${e+r} ${t} L ${e+r} ${t+n} L ${e} ${t+n} Z`:[`M ${e+s} ${t}`,`L ${e+r-s} ${t}`,`A ${s} ${s} 0 0 1 ${e+r} ${t+s}`,`L ${e+r} ${t+n-s}`,`A ${s} ${s} 0 0 1 ${e+r-s} ${t+n}`,`L ${e+s} ${t+n}`,`A ${s} ${s} 0 0 1 ${e} ${t+n-s}`,`L ${e} ${t+s}`,`A ${s} ${s} 0 0 1 ${e+s} ${t}`,"Z"].join(" ")}function Ir(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 s=[];for(let m=0;m<e.length;m+=1){let{rect:f,borderRadius:w}=e[m],A=f.left-.5,h=f.top-.5,l=f.width+1,C=f.height+1,_=Math.min(w+.5,l/2,C/2),k=In(A,h,l,C,_),v=`__fork-glow-${m}`,L=document.createElementNS(t,"filter");L.setAttribute("id",v),L.setAttribute("x","-100%"),L.setAttribute("y","-100%"),L.setAttribute("width","300%"),L.setAttribute("height","300%");let D=document.createElementNS(t,"feGaussianBlur");D.setAttribute("in","SourceGraphic"),D.setAttribute("stdDeviation","8"),L.appendChild(D),o.appendChild(L);let B=`__fork-mask-${m}`,U=document.createElementNS(t,"mask");U.setAttribute("id",B),U.setAttribute("maskUnits","userSpaceOnUse"),U.setAttribute("x",String(A-200)),U.setAttribute("y",String(h-200)),U.setAttribute("width",String(l+400)),U.setAttribute("height",String(C+400));let R=document.createElementNS(t,"rect");R.setAttribute("x",String(A-200)),R.setAttribute("y",String(h-200)),R.setAttribute("width",String(l+400)),R.setAttribute("height",String(C+400)),R.setAttribute("fill","white"),U.appendChild(R);let $=document.createElementNS(t,"path");$.setAttribute("d",k),$.setAttribute("fill","black"),U.appendChild($),o.appendChild(U);let O=document.createElementNS(t,"g");O.setAttribute("mask",`url(#${B})`),O.setAttribute("opacity","0");let y=document.createElementNS(t,"g");y.setAttribute("filter",`url(#${v})`);let u=document.createElementNS(t,"path");u.setAttribute("d",k),u.setAttribute("fill","none"),u.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),u.setAttribute("stroke-width","6"),u.setAttribute("stroke-linecap","round"),y.appendChild(u),O.appendChild(y),n.appendChild(O);let F=document.createElementNS(t,"path");F.setAttribute("d",k),F.setAttribute("fill","none"),F.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),F.setAttribute("stroke-width","2"),F.setAttribute("stroke-linecap","round"),F.setAttribute("opacity","0"),n.appendChild(F),s.push(u,F),u.__group=O;}r.appendChild(n),document.body.appendChild(r);let i=[];for(let m=0;m<s.length;m+=2){let f=s[m],w=s[m+1],A=f.__group;if(!A)continue;let h=w.getTotalLength(),l=f.getTotalLength();if(h<=0)continue;let C=h*.35;w.setAttribute("stroke-dasharray",`${C} ${h-C}`),w.setAttribute("stroke-dashoffset","0"),i.push(w.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*h,opacity:.92,offset:.06},{strokeDashoffset:-2*h,opacity:.92,offset:.92},{strokeDashoffset:-2.25*h,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let _=l*.35;f.setAttribute("stroke-dasharray",`${_} ${l-_}`),f.setAttribute("stroke-dashoffset","0"),i.push(f.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*l,offset:.06},{strokeDashoffset:-2*l,offset:.92},{strokeDashoffset:-2.25*l,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"})),i.push(A.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(b);for(let f of i)try{f.cancel();}catch{}let m=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});m.onfinish=()=>r.remove(),window.removeEventListener("click",d);},b=setTimeout(d,14500);return setTimeout(()=>{a||window.addEventListener("click",d);},500),d}function Cn(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"),s=document.createElementNS(t,"filter");s.setAttribute("id","__fork-removed-shadow"),s.setAttribute("x","-10%"),s.setAttribute("y","-10%"),s.setAttribute("width","120%"),s.setAttribute("height","120%");let i=document.createElementNS(t,"feDropShadow");i.setAttribute("dx","0"),i.setAttribute("dy","1"),i.setAttribute("stdDeviation","2"),i.setAttribute("flood-color","rgba(0,0,0,0.15)"),s.appendChild(i),o.appendChild(s),n.appendChild(o);for(let{rect:a,borderRadius:d}of e){let b=document.createElementNS(t,"path");b.setAttribute("d",In(a.left,a.top,a.width,a.height,d)),b.setAttribute("fill","none"),b.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),b.setAttribute("stroke-width","1.5"),b.setAttribute("stroke-dasharray","8 4"),b.setAttribute("stroke-linecap","round"),b.setAttribute("filter","url(#__fork-removed-shadow)"),b.setAttribute("opacity","0"),n.appendChild(b),b.animate([{opacity:0,offset:0},{opacity:.6,offset:.08},{opacity:.05,offset:.45},{opacity:.6,offset:.85},{opacity:.05,offset:1}],{duration:5e3,easing:"ease-in-out",fill:"forwards"});}return r.appendChild(n),document.body.appendChild(r),r}function $n(e,t){if(Fs(t.selector))return En(e,t);let n=En(e,t);if(n)return n;try{let s=document.querySelector(t.selector);if(s instanceof HTMLElement&&s!==e&&e.contains(s))return s}catch{}if(Rn(t.selector))try{let s=e.querySelector(t.selector);if(s instanceof HTMLElement&&s!==e)return s}catch{}if(t.textHint){let s=t.textHint.trim();if(s){let i=Rr(e,m=>m===s);if(i)return i;let a=s.toLowerCase(),d=Rr(e,m=>m.toLowerCase()===a);if(d)return d;let b=Rr(e,m=>m.toLowerCase().includes(a));if(b)return b}}let o=xs(t.selector);if(o&&o!==t.selector&&Rn(o))try{let s=e.querySelector(o);if(s instanceof HTMLElement&&s!==e)return s}catch{}return null}function Rn(e){let t=e.split(/\s+|>|~|\+/),r=t[t.length-1]??"";return /[#\[]|:not\(|:nth-/.test(r)}function En(e,t){let r=Array.from(e.querySelectorAll("[data-fork-new]"));if(r.length===0)return null;let n=Cr(t.label),o=Cr(t.textHint);return r.find(i=>{let a=Cr(i.getAttribute("data-fork-new"));return !!a&&(a===n||a===o)})??null}function Fs(e){return e.trim()==="[data-fork-new]"}function Cr(e){return e?.trim().replace(/\s+/g," ").toLowerCase()||null}function xs(e){return e.replace(/\[class[\*~|^$]?=("[^"]*"|'[^']*'|[^\]]+)\]/g,"").replace(/\.[A-Za-z_][\w-]*/g,"").replace(/\s+/g," ").trim()}function Rr(e,t){let r=null,n=1/0,o=e.querySelectorAll("*");for(let s of o){let i=s.textContent?.trim();if(!i||!t(i))continue;let a=s.getBoundingClientRect();if(a.width<4||a.height<4)continue;let d=a.width*a.height;d<n&&(r=s,n=d);}return r}var Er=2147483600,As=1600,Is=3e4,Cs=300,Ke=10;function Rs(e){let r=getComputedStyle(e).borderTopLeftRadius;if(!r)return 4;if(r.endsWith("%")){let i=parseFloat(r);if(!Number.isFinite(i)||i<=0)return 4;let a=e.getBoundingClientRect(),d=Math.min(a.width,a.height);return Math.max(4,i/100*d)}let n=parseFloat(r);if(!Number.isFinite(n)||n<=0)return 4;let o=e.getBoundingClientRect(),s=Math.min(o.width,o.height)/2;return n>=s?s:Math.min(n,16)}function Es(e,t,r,n){let s=window.innerWidth,i=window.innerHeight,a=e;a==="top"&&t.top<n+Ke+8?a="bottom":a==="bottom"&&i-t.bottom<n+Ke+8?a="top":a==="left"&&t.left<r+Ke+8?a="right":a==="right"&&s-t.right<r+Ke+8&&(a="left");let d=0,b=0;return a==="top"?(d=t.top-n-Ke,b=t.left+t.width/2-r/2):a==="bottom"?(d=t.bottom+Ke,b=t.left+t.width/2-r/2):a==="left"?(d=t.top+t.height/2-n/2,b=t.left-r-Ke):(d=t.top+t.height/2-n/2,b=t.right+Ke),b=Math.max(8,Math.min(b,s-r-8)),d=Math.max(8,Math.min(d,i-n-8)),{top:d,left:b,placement:a}}function $s(e){let t=document.createElement("div");t.setAttribute("data-fork-highlight-outline","true"),t.style.cssText=["position:fixed","pointer-events:none",`z-index:${Er}`,"border:1.5px solid rgba(59,130,246,0.85)","box-sizing:border-box","opacity:0","transition:opacity 200ms ease-out"].join(";");let r=document.createElement("div");r.setAttribute("data-fork-highlight-glow","true"),r.style.cssText=["position:fixed","pointer-events:none",`z-index:${Er-1}`,"box-sizing:border-box","border:1px solid rgba(59,130,246,0.36)","box-shadow:0 0 0 4px rgba(59,130,246,0.16), 0 0 18px 2px rgba(59,130,246,0.31)","opacity:0","transition:opacity 200ms ease-out"].join(";");let n=document.createElement("div");return n.setAttribute("data-fork-highlight-tooltip","true"),n.style.cssText=["position:fixed","pointer-events:none",`z-index:${Er+1}`,"padding:6px 10px","font:500 12px/1.2 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif","color:#ffffff","background:linear-gradient(135deg,#64748b,#475569)","border-radius:999px","box-shadow:0 4px 14px rgba(71,85,105,0.31),0 1px 2px rgba(0,0,0,0.1)","white-space:nowrap","opacity:0","transform:translateY(-2px)","transition:opacity 200ms ease-out, transform 200ms ease-out"].join(";"),n.textContent=`New: ${e}`,{outline:t,glow:r,tooltip:n}}function Ts(){if(document.getElementById("__fork-highlight-keyframes"))return;let e=document.createElement("style");e.id="__fork-highlight-keyframes",e.textContent=`
|
|
60
59
|
@keyframes __fork-highlight-pulse {
|
|
61
60
|
0%, 100% { box-shadow: 0 0 0 3px rgba(59,130,246,0.11), 0 0 12px 1px rgba(59,130,246,0.22); }
|
|
62
61
|
50% { box-shadow: 0 0 0 6px rgba(59,130,246,0.25), 0 0 22px 4px rgba(59,130,246,0.49); }
|
|
63
62
|
}
|
|
64
|
-
`,document.head.appendChild(e);}function Qn(e,t,r="top"){ii();let{outline:n,glow:o,tooltip:s}=si(t),i=ni(e);n.style.borderRadius=`${i}px`,o.style.borderRadius=`${i+1}px`,o.style.animation=`__fork-highlight-pulse ${ei}ms ease-in-out infinite`,document.body.append(o,n,s);let a=()=>{let f=e.getBoundingClientRect();if(f.width===0&&f.height===0)return;n.style.top=`${f.top}px`,n.style.left=`${f.left}px`,n.style.width=`${f.width}px`,n.style.height=`${f.height}px`,o.style.top=`${f.top-1}px`,o.style.left=`${f.left-1}px`,o.style.width=`${f.width+2}px`,o.style.height=`${f.height+2}px`;let E=s.getBoundingClientRect(),$=E.width||s.offsetWidth||80,F=E.height||s.offsetHeight||26,h=oi(r,f,$,F);s.style.top=`${h.top}px`,s.style.left=`${h.left}px`;};a(),requestAnimationFrame(()=>{n.style.opacity="1",o.style.opacity="1",s.style.opacity="1",s.style.transform="translateY(0)",requestAnimationFrame(a);});let c=false,y=new ResizeObserver(a);y.observe(e);let S=()=>a(),u=()=>a();window.addEventListener("scroll",S,true),window.addEventListener("resize",u);let m=()=>{c||(c=true,clearTimeout(v),y.disconnect(),window.removeEventListener("scroll",S,true),window.removeEventListener("resize",u),window.removeEventListener("click",I,true),n.style.opacity="0",o.style.opacity="0",s.style.opacity="0",s.style.transform="translateY(-2px)",setTimeout(()=>{n.remove(),o.remove(),s.remove();},ri));},I=()=>m();setTimeout(()=>{c||window.addEventListener("click",I,{once:true,capture:true});},250);let v=setTimeout(m,ti);return m}var ai="fork:highlight:v1:seen";function Zn(e){return `${ai}:${e}`}function eo(e){if(typeof window>"u")return new Set;try{let t=window.localStorage.getItem(e);if(!t)return new Set;let r=JSON.parse(t);return Array.isArray(r)?new Set(r.filter(n=>typeof n=="string")):new Set}catch{return new Set}}function li(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify([...t].slice(-200)));}catch{}}var to=new Set;function ro(e,t,r){return `${r}::${e}:${t}`}function zr(e,t,r){let n=ro(e,t,r);return to.has(n)?true:eo(Zn(r)).has(`${e}:${t}`)}function no(e,t,r){let n=ro(e,t,r);to.add(n);let o=Zn(r),s=`${e}:${t}`,i=eo(o);i.has(s)||(i.add(s),li(o,i));}var Ct=new Map,Pt=new Map,Wr=new Map;function ui(e){for(let t of e)Pt.set(t,(Pt.get(t)??0)+1);}function di(e){if(!(typeof document>"u"))for(let t of e){let r=(Pt.get(t)??0)-1;if(r>0){Pt.set(t,r);continue}Pt.delete(t),Ct.delete(t);let n=document.querySelector(`link[data-fork-override-href="${CSS.escape(t)}"]`);n&&n.remove();}}function fi(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function so(e){let t=e.getBoundingClientRect();if(t.width<=0||t.height<=0)return false;let r=window.innerWidth||document.documentElement.clientWidth,n=window.innerHeight||document.documentElement.clientHeight;return t.bottom>0&&t.right>0&&t.top<n&&t.left<r}function io(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 pi(e){if(!e||typeof document>"u")return Promise.resolve();let t=Ct.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((s,i)=>{let a=()=>{r.removeEventListener("load",a),r.removeEventListener("error",c),s();},c=()=>{r.removeEventListener("load",a),r.removeEventListener("error",c),i(new Error(`Failed to load boundary stylesheet: ${e}`));};r.addEventListener("load",a,{once:true}),r.addEventListener("error",c,{once:true});});return Ct.set(e,o),o}let n=new Promise((o,s)=>{let i=document.createElement("link");i.rel="stylesheet",i.href=e,i.setAttribute("data-fork-override-href",e),i.onload=()=>o(),i.onerror=()=>{i.remove(),s(new Error(`Failed to load boundary stylesheet: ${e}`));},document.head.appendChild(i);}).catch(o=>{throw Ct.delete(e),o});return Ct.set(e,n),n}var Et=null;function gi(){if(Et)return Et;try{Et=new Function("u","return import(/*webpackIgnore:true*//*@vite-ignore*/u)");}catch{Et=e=>import(/*webpackIgnore:true*//*@vite-ignore*/e);}return Et}function mi(e){let t=Wr.get(e);if(t)return t;let r=gi()(e).catch(n=>{throw Wr.delete(e),n});return Wr.set(e,r),r}async function hi(e,t,r){if(e)try{await Promise.all(e.cssUrls.map(s=>pi(s)));let o=await mi(e.moduleUrl);return io(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 io(n,r)}function yi(e){function t(r){let{appId:n,moduleOverridesEnabled:o,moduleManifestReady:s,moduleManifestVersion:i,registerBoundary:a,getBoundaryOverride:c,consumeBoundaryAnimation:y,highlightScope:S}=we(),[u,m]=Fr.useState(null),[I,v]=Fr.useState(null),f=Fr.useRef(null),E=Fr.useRef(null),$=Fr.useRef(null),F=Fr.useRef(false),h=Fr.useRef(null),N=Fr.useRef(null),D=Fr.useRef(null),U=Fr.useRef(false),O=Fr.useRef(false),C=c(e.id),M=C?`override:${C.id}`:"original",j=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if(Fr.useEffect(()=>()=>{N.current&&(clearTimeout(N.current),N.current=null),h.current&&(h.current.remove(),h.current=null),D.current&&(D.current(),D.current=null);},[]),Fr.useEffect(()=>{a({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[n,a,e.id,e.exportName,j]),Fr.useEffect(()=>{let k=C?.cssUrls??[];if(k.length!==0)return ui(k),()=>di(k)},[C?.cssUrls.join("|")]),Fr.useEffect(()=>{if(o&&!s&&!u||E.current===M&&u)return;let k=false;return v(null),hi(C,e.original,e.exportName).then(d=>{if(k)return;let w=C?.id?y(e.id,C.id):false;if(U.current=w,w&&f.current){let H=Ur(f.current);if(H){let R=Br(H);R.length>0&&($.current=R,F.current=true,N.current&&(clearTimeout(N.current),N.current=null),h.current&&h.current.remove(),h.current=zn(H));}}E.current=M,Fr.startTransition(()=>{m(()=>d);});}).catch(d=>{k||v(fi(d));}),()=>{k=true;}},[y,M,o,s,i,C?.id,C?.moduleUrl,C?.integrity,C?.cssUrls.join("|"),e.exportName,e.original,u]),Fr.useEffect(()=>{if(!u||!f.current)return;let k=false,d=null,w=()=>{if(k||!f.current)return false;let H=C?.highlightHint,R=C?.id,A=C?.createdAt?String(C.createdAt):"";if(!H||!R||zr(R,A,S))return false;let b=Array.from(f.current.querySelectorAll("[data-fork-new]"));b.length,b.map(G=>G.getAttribute("data-fork-new")),H.label,H.textHint,H.selector;let P=Yn(f.current,H);return P?.tagName,P?.getAttribute("data-fork-new"),P?.getAttribute("aria-label"),P?.textContent?.trim().slice(0,60),!P||!so(P)?(P&&so(P),P?.getBoundingClientRect(),false):(no(R,A,S),h.current&&(h.current.remove(),h.current=null),D.current&&D.current(),D.current=Qn(P,H.label,H.position??"top"),true)};return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(k||!f.current)return;let H=U.current,R=!O.current;O.current=true;let A=H||R,b=A?w():false;if(A&&!b&&C?.highlightHint&&C?.id&&!zr(C.id,String(C.createdAt??""),S)){let xe=[150,400,800],Ae=0,K=()=>{if(k||Ae>=xe.length)return;let V=xe[Ae];Ae+=1,d=setTimeout(()=>{if(w()){b=true;return}K();},V);};K();}let P=F.current,G=!!C?.highlightHint,te=$.current;if($.current=null,F.current=false,b||G||!P){h.current&&(h.current.remove(),h.current=null);return}let z=Ur(f.current);if(!te||!z){h.current&&(h.current.remove(),h.current=null);return}let Q=Br(z),J=Wn(te,Q),ie=Jn(te,Q),L=h.current;if(ie.length>0&&L){let xe=qn(ie);N.current=setTimeout(()=>{N.current=null;let Ae=400;L.animate([{opacity:1},{opacity:0}],{duration:Ae,fill:"forwards"}),xe.animate([{opacity:1},{opacity:0}],{duration:Ae,fill:"forwards"}),setTimeout(()=>{L.remove(),xe.remove(),h.current===L&&(h.current=null),J.length>0&&Nr(J);},Ae);},3500);}else L&&(L.remove(),h.current===L&&(h.current=null)),J.length>0&&Nr(J);});}),()=>{k=true,d!==null&&(clearTimeout(d),d=null);}},[u,C?.id,C?.createdAt,C?.highlightHint,S]),I)throw I;return u?So.jsx("div",{ref:f,"data-fork-boundary":e.id,style:{display:"contents"},children:So.jsx(u,{...r})}):So.jsx(So.Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function bi({slotId:e,title:t,slotLabel:r}){return So.jsx(Rt,{slotId:e,title:t,slotLabel:r})}function Si(e){return e.replace(/\/+$/,"")}function Fi(e){return {namespace:e.namespace||"default",type:e.type,id:e.id}}function $t(e,t="value"){let r=Fi(e);return `${r.namespace}:${r.type}:${r.id}:${t}`}function Vr(e){if(Array.isArray(e))return e.map(Vr);if(!e||typeof e!="object")return e;let t=e,r={};for(let n of Object.keys(t).sort())r[n]=Vr(t[n]);return r}function uo(e){return JSON.stringify(Vr(e))}function ao(e){let t={Authorization:`Bearer ${e.apiKey}`,"Content-Type":"application/json","X-Fork-App-Id":e.appId,...e.extraHeaders??{}};return e.userId&&(t["X-Fork-User-Id"]=e.userId),e.userHash&&(t["X-Fork-User-Hash"]=e.userHash),t}async function lo(e){let t=await e.json().catch(()=>({}));if(!e.ok){let r=typeof t.error=="string"?t.error:`Fork data API ${e.status}`;throw new Error(r)}return t}function fo(e){let t=Si(e.baseUrl),r={appId:e.appId,containerId:e.containerId},n=async(s,i)=>{let a=i&&typeof i=="object"&&!Array.isArray(i)?i:{},c=await fetch(`${t}/api/v1/data${s}`,{method:"POST",headers:ao(e),body:JSON.stringify({...r,...a})});return lo(c)},o=async(s,i)=>{let a=new URLSearchParams({appId:e.appId,containerId:e.containerId});for(let[y,S]of Object.entries(i))S&&a.set(y,S);let c=await fetch(`${t}/api/v1/data${s}?${a.toString()}`,{headers:ao(e)});return lo(c)};return {listFeatures(){return o("/features",{})},ensureFeature(s){return n("/features",s)},queryValues(s){return n("/values/query",s)},setValues(s){return n("/values",s)},listOptions(s){return o("/options",{featureId:s.featureId,featureKey:s.featureKey,includeArchived:s.includeArchived?"true":void 0})},setOptions(s){return n("/options",s)},ensureLlmJobs(s){return n("/llm/ensure",s)},queryLlmJobs(s){return n("/llm/jobs/query",s)}}}function sr(e){let{apiKey:t,appId:r,baseUrl:n,currentContainerId:o,previewSession:s,userHash:i,userId:a}=we(),c=e||o;return Fr.useMemo(()=>{if(!r||!c)return null;let y=s?ne():{};return fo({apiKey:t,appId:r,baseUrl:n,containerId:c,userId:s?void 0:a,userHash:s?void 0:i,extraHeaders:y})},[t,r,n,c,s,i,a])}function xi(e){let t=sr(e.containerId),[r,n]=Fr.useState(null),[o,s]=Fr.useState([]),[i,a]=Fr.useState(false),[c,y]=Fr.useState(null),S=uo({featureId:e.featureId,featureKey:e.featureKey,entities:e.entities,valueKeys:e.valueKeys,enabled:e.enabled!==false}),u=Fr.useCallback(async()=>{if(!(!t||e.enabled===false)&&!(!e.featureId&&!e.featureKey)){a(true);try{let v=await t.queryValues({featureId:e.featureId,featureKey:e.featureKey,entities:e.entities,valueKeys:e.valueKeys});n(v.feature),s(v.values),y(null);}catch(v){y(v instanceof Error?v:new Error(String(v)));}finally{a(false);}}},[t,S]);Fr.useEffect(()=>{u();},[u]),Fr.useEffect(()=>{if(!e.pollMs||e.pollMs<=0)return;let v=setInterval(()=>{u();},e.pollMs);return ()=>clearInterval(v)},[e.pollMs,u]);let m=Fr.useMemo(()=>new Map(o.map(v=>[$t(v.entity,v.valueKey),v])),[o]),I=Fr.useCallback((v,f="value")=>m.get($t(v,f))??null,[m]);return {feature:r,values:o,byKey:m,getValue:I,loading:i,error:c,refresh:u}}function Ai(e){let t=sr(e),r=Fr.useCallback(async s=>{if(!t)throw new Error("Fork data is unavailable until appId and containerId are resolved");return t.ensureFeature(s)},[t]),n=Fr.useCallback(async s=>{if(!t)throw new Error("Fork data is unavailable until appId and containerId are resolved");return t.setValues(s)},[t]),o=Fr.useCallback(async s=>{if(!t)throw new Error("Fork data is unavailable until appId and containerId are resolved");return t.setOptions(s)},[t]);return {client:t,ensureFeature:r,setValues:n,setOptions:o}}function co(e){return e.some(t=>t.status==="queued"||t.status==="running")}function Ii(e){let t=sr(e.containerId),[r,n]=Fr.useState(null),[o,s]=Fr.useState([]),[i,a]=Fr.useState([]),[c,y]=Fr.useState(false),[S,u]=Fr.useState(null),m=Fr.useRef(""),I=uo({featureId:e.featureId,featureKey:e.featureKey,kind:e.kind,config:e.config,forkId:e.forkId,targetKind:e.targetKind,targetId:e.targetId,operation:e.operation,model:e.model,prompt:e.prompt,system:e.system,promptHash:e.promptHash,outputFormat:e.outputFormat,maxTokens:e.maxTokens,temperature:e.temperature,force:e.force,jobs:e.jobs,enabled:e.enabled!==false}),v=Fr.useCallback(async()=>{if(!(!t||e.enabled===false)&&!(!e.featureId&&!e.featureKey)&&!(!e.jobs||e.jobs.length===0)){y(true);try{let F=await t.ensureLlmJobs(e);m.current=I,n(F.feature),s(F.jobs),a(F.values),u(null);}catch(F){u(F instanceof Error?F:new Error(String(F)));}finally{y(false);}}},[t,I]),f=Fr.useCallback(async()=>{if(!t)return;let F=o.map(h=>h.id);try{if(F.length>0){let h=await t.queryLlmJobs({jobIds:F});s(h.jobs);}if(e.featureId||e.featureKey){let h=await t.queryValues({featureId:e.featureId,featureKey:e.featureKey,entities:e.jobs.map(N=>N.entity),valueKeys:Array.from(new Set(e.jobs.map(N=>N.valueKey||"value")))});n(h.feature),a(h.values);}u(null);}catch(h){u(h instanceof Error?h:new Error(String(h)));}},[t,o,I]);Fr.useEffect(()=>{m.current!==I&&v();},[v,I]),Fr.useEffect(()=>{let F=e.pollMs??3e3;if(F<=0||!co(o))return;let h=setInterval(()=>{f();},F);return ()=>clearInterval(h)},[e.pollMs,o,f]);let E=Fr.useMemo(()=>new Map(i.map(F=>[$t(F.entity,F.valueKey),F])),[i]),$=Fr.useCallback((F,h="value")=>E.get($t(F,h))??null,[E]);return {feature:r,jobs:o,values:i,byKey:E,getValue:$,loading:c,error:S,ensure:v,refresh:f,running:co(o)}}exports.ForkBoundaryUI=Gs;exports.ForkButton=_r;exports.ForkChatInterface=Rt;exports.ForkPanel=Zt;exports.ForkProvider=qo;exports.ForkSlot=as;exports.ForkUI=bi;exports.clearCachedManifest=$o;exports.createForkDataClient=fo;exports.forkEntityValueKey=$t;exports.forkable=yi;exports.loadManifest=Wt;exports.manifestDiffers=To;exports.readCachedManifest=Co;exports.registerForkShared=dr;exports.useBoundaryFork=Tr;exports.useFork=Mr;exports.useForkChatPanel=Hr;exports.useForkDataClient=sr;exports.useForkDataMutation=Ai;exports.useForkFeatureValues=xi;exports.useForkLlmJobs=Ii;exports.usePreviewSession=zt;exports.writeCachedManifest=Po;
|
|
63
|
+
`,document.head.appendChild(e);}function Tn(e,t,r="top"){Ts();let{outline:n,glow:o,tooltip:s}=$s(t),i=Rs(e);n.style.borderRadius=`${i}px`,o.style.borderRadius=`${i+1}px`,o.style.animation=`__fork-highlight-pulse ${As}ms ease-in-out infinite`,document.body.append(o,n,s);let a=()=>{let l=e.getBoundingClientRect();if(l.width===0&&l.height===0)return;n.style.top=`${l.top}px`,n.style.left=`${l.left}px`,n.style.width=`${l.width}px`,n.style.height=`${l.height}px`,o.style.top=`${l.top-1}px`,o.style.left=`${l.left-1}px`,o.style.width=`${l.width+2}px`,o.style.height=`${l.height+2}px`;let C=s.getBoundingClientRect(),_=C.width||s.offsetWidth||80,k=C.height||s.offsetHeight||26,v=Es(r,l,_,k);s.style.top=`${v.top}px`,s.style.left=`${v.left}px`;};a(),requestAnimationFrame(()=>{n.style.opacity="1",o.style.opacity="1",s.style.opacity="1",s.style.transform="translateY(0)",requestAnimationFrame(a);});let d=false,b=new ResizeObserver(a);b.observe(e);let m=()=>a(),f=()=>a();window.addEventListener("scroll",m,true),window.addEventListener("resize",f);let w=()=>{d||(d=true,clearTimeout(h),b.disconnect(),window.removeEventListener("scroll",m,true),window.removeEventListener("resize",f),window.removeEventListener("click",A,true),n.style.opacity="0",o.style.opacity="0",s.style.opacity="0",s.style.transform="translateY(-2px)",setTimeout(()=>{n.remove(),o.remove(),s.remove();},Cs));},A=()=>w();setTimeout(()=>{d||window.addEventListener("click",A,{once:true,capture:true});},250);let h=setTimeout(w,Is);return w}var Ms="fork:highlight:v1:seen";function Mn(e){return `${Ms}:${e}`}function Pn(e){if(typeof window>"u")return new Set;try{let t=window.localStorage.getItem(e);if(!t)return new Set;let r=JSON.parse(t);return Array.isArray(r)?new Set(r.filter(n=>typeof n=="string")):new Set}catch{return new Set}}function Ps(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify([...t].slice(-200)));}catch{}}var _n=new Set;function Ln(e,t,r){return `${r}::${e}:${t}`}function $r(e,t,r){let n=Ln(e,t,r);return _n.has(n)?true:Pn(Mn(r)).has(`${e}:${t}`)}function Hn(e,t,r){let n=Ln(e,t,r);_n.add(n);let o=Mn(r),s=`${e}:${t}`,i=Pn(o);i.has(s)||(i.add(s),Ps(o,i));}var vt=new Map,St=new Map,Tr=new Map;function Ls(e){for(let t of e)St.set(t,(St.get(t)??0)+1);}function Hs(e){if(!(typeof document>"u"))for(let t of e){let r=(St.get(t)??0)-1;if(r>0){St.set(t,r);continue}St.delete(t),vt.delete(t);let n=document.querySelector(`link[data-fork-override-href="${CSS.escape(t)}"]`);n&&n.remove();}}function Us(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function On(e){let t=e.getBoundingClientRect();if(t.width<=0||t.height<=0)return false;let r=window.innerWidth||document.documentElement.clientWidth,n=window.innerHeight||document.documentElement.clientHeight;return t.bottom>0&&t.right>0&&t.top<n&&t.left<r}function Nn(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 Os(e){if(!e||typeof document>"u")return Promise.resolve();let t=vt.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((s,i)=>{let a=()=>{r.removeEventListener("load",a),r.removeEventListener("error",d),s();},d=()=>{r.removeEventListener("load",a),r.removeEventListener("error",d),i(new Error(`Failed to load boundary stylesheet: ${e}`));};r.addEventListener("load",a,{once:true}),r.addEventListener("error",d,{once:true});});return vt.set(e,o),o}let n=new Promise((o,s)=>{let i=document.createElement("link");i.rel="stylesheet",i.href=e,i.setAttribute("data-fork-override-href",e),i.onload=()=>o(),i.onerror=()=>{i.remove(),s(new Error(`Failed to load boundary stylesheet: ${e}`));},document.head.appendChild(i);}).catch(o=>{throw vt.delete(e),o});return vt.set(e,n),n}var wt=null;function Ns(){if(wt)return wt;try{wt=new Function("u","return import(/*webpackIgnore:true*//*@vite-ignore*/u)");}catch{wt=e=>import(/*webpackIgnore:true*//*@vite-ignore*/e);}return wt}function Bs(e){let t=Tr.get(e);if(t)return t;let r=Ns()(e).catch(n=>{throw Tr.delete(e),n});return Tr.set(e,r),r}async function Ds(e,t,r){if(e)try{await Promise.all(e.cssUrls.map(s=>Os(s)));let o=await Bs(e.moduleUrl);return Nn(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 Nn(n,r)}function Ks(e){function t(r){let{appId:n,moduleOverridesEnabled:o,moduleManifestReady:s,moduleManifestVersion:i,registerBoundary:a,getBoundaryOverride:d,consumeBoundaryAnimation:b,highlightScope:m}=he(),[f,w]=cr.useState(null),[A,h]=cr.useState(null),l=cr.useRef(null),C=cr.useRef(null),_=cr.useRef(null),k=cr.useRef(false),v=cr.useRef(null),L=cr.useRef(null),D=cr.useRef(null),B=cr.useRef(false),U=cr.useRef(false),R=d(e.id),$=R?`override:${R.id}`:"original",O=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if(cr.useEffect(()=>()=>{L.current&&(clearTimeout(L.current),L.current=null),v.current&&(v.current.remove(),v.current=null),D.current&&(D.current(),D.current=null);},[]),cr.useEffect(()=>{a({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[n,a,e.id,e.exportName,O]),cr.useEffect(()=>{let y=R?.cssUrls??[];if(y.length!==0)return Ls(y),()=>Hs(y)},[R?.cssUrls.join("|")]),cr.useEffect(()=>{if(o&&!s&&!f||C.current===$&&f)return;let y=false;return h(null),Ds(R,e.original,e.exportName).then(u=>{if(y)return;let F=R?.id?b(e.id,R.id):false;if(B.current=F,F&&l.current){let T=xr(l.current);if(T){let M=Ar(T);M.length>0&&(_.current=M,k.current=true,L.current&&(clearTimeout(L.current),L.current=null),v.current&&v.current.remove(),v.current=Fn(T));}}C.current=$,cr.startTransition(()=>{w(()=>u);});}).catch(u=>{y||h(Us(u));}),()=>{y=true;}},[b,$,o,s,i,R?.id,R?.moduleUrl,R?.integrity,R?.cssUrls.join("|"),e.exportName,e.original,f]),cr.useEffect(()=>{if(!f||!l.current)return;let y=false,u=null,F=()=>{if(y||!l.current)return false;let T=R?.highlightHint,M=R?.id,I=R?.createdAt?String(R.createdAt):"";if(!T||!M||$r(M,I,m))return false;let S=Array.from(l.current.querySelectorAll("[data-fork-new]"));S.length,S.map(Y=>Y.getAttribute("data-fork-new")),T.label,T.textHint,T.selector;let H=$n(l.current,T);return H?.tagName,H?.getAttribute("data-fork-new"),H?.getAttribute("aria-label"),H?.textContent?.trim().slice(0,60),!H||!On(H)?(H&&On(H),H?.getBoundingClientRect(),false):(Hn(M,I,m),v.current&&(v.current.remove(),v.current=null),D.current&&D.current(),D.current=Tn(H,T.label,T.position??"top"),true)};return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(y||!l.current)return;let T=B.current,M=!U.current;U.current=true;let I=T||M,S=I?F():false;if(I&&!S&&R?.highlightHint&&R?.id&&!$r(R.id,String(R.createdAt??""),m)){let ke=[150,400,800],Se=0,Ue=()=>{if(y||Se>=ke.length)return;let W=ke[Se];Se+=1,u=setTimeout(()=>{if(F()){S=true;return}Ue();},W);};Ue();}let H=k.current,Y=!!R?.highlightHint,ae=_.current;if(_.current=null,k.current=false,S||Y||!H){v.current&&(v.current.remove(),v.current=null);return}let Q=xr(l.current);if(!ae||!Q){v.current&&(v.current.remove(),v.current=null);return}let re=Ar(Q),V=xn(ae,re),Z=An(ae,re),q=v.current;if(Z.length>0&&q){let ke=Cn(Z);L.current=setTimeout(()=>{L.current=null;let Se=400;q.animate([{opacity:1},{opacity:0}],{duration:Se,fill:"forwards"}),ke.animate([{opacity:1},{opacity:0}],{duration:Se,fill:"forwards"}),setTimeout(()=>{q.remove(),ke.remove(),v.current===q&&(v.current=null),V.length>0&&Ir(V);},Se);},3500);}else q&&(q.remove(),v.current===q&&(v.current=null)),V.length>0&&Ir(V);});}),()=>{y=true,u!==null&&(clearTimeout(u),u=null);}},[f,R?.id,R?.createdAt,R?.highlightHint,m]),A)throw A;return f?eo.jsx("div",{ref:l,"data-fork-boundary":e.id,style:{display:"contents"},children:eo.jsx(f,{...r})}):eo.jsx(eo.Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function zs({slotId:e,title:t,slotLabel:r}){return eo.jsx(kt,{slotId:e,title:t,slotLabel:r})}function Js(e){return e.replace(/\/+$/,"")}function qs(e){return {namespace:e.namespace||"default",type:e.type,id:e.id}}function Ft(e,t="value"){let r=qs(e);return `${r.namespace}:${r.type}:${r.id}:${t}`}function Pr(e){if(Array.isArray(e))return e.map(Pr);if(!e||typeof e!="object")return e;let t=e,r={};for(let n of Object.keys(t).sort())r[n]=Pr(t[n]);return r}function jn(e){return JSON.stringify(Pr(e))}function Bn(e){let t={Authorization:`Bearer ${e.apiKey}`,"Content-Type":"application/json","X-Fork-App-Id":e.appId,...e.extraHeaders??{}};return e.userId&&(t["X-Fork-User-Id"]=e.userId),e.userHash&&(t["X-Fork-User-Hash"]=e.userHash),t}async function Dn(e){let t=await e.json().catch(()=>({}));if(!e.ok){let r=typeof t.error=="string"?t.error:`Fork data API ${e.status}`;throw new Error(r)}return t}function zn(e){let t=Js(e.baseUrl),r={appId:e.appId,containerId:e.containerId},n=async(s,i)=>{let a=i&&typeof i=="object"&&!Array.isArray(i)?i:{},d=await fetch(`${t}/api/v1/data${s}`,{method:"POST",headers:Bn(e),body:JSON.stringify({...r,...a})});return Dn(d)},o=async(s,i)=>{let a=new URLSearchParams({appId:e.appId,containerId:e.containerId});for(let[b,m]of Object.entries(i))m&&a.set(b,m);let d=await fetch(`${t}/api/v1/data${s}?${a.toString()}`,{headers:Bn(e)});return Dn(d)};return {listFeatures(){return o("/features",{})},ensureFeature(s){return n("/features",s)},queryValues(s){return n("/values/query",s)},setValues(s){return n("/values",s)},listOptions(s){return o("/options",{featureId:s.featureId,featureKey:s.featureKey,includeArchived:s.includeArchived?"true":void 0})},setOptions(s){return n("/options",s)},ensureLlmJobs(s){return n("/llm/ensure",s)},queryLlmJobs(s){return n("/llm/jobs/query",s)}}}function Jt(e){let{apiKey:t,appId:r,baseUrl:n,currentContainerId:o,userHash:s,userId:i}=he(),a=e||o;return cr.useMemo(()=>{if(!r||!a)return null;let d=ie();return zn({apiKey:t,appId:r,baseUrl:n,containerId:a,userId:i,userHash:s,extraHeaders:d})},[t,r,n,a,s,i])}function Xs(e){let t=Jt(e.containerId),[r,n]=cr.useState(null),[o,s]=cr.useState([]),[i,a]=cr.useState(false),[d,b]=cr.useState(null),m=jn({featureId:e.featureId,featureKey:e.featureKey,entities:e.entities,valueKeys:e.valueKeys,enabled:e.enabled!==false}),f=cr.useCallback(async()=>{if(!(!t||e.enabled===false)&&!(!e.featureId&&!e.featureKey)){a(true);try{let h=await t.queryValues({featureId:e.featureId,featureKey:e.featureKey,entities:e.entities,valueKeys:e.valueKeys});n(h.feature),s(h.values),b(null);}catch(h){b(h instanceof Error?h:new Error(String(h)));}finally{a(false);}}},[t,m]);cr.useEffect(()=>{f();},[f]),cr.useEffect(()=>{if(!e.pollMs||e.pollMs<=0)return;let h=setInterval(()=>{f();},e.pollMs);return ()=>clearInterval(h)},[e.pollMs,f]);let w=cr.useMemo(()=>new Map(o.map(h=>[Ft(h.entity,h.valueKey),h])),[o]),A=cr.useCallback((h,l="value")=>w.get(Ft(h,l))??null,[w]);return {feature:r,values:o,byKey:w,getValue:A,loading:i,error:d,refresh:f}}function Gs(e){let t=Jt(e),r=cr.useCallback(async s=>{if(!t)throw new Error("Fork data is unavailable until appId and containerId are resolved");return t.ensureFeature(s)},[t]),n=cr.useCallback(async s=>{if(!t)throw new Error("Fork data is unavailable until appId and containerId are resolved");return t.setValues(s)},[t]),o=cr.useCallback(async s=>{if(!t)throw new Error("Fork data is unavailable until appId and containerId are resolved");return t.setOptions(s)},[t]);return {client:t,ensureFeature:r,setValues:n,setOptions:o}}function Kn(e){return e.some(t=>t.status==="queued"||t.status==="running")}function Ys(e){let t=Jt(e.containerId),[r,n]=cr.useState(null),[o,s]=cr.useState([]),[i,a]=cr.useState([]),[d,b]=cr.useState(false),[m,f]=cr.useState(null),w=cr.useRef(""),A=jn({featureId:e.featureId,featureKey:e.featureKey,kind:e.kind,config:e.config,forkId:e.forkId,targetKind:e.targetKind,targetId:e.targetId,operation:e.operation,model:e.model,prompt:e.prompt,system:e.system,promptHash:e.promptHash,outputFormat:e.outputFormat,maxTokens:e.maxTokens,temperature:e.temperature,force:e.force,jobs:e.jobs,enabled:e.enabled!==false}),h=cr.useCallback(async()=>{if(!(!t||e.enabled===false)&&!(!e.featureId&&!e.featureKey)&&!(!e.jobs||e.jobs.length===0)){b(true);try{let k=await t.ensureLlmJobs(e);w.current=A,n(k.feature),s(k.jobs),a(k.values),f(null);}catch(k){f(k instanceof Error?k:new Error(String(k)));}finally{b(false);}}},[t,A]),l=cr.useCallback(async()=>{if(!t)return;let k=o.map(v=>v.id);try{if(k.length>0){let v=await t.queryLlmJobs({jobIds:k});s(v.jobs);}if(e.featureId||e.featureKey){let v=await t.queryValues({featureId:e.featureId,featureKey:e.featureKey,entities:e.jobs.map(L=>L.entity),valueKeys:Array.from(new Set(e.jobs.map(L=>L.valueKey||"value")))});n(v.feature),a(v.values);}f(null);}catch(v){f(v instanceof Error?v:new Error(String(v)));}},[t,o,A]);cr.useEffect(()=>{w.current!==A&&h();},[h,A]),cr.useEffect(()=>{let k=e.pollMs??3e3;if(k<=0||!Kn(o))return;let v=setInterval(()=>{l();},k);return ()=>clearInterval(v)},[e.pollMs,o,l]);let C=cr.useMemo(()=>new Map(i.map(k=>[Ft(k.entity,k.valueKey),k])),[i]),_=cr.useCallback((k,v="value")=>C.get(Ft(k,v))??null,[C]);return {feature:r,jobs:o,values:i,byKey:C,getValue:_,loading:d,error:m,ensure:h,refresh:l,running:Kn(o)}}exports.ForkBoundaryUI=vs;exports.ForkButton=gr;exports.ForkChatInterface=kt;exports.ForkPanel=Dt;exports.ForkProvider=vo;exports.ForkSlot=_o;exports.ForkUI=zs;exports.clearCachedManifest=so;exports.createForkDataClient=zn;exports.forkEntityValueKey=Ft;exports.forkable=Ks;exports.loadManifest=or;exports.manifestDiffers=io;exports.readCachedManifest=no;exports.registerForkShared=tr;exports.useBoundaryFork=br;exports.useFork=wr;exports.useForkChatPanel=Sr;exports.useForkDataClient=Jt;exports.useForkDataMutation=Gs;exports.useForkFeatureValues=Xs;exports.useForkLlmJobs=Ys;exports.writeCachedManifest=oo;
|