@fork-api/chat-sdk 0.1.178 → 0.1.181
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 +8 -7
- package/dist/index.d.cts +102 -51
- package/dist/index.d.ts +102 -51
- package/dist/index.js +8 -7
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
'use strict';var kr=require('react'),mo=require('react-dom'),ho=require('react/jsx-runtime'),yo=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 kr__namespace=/*#__PURE__*/_interopNamespace(kr);var mo__namespace=/*#__PURE__*/_interopNamespace(mo);var ho__namespace=/*#__PURE__*/_interopNamespace(ho);var yo__namespace=/*#__PURE__*/_interopNamespace(yo);var tt="__FORK_SHARED__";function ur(){var t,r,n,o;let e=globalThis;return e[tt]||(e[tt]={}),(t=e[tt]).react||(t.react=kr__namespace),(r=e[tt])["react-dom"]||(r["react-dom"]=mo__namespace),(n=e[tt])["react/jsx-runtime"]||(n["react/jsx-runtime"]=ho__namespace),(o=e[tt])["react/jsx-dev-runtime"]||(o["react/jsx-dev-runtime"]=yo__namespace),e[tt]}function cr(e){return Object.assign(ur(),e)}var rn=false,dr=null,fr=null;function nn(e,t,r){rn=e,dr=t,fr=r;}function ce(){if(!rn)return {};let e={};return dr&&(e["X-Fork-App-Id"]=dr),fr&&(e["X-Fork-Container-Id"]=fr),e}async function pr(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[l,f]of Object.entries(s.modules)){let w=f.moduleUrl??f.bundleUrl??null,h=f.legacyModuleUrl??f.legacyBundleUrl??null;i[l]={forkId:f.forkId,moduleUrl:w,legacyModuleUrl:h,bundleUrl:f.bundleUrl??w,legacyBundleUrl:f.legacyBundleUrl??h,cssUrls:f.cssUrls??[],integrity:f.integrity,metadata:f.metadata,highlightHint:f.highlightHint,buildId:f.buildId,updatedAt:f.updatedAt};}return {containerId:s.containerId,forksPaused:!!s.forksPaused,slots:s.slots,modules:i,generatedAt:s.generatedAt,etag:o.headers.get("ETag")??void 0}}var ko="fork:manifest:v1";function gr(e,t,r){return `${ko}:${e}:${t}:${r}`}function bo(e,t,r){if(typeof window>"u")return null;try{let n=window.localStorage.getItem(gr(e,t,r));return n?JSON.parse(n):null}catch{return null}}function wo(e,t,r,n){if(!(typeof window>"u"))try{window.localStorage.setItem(gr(e,t,r),JSON.stringify(n));}catch{}}function vo(e,t,r){if(!(typeof window>"u"))try{window.localStorage.removeItem(gr(e,t,r));}catch{}}function Fo(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,l]of r){let f=t.slots[i];if(!f||f.forkId!==l.forkId||f.buildId!==l.buildId)return true}let o=Object.entries(e.modules),s=Object.entries(t.modules);if(o.length!==s.length)return true;for(let[i,l]of o){let f=t.modules[i];if(!f||f.forkId!==l.forkId||f.buildId!==l.buildId)return true}return false}var jt={isAdmin:false,actingUserId:null,containerId:null,containerName:null,containers:[]},an=kr.createContext(null),Ao=12e3,Io=45e3,on="fork:activity:v1",Ro=new Set(["pending","running","building"]),Co="Setting up environment";function $e(e){return Ro.has(e)}function Eo(e,t){return t?.targetId?t:e.boundaryId?{targetKind:"module",targetId:e.boundaryId}:e.slotId?{targetKind:"slot",targetId:e.slotId}:null}function $o(e,t){let r=Eo(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 sn(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 Kt(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 rt(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 nt(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify([...t].slice(-200)));}catch{}}function To(e){if(e.estimateMinutes)return `~${e.estimateMinutes}m`}function Mo(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 Po(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():Co,detail:s?To(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 mr(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function _o(e,t,r,n){let o={};for(let[s,i]of Object.entries(t.slots)){let l=i.bundleUrl??i.legacyBundleUrl;l&&(o[s]={id:i.forkId,userId:r,prompt:"",status:"complete",slotId:s,appId:n,bundleUrl:mr(e,l),revealPending:i.revealPending===true,createdAt:i.updatedAt,completedAt:i.updatedAt});}return o}function Lo(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:mr(e,s),cssUrls:(o.cssUrls??[]).map(i=>mr(e,i)),integrity:o.integrity,metadata:o.metadata,highlightHint:o.highlightHint,createdAt:o.updatedAt});}return r}function Ho(e){let{apiKey:t,baseUrl:r,children:n,appId:o,shared:s}=e,i="userId"in e?e.userId:void 0,l="userHash"in e?e.userHash:void 0,f="authUrl"in e?e.authUrl:void 0,[w,h]=kr.useState({}),[p,F]=kr.useState(i?{userId:i,userHash:l}:null),[I,y]=kr.useState(!!i),[u,O]=kr.useState(jt),[P,R]=kr.useState(false),[g,C]=kr.useState(false),[_,D]=kr.useState({}),[U,T]=kr.useState(!o),[se,W]=kr.useState(0),[A,S]=kr.useState(null),[N,B]=kr.useState(false),[K,X]=kr.useState([]),[G,q]=kr.useState(()=>typeof document>"u"?true:document.visibilityState!=="hidden"),L=kr.useRef(new Map),k=kr.useRef(new Map),[E,x]=kr.useState(0),d=kr.useRef(new Set),M=kr.useRef(new Map),v=kr.useRef(void 0),j=kr.useRef(new Map),ne=kr.useRef([]),Ee=kr.useRef(new Set),Le=kr.useRef(false);ur(),kr.useEffect(()=>{if(!o||!p?.userHash||!p.userId){O(jt),R(true);return}let c=false;R(false);let m=new URLSearchParams({app:o});return fetch(`${r}/api/v1/admin/containers?${m.toString()}`,{headers:{Authorization:`Bearer ${t}`,"X-Fork-App-Id":o,"X-Fork-User-Id":p.userId,"X-Fork-User-Hash":p.userHash}}).then(async b=>b.status===403||!b.ok?null:b.json()).then(b=>{if(c)return;if(!b){O(jt),R(true);return}let V=Array.isArray(b.containers)?b.containers:[],Y=b.currentContainerId??null,Q=V.find(Z=>Z.id===Y)?.name??null;O({isAdmin:true,actingUserId:typeof b.actingUserId=="string"?b.actingUserId:null,containerId:Y,containerName:Q,containers:V}),R(true);}).catch(()=>{c||(O(jt),R(true));}),()=>{c=true;}},[t,o,p?.userHash,p?.userId,r]),kr.useEffect(()=>{nn(u.isAdmin,o??null,u.containerId);},[u.isAdmin,u.containerId,o]);let Ge=kr.useCallback((c,m)=>{O(b=>{if(!b.isAdmin)return b;let V=b.containers.find(Z=>Z.id===c),Y=m??V?.name??null,Q=V?b.containers.map(Z=>({...Z,isPrimary:Z.id===c})):[{id:c,name:Y??"New container",isPrimary:true,forkCount:0},...b.containers.map(Z=>({...Z,isPrimary:false}))];return {...b,containerId:c,containerName:Y,containers:Q}}),C(false);},[]);s&&v.current!==s&&(cr(s),v.current=s),kr.useEffect(()=>{f&&(y(false),fetch(f,{credentials:"include"}).then(c=>{if(!c.ok)throw new Error(`Auth endpoint returned ${c.status}`);return c.json()}).then(c=>{if(!c.userId||typeof c.userId!="string")throw new Error("authUrl response must include userId");F({userId:c.userId,userHash:typeof c.userHash=="string"?c.userHash:void 0});}).catch(c=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",c.message);}).finally(()=>{y(true);}));},[f]),kr.useEffect(()=>{!f&&i&&(F({userId:i,userHash:l}),y(true));},[i,l,f]);let J=p?.userId??"",re=p?.userHash,He=!!o,Fe=kr.useCallback(async()=>{if(!He){S(null),B(false),D({}),T(true),W(m=>m+1);return}if(!I){T(false);return}if(!J||!o){S(null),B(false),h({}),D({}),T(true),W(m=>m+1);return}T(false);let c=u.isAdmin?u.containerId:null;if(u.isAdmin&&g){B(true),h({}),D({}),W(m=>m+1),T(true);return}try{let m=await pr({baseUrl:r,apiKey:t,appId:o,userId:J,userHash:re,containerId:c??void 0});m&&(S(m.containerId),B(u.isAdmin?!1:!!m.forksPaused),h(_o(r,m,J,o)),D(Lo(r,m)));}catch(m){console.error("[ForkProvider] Failed to fetch fork manifest:",m.message),S(null),B(false),h({}),D({});}finally{W(m=>m+1),T(true);}},[t,o,r,I,He,re,J,u.isAdmin,u.containerId,g]);kr.useEffect(()=>{if(!J||o)return;let c=new URLSearchParams({userId:J});re&&c.set("userHash",re),fetch(`${r}/api/v1/forks/active?${c.toString()}`,{headers:{Authorization:`Bearer ${t}`,...ce()}}).then(m=>{if(!m.ok)throw new Error(`${m.status}`);return m.json()}).then(m=>{m&&typeof m=="object"&&h(m);}).catch(()=>{});},[t,o,J,re,r]),kr.useEffect(()=>{Fe();},[Fe]);let Me=kr.useCallback(async c=>{if(o){if(u.isAdmin){C(c),B(c),c?(h({}),D({}),W(m=>m+1)):await Fe();return}if(J){B(c),c&&(h({}),D({}),W(m=>m+1));try{let m=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:c,userId:J,userHash:re})});if(!m.ok)throw new Error(`${m.status}`);c||await Fe();}catch(m){console.error("[ForkProvider] Failed to persist fork pause state:",m?.message??m),Fe().catch(()=>{});}}}},[t,o,r,Fe,u.isAdmin,re,J]),Ye=kr.useCallback((c,m)=>{h(b=>({...b,[c]:m}));},[]),rr=kr.useCallback(c=>{h(m=>{let b={...m};return delete b[c],b});},[]),Mt=kr.useCallback(c=>{d.current.add(c);},[]),nr=kr.useCallback(c=>d.current.has(c)?(d.current.delete(c),true):false,[]),Pt=kr.useCallback(c=>{if(c.slotId&&h(b=>{let V=b[c.slotId];return !V||V.id!==c.id||!V.revealPending?b:{...b,[c.slotId]:{...V,revealPending:false}}}),u.isAdmin||!J)return;let m={Authorization:`Bearer ${t}`,"Content-Type":"application/json","X-Fork-User-Id":J};re&&(m["X-Fork-User-Hash"]=re),fetch(`${r}/api/v1/forks/reveals`,{method:"POST",headers:m,body:JSON.stringify({forkId:c.id,userId:J,userHash:re})}).catch(()=>{});},[t,r,u.isAdmin,re,J]),ae=kr.useCallback((c,m)=>{M.current.set(c,m);},[]),it=kr.useCallback((c,m)=>M.current.get(c)!==m?false:(M.current.delete(c),true),[]),or=kr.useCallback(c=>{if(!o)return;let m=JSON.stringify(c);L.current.get(c.id)===m||k.current.get(c.id)?.signature===m||(k.current.set(c.id,{boundary:c,signature:m}),x(V=>V+1));},[o]);kr.useEffect(()=>{if(!o||k.current.size===0)return;let c=setTimeout(()=>{let m=Array.from(k.current.values());m.length!==0&&fetch(`${r}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:o,boundaries:m.map(b=>b.boundary)})}).then(b=>{if(!b.ok)throw new Error(`${b.status}`)}).then(()=>{for(let b of m)k.current.get(b.boundary.id)?.signature===b.signature&&(k.current.delete(b.boundary.id),L.current.set(b.boundary.id,b.signature));}).catch(b=>{console.error("[ForkProvider] Failed to register module boundaries:",b.message);});},50);return ()=>{clearTimeout(c);}},[t,o,r,E]);let _t=kr.useCallback(c=>_[c],[_]),ft=u.isAdmin?`admin:${u.actingUserId??"op"}`:J,Qe=`${t}:${o||"no-app"}:${A||"no-container"}:${ft||"anonymous"}`,Oe=u.isAdmin?`op:${u.actingUserId??"op"}`:J,Ze=`${t}:${o||"no-app"}:${Oe||"anonymous"}`,Ie=`${on}:seen:${Qe}`,be=`${on}:tracked:${Qe}`;kr.useEffect(()=>{ne.current=K;},[K]);let Ne=kr.useCallback(()=>{let c={Authorization:`Bearer ${t}`,...ce()};return o&&(c["X-Fork-App-Id"]=o),J&&(c["X-Fork-User-Id"]=J),re&&(c["X-Fork-User-Hash"]=re),c},[t,o,re,J]);kr.useEffect(()=>{if(typeof window>"u")return;let c=window.__FORK_RUNTIME__,m={dataFetch:async(b,V,Y="POST")=>{if(!o||!A)throw new Error("Fork data is unavailable until appId and containerId are resolved");let Q=typeof b=="string"&&b.startsWith("/")?b:`/${String(b||"")}`,Z=Q.startsWith("/api/v1/data")?Q:`/api/v1/data${Q}`,de=Y.toUpperCase(),ie=new URL(`${r}${Z}`),pe={Authorization:`Bearer ${t}`,"Content-Type":"application/json","X-Fork-App-Id":o,...ce()};J&&(pe["X-Fork-User-Id"]=J),re&&(pe["X-Fork-User-Hash"]=re);let ge={method:de,headers:pe};de==="GET"?(ie.searchParams.set("appId",o),ie.searchParams.set("containerId",A)):ge.body=JSON.stringify({appId:o,containerId:A,...V&&typeof V=="object"?V:{}});let oe=await fetch(ie.toString(),ge),fe=await oe.json().catch(()=>({}));if(!oe.ok)throw new Error(typeof fe?.error=="string"?fe.error:`Fork data API ${oe.status}`);return fe}};return window.__FORK_RUNTIME__=m,()=>{window.__FORK_RUNTIME__===m&&(window.__FORK_RUNTIME__=c);}},[t,o,r,A,re,J]);let Ue=kr.useCallback(async()=>{if(!A||!P)return;let c=new URLSearchParams({container_id:A}),m=await fetch(`${r}/api/v1/forks?${c.toString()}`,{headers:Ne()}).catch(()=>null);if(!m||!m.ok)return;let b=await m.json().catch(()=>({})),V=Array.isArray(b.forks)?b.forks:[],Y=rt(Ie),Q=rt(be),Z=false,de=new Map(ne.current.map(pe=>[pe.id,pe])),ie=[];for(let pe of V){let ge=sn(pe);$e(ge.status)&&!Q.has(ge.id)&&(Q.add(ge.id),Z=true);let oe=de.get(ge.id),fe=oe?$e(oe.status):false,Re=yt(ge);ge.status==="complete"&&(Q.has(ge.id)||fe)&&!Y.has(Re)&&!Ee.current.has(Re)&&!oe?.unread&&(Le.current||Q.has(ge.id)||fe)&&(Ee.current.add(Re),ie.push(ge));}if(X(pe=>{let ge=new Map(pe.map(me=>[me.id,me])),oe=new Set,fe=new Map;for(let me of V){let ve=sn(me);oe.add(ve.id);let Te=ge.get(ve.id),_e=Te?$e(Te.status):false,lt=yt(ve),Ht=ve.status==="complete"&&(Q.has(ve.id)||_e)&&!Y.has(lt),Ce=Kt(Te,{...ve,unread:Ht});fe.set(ve.id,Ce);}for(let me of pe)oe.has(me.id)||($e(me.status)||me.unread)&&fe.set(me.id,me);let Re=[...fe.values()].sort((me,ve)=>Date.parse(ve.updatedAt)-Date.parse(me.updatedAt));return ne.current=Re,Re}),Z&&nt(be,Q),ie.length>0){for(let pe of ie)pe.targetKind==="module"&&ae(pe.targetId,pe.id);Fe().catch(()=>{});}Le.current=true;},[Ie,be,P,r,Ne,A,Fe,ae]),pt=kr.useCallback((c,m)=>{let b=$o(c,m);if(!b)return;let V=c.containerId??c._containerId;if(V&&!A&&S(V),$e(b.status)){let Z=rt(be);Z.has(b.id)||(Z.add(b.id),nt(be,Z)),B(false),u.isAdmin&&C(false);}let Y=new Map(ne.current.map(Z=>[Z.id,Z]));Y.set(b.id,Kt(Y.get(b.id),b));let Q=[...Y.values()].sort((Z,de)=>Date.parse(de.updatedAt)-Date.parse(Z.updatedAt));ne.current=Q,X(Q);},[be,t,o,A,u.isAdmin]),Pe=kr.useCallback((c,m)=>{let b=Mo(m),V=rt(Ie),Y=rt(be),Q=ne.current.find(oe=>oe.id===c),Z=Q?$e(Q.status):false;b.status&&$e(b.status)&&!Y.has(c)&&(Y.add(c),nt(be,Y));let de=Q?Kt(Q,{...Q,...b}):null,ie=de?yt(de):null,pe=!!(de&&de.status==="complete"&&(Y.has(c)||Z)&&ie&&!V.has(ie)&&!Ee.current.has(ie)&&!Q?.unread),ge=m.type==="complete"&&Q?.targetKind==="module"?Q.targetId:null;if(X(oe=>{let fe=oe.find(_e=>_e.id===c);if(!fe)return oe;let Re=Kt(fe,{...fe,...b}),me=Re.status==="complete"&&(Y.has(c)||$e(fe.status))&&!V.has(yt(Re)),ve={...Re,unread:me},Te=oe.map(_e=>_e.id===c?ve:_e).sort((_e,lt)=>Date.parse(lt.updatedAt)-Date.parse(_e.updatedAt));return ne.current=Te,Te}),pe&&de&&ie&&Ee.current.add(ie),m.type==="complete"){let oe=m.data&&typeof m.data=="object"?m.data:{},fe=typeof oe.boundaryId=="string"?oe.boundaryId:ge;fe&&ae(fe,c),Fe().catch(()=>{});}},[Ie,be,Fe,ae]),Lt=kr.useCallback(c=>{let m=rt(Ie),b=rt(be),V=false,Y=false;for(let Q of ne.current){if(Q.status!=="complete"||c&&Q.id!==c)continue;let Z=yt(Q);m.has(Z)||(m.add(Z),V=true),b.delete(Q.id)&&(Y=true);}X(Q=>{let Z=Q.map(de=>de.status!=="complete"||c&&de.id!==c?de:{...de,unread:false});return ne.current=Z,Z}),V&&nt(Ie,m),Y&&nt(be,b);},[Ie,be]);kr.useEffect(()=>{Le.current=false,Ee.current.clear(),X([]);for(let c of j.current.values())c.close();j.current.clear(),A&&Ue();},[A,Ue]),kr.useEffect(()=>{if(typeof document>"u")return;let c=()=>{let m=document.visibilityState!=="hidden";q(m),m&&A&&Ue();};return document.addEventListener("visibilitychange",c),window.addEventListener("focus",c),window.addEventListener("online",c),()=>{document.removeEventListener("visibilitychange",c),window.removeEventListener("focus",c),window.removeEventListener("online",c);}},[A,Ue]),kr.useEffect(()=>{let c=K.filter(V=>$e(V.status));if(!A||c.length===0)return;let m=G?Ao:Io,b=window.setInterval(()=>{Ue();},m);return ()=>window.clearInterval(b)},[A,G,K,Ue]),kr.useEffect(()=>{for(let c of j.current.values())c.close();j.current.clear();},[t,r,u.containerId,re,J]),kr.useEffect(()=>{let c=new Set(K.filter(m=>$e(m.status)).map(m=>m.id));for(let[m,b]of j.current.entries())c.has(m)||(b.close(),j.current.delete(m));for(let m of c){if(j.current.has(m))continue;let b=new URLSearchParams({key:t});J&&b.set("userId",J),re&&b.set("userHash",re),u.isAdmin&&u.containerId&&b.set("containerId",u.containerId);let V=new EventSource(`${r}/api/v1/forks/${m}/events?${b.toString()}`);V.onmessage=Y=>{try{Pe(m,JSON.parse(Y.data));}catch{}},V.onerror=()=>{V.close(),j.current.delete(m);},j.current.set(m,V);}},[t,r,K,u.isAdmin,u.containerId,Pe,re,J]),kr.useEffect(()=>()=>{for(let c of j.current.values())c.close();j.current.clear();},[]);let Ve=Po(K),at=kr.useCallback(async()=>{if(!J)throw new Error("Reset requires a resolved user identity.");let c=new URLSearchParams({userId:J});re&&c.set("userHash",re);let m={Authorization:`Bearer ${t}`,...ce()};o&&(m["X-Fork-App-Id"]=o);let b=await fetch(`${r}/api/v1/forks/all?${c.toString()}`,{method:"DELETE",headers:m});if(!b.ok){let Y=await b.json().catch(()=>({}));throw new Error(Y.error||`API error: ${b.status}`)}let V=await b.json().catch(()=>({}));return h({}),D({}),T(true),W(Y=>Y+1),X([]),Ee.current.clear(),nt(Ie,new Set),nt(be,new Set),d.current.clear(),M.current.clear(),V},[Ie,be,t,o,r,re,J]);return ho.jsx(an.Provider,{value:{apiKey:t,userId:J,userHash:re,baseUrl:r,appId:o,forks:w,moduleOverridesEnabled:He,moduleManifestReady:U,moduleManifestVersion:se,currentContainerId:A,forksPaused:N,setForksPaused:Me,forkActivities:K,activitySummary:Ve,adminContext:u,setAdminContainer:Ge,trackForkActivity:pt,recordForkActivityEvent:Pe,markForkActivitySeen:Lt,refreshForkActivities:Ue,setSlotFork:Ye,clearSlotFork:rr,skipAnimationForSlot:Mt,shouldSkipAnimation:nr,markRevealSeen:Pt,queueBoundaryAnimation:ae,consumeBoundaryAnimation:it,registerBoundary:or,getBoundaryOverride:_t,refreshModuleManifest:Fe,resetAllForks:at,highlightScope:Ze},children:n})}function we(){let e=kr.useContext(an);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function zt(e){return we().forks[e]}var kt=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 hr=new Set;function br(e,t){let r;try{r=kr.Children.only(e);}catch{let o=kr.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 un=new Set;function cn(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 Do(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 l=r[i];l.rect.top>=n.rect.top&&l.rect.left>=n.rect.left&&l.rect.right<=n.rect.right&&l.rect.bottom<=n.rect.bottom&&r.splice(i,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function jo(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 l=r[i];l.rect.top>=n.rect.top&&l.rect.left>=n.rect.left&&l.rect.right<=n.rect.right&&l.rect.bottom<=n.rect.bottom&&r.splice(i,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function fn(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 dn(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 h=0;h<e.length;h++){let{rect:p,borderRadius:F}=e[h],I=p.left-.5,y=p.top-.5,u=p.width+1,O=p.height+1,P=Math.min(F+.5,u/2,O/2),R=fn(I,y,u,O,P),g=`__fork-glow-${h}`,C=document.createElementNS(t,"filter");C.setAttribute("id",g),C.setAttribute("x","-100%"),C.setAttribute("y","-100%"),C.setAttribute("width","300%"),C.setAttribute("height","300%");let _=document.createElementNS(t,"feGaussianBlur");_.setAttribute("in","SourceGraphic"),_.setAttribute("stdDeviation","8"),C.appendChild(_),o.appendChild(C);let D=`__fork-mask-${h}`,U=document.createElementNS(t,"mask");U.setAttribute("id",D),U.setAttribute("maskUnits","userSpaceOnUse"),U.setAttribute("x",String(I-200)),U.setAttribute("y",String(y-200)),U.setAttribute("width",String(u+400)),U.setAttribute("height",String(O+400));let T=document.createElementNS(t,"rect");T.setAttribute("x",String(I-200)),T.setAttribute("y",String(y-200)),T.setAttribute("width",String(u+400)),T.setAttribute("height",String(O+400)),T.setAttribute("fill","white"),U.appendChild(T);let se=document.createElementNS(t,"path");se.setAttribute("d",R),se.setAttribute("fill","black"),U.appendChild(se),o.appendChild(U);let W=document.createElementNS(t,"g");W.setAttribute("mask",`url(#${D})`),W.setAttribute("opacity","0");let A=document.createElementNS(t,"g");A.setAttribute("filter",`url(#${g})`);let S=document.createElementNS(t,"path");S.setAttribute("d",R),S.setAttribute("fill","none"),S.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),S.setAttribute("stroke-width","6"),S.setAttribute("stroke-linecap","round"),A.appendChild(S),W.appendChild(A),n.appendChild(W);let N=document.createElementNS(t,"path");N.setAttribute("d",R),N.setAttribute("fill","none"),N.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),N.setAttribute("stroke-width","2"),N.setAttribute("stroke-linecap","round"),N.setAttribute("opacity","0"),n.appendChild(N),s.push(S,N),S.__group=W;}r.appendChild(n),document.body.appendChild(r);let i=[];for(let h=0;h<s.length;h+=2){let p=s[h],F=s[h+1],I=p.__group,y=F.getTotalLength(),u=p.getTotalLength();if(y<=0)continue;let O=y*.35;F.setAttribute("stroke-dasharray",`${O} ${y-O}`),F.setAttribute("stroke-dashoffset","0"),i.push(F.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*y,opacity:.92,offset:.06},{strokeDashoffset:-2*y,opacity:.92,offset:.92},{strokeDashoffset:-2.25*y,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let P=u*.35;p.setAttribute("stroke-dasharray",`${P} ${u-P}`),p.setAttribute("stroke-dashoffset","0"),i.push(p.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*u,offset:.06},{strokeDashoffset:-2*u,offset:.92},{strokeDashoffset:-2.25*u,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 l=false,f=()=>{if(l)return;l=true,clearTimeout(w);for(let p of i)try{p.cancel();}catch{}let h=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});h.onfinish=()=>r.remove(),window.removeEventListener("click",f);},w=setTimeout(f,14500);return setTimeout(()=>{l||window.addEventListener("click",f);},500),f}function Ko(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:l,borderRadius:f}of e){let w=l.left,h=l.top,p=l.width,F=l.height,I=Math.min(f,p/2,F/2),y=fn(w,h,p,F,I),u=document.createElementNS(t,"path");u.setAttribute("d",y),u.setAttribute("fill","none"),u.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),u.setAttribute("stroke-width","1.5"),u.setAttribute("stroke-dasharray","8 4"),u.setAttribute("stroke-linecap","round"),u.setAttribute("filter","url(#__fork-removed-shadow)"),u.setAttribute("opacity","0"),n.appendChild(u),u.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 zo(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 Wo=kr__namespace.default.memo(function({component:t,containerRef:r,wrapperStyle:n,hostProps:o}){return ho.jsx("div",{ref:r,style:n,children:ho.jsx(t,{...o})})},(e,t)=>e.component===t.component&&zo(e.hostProps,t.hostProps)),yr=class extends kr__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 pn({slotId:e,children:t,githubRepo:r,shared:n,events:o,entityBindings:s}){br(t,e);let i=zt(e),{baseUrl:l,apiKey:f,appId:w,shouldSkipAnimation:h,markRevealSeen:p}=we(),[F,I]=kr.useState(null),y=kr.useRef(null),u=kr.useRef(null),O=kr.useRef(null),P=kr.useRef(false),R=kr.useRef(null),g=kr.useRef(null),C=!!(n||o),_=kr.useRef(null);C&&!_.current&&(_.current=new kt(e));let D=kr.useRef(o);if(D.current=o,kr.useEffect(()=>{if(C)return ()=>{_.current?.destroy(),_.current=null;}},[C,e]),C&&_.current&&n)for(let[A,S]of Object.entries(n))_.current.set(A,S);kr.useEffect(()=>{if(!C)return;_.current||(_.current=new kt(e));let A=_.current,S=Object.keys(D.current||{}).map(N=>A.on(N,(...B)=>D.current?.[N]?.(...B)));return ()=>S.forEach(N=>N())},[C,e]),kr.useEffect(()=>{if(un.has(e))return;un.add(e);let A={id:e,appId:w,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(`${l}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${f}`,"Content-Type":"application/json"},body:JSON.stringify(A)}).catch(()=>{});},[e,l,f,r,w,s]);let U=i?.id||null;kr.useEffect(()=>{if(i?.bundleUrl,y.current,u.current,!i?.bundleUrl||!U){return}let A=`${l}${i.bundleUrl.replace("bundle.js","component.js")}`,S=i.revealPending===true&&!hr.has(U),N=h(e),B=!N&&S;if(i.revealPending,N&&S&&(hr.add(U),p(i)),B&&u.current){let L=cn(u.current);O.current=L,P.current=true,`${e}${L.length}`;}window.__FORK_REACT__=kr__namespace.default,window.__FORK_REACT_DOM__=mo__namespace,window.__FORK_REACT_JSX__=ho__namespace;let K=Date.now(),X=`${l}${i.bundleUrl.replace("bundle.js","component.css")}?t=${K}`,G=document.createElement("link");G.rel="stylesheet",G.href=X,G.dataset.forkSlot=e,document.head.appendChild(G);let q=document.createElement("script");return q.src=A+"?t="+K,q.onload=()=>{let L=window.__FORK_EXPORT__;if(L?.default){if(u.current&&O.current&&P.current){let k=u.current.getBoundingClientRect(),E=u.current.cloneNode(true);E.setAttribute("data-fork-clone-overlay","true"),E.style.position="fixed",E.style.top=`${k.top}px`,E.style.left=`${k.left}px`,E.style.width=`${k.width}px`,E.style.height=`${k.height}px`,E.style.flex="none",E.style.minHeight="auto",E.style.zIndex="9998",E.style.pointerEvents="none",E.style.overflow="hidden";let x=getComputedStyle(u.current).backgroundColor;E.style.backgroundColor=x&&x!=="rgba(0, 0, 0, 0)"&&x!=="transparent"?x:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(E);let d=u.current.querySelectorAll("*"),M=E.querySelectorAll("*");for(let v=0;v<d.length;v++)d[v].scrollTop!==0&&(M[v].scrollTop=d[v].scrollTop),d[v].scrollLeft!==0&&(M[v].scrollLeft=d[v].scrollLeft);R.current=E;}I(()=>L.default),y.current=U;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},q.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(q),()=>{q.remove(),G.remove(),g.current&&(clearTimeout(g.current),g.current=null),R.current&&(R.current.remove(),R.current=null);}},[U,l,e]),kr.useEffect(()=>{if(!P.current||!F||!u.current){`${e}${P.current}`,u.current;return}let A=O.current;if(!A){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!u.current)return;let S=cn(u.current),N=Do(A,S),B=jo(A,S),K=R.current;if(`${e}${N.length}${B.length}`,B.length>0&&K){let X=Ko(B);g.current=setTimeout(()=>{g.current=null;let G=400;K.animate([{opacity:1},{opacity:0}],{duration:G,fill:"forwards"}),X.animate([{opacity:1},{opacity:0}],{duration:G,fill:"forwards"}),setTimeout(()=>{K.remove(),X.remove(),R.current=null,N.length>0&&(dn(N));},G);},3500);}else K&&(K.remove(),R.current=null),N.length>0&&(dn(N));O.current=null,P.current=false,i&&U&&(hr.add(U),p(i),`${e}`);});});},[F]);let T={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!i||i.status!=="complete"||!i.bundleUrl)return ho.jsx("div",{ref:u,style:T,children:t});if(!F)return ho.jsx("div",{ref:u,style:T,children:t});let W=t?.props??{};return ho.jsx(yr,{slotId:e,resetKey:U,fallback:ho.jsx("div",{ref:u,style:T,children:t}),children:ho.jsx(Wo,{component:F,containerRef:u,wrapperStyle:T,hostProps:W})})}var mn=new Set;function qo(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 hn(e,t=new Set){return kr.Children.forEach(e,r=>{if(!kr.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&&hn(n.children,t);}),t}function Xo({slotId:e,props:t,children:r,allowedFetches:n,entityBindings:o,githubRepo:s,callbacks:i,mode:l="iframe",shared:f,events:w}){if(br(r,e),l==="direct")return ho.jsx(pn,{slotId:e,githubRepo:s,shared:f,events:w,entityBindings:o,children:r});let h=zt(e),{baseUrl:p,apiKey:F,appId:I,userId:y,userHash:u,currentContainerId:O}=we(),P=kr.useRef(null),R=kr.useRef(false),g=kr.useRef(null),C=kr.useRef(i);C.current=i;let _=kr.useRef(t);_.current=t;let D=kr.useRef(n);D.current=n,kr.useEffect(()=>{if(typeof process<"u")return;let W=hn(r),A=new Set(i?Object.keys(i):[]),S=[...W].filter(N=>!A.has(N));S.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
|
-
`+
|
|
3
|
-
`)+"\n\nThe forked component will not be able to call these. Add them to the `callbacks` prop of <ForkSlot>.");},[e,r,i]),kr.useEffect(()=>{mn.has(e)||(mn.add(e),fetch(`${p}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${F}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:I,label:e,propsShape:t?qo(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:s,callbackNames:i?Object.keys(i):[],mode:l||"iframe",entityBindings:o||{}})}).catch(()=>{}));},[e,p,F,s,I,o]);let U=kr.useCallback(W=>{let A=P.current;if(A?.contentWindow&&R.current){let S=C.current?Object.keys(C.current):[];A.contentWindow.postMessage({type:"slot:props",props:W,callbackNames:S},"*"),g.current=null;}else g.current=W;},[]),T=kr.useCallback((W,A)=>{let S=D.current;return !S||S.length===0?false:S.some(N=>{let[B,K]=N.split(" "),X=A.split("?")[0];return W.toUpperCase()===B.toUpperCase()&&X.startsWith(K)})},[]);if(kr.useEffect(()=>{if(!h?.bundleUrl)return;let W=async A=>{if(A.source===P.current?.contentWindow){if(A.data?.type==="slot:ready")R.current=true,P.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:D.current||[]},"*"),D.current,g.current?U(g.current):U(_.current||{});else if(A.data?.type==="slot:event"){let S=A.data.event;S?.navigate&&(window.location.hash=S.navigate);}else if(A.data?.type==="slot:clipboard-write")navigator.clipboard.writeText(A.data.text).catch(S=>{console.warn(`[ForkSlot:${e}] clipboard write failed:`,S.message);});else if(A.data?.type==="slot:callback"){let{name:S,args:N}=A.data,B=C.current?.[S];B?(B(...N||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${S}`);}else if(A.data?.type==="slot:fetch"){let{id:S,method:N,url:B,body:K}=A.data,X=P.current?.contentWindow;if(!X)return;let G=N||"GET";if(!T(G,B)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${S}: ${G} ${B} \u2014 not in allowedFetches`),X.postMessage({type:"slot:fetch-response",id:S,error:`Fetch not allowed: ${G} ${B}`},"*");return}try{let q={method:G};K&&G!=="GET"&&(q.headers={"Content-Type":"application/json"},q.body=JSON.stringify(K));let L=await fetch(B,q),k=await L.json();`${e}${S}${L.status}`,X.postMessage({type:"slot:fetch-response",id:S,data:k,status:L.status},"*");}catch(q){console.error(`[ForkSlot:${e}] fetch #${S} failed:`,q.message),X.postMessage({type:"slot:fetch-response",id:S,error:q.message},"*");}}else if(A.data?.type==="slot:fork-data"){let{id:S,path:N,method:B,body:K}=A.data,X=P.current?.contentWindow;if(!X)return;if(!O||!I){X.postMessage({type:"slot:fork-data-response",id:S,error:"Fork data is unavailable until appId and containerId are resolved"},"*");return}let G=typeof N=="string"&&N.startsWith("/")?N:`/${String(N||"")}`,q=G.startsWith("/api/v1/data")?G:`/api/v1/data${G}`;try{let L={Authorization:`Bearer ${F}`,"Content-Type":"application/json","X-Fork-App-Id":I,...ce()};y&&(L["X-Fork-User-Id"]=y),u&&(L["X-Fork-User-Hash"]=u);let k=typeof B=="string"?B.toUpperCase():"POST",E=new URL(`${p}${q}`),x={method:k,headers:L};k==="GET"?(E.searchParams.set("appId",I),E.searchParams.set("containerId",O)):x.body=JSON.stringify({appId:I,containerId:O,...K&&typeof K=="object"?K:{}});let d=await fetch(E.toString(),x),M=await d.json().catch(()=>({}));if(!d.ok){let v=typeof M?.error=="string"?M.error:`Fork data API ${d.status}`;X.postMessage({type:"slot:fork-data-response",id:S,error:v,status:d.status},"*");return}X.postMessage({type:"slot:fork-data-response",id:S,data:M,status:d.status},"*");}catch(L){X.postMessage({type:"slot:fork-data-response",id:S,error:L.message},"*");}}}};return window.addEventListener("message",W),()=>{window.removeEventListener("message",W),R.current=false;}},[h?.bundleUrl,e,U,T,O,I,F,p,u,y]),kr.useEffect(()=>{h?.bundleUrl&&R.current&&U(t||{});},[t,h?.bundleUrl,U]),!h||h.status!=="complete"||!h.bundleUrl)return `${e}${h?.status||"none"}${h?.bundleUrl||"none"}`,ho.jsx(ho.Fragment,{children:r});`${e}${h.bundleUrl}`;let se=`${p}${h.bundleUrl.replace("/bundle.js","/host")}`;return ho.jsx("iframe",{ref:P,src:se,sandbox:"allow-scripts allow-same-origin allow-forms allow-clipboard-write",title:`Forked ${e}`,style:{width:"100%",border:"none",flex:1,minHeight:0}})}function Vt({style:e={width:20,height:20},...t}){return ho.jsxs("svg",{viewBox:"320 95 270 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:e,...t,children:[ho.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"}),ho.jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M387.096 174.735v188"}),ho.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"}),ho.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"}),ho.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 yn=5600,vr=2147483002;function es(e){return !e||e.state!=="complete"||!e.latest?null:`${e.latest.id}:${e.latest.completedAt??e.latest.updatedAt}`}function ts(){return typeof document>"u"?false:!!document.querySelector("[data-fork-clone-overlay], [data-fork-removed], [data-fork-highlights]")}function Fr(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 rs(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 Sr({onClick:e,hasNotification:t=false,activity:r}){let[n,o]=kr.useState(false),[s,i]=kr.useState(false),[l,f]=kr.useState(null),[w,h]=kr.useState(null),[p,F]=kr.useState(null),I=kr.useRef(0),y=n?48:40,u=es(r),O=!!(u&&r?.state==="complete"&&r.unreadCompletedCount>0),P=O?u:w?.key??null,R=!!(r&&r.state==="running"&&r.runningCount>0),g=!!(P&&P!==l&&(O||w)),C=R||g,_=O?r?.label:w?.label,D=g?"Built":r?.label??"Fork this app",U=g?_:r?.detail,T=Fr(r?.label??"Fork this app",r?.detail),se=Fr(D,U),W=g?Math.min(420,Math.max(326,se,w?.width??0,I.current+40)):se,A=g?46:40,S=C?[D,U].filter(Boolean).join(" "):rs(r,t)??"Fork this app",N=C?`${D}:${U??""}`:"idle",B=(t||r?.state==="complete"&&r.unreadCompletedCount>0)&&!C;kr.useEffect(()=>{if(typeof document>"u")return;let d=document.createElement("div");return d.setAttribute("data-fork-button-host","true"),d.style.position="relative",d.style.zIndex=String(vr),document.body.appendChild(d),F(d),()=>{d.remove(),F(null);}},[]),kr.useEffect(()=>{R&&(I.current=T);},[T,R]),kr.useEffect(()=>{!O||!u||!r?.label||h(d=>{if(d?.key===u)return d;let M=Math.min(420,Math.max(326,Fr("Built",r.label),I.current+40));return {key:u,label:r.label,width:M,startedAt:Date.now()}});},[r?.label,u,O]),kr.useEffect(()=>{r&&r.unreadCompletedCount===0&&r.state!=="running"&&h(null);},[r,r?.state,r?.unreadCompletedCount]),kr.useEffect(()=>{if(!P||!g||P===l)return;let d,M=w?.key===P?w.startedAt:Date.now(),v=()=>{let j=Date.now()-M;if(j>=yn&&!ts()||j>=yn*3){f(P);return}d=window.setTimeout(v,250);};return d=window.setTimeout(v,250),()=>{d!==void 0&&window.clearTimeout(d);}},[P,l,w?.key,w?.startedAt,g]);let K=C?{position:"fixed",bottom:24,right:24,zIndex:vr,width:`min(${W}px, calc(100vw - 32px))`,height:A,minWidth:0,maxWidth:"calc(100vw - 32px)",borderRadius:g?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:g?"flex-start":"center",gap:g?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:g?"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:vr,width:y,height:y,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"},X={minWidth:0,maxWidth:R?286:g?82:U?116:238,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13,fontWeight:650,lineHeight:"16px",letterSpacing:0},G={minWidth:0,maxWidth:g?278:void 0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flexShrink:g?1:0,color:"#64748b",fontSize:R?13:12,fontWeight:650,lineHeight:"16px",letterSpacing:0},q={minWidth:0,flex:g?1:void 0,display:"inline-flex",alignItems:"center",justifyContent:g?"flex-start":void 0,gap:8,animation:"__forkButtonTextSwap 220ms ease-out"},L={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:g?"__forkButtonBuiltDot 420ms ease-out":void 0,flexShrink:0},x=ho.jsxs(ho.Fragment,{children:[ho.jsx("style",{children:`
|
|
1
|
+
'use strict';var Pn=require('react'),as=require('react-dom'),ls=require('react/jsx-runtime'),cs=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 Pn__namespace=/*#__PURE__*/_interopNamespace(Pn);var as__namespace=/*#__PURE__*/_interopNamespace(as);var ls__namespace=/*#__PURE__*/_interopNamespace(ls);var cs__namespace=/*#__PURE__*/_interopNamespace(cs);var rt="__FORK_SHARED__";function xn(){var t,n,r,o;let e=globalThis;return e[rt]||(e[rt]={}),(t=e[rt]).react||(t.react=Pn__namespace),(n=e[rt])["react-dom"]||(n["react-dom"]=as__namespace),(r=e[rt])["react/jsx-runtime"]||(r["react/jsx-runtime"]=ls__namespace),(o=e[rt])["react/jsx-dev-runtime"]||(o["react/jsx-dev-runtime"]=cs__namespace),e[rt]}function An(e){return Object.assign(xn(),e)}var Tr=false,En=null,Rn=null;function $r(e,t,n){Tr=e,En=t,Rn=n;}function pe(){if(!Tr)return {};let e={};return En&&(e["X-Fork-App-Id"]=En),Rn&&(e["X-Fork-Container-Id"]=Rn),e}async function In(e){let t=new URLSearchParams({app:e.appId,user:e.userId});e.containerId&&t.set("containerId",e.containerId);let n=`${e.baseUrl}/api/v1/manifest?${t.toString()}`,r={Authorization:`Bearer ${e.apiKey}`,"X-Fork-App-Id":e.appId,"X-Fork-User-Id":e.userId,...e.extraHeaders??{}};e.userHash&&(r["X-Fork-User-Hash"]=e.userHash),e.userJwt&&(r["X-Fork-User-Jwt"]=e.userJwt),e.previous?.etag&&(r["If-None-Match"]=e.previous.etag);let o=await fetch(n,{headers:r,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[l,u]of Object.entries(s.modules)){let h=u.moduleUrl??u.bundleUrl??null,b=u.legacyModuleUrl??u.legacyBundleUrl??null;i[l]={forkId:u.forkId,moduleUrl:h,legacyModuleUrl:b,bundleUrl:u.bundleUrl??h,legacyBundleUrl:u.legacyBundleUrl??b,cssUrls:u.cssUrls??[],integrity:u.integrity,metadata:u.metadata,highlightHint:u.highlightHint,buildId:u.buildId,updatedAt:u.updatedAt};}return {containerId:s.containerId,forksPaused:!!s.forksPaused,slots:s.slots,modules:i,generatedAt:s.generatedAt,etag:o.headers.get("ETag")??void 0}}var us="fork:manifest:v1";function Cn(e,t,n){return `${us}:${e}:${t}:${n}`}function ds(e,t,n){if(typeof window>"u")return null;try{let r=window.localStorage.getItem(Cn(e,t,n));return r?JSON.parse(r):null}catch{return null}}function fs(e,t,n,r){if(!(typeof window>"u"))try{window.localStorage.setItem(Cn(e,t,n),JSON.stringify(r));}catch{}}function ps(e,t,n){if(!(typeof window>"u"))try{window.localStorage.removeItem(Cn(e,t,n));}catch{}}function ms(e,t){if(!e||!t)return e!==t;if(e.containerId!==t.containerId||!!e.forksPaused!=!!t.forksPaused)return true;let n=Object.entries(e.slots),r=Object.entries(t.slots);if(n.length!==r.length)return true;for(let[i,l]of n){let u=t.slots[i];if(!u||u.forkId!==l.forkId||u.buildId!==l.buildId)return true}let o=Object.entries(e.modules),s=Object.entries(t.modules);if(o.length!==s.length)return true;for(let[i,l]of o){let u=t.modules[i];if(!u||u.forkId!==l.forkId||u.buildId!==l.buildId)return true}return false}var Zt={isAdmin:false,actingUserId:null,containerId:null,containerName:null,containers:[]},Lr=Pn.createContext(null),ys=12e3,ks=45e3,Pr="fork:activity:v1",bs=new Set(["pending","running","building"]),ws="Setting up environment";function _e(e){return bs.has(e)}function vs(e,t){return t?.targetId?t:e.boundaryId?{targetKind:"module",targetId:e.boundaryId}:e.slotId?{targetKind:"slot",targetId:e.slotId}:null}function Ss(e,t){let n=vs(e,t);if(!n)return null;let r=new Date().toISOString();return {id:e.id,status:e.status,targetKind:n.targetKind,targetId:n.targetId,summary:e.summary??null,estimateMinutes:e.estimateMinutes??null,createdAt:e.createdAt||r,updatedAt:e.completedAt||r,completedAt:e.completedAt??null}}function _r(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 Qt(e,t){let n=typeof t.summary=="string"&&t.summary.trim()?t.summary.trim():void 0,r=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:n??r??null,estimateMinutes:o??s??null,latestMessage:t.latestMessage??e?.latestMessage??null,unread:t.unread??e?.unread??false}}function At(e){return `${e.id}:${e.completedAt||e.updatedAt}`}function ot(e){if(typeof window>"u")return new Set;try{let t=window.localStorage.getItem(e);if(!t)return new Set;let n=JSON.parse(t);return Array.isArray(n)?new Set(n.filter(r=>typeof r=="string")):new Set}catch{return new Set}}function st(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify([...t].slice(-200)));}catch{}}function Fs(e){if(e.estimateMinutes)return `~${e.estimateMinutes}m`}function xs(e){let t=e.data&&typeof e.data=="object"?e.data:{};if(e.type==="status"){let n=typeof t.status=="string"?t.status:"running",r=typeof t.summary=="string"?t.summary:void 0;return {status:n,latestMessage:_e(n)?"Building":void 0,summary:r,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 As(e){let t=e.filter(o=>_e(o.status)),n=e.filter(o=>o.status==="complete"&&o.unread),r=[...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:n.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():ws,detail:s?Fs(o):void 0,count:1,runningCount:1,unreadCompletedCount:n.length,latest:o}}if(n.length>1)return {state:"complete",label:`${n.length} forks ready`,count:n.length,runningCount:0,unreadCompletedCount:n.length,latest:n[0]};if(n.length===1){let o=n[0];return {state:"complete",label:o.summary||"Fork ready",count:1,runningCount:0,unreadCompletedCount:1,latest:o}}return {state:r?.status==="error"?"error":"idle",label:"Fork",count:0,runningCount:0,unreadCompletedCount:0,latest:r}}function Mn(e,t){if(!t)return t;try{return new URL(t,`${e.replace(/\/+$/,"")}/`).toString()}catch{return t}}function Es(e,t,n,r){let o={};for(let[s,i]of Object.entries(t.slots)){let l=i.bundleUrl??i.legacyBundleUrl;l&&(o[s]={id:i.forkId,userId:n,prompt:"",status:"complete",slotId:s,appId:r,bundleUrl:Mn(e,l),revealPending:i.revealPending===true,createdAt:i.updatedAt,completedAt:i.updatedAt});}return o}function Rs(e,t){let n={};for(let[r,o]of Object.entries(t.modules)){let s=o.moduleUrl??o.legacyModuleUrl??o.bundleUrl??"";s&&(n[r]={id:o.forkId,boundaryId:r,moduleUrl:Mn(e,s),cssUrls:(o.cssUrls??[]).map(i=>Mn(e,i)),integrity:o.integrity,metadata:o.metadata,highlightHint:o.highlightHint,createdAt:o.updatedAt});}return n}function Is(e){let{apiKey:t,baseUrl:n,children:r,appId:o,shared:s}=e,i="userId"in e?e.userId:void 0,l="userHash"in e?e.userHash:void 0,u="userJwt"in e?e.userJwt:void 0,h="authUrl"in e?e.authUrl:void 0,[b,d]=Pn.useState({}),[k,R]=Pn.useState(i?{userId:i,userHash:l,userJwt:u}:null),[v,f]=Pn.useState(!!i),[g,S]=Pn.useState(Zt),[I,m]=Pn.useState(false),[P,L]=Pn.useState(false),[j,O]=Pn.useState({}),[N,oe]=Pn.useState(!o),[Y,_]=Pn.useState(0),[F,H]=Pn.useState(null),[D,K]=Pn.useState(false),[V,W]=Pn.useState([]),[X,U]=Pn.useState(()=>typeof document>"u"?true:document.visibilityState!=="hidden"),C=Pn.useRef(new Map),M=Pn.useRef(new Map),[w,p]=Pn.useState(0),$=Pn.useRef(new Set),x=Pn.useRef(new Map),q=Pn.useRef(void 0),re=Pn.useRef(new Map),Ae=Pn.useRef([]),Te=Pn.useRef(new Set),Ue=Pn.useRef(false);xn(),Pn.useEffect(()=>{if(!o||!k?.userId||!(k.userHash||k.userJwt)){S(Zt),m(true);return}let c=false;m(false);let y=new URLSearchParams({app:o});return fetch(`${n}/api/v1/admin/containers?${y.toString()}`,{headers:{Authorization:`Bearer ${t}`,"X-Fork-App-Id":o,"X-Fork-User-Id":k.userId,...k.userHash?{"X-Fork-User-Hash":k.userHash}:{},...k.userJwt?{"X-Fork-User-Jwt":k.userJwt}:{}}}).then(async A=>A.status===403||!A.ok?null:A.json()).then(A=>{if(c)return;if(!A){S(Zt),m(true);return}let z=Array.isArray(A.containers)?A.containers:[],Q=A.currentContainerId??null,Z=z.find(ne=>ne.id===Q)?.name??null;S({isAdmin:true,actingUserId:typeof A.actingUserId=="string"?A.actingUserId:null,containerId:Q,containerName:Z,containers:z}),m(true);}).catch(()=>{c||(S(Zt),m(true));}),()=>{c=true;}},[t,o,k?.userHash,k?.userJwt,k?.userId,n]),Pn.useEffect(()=>{$r(g.isAdmin,o??null,g.containerId);},[g.isAdmin,g.containerId,o]);let Se=Pn.useCallback((c,y)=>{S(A=>{if(!A.isAdmin)return A;let z=A.containers.find(ne=>ne.id===c),Q=y??z?.name??null,Z=z?A.containers.map(ne=>({...ne,isPrimary:ne.id===c})):[{id:c,name:Q??"New container",isPrimary:true,forkCount:0},...A.containers.map(ne=>({...ne,isPrimary:false}))];return {...A,containerId:c,containerName:Q,containers:Z}}),L(false);},[]);s&&q.current!==s&&(An(s),q.current=s),Pn.useEffect(()=>{h&&(f(false),fetch(h,{credentials:"include"}).then(c=>{if(!c.ok)throw new Error(`Auth endpoint returned ${c.status}`);return c.json()}).then(c=>{if(!c.userId||typeof c.userId!="string")throw new Error("authUrl response must include userId");R({userId:c.userId,userHash:typeof c.userHash=="string"?c.userHash:void 0,userJwt:typeof c.userJwt=="string"?c.userJwt:void 0});}).catch(c=>{console.error("[ForkProvider] Failed to fetch user identity from authUrl:",c.message);}).finally(()=>{f(true);}));},[h]),Pn.useEffect(()=>{!h&&i&&(R({userId:i,userHash:l,userJwt:u}),f(true));},[i,l,u,h]);let te=k?.userId??"",se=k?.userHash,lt=k?.userJwt,$e=!!o,ke=Pn.useCallback(async()=>{if(!$e){H(null),K(false),O({}),oe(true),_(y=>y+1);return}if(!v){oe(false);return}if(!te||!o){H(null),K(false),d({}),O({}),oe(true),_(y=>y+1);return}oe(false);let c=g.isAdmin?g.containerId:null;if(g.isAdmin&&P){K(true),d({}),O({}),_(y=>y+1),oe(true);return}try{let y=await In({baseUrl:n,apiKey:t,appId:o,userId:te,userHash:se,userJwt:lt,containerId:c??void 0});y&&(H(y.containerId),K(g.isAdmin?!1:!!y.forksPaused),d(Es(n,y,te,o)),O(Rs(n,y)));}catch(y){console.error("[ForkProvider] Failed to fetch fork manifest:",y.message),H(null),K(false),d({}),O({});}finally{_(y=>y+1),oe(true);}},[t,o,n,v,$e,se,lt,te,g.isAdmin,g.containerId,P]);Pn.useEffect(()=>{if(!te||o)return;let c=new URLSearchParams({userId:te});se&&c.set("userHash",se),fetch(`${n}/api/v1/forks/active?${c.toString()}`,{headers:{Authorization:`Bearer ${t}`,...pe()}}).then(y=>{if(!y.ok)throw new Error(`${y.status}`);return y.json()}).then(y=>{y&&typeof y=="object"&&d(y);}).catch(()=>{});},[t,o,te,se,n]),Pn.useEffect(()=>{ke();},[ke]);let hn=Pn.useCallback(async c=>{if(o){if(g.isAdmin){L(c),K(c),c?(d({}),O({}),_(y=>y+1)):await ke();return}if(te){K(c),c&&(d({}),O({}),_(y=>y+1));try{let y=await fetch(`${n}/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:c,userId:te,userHash:se})});if(!y.ok)throw new Error(`${y.status}`);c||await ke();}catch(y){console.error("[ForkProvider] Failed to persist fork pause state:",y?.message??y),ke().catch(()=>{});}}}},[t,o,n,ke,g.isAdmin,se,te]),Bt=Pn.useCallback((c,y)=>{d(A=>({...A,[c]:y}));},[]),yn=Pn.useCallback(c=>{d(y=>{let A={...y};return delete A[c],A});},[]),Dt=Pn.useCallback(c=>{$.current.add(c);},[]),ge=Pn.useCallback(c=>$.current.has(c)?($.current.delete(c),true):false,[]),ct=Pn.useCallback(c=>{if(c.slotId&&d(A=>{let z=A[c.slotId];return !z||z.id!==c.id||!z.revealPending?A:{...A,[c.slotId]:{...z,revealPending:false}}}),g.isAdmin||!te)return;let y={Authorization:`Bearer ${t}`,"Content-Type":"application/json","X-Fork-User-Id":te};se&&(y["X-Fork-User-Hash"]=se),fetch(`${n}/api/v1/forks/reveals`,{method:"POST",headers:y,body:JSON.stringify({forkId:c.id,userId:te,userHash:se})}).catch(()=>{});},[t,n,g.isAdmin,se,te]),tt=Pn.useCallback((c,y)=>{x.current.set(c,y);},[]),jt=Pn.useCallback((c,y)=>x.current.get(c)!==y?false:(x.current.delete(c),true),[]),bt=Pn.useCallback(c=>{if(!o)return;let y=JSON.stringify(c);C.current.get(c.id)===y||M.current.get(c.id)?.signature===y||(M.current.set(c.id,{boundary:c,signature:y}),p(z=>z+1));},[o]);Pn.useEffect(()=>{if(!o||M.current.size===0)return;let c=setTimeout(()=>{let y=Array.from(M.current.values());y.length!==0&&fetch(`${n}/api/v1/boundaries`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({appId:o,boundaries:y.map(A=>A.boundary)})}).then(A=>{if(!A.ok)throw new Error(`${A.status}`)}).then(()=>{for(let A of y)M.current.get(A.boundary.id)?.signature===A.signature&&(M.current.delete(A.boundary.id),C.current.set(A.boundary.id,A.signature));}).catch(A=>{console.error("[ForkProvider] Failed to register module boundaries:",A.message);});},50);return ()=>{clearTimeout(c);}},[t,o,n,w]);let ut=Pn.useCallback(c=>j[c],[j]),Be=g.isAdmin?`admin:${g.actingUserId??"op"}`:te,Xe=`${t}:${o||"no-app"}:${F||"no-container"}:${Be||"anonymous"}`,wt=g.isAdmin?`op:${g.actingUserId??"op"}`:te,Kt=`${t}:${o||"no-app"}:${wt||"anonymous"}`,Fe=`${Pr}:seen:${Xe}`,xe=`${Pr}:tracked:${Xe}`;Pn.useEffect(()=>{Ae.current=V;},[V]);let dt=Pn.useCallback(()=>{let c={Authorization:`Bearer ${t}`,...pe()};return o&&(c["X-Fork-App-Id"]=o),te&&(c["X-Fork-User-Id"]=te),se&&(c["X-Fork-User-Hash"]=se),c},[t,o,se,te]);Pn.useEffect(()=>{if(typeof window>"u")return;let c=window.__FORK_RUNTIME__,y={dataFetch:async(A,z,Q="POST")=>{if(!o||!F)throw new Error("Fork data is unavailable until appId and containerId are resolved");let Z=typeof A=="string"&&A.startsWith("/")?A:`/${String(A||"")}`,ne=Z.startsWith("/api/v1/data")?Z:`/api/v1/data${Z}`,ie=Q.toUpperCase(),be=new URL(`${n}${ne}`),ce={Authorization:`Bearer ${t}`,"Content-Type":"application/json","X-Fork-App-Id":o,...pe()};te&&(ce["X-Fork-User-Id"]=te),se&&(ce["X-Fork-User-Hash"]=se);let me={method:ie,headers:ce};ie==="GET"?(be.searchParams.set("appId",o),be.searchParams.set("containerId",F)):me.body=JSON.stringify({appId:o,containerId:F,...z&&typeof z=="object"?z:{}});let ae=await fetch(be.toString(),me),de=await ae.json().catch(()=>({}));if(!ae.ok)throw new Error(typeof de?.error=="string"?de.error:`Fork data API ${ae.status}`);return de}};return window.__FORK_RUNTIME__=y,()=>{window.__FORK_RUNTIME__===y&&(window.__FORK_RUNTIME__=c);}},[t,o,n,F,se,te]);let Ie=Pn.useCallback(async()=>{if(!F||!I)return;let c=new URLSearchParams({container_id:F}),y=await fetch(`${n}/api/v1/forks?${c.toString()}`,{headers:dt()}).catch(()=>null);if(!y||!y.ok)return;let A=await y.json().catch(()=>({})),z=Array.isArray(A.forks)?A.forks:[],Q=ot(Fe),Z=ot(xe),ne=false,ie=new Map(Ae.current.map(ce=>[ce.id,ce])),be=[];for(let ce of z){let me=_r(ce);_e(me.status)&&!Z.has(me.id)&&(Z.add(me.id),ne=true);let ae=ie.get(me.id),de=ae?_e(ae.status):false,we=At(me);me.status==="complete"&&(Z.has(me.id)||de)&&!Q.has(we)&&!Te.current.has(we)&&!ae?.unread&&(Ue.current||Z.has(me.id)||de)&&(Te.current.add(we),be.push(me));}if(W(ce=>{let me=new Map(ce.map(fe=>[fe.id,fe])),ae=new Set,de=new Map;for(let fe of z){let Ee=_r(fe);ae.add(Ee.id);let Pe=me.get(Ee.id),Le=Pe?_e(Pe.status):false,pt=At(Ee),Wt=Ee.status==="complete"&&(Z.has(Ee.id)||Le)&&!Q.has(pt),qe=Qt(Pe,{...Ee,unread:Wt});de.set(Ee.id,qe);}for(let fe of ce)ae.has(fe.id)||(_e(fe.status)||fe.unread)&&de.set(fe.id,fe);let we=[...de.values()].sort((fe,Ee)=>Date.parse(Ee.updatedAt)-Date.parse(fe.updatedAt));return Ae.current=we,we}),ne&&st(xe,Z),be.length>0){for(let ce of be)ce.targetKind==="module"&&tt(ce.targetId,ce.id);ke().catch(()=>{});}Ue.current=true;},[Fe,xe,I,n,dt,F,ke,tt]),zt=Pn.useCallback((c,y)=>{let A=Ss(c,y);if(!A)return;let z=c.containerId??c._containerId;if(z&&!F&&H(z),_e(A.status)){let ne=ot(xe);ne.has(A.id)||(ne.add(A.id),st(xe,ne)),K(false),g.isAdmin&&L(false);}let Q=new Map(Ae.current.map(ne=>[ne.id,ne]));Q.set(A.id,Qt(Q.get(A.id),A));let Z=[...Q.values()].sort((ne,ie)=>Date.parse(ie.updatedAt)-Date.parse(ne.updatedAt));Ae.current=Z,W(Z);},[xe,t,o,F,g.isAdmin]),Ne=Pn.useCallback((c,y)=>{let A=xs(y),z=ot(Fe),Q=ot(xe),Z=Ae.current.find(ae=>ae.id===c),ne=Z?_e(Z.status):false;A.status&&_e(A.status)&&!Q.has(c)&&(Q.add(c),st(xe,Q));let ie=Z?Qt(Z,{...Z,...A}):null,be=ie?At(ie):null,ce=!!(ie&&ie.status==="complete"&&(Q.has(c)||ne)&&be&&!z.has(be)&&!Te.current.has(be)&&!Z?.unread),me=y.type==="complete"&&Z?.targetKind==="module"?Z.targetId:null;if(W(ae=>{let de=ae.find(Le=>Le.id===c);if(!de)return ae;let we=Qt(de,{...de,...A}),fe=we.status==="complete"&&(Q.has(c)||_e(de.status))&&!z.has(At(we)),Ee={...we,unread:fe},Pe=ae.map(Le=>Le.id===c?Ee:Le).sort((Le,pt)=>Date.parse(pt.updatedAt)-Date.parse(Le.updatedAt));return Ae.current=Pe,Pe}),ce&&ie&&be&&Te.current.add(be),y.type==="complete"){let ae=y.data&&typeof y.data=="object"?y.data:{},de=typeof ae.boundaryId=="string"?ae.boundaryId:me;de&&tt(de,c),ke().catch(()=>{});}},[Fe,xe,ke,tt]),ft=Pn.useCallback(c=>{let y=ot(Fe),A=ot(xe),z=false,Q=false;for(let Z of Ae.current){if(Z.status!=="complete"||c&&Z.id!==c)continue;let ne=At(Z);y.has(ne)||(y.add(ne),z=true),A.delete(Z.id)&&(Q=true);}W(Z=>{let ne=Z.map(ie=>ie.status!=="complete"||c&&ie.id!==c?ie:{...ie,unread:false});return Ae.current=ne,ne}),z&&st(Fe,y),Q&&st(xe,A);},[Fe,xe]);Pn.useEffect(()=>{Ue.current=false,Te.current.clear(),W([]);for(let c of re.current.values())c.close();re.current.clear(),F&&Ie();},[F,Ie]),Pn.useEffect(()=>{if(typeof document>"u")return;let c=()=>{let y=document.visibilityState!=="hidden";U(y),y&&F&&Ie();};return document.addEventListener("visibilitychange",c),window.addEventListener("focus",c),window.addEventListener("online",c),()=>{document.removeEventListener("visibilitychange",c),window.removeEventListener("focus",c),window.removeEventListener("online",c);}},[F,Ie]),Pn.useEffect(()=>{let c=V.filter(z=>_e(z.status));if(!F||c.length===0)return;let y=X?ys:ks,A=window.setInterval(()=>{Ie();},y);return ()=>window.clearInterval(A)},[F,X,V,Ie]),Pn.useEffect(()=>{for(let c of re.current.values())c.close();re.current.clear();},[t,n,g.containerId,se,te]),Pn.useEffect(()=>{let c=new Set(V.filter(y=>_e(y.status)).map(y=>y.id));for(let[y,A]of re.current.entries())c.has(y)||(A.close(),re.current.delete(y));for(let y of c){if(re.current.has(y))continue;let A=new URLSearchParams({key:t});te&&A.set("userId",te),se&&A.set("userHash",se),g.isAdmin&&g.containerId&&A.set("containerId",g.containerId);let z=new EventSource(`${n}/api/v1/forks/${y}/events?${A.toString()}`);z.onmessage=Q=>{try{Ne(y,JSON.parse(Q.data));}catch{}},z.onerror=()=>{z.close(),re.current.delete(y);},re.current.set(y,z);}},[t,n,V,g.isAdmin,g.containerId,Ne,se,te]),Pn.useEffect(()=>()=>{for(let c of re.current.values())c.close();re.current.clear();},[]);let kn=As(V),bn=Pn.useCallback(async()=>{if(!te)throw new Error("Reset requires a resolved user identity.");let c=new URLSearchParams({userId:te});se&&c.set("userHash",se);let y={Authorization:`Bearer ${t}`,...pe()};o&&(y["X-Fork-App-Id"]=o);let A=await fetch(`${n}/api/v1/forks/all?${c.toString()}`,{method:"DELETE",headers:y});if(!A.ok){let Q=await A.json().catch(()=>({}));throw new Error(Q.error||`API error: ${A.status}`)}let z=await A.json().catch(()=>({}));return d({}),O({}),oe(true),_(Q=>Q+1),W([]),Te.current.clear(),st(Fe,new Set),st(xe,new Set),$.current.clear(),x.current.clear(),z},[Fe,xe,t,o,n,se,te]);return ls.jsx(Lr.Provider,{value:{apiKey:t,userId:te,userHash:se,baseUrl:n,appId:o,forks:b,moduleOverridesEnabled:$e,moduleManifestReady:N,moduleManifestVersion:Y,currentContainerId:F,forksPaused:D,setForksPaused:hn,forkActivities:V,activitySummary:kn,adminContext:g,setAdminContainer:Se,trackForkActivity:zt,recordForkActivityEvent:Ne,markForkActivitySeen:ft,refreshForkActivities:Ie,setSlotFork:Bt,clearSlotFork:yn,skipAnimationForSlot:Dt,shouldSkipAnimation:ge,markRevealSeen:ct,queueBoundaryAnimation:tt,consumeBoundaryAnimation:jt,registerBoundary:bt,getBoundaryOverride:ut,refreshModuleManifest:ke,resetAllForks:bn,highlightScope:Kt},children:r})}function ve(){let e=Pn.useContext(Lr);if(!e)throw new Error("useForkContext must be used within <ForkProvider>");return e}function en(e){return ve().forks[e]}var Et=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,n){let r=this.values.get(t);if(Object.is(r,n))return;if(r!==void 0&&n!==null&&r!==null&&typeof r=="object"&&typeof n=="object")try{if(JSON.stringify(r)===JSON.stringify(n))return}catch{}this.values.set(t,n),this.snapshots.set(t,n);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,n){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(n),()=>{this.listeners.get(t)?.delete(n);}}useValue(t){let n=window.__FORK_REACT__;return n?.useSyncExternalStore?n.useSyncExternalStore(r=>this.subscribe(t,r),()=>this.getSnapshot(t)):(console.warn("[ForkBridge] React.useSyncExternalStore not available, returning static value"),this.values.get(t))}emit(t,...n){let r=this.eventHandlers.get(t);r&&r.forEach(o=>o(...n));}on(t,n){return this.eventHandlers.has(t)||this.eventHandlers.set(t,new Set),this.eventHandlers.get(t).add(n),()=>{this.eventHandlers.get(t)?.delete(n);}}destroy(){this.listeners.clear(),this.eventHandlers.clear(),this.values.clear(),this.snapshots.clear();let t=window.__FORK_BRIDGE__;t&&delete t[this.slotId];}};var Tn=new Set;function _n(e,t){let n;try{n=Pn.Children.only(e);}catch{let o=Pn.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 r=n.type;if(typeof r=="string")throw new Error(`<ForkSlot slotId="${t}"> child must be a React component (function or class), not an HTML element <${r}>. Wrap your slot's contents in a single named component, e.g. <ForkSlot slotId="${t}"><MyShell ...props /></ForkSlot>.`);if(typeof r=="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 n}var Or=new Set;function Nr(e){let t=[],n=e.querySelectorAll("*");for(let r of n){if(!(r instanceof HTMLElement))continue;let o=r.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(r.tagName))continue;let s=getComputedStyle(r),i=parseFloat(s.borderTopLeftRadius)||0;t.push({tag:r.tagName,className:r.className||"",text:(r.textContent||"").slice(0,50).trim(),rect:o,borderRadius:i});}return t}function Ps(e,t){let n=[];for(let r of t)if(!e.find(s=>s.tag===r.tag&&s.className===r.className&&Math.abs(s.rect.top-r.rect.top)<20&&Math.abs(s.rect.left-r.rect.left)<20)&&!n.some(i=>r.rect.top>=i.rect.top&&r.rect.left>=i.rect.left&&r.rect.right<=i.rect.right&&r.rect.bottom<=i.rect.bottom)){for(let i=n.length-1;i>=0;i--){let l=n[i];l.rect.top>=r.rect.top&&l.rect.left>=r.rect.left&&l.rect.right<=r.rect.right&&l.rect.bottom<=r.rect.bottom&&n.splice(i,1);}n.push({rect:r.rect,borderRadius:r.borderRadius});}return n}function _s(e,t){let n=[];for(let r of e)if(!t.find(s=>s.tag===r.tag&&s.className===r.className&&Math.abs(s.rect.top-r.rect.top)<20&&Math.abs(s.rect.left-r.rect.left)<20)&&!n.some(i=>r.rect.top>=i.rect.top&&r.rect.left>=i.rect.left&&r.rect.right<=i.rect.right&&r.rect.bottom<=i.rect.bottom)){for(let i=n.length-1;i>=0;i--){let l=n[i];l.rect.top>=r.rect.top&&l.rect.left>=r.rect.left&&l.rect.right<=r.rect.right&&l.rect.bottom<=r.rect.bottom&&n.splice(i,1);}n.push({rect:r.rect,borderRadius:r.borderRadius});}return n}function Br(e,t,n,r,o){return o=Math.max(0,Math.min(o,n/2,r/2)),o===0?`M ${e} ${t} L ${e+n} ${t} L ${e+n} ${t+r} L ${e} ${t+r} Z`:[`M ${e+o} ${t}`,`L ${e+n-o} ${t}`,`A ${o} ${o} 0 0 1 ${e+n} ${t+o}`,`L ${e+n} ${t+r-o}`,`A ${o} ${o} 0 0 1 ${e+n-o} ${t+r}`,`L ${e+o} ${t+r}`,`A ${o} ${o} 0 0 1 ${e} ${t+r-o}`,`L ${e} ${t+o}`,`A ${o} ${o} 0 0 1 ${e+o} ${t}`,"Z"].join(" ")}function Ur(e){let t="http://www.w3.org/2000/svg",n=document.createElement("div");n.setAttribute("data-fork-highlights","true"),n.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let r=document.createElementNS(t,"svg");r.setAttribute("width","100%"),r.setAttribute("height","100%"),r.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");r.appendChild(o);let s=[];for(let b=0;b<e.length;b++){let{rect:d,borderRadius:k}=e[b],R=d.left-.5,v=d.top-.5,f=d.width+1,g=d.height+1,S=Math.min(k+.5,f/2,g/2),I=Br(R,v,f,g,S),m=`__fork-glow-${b}`,P=document.createElementNS(t,"filter");P.setAttribute("id",m),P.setAttribute("x","-100%"),P.setAttribute("y","-100%"),P.setAttribute("width","300%"),P.setAttribute("height","300%");let L=document.createElementNS(t,"feGaussianBlur");L.setAttribute("in","SourceGraphic"),L.setAttribute("stdDeviation","8"),P.appendChild(L),o.appendChild(P);let j=`__fork-mask-${b}`,O=document.createElementNS(t,"mask");O.setAttribute("id",j),O.setAttribute("maskUnits","userSpaceOnUse"),O.setAttribute("x",String(R-200)),O.setAttribute("y",String(v-200)),O.setAttribute("width",String(f+400)),O.setAttribute("height",String(g+400));let N=document.createElementNS(t,"rect");N.setAttribute("x",String(R-200)),N.setAttribute("y",String(v-200)),N.setAttribute("width",String(f+400)),N.setAttribute("height",String(g+400)),N.setAttribute("fill","white"),O.appendChild(N);let oe=document.createElementNS(t,"path");oe.setAttribute("d",I),oe.setAttribute("fill","black"),O.appendChild(oe),o.appendChild(O);let Y=document.createElementNS(t,"g");Y.setAttribute("mask",`url(#${j})`),Y.setAttribute("opacity","0");let _=document.createElementNS(t,"g");_.setAttribute("filter",`url(#${m})`);let F=document.createElementNS(t,"path");F.setAttribute("d",I),F.setAttribute("fill","none"),F.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),F.setAttribute("stroke-width","6"),F.setAttribute("stroke-linecap","round"),_.appendChild(F),Y.appendChild(_),r.appendChild(Y);let H=document.createElementNS(t,"path");H.setAttribute("d",I),H.setAttribute("fill","none"),H.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),H.setAttribute("stroke-width","2"),H.setAttribute("stroke-linecap","round"),H.setAttribute("opacity","0"),r.appendChild(H),s.push(F,H),F.__group=Y;}n.appendChild(r),document.body.appendChild(n);let i=[];for(let b=0;b<s.length;b+=2){let d=s[b],k=s[b+1],R=d.__group,v=k.getTotalLength(),f=d.getTotalLength();if(v<=0)continue;let g=v*.35;k.setAttribute("stroke-dasharray",`${g} ${v-g}`),k.setAttribute("stroke-dashoffset","0"),i.push(k.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 S=f*.35;d.setAttribute("stroke-dasharray",`${S} ${f-S}`),d.setAttribute("stroke-dashoffset","0"),i.push(d.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(R.animate([{opacity:0,offset:0},{opacity:.92,offset:.06},{opacity:.92,offset:.92},{opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));}let l=false,u=()=>{if(l)return;l=true,clearTimeout(h);for(let d of i)try{d.cancel();}catch{}let b=n.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});b.onfinish=()=>n.remove(),window.removeEventListener("click",u);},h=setTimeout(u,14500);return setTimeout(()=>{l||window.addEventListener("click",u);},500),u}function Ls(e){let t="http://www.w3.org/2000/svg",n=document.createElement("div");n.setAttribute("data-fork-removed","true"),n.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let r=document.createElementNS(t,"svg");r.setAttribute("width","100%"),r.setAttribute("height","100%"),r.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),r.appendChild(o);for(let{rect:l,borderRadius:u}of e){let h=l.left,b=l.top,d=l.width,k=l.height,R=Math.min(u,d/2,k/2),v=Br(h,b,d,k,R),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"),r.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 n.appendChild(r),document.body.appendChild(n),n}function Hs(e,t){if(e===t)return true;let n=Object.keys(e);if(n.length!==Object.keys(t).length)return false;for(let r of n)if(!Object.is(e[r],t[r]))return false;return true}var Os=Pn__namespace.default.memo(function({component:t,containerRef:n,wrapperStyle:r,hostProps:o}){return ls.jsx("div",{ref:n,style:r,children:ls.jsx(t,{...o})})},(e,t)=>e.component===t.component&&Hs(e.hostProps,t.hostProps)),$n=class extends Pn__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 Dr({slotId:e,children:t,githubRepo:n,shared:r,events:o,entityBindings:s}){_n(t,e);let i=en(e),{baseUrl:l,apiKey:u,appId:h,shouldSkipAnimation:b,markRevealSeen:d}=ve(),[k,R]=Pn.useState(null),v=Pn.useRef(null),f=Pn.useRef(null),g=Pn.useRef(null),S=Pn.useRef(false),I=Pn.useRef(null),m=Pn.useRef(null),P=!!(r||o),L=Pn.useRef(null);P&&!L.current&&(L.current=new Et(e));let j=Pn.useRef(o);if(j.current=o,Pn.useEffect(()=>{if(P)return ()=>{L.current?.destroy(),L.current=null;}},[P,e]),P&&L.current&&r)for(let[_,F]of Object.entries(r))L.current.set(_,F);Pn.useEffect(()=>{if(!P)return;L.current||(L.current=new Et(e));let _=L.current,F=Object.keys(j.current||{}).map(H=>_.on(H,(...D)=>j.current?.[H]?.(...D)));return ()=>F.forEach(H=>H())},[P,e]),Pn.useEffect(()=>{if(Or.has(e))return;Or.add(e);let _={id:e,appId:h,label:e,eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:n,mode:"direct",sharedKeys:r?Object.keys(r):[],eventNames:o?Object.keys(o):[],propsShape:"",callbackNames:[],entityBindings:s||{}};fetch(`${l}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${u}`,"Content-Type":"application/json"},body:JSON.stringify(_)}).catch(()=>{});},[e,l,u,n,h,s]);let O=i?.id||null;Pn.useEffect(()=>{if(i?.bundleUrl,v.current,f.current,!i?.bundleUrl||!O){return}let _=`${l}${i.bundleUrl.replace("bundle.js","component.js")}`,F=i.revealPending===true&&!Tn.has(O),H=b(e),D=!H&&F;if(i.revealPending,H&&F&&(Tn.add(O),d(i)),D&&f.current){let U=Nr(f.current);g.current=U,S.current=true,`${e}${U.length}`;}window.__FORK_REACT__=Pn__namespace.default,window.__FORK_REACT_DOM__=as__namespace,window.__FORK_REACT_JSX__=ls__namespace;let K=Date.now(),V=`${l}${i.bundleUrl.replace("bundle.js","component.css")}?t=${K}`,W=document.createElement("link");W.rel="stylesheet",W.href=V,W.dataset.forkSlot=e,document.head.appendChild(W);let X=document.createElement("script");return X.src=_+"?t="+K,X.onload=()=>{let U=window.__FORK_EXPORT__;if(U?.default){if(f.current&&g.current&&S.current){let C=f.current.getBoundingClientRect(),M=f.current.cloneNode(true);M.setAttribute("data-fork-clone-overlay","true"),M.style.position="fixed",M.style.top=`${C.top}px`,M.style.left=`${C.left}px`,M.style.width=`${C.width}px`,M.style.height=`${C.height}px`,M.style.flex="none",M.style.minHeight="auto",M.style.zIndex="9998",M.style.pointerEvents="none",M.style.overflow="hidden";let w=getComputedStyle(f.current).backgroundColor;M.style.backgroundColor=w&&w!=="rgba(0, 0, 0, 0)"&&w!=="transparent"?w:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(M);let p=f.current.querySelectorAll("*"),$=M.querySelectorAll("*");for(let x=0;x<p.length;x++)p[x].scrollTop!==0&&($[x].scrollTop=p[x].scrollTop),p[x].scrollLeft!==0&&($[x].scrollLeft=p[x].scrollLeft);I.current=M;}R(()=>U.default),v.current=O;}else console.error(`[Fork:${e}] component.js loaded but no default export found`);window.__FORK_EXPORT__=void 0;},X.onerror=()=>{console.error(`[Fork:${e}] failed to load component.js`);},document.head.appendChild(X),()=>{X.remove(),W.remove(),m.current&&(clearTimeout(m.current),m.current=null),I.current&&(I.current.remove(),I.current=null);}},[O,l,e]),Pn.useEffect(()=>{if(!S.current||!k||!f.current){`${e}${S.current}`,f.current;return}let _=g.current;if(!_){return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!f.current)return;let F=Nr(f.current),H=Ps(_,F),D=_s(_,F),K=I.current;if(`${e}${H.length}${D.length}`,D.length>0&&K){let V=Ls(D);m.current=setTimeout(()=>{m.current=null;let W=400;K.animate([{opacity:1},{opacity:0}],{duration:W,fill:"forwards"}),V.animate([{opacity:1},{opacity:0}],{duration:W,fill:"forwards"}),setTimeout(()=>{K.remove(),V.remove(),I.current=null,H.length>0&&(Ur(H));},W);},3500);}else K&&(K.remove(),I.current=null),H.length>0&&(Ur(H));g.current=null,S.current=false,i&&O&&(Tn.add(O),d(i),`${e}`);});});},[k]);let N={flex:1,minHeight:0,display:"flex",flexDirection:"column"};if(!i||i.status!=="complete"||!i.bundleUrl)return ls.jsx("div",{ref:f,style:N,children:t});if(!k)return ls.jsx("div",{ref:f,style:N,children:t});let Y=t?.props??{};return ls.jsx($n,{slotId:e,resetKey:O,fallback:ls.jsx("div",{ref:f,style:N,children:t}),children:ls.jsx(Os,{component:k,containerRef:f,wrapperStyle:N,hostProps:Y})})}var Kr=new Set;function Bs(e){return `{ ${Object.entries(e).map(([n,r])=>r==null?`${n}: unknown`:Array.isArray(r)?`${n}: ${r.length>0?typeof r[0]:"unknown"}[]`:`${n}: ${typeof r}`).join("; ")} }`}function zr(e,t=new Set){return Pn.Children.forEach(e,n=>{if(!Pn.isValidElement(n))return;let r=n.props;for(let[o,s]of Object.entries(r))typeof s=="function"&&/^on[A-Z]/.test(o)&&t.add(o);r.children&&zr(r.children,t);}),t}function Ds({slotId:e,props:t,children:n,allowedFetches:r,entityBindings:o,githubRepo:s,callbacks:i,mode:l="iframe",shared:u,events:h}){if(_n(n,e),l==="direct")return ls.jsx(Dr,{slotId:e,githubRepo:s,shared:u,events:h,entityBindings:o,children:n});let b=en(e),{baseUrl:d,apiKey:k,appId:R,userId:v,userHash:f,currentContainerId:g}=ve(),S=Pn.useRef(null),I=Pn.useRef(false),m=Pn.useRef(null),P=Pn.useRef(i);P.current=i;let L=Pn.useRef(t);L.current=t;let j=Pn.useRef(r);j.current=r,Pn.useEffect(()=>{if(typeof process<"u")return;let Y=zr(n),_=new Set(i?Object.keys(i):[]),F=[...Y].filter(H=>!_.has(H));F.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
|
+
`+F.map(H=>` - ${H}`).join(`
|
|
3
|
+
`)+"\n\nThe forked component will not be able to call these. Add them to the `callbacks` prop of <ForkSlot>.");},[e,n,i]),Pn.useEffect(()=>{Kr.has(e)||(Kr.add(e),fetch(`${d}/api/v1/slots`,{method:"POST",headers:{Authorization:`Bearer ${k}`,"Content-Type":"application/json"},body:JSON.stringify({id:e,appId:R,label:e,propsShape:t?Bs(t):"",eventsShape:"{ navigate?: string }",currentLayout:"",githubRepo:s,callbackNames:i?Object.keys(i):[],mode:l||"iframe",entityBindings:o||{}})}).catch(()=>{}));},[e,d,k,s,R,o]);let O=Pn.useCallback(Y=>{let _=S.current;if(_?.contentWindow&&I.current){let F=P.current?Object.keys(P.current):[];_.contentWindow.postMessage({type:"slot:props",props:Y,callbackNames:F},"*"),m.current=null;}else m.current=Y;},[]),N=Pn.useCallback((Y,_)=>{let F=j.current;return !F||F.length===0?false:F.some(H=>{let[D,K]=H.split(" "),V=_.split("?")[0];return Y.toUpperCase()===D.toUpperCase()&&V.startsWith(K)})},[]);if(Pn.useEffect(()=>{if(!b?.bundleUrl)return;let Y=async _=>{if(_.source===S.current?.contentWindow){if(_.data?.type==="slot:ready")I.current=true,S.current?.contentWindow?.postMessage({type:"slot:allowed-fetches",paths:j.current||[]},"*"),j.current,m.current?O(m.current):O(L.current||{});else if(_.data?.type==="slot:event"){let F=_.data.event;F?.navigate&&(window.location.hash=F.navigate);}else if(_.data?.type==="slot:clipboard-write")navigator.clipboard.writeText(_.data.text).catch(F=>{console.warn(`[ForkSlot:${e}] clipboard write failed:`,F.message);});else if(_.data?.type==="slot:callback"){let{name:F,args:H}=_.data,D=P.current?.[F];D?(D(...H||[])):console.warn(`[ForkSlot:${e}] unknown callback: ${F}`);}else if(_.data?.type==="slot:fetch"){let{id:F,method:H,url:D,body:K}=_.data,V=S.current?.contentWindow;if(!V)return;let W=H||"GET";if(!N(W,D)){console.warn(`[ForkSlot:${e}] BLOCKED fetch #${F}: ${W} ${D} \u2014 not in allowedFetches`),V.postMessage({type:"slot:fetch-response",id:F,error:`Fetch not allowed: ${W} ${D}`},"*");return}try{let X={method:W};K&&W!=="GET"&&(X.headers={"Content-Type":"application/json"},X.body=JSON.stringify(K));let U=await fetch(D,X),C=await U.json();`${e}${F}${U.status}`,V.postMessage({type:"slot:fetch-response",id:F,data:C,status:U.status},"*");}catch(X){console.error(`[ForkSlot:${e}] fetch #${F} failed:`,X.message),V.postMessage({type:"slot:fetch-response",id:F,error:X.message},"*");}}else if(_.data?.type==="slot:fork-data"){let{id:F,path:H,method:D,body:K}=_.data,V=S.current?.contentWindow;if(!V)return;if(!g||!R){V.postMessage({type:"slot:fork-data-response",id:F,error:"Fork data is unavailable until appId and containerId are resolved"},"*");return}let W=typeof H=="string"&&H.startsWith("/")?H:`/${String(H||"")}`,X=W.startsWith("/api/v1/data")?W:`/api/v1/data${W}`;try{let U={Authorization:`Bearer ${k}`,"Content-Type":"application/json","X-Fork-App-Id":R,...pe()};v&&(U["X-Fork-User-Id"]=v),f&&(U["X-Fork-User-Hash"]=f);let C=typeof D=="string"?D.toUpperCase():"POST",M=new URL(`${d}${X}`),w={method:C,headers:U};C==="GET"?(M.searchParams.set("appId",R),M.searchParams.set("containerId",g)):w.body=JSON.stringify({appId:R,containerId:g,...K&&typeof K=="object"?K:{}});let p=await fetch(M.toString(),w),$=await p.json().catch(()=>({}));if(!p.ok){let x=typeof $?.error=="string"?$.error:`Fork data API ${p.status}`;V.postMessage({type:"slot:fork-data-response",id:F,error:x,status:p.status},"*");return}V.postMessage({type:"slot:fork-data-response",id:F,data:$,status:p.status},"*");}catch(U){V.postMessage({type:"slot:fork-data-response",id:F,error:U.message},"*");}}}};return window.addEventListener("message",Y),()=>{window.removeEventListener("message",Y),I.current=false;}},[b?.bundleUrl,e,O,N,g,R,k,d,f,v]),Pn.useEffect(()=>{b?.bundleUrl&&I.current&&O(t||{});},[t,b?.bundleUrl,O]),!b||b.status!=="complete"||!b.bundleUrl)return `${e}${b?.status||"none"}${b?.bundleUrl||"none"}`,ls.jsx(ls.Fragment,{children:n});`${e}${b.bundleUrl}`;let oe=`${d}${b.bundleUrl.replace("/bundle.js","/host")}`;return ls.jsx("iframe",{ref:S,src:oe,sandbox:"allow-scripts allow-same-origin allow-forms allow-clipboard-write",title:`Forked ${e}`,style:{width:"100%",border:"none",flex:1,minHeight:0}})}function nn({style:e={width:20,height:20},...t}){return ls.jsxs("svg",{viewBox:"320 95 270 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:e,...t,children:[ls.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"}),ls.jsx("path",{stroke:"currentColor",strokeWidth:"30",strokeLinejoin:"round",strokeLinecap:"round",d:"M387.096 174.735v188"}),ls.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"}),ls.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"}),ls.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 Wr=5600,Hn=2147483002;function Js(e){return !e||e.state!=="complete"||!e.latest?null:`${e.latest.id}:${e.latest.completedAt??e.latest.updatedAt}`}function Vs(){return typeof document>"u"?false:!!document.querySelector("[data-fork-clone-overlay], [data-fork-removed], [data-fork-highlights]")}function On(e,t){let n=Math.min(e.length,t?26:34)*7.4,r=t?Math.min(t.length,24)*6.8+10:0;return Math.round(Math.min(390,Math.max(116,56+n+r)))}function Xs(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 Nn({onClick:e,hasNotification:t=false,activity:n}){let[r,o]=Pn.useState(false),[s,i]=Pn.useState(false),[l,u]=Pn.useState(null),[h,b]=Pn.useState(null),[d,k]=Pn.useState(null),R=Pn.useRef(0),v=r?48:40,f=Js(n),g=!!(f&&n?.state==="complete"&&n.unreadCompletedCount>0),S=g?f:h?.key??null,I=!!(n&&n.state==="running"&&n.runningCount>0),m=!!(S&&S!==l&&(g||h)),P=I||m,L=g?n?.label:h?.label,j=m?"Built":n?.label??"Fork this app",O=m?L:n?.detail,N=On(n?.label??"Fork this app",n?.detail),oe=On(j,O),Y=m?Math.min(420,Math.max(326,oe,h?.width??0,R.current+40)):oe,_=m?46:40,F=P?[j,O].filter(Boolean).join(" "):Xs(n,t)??"Fork this app",H=P?`${j}:${O??""}`:"idle",D=(t||n?.state==="complete"&&n.unreadCompletedCount>0)&&!P;Pn.useEffect(()=>{if(typeof document>"u")return;let p=document.createElement("div");return p.setAttribute("data-fork-button-host","true"),p.style.position="relative",p.style.zIndex=String(Hn),document.body.appendChild(p),k(p),()=>{p.remove(),k(null);}},[]),Pn.useEffect(()=>{I&&(R.current=N);},[N,I]),Pn.useEffect(()=>{!g||!f||!n?.label||b(p=>{if(p?.key===f)return p;let $=Math.min(420,Math.max(326,On("Built",n.label),R.current+40));return {key:f,label:n.label,width:$,startedAt:Date.now()}});},[n?.label,f,g]),Pn.useEffect(()=>{n&&n.unreadCompletedCount===0&&n.state!=="running"&&b(null);},[n,n?.state,n?.unreadCompletedCount]),Pn.useEffect(()=>{if(!S||!m||S===l)return;let p,$=h?.key===S?h.startedAt:Date.now(),x=()=>{let q=Date.now()-$;if(q>=Wr&&!Vs()||q>=Wr*3){u(S);return}p=window.setTimeout(x,250);};return p=window.setTimeout(x,250),()=>{p!==void 0&&window.clearTimeout(p);}},[S,l,h?.key,h?.startedAt,m]);let K=P?{position:"fixed",bottom:24,right:24,zIndex:Hn,width:`min(${Y}px, calc(100vw - 32px))`,height:_,minWidth:0,maxWidth:"calc(100vw - 32px)",borderRadius:m?12:999,backgroundColor:r?"#ffffff":"rgba(255, 255, 255, 0.92)",border:"1px solid rgba(148, 163, 184, 0.42)",display:"inline-flex",alignItems:"center",justifyContent:m?"flex-start":"center",gap:m?10:8,color:"#111827",boxShadow:r?"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:m?"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:Hn,width:v,height:v,borderRadius:"50%",backgroundColor:r?"rgba(255, 255, 255, 1)":"rgba(255, 255, 255, 0.3)",border:r?"1px solid rgba(156, 163, 175, 1)":"1px solid rgba(156, 163, 175, 0.3)",display:"flex",alignItems:"center",justifyContent:"center",color:r?"#111827":"rgba(17, 24, 39, 0.5)",boxShadow:r?"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"},V={minWidth:0,maxWidth:I?286:m?82:O?116:238,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13,fontWeight:650,lineHeight:"16px",letterSpacing:0},W={minWidth:0,maxWidth:m?278:void 0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flexShrink:m?1:0,color:"#64748b",fontSize:I?13:12,fontWeight:650,lineHeight:"16px",letterSpacing:0},X={minWidth:0,flex:m?1:void 0,display:"inline-flex",alignItems:"center",justifyContent:m?"flex-start":void 0,gap:8,animation:"__forkButtonTextSwap 220ms ease-out"},U={width:8,height:8,borderRadius:"50%",backgroundColor:n?.state==="complete"?"#16a34a":"#ef4444",boxShadow:n?.state==="complete"?"0 0 0 3px rgba(22, 163, 74, 0.14)":"none",animation:m?"__forkButtonBuiltDot 420ms ease-out":void 0,flexShrink:0},w=ls.jsxs(ls.Fragment,{children:[ls.jsx("style",{children:`
|
|
4
4
|
@keyframes __forkButtonSpin { to { transform: rotate(360deg); } }
|
|
5
5
|
@keyframes __forkButtonTextSwap {
|
|
6
6
|
from { opacity: 0; transform: translateY(2px); }
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
70% { opacity: 1; transform: scale(1.18); }
|
|
16
16
|
100% { opacity: 1; transform: scale(1); }
|
|
17
17
|
}
|
|
18
|
-
`}),
|
|
18
|
+
`}),ls.jsxs("button",{onClick:e,onMouseEnter:()=>o(true),onMouseLeave:()=>{o(false),i(false);},onMouseDown:()=>i(true),onMouseUp:()=>i(false),style:K,title:F,"aria-label":F,children:[P&&n?ls.jsxs(ls.Fragment,{children:[I?ls.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"}}):ls.jsx("span",{"aria-hidden":true,style:U}),ls.jsxs("span",{style:X,children:[ls.jsx("span",{style:V,children:j}),O&&ls.jsx("span",{style:W,children:O})]},H)]}):ls.jsx(nn,{style:{width:24,height:24,animation:"__forkButtonLogoIn 220ms ease-out"}}),D&&ls.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 d?as.createPortal(w,d):w}var ni={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},ri={status:"#60a5fa",agent_message:"#a0a0a0",tool_use:"#fbbf24",build_start:"#c084fc",build_complete:"#6b7280",build_error:"#f87171",complete:"#6b7280",error:"#f87171"},oi={read:lucideReact.FileSearch,write:lucideReact.Pencil,search:lucideReact.FileSearch,shell:lucideReact.Terminal,build:lucideReact.Package},si={read:"#60a5fa",write:"#fbbf24",search:"#60a5fa",shell:"#a78bfa",build:"#c084fc"};function Bn(e){let t=e.data;switch(e.type){case "status":return `${t.message||t.status||"..."}`;case "agent_message":{let n=String(t.content||"");return /failed:/i.test(n)&&(n.includes("ENOENT")||n.includes("{")||n.includes("/Users/"))?"Adapting approach...":n}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 Zr({events:e}){let t=Pn.useRef(null);return Pn.useEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight);},[e]),ls.jsxs(ls.Fragment,{children:[ls.jsx("style",{children:`
|
|
19
19
|
@keyframes __fork-spin {
|
|
20
20
|
from { transform: rotate(0deg); }
|
|
21
21
|
to { transform: rotate(360deg); }
|
|
@@ -33,7 +33,8 @@
|
|
|
33
33
|
.__fork-stream::-webkit-scrollbar-thumb:hover {
|
|
34
34
|
background: rgba(255, 255, 255, 0.3);
|
|
35
35
|
}
|
|
36
|
-
`}),ho.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&&ho.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"#6b7280",fontSize:"11px"},children:[ho.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"),l=cs[r.type]||lucideReact.Code,f=ds[r.type]||"#9ca3af";if(r.type==="tool_use"){let w=String(r.data.category||"");l=fs[w]||lucideReact.Wrench,f=ps[w]||"#fbbf24";}return i?l=lucideReact.Loader2:!o&&r.type==="status"&&(l=lucideReact.Check,f="#4ade80"),ho.jsxs("div",{style:{display:"flex",gap:"6px",marginBottom:"6px",lineHeight:1.625},children:[ho.jsx(l,{style:{width:"12px",height:"12px",marginTop:"2px",flexShrink:0,color:f,...i?{animation:"__fork-spin 1s linear infinite"}:{}}}),ho.jsx("span",{style:{color:o&&!s?"#d1d5db":"#6b7280",wordBreak:"break-all"},children:Ar(r)})]},n)})]})]})}var Rn=35,Fs="Setting up environment",Ss="Built Custom Feature",Cn=360,St=380;function xs(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 As(e){return e.length<=Rn?e:e.slice(0,Rn-3).trimEnd()+"..."}function Is({events:e}){let[t,r]=kr.useState("Setting up environment..."),[n,o]=kr.useState(true),s=kr.useRef(t),i=kr.useRef(false);return kr.useEffect(()=>{if(!i.current){for(let f of e)if(f.type==="status"&&String(f.data.message||"").includes("Agent started")){i.current=true;break}}let l="Setting up environment...";if(i.current)for(let f=e.length-1;f>=0;f--){let w=e[f];if(w.type==="tool_use"||w.type==="build_start"||w.type==="build_complete"){l=As(Ar(w));break}}if(l!==s.current){o(false);let f=setTimeout(()=>{r(l),s.current=l,o(true);},200);return ()=>clearTimeout(f)}},[e]),ho.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 Rs({children:e}){let[t,r]=kr.useState(null);return kr.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?mo.createPortal(e,t):null}function Yt({state:e,fork:t,events:r,error:n,runs:o={},slotId:s,targetId:i,targetLabel:l,historyMode:f="slot",onSubmit:w,onUndo:h,onClose:p,baseUrl:F,apiKey:I,userId:y,userHash:u,appId:O,embedded:P=false,completeVariant:R="bubble"}){let[g,C]=kr.useState(""),[_,D]=kr.useState([]),[U,T]=kr.useState(false),[se,W]=kr.useState(false),[A,S]=kr.useState(false),[N,B]=kr.useState(false),[K,X]=kr.useState(false),[G,q]=kr.useState(false),[L,k]=kr.useState(false),[E,x]=kr.useState(false),[d,M]=kr.useState(false),[v,j]=kr.useState(null),[ne,Ee]=kr.useState(false),[Le,Ge]=kr.useState([]),[J,re]=kr.useState(null),[He,Fe]=kr.useState(false),[Me,Ye]=kr.useState(false),[rr,Mt]=kr.useState(false),[nr,Pt]=kr.useState(null),[ae,it]=kr.useState(null),[or,_t]=kr.useState(false),[ft,Qe]=kr.useState(false),[Oe,Ze]=kr.useState(""),Ie=kr.useRef(null),[be,Ne]=kr.useState(null),[Ue,pt]=kr.useState(false),[Pe,Lt]=kr.useState(null),[Ve,at]=kr.useState([]),[c,m]=kr.useState(null),[b,V]=kr.useState(false),Y=kr.useRef(false),Q=kr.useRef(null),Z=kr.useRef(null),{resetAllForks:de,adminContext:ie,setAdminContainer:pe,currentContainerId:ge,forksPaused:oe,setForksPaused:fe,forkActivities:Re,markForkActivitySeen:me}=we(),ve=ie.containerId??ge,Te=!!(ie.isAdmin&&Ue),_e=!!(ie.containerId??ge),[lt,Ht]=kr.useState(false),Ce=Pe!==null,Kr=kr.useRef(p);kr.useEffect(()=>{Kr.current=p;});let sr=kr.useRef(null),Ot=kr.useRef(false),zr=typeof window<"u"&&"documentPictureInPicture"in window,so=async()=>{if(!(!zr||Ce))try{let a=await window.documentPictureInPicture.requestWindow({width:Cn,height:640});a.document.body.style.margin="0",a.document.body.style.padding="0",a.document.body.style.height="100vh",a.document.body.style.overflow="hidden",a.document.body.style.background="#ffffff";try{let H=document.adoptedStyleSheets??[];H.length>0&&(a.document.adoptedStyleSheets=[...H]);}catch{}a.addEventListener("pagehide",()=>{sr.current=null,Lt(null),Ot.current||Kr.current(),Ot.current=!1;},{once:!0}),sr.current=a,Lt(a);}catch(a){console.warn("[Fork] PiP open failed:",a);}},io=()=>{Pe&&(Ot.current=true,Pe.close());};kr.useEffect(()=>()=>{Ot.current=true,sr.current?.close();},[]);let ut=i??s??"";(l||ut).replace(/[-_]+/g," ").replace(/\b\w/g,a=>a.toUpperCase());let Nt=kr.useRef(""),gt=()=>{let a={Authorization:`Bearer ${I}`,...ce()};return O&&(a["X-Fork-App-Id"]=O),y&&(a["X-Fork-User-Id"]=y),u&&(a["X-Fork-User-Hash"]=u),a},ct=P?true:se&&!A,mt=c?o[c]??null:null,Wr=c?Ve.find(a=>a.id===c)??null:null,ao=Wr?(a=>a==="pending"||a==="running"||a==="building")(Wr.status):false,Be=c?mt?.state??(ao?"running":null):b?e:null,Ut=c?mt?.events??[]:b?r:[],lo=c?mt?.state==="error"?mt.error:null:b&&e==="error"?n:null,ir=c?mt?.fork??null:b?t:null,uo=Object.values(o).filter(a=>a.state!=="running").length,Vr=c?!!Re.find(a=>a.id===c)?.unread:false;kr.useEffect(()=>{c&&Vr&&me(c);},[c,Vr,me]);let co=Ut.find(a=>{let H=a.data;return a.type==="status"&&H.summary})?.data?.summary||ir?.summary||Fs,et=Ut.find(a=>{let H=a.data;return (a.type==="status"||a.type==="complete")&&typeof H?.estimateMinutes=="number"})?.data?.estimateMinutes??ir?.estimateMinutes;kr.useEffect(()=>{if(f==="none"){T(true);return}if(!F||!I)return;if(!c){D([]),T(true);return}let a=new AbortController;return fetch(`${F}/api/v1/forks/${encodeURIComponent(c)}/messages`,{headers:gt(),signal:a.signal}).then(H=>H.ok?H.json():[]).then(H=>{if(a.signal.aborted)return;let z=[];for(let le of H){let he=le.forkId??c;le.role==="user"?z.push({type:"user",text:le.content,forkId:he}):z.push({type:"applied",text:le.content,forkId:he});}D(z),T(true);}).catch(()=>{a.signal.aborted||T(true);}),()=>{a.abort();}},[I,O,F,f,c,ie.containerId,u,y,t?.id,t?.completedAt]),kr.useEffect(()=>{if(f==="none"||!F||!I||!He)return;if(!J){at([]);return}let a=new AbortController,H=new URLSearchParams({container_id:J});return fetch(`${F}/api/v1/forks?${H.toString()}`,{headers:gt(),signal:a.signal}).then(z=>z.ok?z.json():{forks:[]}).then(z=>{a.signal.aborted||at(z.forks??[]);}).catch(()=>{}),()=>{a.abort();}},[I,O,F,f,J,He,t?.id,t?.completedAt,uo,ie.containerId,u,y]),kr.useEffect(()=>{e==="complete"&&x(false);},[e]);let Jr=Ve.some(a=>a.status==="pending"||a.status==="running"||a.status==="building");kr.useEffect(()=>{if(!Jr||!F||!I||!J)return;let a=new URLSearchParams({container_id:J}),H=gt(),le=setInterval(async()=>{try{let he=await fetch(`${F}/api/v1/forks?${a.toString()}`,{headers:H});if(!he.ok)return;let ye=await he.json();at(ye.forks??[]);}catch{}},3e3);return ()=>clearInterval(le)},[Jr,F,I,O,J]),kr.useEffect(()=>{if(P&&f==="none"){Ge([]),re(null),Fe(true),pt(false);return}if(ie.isAdmin){Ne(null),Ge(ie.containers.map(a=>({id:a.id,name:a.name,createdAt:"",hasAccess:true,isPrimary:a.isPrimary}))),re(ie.containerId??null),pt(true),Fe(true);return}ve?(Ge([{id:ve,name:"Primary container",createdAt:""}]),re(ve)):(Ge([]),re(null)),Fe(true),pt(false);},[I,ve,F,P,f,ie.isAdmin,ie.containerId,ie.containers]);let Bt=kr.useRef(void 0);kr.useEffect(()=>{if(He){if(Bt.current===void 0){Bt.current=J;return}Bt.current!==J&&(Bt.current=J,D([]),T(false));}},[J,He]);let Dt=kr.useRef(null);kr.useEffect(()=>{if(!Me)return;let a=z=>{if(!Dt.current)return;let le=typeof z.composedPath=="function"?z.composedPath():[];Dt.current.contains(z.target)||le.includes(Dt.current)||Ye(false);},H=z=>{z.key==="Escape"&&Ye(false);};return document.addEventListener("mousedown",a,true),document.addEventListener("keydown",H,true),()=>{document.removeEventListener("mousedown",a,true),document.removeEventListener("keydown",H,true);}},[Me]),kr.useEffect(()=>{if(P||!ct||A||Ce)return;let a=H=>{(typeof H.composedPath=="function"?H.composedPath():[]).some(he=>he instanceof Element&&he.hasAttribute("data-fork-panel-host"))||(S(true),W(false),setTimeout(()=>p(),St));};return document.addEventListener("mousedown",a,true),()=>{document.removeEventListener("mousedown",a,true);}},[P,ct,A,Ce,p]),kr.useEffect(()=>{Me||(Qe(false),Ze(""));},[Me]),kr.useEffect(()=>{ft&&(Ie.current?.focus(),Ie.current?.select());},[ft]),kr.useEffect(()=>{if(P)return;let a=requestAnimationFrame(()=>W(true));return ()=>cancelAnimationFrame(a)},[P]),kr.useEffect(()=>{let a=P||Ce;if((a||ct)&&(e==="prompting"||e==="complete")){let H=setTimeout(()=>Q.current?.focus(),a?100:St+100);return ()=>clearTimeout(H)}},[ct,P,Ce,e]);let qr=kr.useRef(new Set);kr.useEffect(()=>{for(let a of Object.values(o)){if(a.state!=="complete"||a.events.length===0)continue;let H=`${a.forkId}:${a.fork.completedAt??""}`;if(qr.current.has(H))continue;qr.current.add(H);let le=a.events.find(he=>he.type==="complete")?.data?.summary||a.fork.summary||Ss;D(he=>{let ye=[...he].reverse().find(lr=>lr.forkId===a.forkId);return ye?.type==="applied"&&ye.text===le?he:[...he,{type:"applied",text:le,forkId:a.forkId}]});}},[o]),kr.useEffect(()=>{Be==="complete"&&Nt.current&&(C(""),setTimeout(()=>Q.current?.focus(),200));},[Be]),kr.useEffect(()=>{Z.current&&(Z.current.scrollTop=Z.current.scrollHeight);},[_,e]);let Xr=()=>{if(g.trim()){Nt.current=g.trim();let a={},H=b||!c;H?(a.forceNew=true,Y.current=true,b||V(true)):a.forkId=c,H||D(z=>[...z,{type:"user",text:g.trim(),forkId:c}]),w(g.trim(),ut,J,a),C("");}};kr.useEffect(()=>{if(Y.current){if(e==="error"){Y.current=false;return}t?.id&&(m(t.id),V(false),Y.current=false);}},[t?.id,e]);let Gr=kr.useRef(new Set);kr.useEffect(()=>{t?.id&&(Y.current||e!=="running"&&e!=="complete"||Gr.current.has(t.id)||(Gr.current.add(t.id),m(a=>a??t.id),V(false)));},[t?.id,e]);let Yr=a=>{pe(a.container.id,a.container.name),re(a.container.id),Ge(H=>{let z=H.filter(le=>le.id!==a.container.id);return [{...a.container,isPrimary:true,hasAccess:true},...z.map(le=>({...le,isPrimary:false}))]}),m(null),V(false),Y.current=false,D([]),T(false),Nt.current="";},fo=async a=>{if(!(!Te||ae)){it(a),Ne(null);try{let H=await fetch(`${F}/api/v1/admin/containers/${encodeURIComponent(a)}/primary`,{method:"POST",headers:gt()});if(!H.ok){let z=await H.json().catch(()=>({}));throw new Error(z.error||`API error: ${H.status}`)}Yr(await H.json()),Ye(!1);}catch(H){Ne(H instanceof Error?H.message:String(H));}finally{it(null);}}},Qr=async a=>{if(!Te||ae)return;let H=a.trim();if(H){it("__new__"),Ne(null);try{let z=await fetch(`${F}/api/v1/admin/containers`,{method:"POST",headers:{...gt(),"Content-Type":"application/json"},body:JSON.stringify({name:H})});if(!z.ok){let le=await z.json().catch(()=>({}));throw new Error(le.error||`API error: ${z.status}`)}Yr(await z.json()),Qe(!1),Ze(""),Ye(!1);}catch(z){Ne(z instanceof Error?z.message:String(z));}finally{it(null);}}},Zr=async()=>{if(!(!h||d||!ut)){M(true);try{let a=await h(ut);D(H=>{let z=[...H];return z.length>=2&&z[z.length-1]?.type==="applied"?z.splice(-2,2):z.length>=1&&z[z.length-1]?.type==="applied"&&z.splice(-1,1),z}),a?.removed&&D([]);}catch{}finally{M(false);}}},en=()=>{if(P){p();return}if(Ce){Pe?.close();return}S(true),W(false),setTimeout(()=>p(),St);},po=P||Ce?{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:Cn,maxWidth:"100vw",background:"#ffffff",boxShadow:ct?"-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:ct?"translateX(0)":"translateX(100%)",transition:`transform ${St}ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow ${St}ms ease`,display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'},tn=Le.find(a=>a.id===J)?.name??(He?"Fork":"Loading..."),ht=b?[]:c?_.filter(a=>a.forkId===c||a.forkId==null):_,ar=ho.jsxs(ho.Fragment,{children:[ho.jsx("style",{children:`
|
|
36
|
+
`}),ls.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&&ls.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"#6b7280",fontSize:"11px"},children:[ls.jsx(lucideReact.Loader2,{style:{width:"12px",height:"12px",animation:"__fork-spin 1s linear infinite",flexShrink:0}}),"Connecting to agent..."]}),e.map((n,r)=>{let o=r===e.length-1,s=n.type==="complete"||n.type==="error"||n.type==="build_complete"||n.type==="build_error",i=o&&!s&&(n.type==="status"||n.type==="tool_use"||n.type==="build_start"),l=ni[n.type]||lucideReact.Code,u=ri[n.type]||"#9ca3af";if(n.type==="tool_use"){let h=String(n.data.category||"");l=oi[h]||lucideReact.Wrench,u=si[h]||"#fbbf24";}return i?l=lucideReact.Loader2:!o&&n.type==="status"&&(l=lucideReact.Check,u="#4ade80"),ls.jsxs("div",{style:{display:"flex",gap:"6px",marginBottom:"6px",lineHeight:1.625},children:[ls.jsx(l,{style:{width:"12px",height:"12px",marginTop:"2px",flexShrink:0,color:u,...i?{animation:"__fork-spin 1s linear infinite"}:{}}}),ls.jsx("span",{style:{color:o&&!s?"#d1d5db":"#6b7280",wordBreak:"break-all"},children:Bn(n)})]},r)})]})]})}var ai=0;function li(e){let t=/^data:([^;,]+);base64,(.+)$/.exec(e);return t?{mediaType:t[1],data:t[2]}:null}function ci(e){return new Promise((t,n)=>{let r=URL.createObjectURL(e),o=new Image;o.onload=()=>{URL.revokeObjectURL(r),t(o);},o.onerror=()=>{URL.revokeObjectURL(r),n(new Error("Failed to decode image"));},o.src=r;})}async function Qr(e){if(!e.type.startsWith("image/"))return null;let t;try{t=await ci(e);}catch{return null}let{naturalWidth:n,naturalHeight:r}=t;if(!n||!r)return null;let o=Math.min(1,1568/Math.max(n,r)),s=document.createElement("canvas");s.width=Math.max(1,Math.round(n*o)),s.height=Math.max(1,Math.round(r*o));let i=s.getContext("2d");if(!i)return null;i.fillStyle="#ffffff",i.fillRect(0,0,s.width,s.height),i.drawImage(t,0,0,s.width,s.height);let l=s.toDataURL("image/png");l.length>2e6&&(l=s.toDataURL("image/jpeg",.85));let u=li(l);return u?{id:`img-${++ai}-${Date.now().toString(36)}`,dataUrl:l,mediaType:u.mediaType,data:u.data}:null}function eo(e){let t=e.clipboardData?.items;if(!t)return [];let n=[];for(let r=0;r<t.length;r++){let o=t[r];if(o.kind==="file"&&o.type.startsWith("image/")){let s=o.getAsFile();s&&n.push(s);}}return n}var ui="rgba(59, 130, 246, 0.16)",di="1px solid #3b82f6";function fi(e){let t=e;for(;t;){if(t.hasAttribute("data-fork-panel-host")||t.hasAttribute("data-fork-button-host")||t.hasAttribute("data-fork-picker-overlay"))return true;let n=t.getRootNode();t=t.parentElement??(n instanceof ShadowRoot?n.host:null);}return false}function to(e){let t=Object.keys(e).find(o=>o.startsWith("__reactFiber$")||o.startsWith("__reactInternalInstance$"));if(!t)return;let n=e[t],r=0;for(;n&&r<30;){let o=n.type;if(typeof o=="function"){let s=o.displayName||o.name;if(s&&!/^(styled|ForwardRef|Anonymous)/.test(s))return s}else if(typeof o=="object"&&o!==null){let s=o.displayName||o.render?.displayName||o.render?.name;if(s)return s}n=n.return,r++;}}function pi(e){let t=[],n=e,r=0;for(;n&&n!==document.body&&r<6;){let o=n.tagName.toLowerCase();if(n.id){t.unshift(`#${CSS.escape(n.id)}`);break}let s=Array.from(n.classList).filter(i=>!/[[\]:]/.test(i)).slice(0,2);if(s.length>0)o+="."+s.map(i=>CSS.escape(i)).join(".");else if(n.parentElement){let i=Array.from(n.parentElement.children).filter(l=>l.tagName===n.tagName);i.length>1&&(o+=`:nth-of-type(${i.indexOf(n)+1})`);}t.unshift(o),n=n.parentElement,r++;}return t.join(" > ")}function mi(e){let t=e.outerHTML;if(t.length>2e3){let n=t.indexOf(">");n>-1&&n<1900?t=t.slice(0,2e3)+`
|
|
37
|
+
<!-- \u2026truncated\u2026 -->`:t=t.slice(0,2e3);}return t}function gi(e){let t=e.getBoundingClientRect(),n=(e.textContent??"").replace(/\s+/g," ").trim(),r={tag:e.tagName.toLowerCase(),selector:pi(e),html:mi(e),rect:{x:Math.round(t.x),y:Math.round(t.y),width:Math.round(t.width),height:Math.round(t.height)}};e.id&&(r.id=e.id);let o=Array.from(e.classList).slice(0,10);o.length>0&&(r.classes=o),n&&(r.text=n.slice(0,300));let s=to(e);return s&&(r.componentName=s),r}function an(e){let t=e.tag;if(e.id)t+=`#${e.id}`;else if(e.classes?.length)t+=`.${e.classes.slice(0,2).join(".")}`;else if(e.componentName)return `<${e.componentName}>`;return t.length>36?t.slice(0,35)+"\u2026":t}function no(e){let t=document.createElement("div");t.setAttribute("data-fork-picker-overlay",""),t.style.cssText=["position: fixed","inset: 0","pointer-events: none","z-index: 2147483001"].join(";");let n=document.createElement("div");n.style.cssText=["position: fixed","display: none",`background: ${ui}`,`border: ${di}`,"border-radius: 2px","pointer-events: none","box-sizing: border-box","transition: all 40ms linear"].join(";");let r=document.createElement("div");r.style.cssText=["position: fixed","display: none","background: #1f2937","color: #ffffff","font: 500 11px/1.4 ui-sans-serif, system-ui, sans-serif","padding: 3px 8px","border-radius: 6px","pointer-events: none","white-space: nowrap","box-shadow: 0 2px 8px rgba(0,0,0,0.25)"].join(";"),t.appendChild(n),t.appendChild(r),document.body.appendChild(t);let o=document.createElement("style");o.textContent="*, * > * { cursor: crosshair !important; }",document.head.appendChild(o);let s=null,i=false,l=()=>{s=null,n.style.display="none",r.style.display="none";},u=g=>{let S=g.getBoundingClientRect();n.style.display="block",n.style.left=`${S.left}px`,n.style.top=`${S.top}px`,n.style.width=`${S.width}px`,n.style.height=`${S.height}px`;let I=to(g),m=g.tagName.toLowerCase();g.id?m+=`#${g.id}`:g.classList.length>0&&(m+=`.${Array.from(g.classList).slice(0,2).join(".")}`),m.length>42&&(m=m.slice(0,41)+"\u2026"),r.textContent=I?`${m} \xB7 ${I} \xB7 ${Math.round(S.width)}\xD7${Math.round(S.height)}`:`${m} \xB7 ${Math.round(S.width)}\xD7${Math.round(S.height)}`,r.style.display="block";let P=S.top>=30?S.top-26:Math.max(4,S.top+4);r.style.top=`${P}px`,r.style.left=`${Math.max(4,Math.min(S.left,window.innerWidth-320))}px`;},h=(g,S)=>{let I=document.elementFromPoint(g,S);return !I||I===document.documentElement||I===document.body||fi(I)?null:I},b=g=>{let S=h(g.clientX,g.clientY);if(!S){l();return}S!==s&&(s=S,u(S));},d=()=>{s&&u(s);},k=g=>{let S=h(g.clientX,g.clientY);if(!S)return;g.preventDefault(),g.stopPropagation();let I=gi(S);f(),e.onPick(I);},R=g=>{h(g.clientX,g.clientY)&&(g.preventDefault(),g.stopPropagation());},v=g=>{g.key==="Escape"&&(g.preventDefault(),g.stopPropagation(),f(),e.onCancel());};function f(){i||(i=true,document.removeEventListener("mousemove",b,true),document.removeEventListener("click",k,true),document.removeEventListener("mousedown",R,true),document.removeEventListener("mouseup",R,true),document.removeEventListener("keydown",v,true),document.removeEventListener("scroll",d,true),window.removeEventListener("resize",d),t.remove(),o.remove());}return document.addEventListener("mousemove",b,true),document.addEventListener("click",k,true),document.addEventListener("mousedown",R,true),document.addEventListener("mouseup",R,true),document.addEventListener("keydown",v,true),document.addEventListener("scroll",d,true),window.addEventListener("resize",d),{stop:f}}function ro(){if(typeof window>"u")return null;let e=window;return e.SpeechRecognition||e.webkitSpeechRecognition||null}function oo(){return ro()!==null}function so(e){let t=ro();if(!t)return null;let n=true,r="",o=null,s=0,i=0,l=()=>{let u=new t;u.lang=typeof navigator<"u"&&navigator.language||"en-US",u.continuous=true,u.interimResults=true,u.onresult=h=>{let b="";for(let d=h.resultIndex;d<h.results.length;d++){let k=h.results[d],R=k[0]?.transcript??"";k.isFinal?r+=R:b+=R;}n&&e.onText(r,b);},u.onerror=h=>{let b=String(h?.error??"");if(b==="no-speech"||b==="aborted")return;n=false;let d=b==="not-allowed"||b==="service-not-allowed"?"not-allowed":b==="network"?"network":"other";e.onError(d);},u.onend=()=>{if(!n)return;let h=Date.now();if(h-s<1e3){if(i++,i>2){n=false,e.onError("other");return}}else i=0;s=h;try{u.start();}catch{try{l();}catch{n=false,e.onError("other");}}},o=u,u.start();};try{l();}catch{return null}return {stop:()=>{n=false;try{o?.stop();}catch{}}}}var lo=35,Ei="Setting up environment",Ri="Built Custom Feature",jn=360,Tt=380;function Kn(e){let t=Date.parse(e);if(Number.isNaN(t))return "";let n=Math.max(1,Math.round((Date.now()-t)/1e3));if(n<60)return `${n}s`;let r=Math.round(n/60);if(r<60)return `${r}m`;let o=Math.round(r/60);return o<24?`${o}h`:`${Math.round(o/24)}d`}function Ii(e){return e.length<=lo?e:e.slice(0,lo-3).trimEnd()+"..."}function Ci({events:e}){let[t,n]=Pn.useState("Setting up environment..."),[r,o]=Pn.useState(true),s=Pn.useRef(t),i=Pn.useRef(false);return Pn.useEffect(()=>{if(!i.current){for(let u of e)if(u.type==="status"&&String(u.data.message||"").includes("Agent started")){i.current=true;break}}let l="Setting up environment...";if(i.current)for(let u=e.length-1;u>=0;u--){let h=e[u];if(h.type==="tool_use"||h.type==="build_start"||h.type==="build_complete"){l=Ii(Bn(h));break}}if(l!==s.current){o(false);let u=setTimeout(()=>{n(l),s.current=l,o(true);},200);return ()=>clearTimeout(u)}},[e]),ls.jsx("span",{style:{fontSize:12.5,color:"#334155",fontWeight:600,opacity:r?1:0,transition:"opacity 0.2s ease",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},children:t})}function Mi({children:e}){let[t,n]=Pn.useState(null);return Pn.useEffect(()=>{if(typeof document>"u")return;let r=document.createElement("div");r.setAttribute("data-fork-panel-host",""),r.style.cssText="all: initial;",document.body.appendChild(r);let o=r.attachShadow({mode:"open"});return n(o),()=>{r.remove();}},[]),t?as.createPortal(e,t):null}function dn({state:e,fork:t,events:n,error:r,runs:o={},slotId:s,targetId:i,targetLabel:l,historyMode:u="slot",onSubmit:h,onUndo:b,onClose:d,baseUrl:k,apiKey:R,userId:v,userHash:f,appId:g,embedded:S=false,completeVariant:I="bubble"}){let[m,P]=Pn.useState(""),[L,j]=Pn.useState([]),[O,N]=Pn.useState(false),[oe,Y]=Pn.useState(false),[_,F]=Pn.useState(false),[H,D]=Pn.useState(false),[K,V]=Pn.useState(false),[W,X]=Pn.useState(false),[U,C]=Pn.useState(false),[M,w]=Pn.useState(false),[p,$]=Pn.useState(false),[x,q]=Pn.useState(null),[re,Ae]=Pn.useState(false),[Te,Ue]=Pn.useState([]),[Se,te]=Pn.useState(null),[se,lt]=Pn.useState(false),[$e,ke]=Pn.useState(false),[hn,Bt]=Pn.useState(false),[yn,Dt]=Pn.useState(null),[ge,ct]=Pn.useState(null),[tt,jt]=Pn.useState(false),[bt,ut]=Pn.useState(false),[Be,Xe]=Pn.useState(""),wt=Pn.useRef(null),[Kt,Fe]=Pn.useState(null),[xe,dt]=Pn.useState(false),[Ie,zt]=Pn.useState(null),[Ne,ft]=Pn.useState([]),[kn,bn]=Pn.useState(0),[c,y]=Pn.useState(null),[A,z]=Pn.useState(false),Q=Pn.useRef(false),Z=Pn.useRef(null),ne=Pn.useRef(null),[ie,be]=Pn.useState([]),[ce,me]=Pn.useState(null),[ae,de]=Pn.useState(false),we=Pn.useRef(null),[fe,Ee]=Pn.useState(false),Pe=Pn.useRef(null),Le=Pn.useRef(""),[pt,Wt]=Pn.useState(null),qe=Pn.useRef(null),ir=Pn.useRef(null),[Bo,ar]=Pn.useState(false),[Do,lr]=Pn.useState(false),[jo,cr]=Pn.useState(false),[Ko,ur]=Pn.useState(null),{resetAllForks:zo,adminContext:He,setAdminContainer:Wo,currentContainerId:dr,forksPaused:mt,setForksPaused:Jo,forkActivities:fr,markForkActivitySeen:pr}=ve(),Jt=He.containerId??dr,Vt=!!(He.isAdmin&&xe),Vo=!!(He.containerId??dr),[mr,gr]=Pn.useState(false),Oe=Ie!==null,hr=Pn.useRef(d);Pn.useEffect(()=>{hr.current=d;});let wn=Pn.useRef(null),Xt=Pn.useRef(false),yr=typeof window<"u"&&"documentPictureInPicture"in window,Xo=async()=>{if(!(!yr||Oe))try{let a=await window.documentPictureInPicture.requestWindow({width:jn,height:640});a.document.body.style.margin="0",a.document.body.style.padding="0",a.document.body.style.height="100vh",a.document.body.style.overflow="hidden",a.document.body.style.background="#ffffff";try{let T=document.adoptedStyleSheets??[];T.length>0&&(a.document.adoptedStyleSheets=[...T]);}catch{}a.addEventListener("pagehide",()=>{wn.current=null,zt(null),Xt.current||hr.current(),Xt.current=!1;},{once:!0}),wn.current=a,zt(a);}catch(a){console.warn("[Fork] PiP open failed:",a);}},qo=()=>{Ie&&(Xt.current=true,Ie.close());};Pn.useEffect(()=>()=>{Xt.current=true,wn.current?.close();},[]);let vt=i??s??"";(l||vt).replace(/[-_]+/g," ").replace(/\b\w/g,a=>a.toUpperCase());let qt=Pn.useRef(""),St=()=>{let a={Authorization:`Bearer ${R}`,...pe()};return g&&(a["X-Fork-App-Id"]=g),v&&(a["X-Fork-User-Id"]=v),f&&(a["X-Fork-User-Hash"]=f),a},gt=S?true:oe&&!_,Ft=c?o[c]??null:null,vn=c?Ne.find(a=>a.id===c)??null:null,Go=vn?(a=>a==="pending"||a==="running"||a==="building")(vn.status):false,De=c?Ft?.state??(Go?"running":null):A?e:null,ht=c?Ft?.events??[]:A?n:[],Yo=c?Ft?.state==="error"?Ft.error:null:A&&e==="error"?r:null,Sn=c?Ft?.fork??null:A?t:null,Zo=Object.values(o).filter(a=>a.state!=="running").length,kr=c?!!fr.find(a=>a.id===c)?.unread:false;Pn.useEffect(()=>{c&&kr&&pr(c);},[c,kr,pr]);let Qo=ht.find(a=>{let T=a.data;return a.type==="status"&&T.summary})?.data?.summary||Sn?.summary||Ei,nt=ht.find(a=>{let T=a.data;return (a.type==="status"||a.type==="complete")&&typeof T?.estimateMinutes=="number"})?.data?.estimateMinutes??Sn?.estimateMinutes;Pn.useEffect(()=>{if(u==="none"){N(true);return}if(!k||!R)return;if(!c){j([]),N(true);return}let a=new AbortController;return fetch(`${k}/api/v1/forks/${encodeURIComponent(c)}/messages`,{headers:St(),signal:a.signal}).then(T=>T.ok?T.json():[]).then(T=>{if(a.signal.aborted)return;let B=[];for(let G of T){let le=G.forkId??c;if(G.role==="user"){let je=(G.attachments??[]).filter(Me=>Me&&typeof Me.mediaType=="string"&&typeof Me.data=="string").map(Me=>({dataUrl:`data:${Me.mediaType};base64,${Me.data}`}));B.push({type:"user",text:G.content,forkId:le,timestamp:G.timestamp,attachments:je.length>0?je:void 0,selectedElement:G.selectedElement?{label:an(G.selectedElement)}:void 0});}else B.push({type:"applied",text:G.content,forkId:le,timestamp:G.timestamp});}j(B),N(true);}).catch(()=>{a.signal.aborted||N(true);}),()=>{a.abort();}},[R,g,k,u,c,He.containerId,f,v,t?.id,t?.completedAt]),Pn.useEffect(()=>{if(u==="none"||!k||!R||!se)return;if(!Se){ft([]);return}let a=new AbortController,T=new URLSearchParams({container_id:Se});return fetch(`${k}/api/v1/forks?${T.toString()}`,{headers:St(),signal:a.signal}).then(B=>B.ok?B.json():{forks:[]}).then(B=>{a.signal.aborted||ft(B.forks??[]);}).catch(()=>{}),()=>{a.abort();}},[R,g,k,u,Se,se,t?.id,t?.completedAt,Zo,kn,He.containerId,f,v]),Pn.useEffect(()=>{e==="complete"&&w(false);},[e]);let br=Ne.some(a=>a.status==="pending"||a.status==="running"||a.status==="building");Pn.useEffect(()=>{if(!br||!k||!R||!Se)return;let a=new URLSearchParams({container_id:Se}),T=St(),G=setInterval(async()=>{try{let le=await fetch(`${k}/api/v1/forks?${a.toString()}`,{headers:T});if(!le.ok)return;let je=await le.json();ft(je.forks??[]);}catch{}},3e3);return ()=>clearInterval(G)},[br,k,R,g,Se]),Pn.useEffect(()=>{if(S&&u==="none"){Ue([]),te(null),lt(true),dt(false);return}if(He.isAdmin){Fe(null),Ue(He.containers.map(a=>({id:a.id,name:a.name,createdAt:"",hasAccess:true,isPrimary:a.isPrimary}))),te(He.containerId??null),dt(true),lt(true);return}Jt?(Ue([{id:Jt,name:"Primary container",createdAt:""}]),te(Jt)):(Ue([]),te(null)),lt(true),dt(false);},[R,Jt,k,S,u,He.isAdmin,He.containerId,He.containers]);let Gt=Pn.useRef(void 0);Pn.useEffect(()=>{if(se){if(Gt.current===void 0){Gt.current=Se;return}Gt.current!==Se&&(Gt.current=Se,j([]),N(false));}},[Se,se]);let Yt=Pn.useRef(null);Pn.useEffect(()=>{if(!$e)return;let a=B=>{if(!Yt.current)return;let G=typeof B.composedPath=="function"?B.composedPath():[];Yt.current.contains(B.target)||G.includes(Yt.current)||ke(false);},T=B=>{B.key==="Escape"&&ke(false);};return document.addEventListener("mousedown",a,true),document.addEventListener("keydown",T,true),()=>{document.removeEventListener("mousedown",a,true),document.removeEventListener("keydown",T,true);}},[$e]),Pn.useEffect(()=>{if(S||!gt||_||Oe||ae)return;let a=T=>{(typeof T.composedPath=="function"?T.composedPath():[]).some(le=>le instanceof Element&&le.hasAttribute("data-fork-panel-host"))||(F(true),Y(false),setTimeout(()=>d(),Tt));};return document.addEventListener("mousedown",a,true),()=>{document.removeEventListener("mousedown",a,true);}},[S,gt,_,Oe,ae,d]),Pn.useEffect(()=>{$e||(ut(false),Xe(""));},[$e]),Pn.useEffect(()=>{bt&&(wt.current?.focus(),wt.current?.select());},[bt]),Pn.useEffect(()=>{if(S)return;let a=requestAnimationFrame(()=>Y(true));return ()=>cancelAnimationFrame(a)},[S]),Pn.useEffect(()=>{let a=S||Oe;if((a||gt)&&(e==="prompting"||e==="complete")){let T=setTimeout(()=>Z.current?.focus(),a?100:Tt+100);return ()=>clearTimeout(T)}},[gt,S,Oe,e]);let wr=Pn.useRef(new Set);Pn.useEffect(()=>{for(let a of Object.values(o)){if(a.state!=="complete"||a.events.length===0)continue;let T=`${a.forkId}:${a.fork.completedAt??""}`;if(wr.current.has(T))continue;wr.current.add(T);let G=a.events.find(le=>le.type==="complete")?.data?.summary||a.fork.summary||Ri;j(le=>{let je=[...le].reverse().find(Me=>Me.forkId===a.forkId);return je?.type==="applied"&&je.text===G?le:[...le,{type:"applied",text:G,forkId:a.forkId,timestamp:a.fork.completedAt??new Date().toISOString()}]});}},[o]),Pn.useEffect(()=>{De==="complete"&&qt.current&&(P(""),setTimeout(()=>Z.current?.focus(),200));},[De]),Pn.useEffect(()=>{ne.current&&(ne.current.scrollTop=ne.current.scrollHeight);},[L,e]),Pn.useEffect(()=>{let a=Z.current;a&&(a.style.height="auto",a.style.height=Math.min(a.scrollHeight,160)+"px");},[m]);let Ge=a=>{Wt(a),qe.current&&clearTimeout(qe.current),qe.current=setTimeout(()=>{qe.current=null,Wt(null);},3200);},vr=async a=>{if(a.length===0)return;let T=4-ie.length;if(T<=0){Ge(`Up to ${4} images per prompt`);return}a.length>T&&Ge(`Up to ${4} images per prompt`);let G=(await Promise.all(a.slice(0,T).map(Qr))).filter(le=>le!==null);G.length!==0&&(be(le=>[...le,...G].slice(0,4)),Z.current?.focus());},Sr=()=>{we.current?.stop(),we.current=null,de(false);},es=()=>{if(ae){Sr();return}de(true),Ge("Click an element on the page \xB7 Esc to cancel"),we.current=no({onPick:a=>{we.current=null,de(false),me(a),Z.current?.focus();},onCancel:()=>{we.current=null,de(false);}});},Fr=()=>{Pe.current?.stop(),Pe.current=null,Ee(false);},ts=()=>{if(fe){Fr();return}if(!oo()){Ge("Voice input is coming soon for this browser");return}let a=m.length>0&&!m.endsWith(" ")?m+" ":m;Le.current=a;let T=so({onText:(B,G)=>{P(Le.current+B+G);},onError:B=>{Pe.current=null,Ee(false),Ge(B==="not-allowed"?"Microphone access is blocked":B==="network"?"Voice input is coming soon for this browser":"Voice input stopped");}});if(!T){Ge("Voice input is coming soon for this browser");return}Pe.current=T,Ee(true);};Pn.useEffect(()=>()=>{we.current?.stop(),Pe.current?.stop(),qe.current&&clearTimeout(qe.current);},[]);let yt=!!(m.trim()||ie.length>0),xr=()=>{if(!yt)return;fe&&Fr(),ae&&Sr();let a=m.trim()||"See the attached screenshot.";qt.current=a;let T={};ie.length>0&&(T.attachments=ie.map(({mediaType:G,data:le})=>({mediaType:G,data:le}))),ce&&(T.selectedElement=ce);let B=A||!c;B?(T.forceNew=true,Q.current=true,A||z(true)):T.forkId=c,B||j(G=>[...G,{type:"user",text:a,forkId:c,attachments:ie.length>0?ie.map(le=>({dataUrl:le.dataUrl})):void 0,selectedElement:ce?{label:an(ce)}:void 0}]),h(a,vt,Se,T),P(""),be([]),me(null);};Pn.useEffect(()=>{if(Q.current){if(e==="error"){Q.current=false;return}t?.id&&(y(t.id),z(false),Q.current=false);}},[t?.id,e]);let Ar=Pn.useRef(new Set);Pn.useEffect(()=>{t?.id&&(Q.current||e!=="running"&&e!=="complete"||Ar.current.has(t.id)||(Ar.current.add(t.id),y(a=>a??t.id),z(false)));},[t?.id,e]);let Er=a=>{Wo(a.container.id,a.container.name),te(a.container.id),Ue(T=>{let B=T.filter(G=>G.id!==a.container.id);return [{...a.container,isPrimary:true,hasAccess:true},...B.map(G=>({...G,isPrimary:false}))]}),y(null),z(false),Q.current=false,j([]),N(false),qt.current="";},ns=async a=>{if(!(!Vt||ge)){ct(a),Fe(null);try{let T=await fetch(`${k}/api/v1/admin/containers/${encodeURIComponent(a)}/primary`,{method:"POST",headers:St()});if(!T.ok){let B=await T.json().catch(()=>({}));throw new Error(B.error||`API error: ${T.status}`)}Er(await T.json()),ke(!1);}catch(T){Fe(T instanceof Error?T.message:String(T));}finally{ct(null);}}},Rr=async a=>{if(!Vt||ge)return;let T=a.trim();if(T){ct("__new__"),Fe(null);try{let B=await fetch(`${k}/api/v1/admin/containers`,{method:"POST",headers:{...St(),"Content-Type":"application/json"},body:JSON.stringify({name:T})});if(!B.ok){let G=await B.json().catch(()=>({}));throw new Error(G.error||`API error: ${B.status}`)}Er(await B.json()),ut(!1),Xe(""),ke(!1);}catch(B){Fe(B instanceof Error?B.message:String(B));}finally{ct(null);}}},Ir=async()=>{if(!(!b||p||!vt)){$(true);try{(await b(vt,c))?.removed?(j([]),y(null),z(!1),Q.current=!1):j(T=>{let B=[...T];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}),bn(T=>T+1);}catch{}finally{$(false);}}},Cr=()=>{if(S){d();return}if(Oe){Ie?.close();return}F(true),Y(false),setTimeout(()=>d(),Tt);},rs=S||Oe?{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:jn,maxWidth:"100vw",background:"#ffffff",boxShadow:gt?"-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:gt?"translateX(0)":"translateX(100%)",transition:`transform ${Tt}ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow ${Tt}ms ease`,display:"flex",flexDirection:"column",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'},Mr=Te.find(a=>a.id===Se)?.name??(se?"Fork":"Loading..."),xt=A?[]:c?L.filter(a=>a.forkId===c||a.forkId==null):L,Fn=ls.jsxs(ls.Fragment,{children:[ls.jsx("style",{children:`
|
|
37
38
|
@keyframes __fork-pulse {
|
|
38
39
|
0%, 100% { opacity: 1; }
|
|
39
40
|
50% { opacity: 0.5; }
|
|
@@ -55,9 +56,9 @@
|
|
|
55
56
|
scrollbar-width: thin;
|
|
56
57
|
scrollbar-color: rgba(0, 0, 0, 0.12) transparent;
|
|
57
58
|
}
|
|
58
|
-
`}),ho.jsxs("div",{className:"__fork-panel",style:po,children:[ho.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:[ho.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:[ho.jsx("span",{onDoubleClick:async a=>{if(a.stopPropagation(),!ne&&confirm("Kill all forks in this container?")){Ee(true);try{let H=await de();`${H?.deleted??0}`,at([]),m(null),V(!1),C("");}catch(H){console.error("[Fork] Reset failed:",H);}finally{Ee(false);}}},style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:4,margin:-4,cursor:"pointer",flexShrink:0},children:ho.jsx(Vt,{style:{width:16,height:16,color:"#111827",pointerEvents:"none"}})}),Be==="running"?ho.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:co}):Le.length===0&&!Te?ho.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:"Fork"}):Te?ho.jsxs("div",{ref:Dt,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[ho.jsxs("button",{type:"button",onClick:()=>{Ye(a=>!a);},onMouseEnter:()=>Mt(true),onMouseLeave:()=>Mt(false),"aria-haspopup":"menu","aria-expanded":Me,style:{display:"inline-flex",alignItems:"center",gap:4,padding:"3px 6px",border:"1px solid transparent",borderRadius:6,background:rr||Me?"#f3f4f6":"transparent",fontSize:13,fontWeight:600,color:"#111827",fontFamily:"inherit",cursor:"pointer",maxWidth:180,minWidth:0,transition:"background-color 0.12s"},children:[ho.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:tn}),ho.jsx(lucideReact.ChevronDown,{style:{width:12,height:12,color:"#6b7280",flexShrink:0,transform:Me?"rotate(180deg)":void 0,transition:"transform 0.15s"}})]}),Me&&ho.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:[Le.map(a=>{let H=a.id===J,z=nr===a.id,le=ae===a.id;return ho.jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>Pt(a.id),onMouseLeave:()=>Pt(null),onClick:()=>{a.id!==J&&fo(a.id);},disabled:!!ae,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:z?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:ae?"default":"pointer",textAlign:"left",fontWeight:H?600:400,opacity:ae&&!le?.55:1},children:[ho.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:H&&ho.jsx(lucideReact.Check,{style:{width:12,height:12}})}),ho.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:le?"Switching...":a.name})]},a.id)}),ho.jsx("div",{style:{height:1,background:"#e5e7eb",margin:"4px 0"}}),ft?ho.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"4px 4px"},children:[ho.jsx("input",{ref:Ie,type:"text",value:Oe,placeholder:"Container name",disabled:ae==="__new__",onChange:a=>Ze(a.target.value),onKeyDown:a=>{a.key==="Enter"?(a.preventDefault(),Qr(Oe)):a.key==="Escape"&&(a.preventDefault(),a.stopPropagation(),Qe(false),Ze(""));},style:{flex:1,minWidth:0,padding:"5px 8px",border:"1px solid #d1d5db",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",background:"#ffffff",outline:"none"},onFocus:a=>{a.currentTarget.style.borderColor="#111827",a.currentTarget.style.boxShadow="0 0 0 2px rgba(17,24,39,0.15)";},onBlur:a=>{a.currentTarget.style.borderColor="#d1d5db",a.currentTarget.style.boxShadow="none";}}),ho.jsx("button",{type:"button",onClick:()=>{Qr(Oe);},disabled:!Oe.trim()||ae==="__new__",title:"Create",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:26,height:26,border:"none",borderRadius:4,background:!Oe.trim()||ae==="__new__"?"#e5e7eb":"#111827",color:!Oe.trim()||ae==="__new__"?"#9ca3af":"#ffffff",cursor:!Oe.trim()||ae==="__new__"?"default":"pointer",flexShrink:0},children:ae==="__new__"?ho.jsx("span",{style:{width:10,height:10,border:"1.5px solid currentColor",borderTopColor:"transparent",borderRadius:"50%",animation:"__fork-spin 0.7s linear infinite"}}):ho.jsx(lucideReact.Check,{style:{width:12,height:12}})})]}):ho.jsx("button",{type:"button",role:"menuitem",onMouseEnter:()=>_t(true),onMouseLeave:()=>_t(false),onClick:()=>{ae||(Ne(null),Ze(""),Qe(true));},disabled:!!ae,style:{display:"flex",alignItems:"center",width:"100%",padding:"6px 8px",border:"none",background:or?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:ae?"default":"pointer",textAlign:"left",opacity:ae&&ae!=="__new__"?.55:1},children:"+ New container"}),be&&ho.jsx("div",{style:{padding:"6px 8px",fontSize:11,lineHeight:1.35,color:"#b91c1c"},children:be})]})]}):ho.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:tn}),Be==="running"&&ho.jsx("span",{title:et?`Estimated ~${et} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:et?"#111827":"#9ca3af",backgroundColor:et?"rgba(17, 24, 39, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:et?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:et?`~${et}m`:"~ m"})]}),ho.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[_e&&ho.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:()=>{fe(!oe);},onMouseEnter:()=>Ht(true),onMouseLeave:()=>Ht(false),style:{position:"relative",width:26,height:15,borderRadius:999,border:"none",padding:0,marginRight:6,flexShrink:0,cursor:"pointer",backgroundColor:oe?lt?"#9ca3af":"#d1d5db":lt?"#374151":"#111827",transition:"background-color 0.18s ease",outline:"none",boxSizing:"border-box"},children:ho.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)"}})}),!P&&ho.jsxs(ho.Fragment,{children:[zr&&ho.jsx("button",{onClick:Ce?io:so,onMouseEnter:()=>X(true),onMouseLeave:()=>X(false),title:Ce?"Redock to sidebar":"Pop out into window",style:{padding:6,borderRadius:6,color:K?"#4b5563":"#9ca3af",backgroundColor:K?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:Ce?ho.jsx(lucideReact.PictureInPicture,{style:{width:16,height:16}}):ho.jsx(lucideReact.PictureInPicture2,{style:{width:16,height:16}})}),ho.jsx("button",{onClick:en,onMouseEnter:()=>B(true),onMouseLeave:()=>B(false),style:{padding:6,borderRadius:6,color:N?"#4b5563":"#9ca3af",backgroundColor:N?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:ho.jsx(lucideReact.X,{style:{width:16,height:16}})})]})]})]}),ho.jsxs("div",{ref:Z,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[(c||b)&&ho.jsxs("div",{style:{padding:"10px 12px 6px 12px",display:"flex",alignItems:"center",gap:8,borderBottom:"1px solid #f3f4f6"},children:[ho.jsx("button",{onClick:()=>{m(null),V(false),Y.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 H=(c?Ve.find(z=>z.id===c)?.targetId:null)??ut;return H?ho.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 ${H}`,children:["Forking ",ho.jsx("span",{style:{color:"#6b7280"},children:H})]}):null})()]}),!c&&!b&&ho.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[ho.jsx("div",{style:{padding:"12px 16px 10px 16px",borderBottom:"1px solid #f3f4f6"},children:ho.jsx("span",{style:{fontSize:12,fontWeight:600,color:"#111827"},children:"Forks"})}),Ve.length===0&&ho.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&&ho.jsx("div",{style:{display:"flex",flexDirection:"column"},children:Ve.map(a=>{let H=o[a.id],le=(H?H.events.find(ye=>{let lr=ye.data;return ye.type==="status"&&lr.summary})?.data?.summary??H.fork.summary:void 0)||a.summary||"Untitled fork",he=!!Re.find(ye=>ye.id===a.id)?.unread;return ho.jsxs("button",{onClick:()=>{V(false),m(a.id);},style:{textAlign:"left",padding:"10px 16px",background:"#ffffff",border:"none",borderBottom:"1px solid #f3f4f6",cursor:"pointer",display:"flex",flexDirection:"column",gap:2},onMouseEnter:ye=>ye.currentTarget.style.background="#fafafa",onMouseLeave:ye=>ye.currentTarget.style.background="#ffffff",children:[ho.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[he&&ho.jsx("span",{"aria-label":"Not viewed yet",title:"Not viewed yet",style:{width:7,height:7,borderRadius:"50%",backgroundColor:"#111827",flexShrink:0}}),ho.jsx("span",{style:{fontSize:13,fontWeight:he?600:500,color:"#111827",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1},children:le}),ho.jsx("span",{style:{fontSize:11,color:"#9ca3af",flexShrink:0},children:xs(a.updatedAt)})]}),ho.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:11,color:"#6b7280"},children:[ho.jsx("span",{style:{fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, "Liberation Mono", "Courier New", monospace',whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:a.targetId}),ho.jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),ho.jsxs("span",{children:[a.promptCount," prompt",a.promptCount===1?"":"s"]}),(()=>{let ye=o[a.id]?.state??a.status;return ye==="running"||ye==="building"||ye==="pending"?ho.jsxs(ho.Fragment,{children:[ho.jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),ho.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,color:"#111827"},children:[ho.jsx("svg",{width:"9",height:"9",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",style:{animation:"__fork-spin 2s linear infinite"},children:ho.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),"running"]})]}):ye==="error"?ho.jsxs(ho.Fragment,{children:[ho.jsx("span",{style:{color:"#d1d5db"},children:"\xB7"}),ho.jsx("span",{style:{color:"#b91c1c"},children:"failed"})]}):null})()]})]},a.id)})})]}),c&&ht.length>0&&ho.jsx("div",{style:{padding:"16px 16px 0 16px"},children:ht.map((a,H)=>ho.jsx("div",{style:{marginBottom:H<ht.length-1?10:0},children:a.type==="user"?ho.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexDirection:"row-reverse"},children:[ho.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:ho.jsx(lucideReact.User,{style:{width:13,height:13,color:"#6b7280"}})}),ho.jsx("div",{style:{backgroundColor:"#f3f4f6",borderRadius:"12px 4px 12px 12px",padding:"8px 12px",fontSize:13,color:"#374151",lineHeight:1.5,maxWidth:"75%"},children:a.text})]}):R==="item"&&H===ht.length-1?ho.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:12,padding:12,borderRadius:8,border:"1px solid #e4e4e7",background:"#ffffff"},children:[ho.jsx("div",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,flexShrink:0,borderRadius:6,background:"#f4f4f5",color:"#0a0a0a"},children:ho.jsx(lucideReact.BadgeCheck,{style:{width:16,height:16}})}),ho.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,flex:1,minWidth:0},children:[ho.jsx("div",{style:{fontSize:13,fontWeight:500,color:"#0a0a0a",lineHeight:1.3},children:"Feature applied"}),ho.jsx("div",{style:{fontSize:13,color:"#71717a",lineHeight:1.4},children:a.text})]}),h&&Be!=="running"&&ho.jsx("button",{onClick:z=>{z.stopPropagation(),Zr();},disabled:d,style:{padding:"4px 10px",fontSize:12,fontWeight:500,borderRadius:6,border:"1px solid #e4e4e7",background:"#ffffff",color:"#0a0a0a",cursor:d?"default":"pointer",opacity:d?.4:1,height:28,flexShrink:0},children:"Undo"})]}):ho.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[ho.jsx("div",{style:{width:22,height:22,borderRadius:"50%",backgroundColor:"#f0fdf4",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2},children:ho.jsx(lucideReact.Check,{style:{width:13,height:13,color:"#9ca3af"}})}),ho.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:[ho.jsx("span",{style:{flex:1},children:a.text}),h&&H===ht.length-1&&Be!=="running"&&ho.jsxs("button",{onClick:z=>{z.stopPropagation(),Zr();},onMouseEnter:()=>j(H),onMouseLeave:()=>j(null),disabled:d,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:v===H?"rgba(0,0,0,0.06)":"transparent",color:v===H?"#6b7280":"#d1d5db",cursor:d?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:d?.4:1,flexShrink:0},children:[ho.jsx(lucideReact.Undo2,{style:{width:12,height:12}}),v===H&&ho.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"})]})]})]})},H))}),Be==="running"&&ho.jsx("div",{style:{padding:16},children:ho.jsxs("div",{onClick:()=>x(!E),style:{backgroundColor:"#1a1a2e",borderRadius:12,overflow:"hidden",cursor:"pointer",transition:"all 0.3s cubic-bezier(0.22, 1, 0.36, 1)"},children:[ho.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 14px"},children:[ho.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[ho.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:ho.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),ho.jsx(Is,{events:Ut},c??"__compose__")]}),ho.jsx("div",{style:{color:"#6b7280",flexShrink:0,marginLeft:8,transition:"transform 0.2s ease",transform:E?"rotate(180deg)":"rotate(0deg)"},children:ho.jsx(lucideReact.ChevronDown,{style:{width:14,height:14}})})]}),ho.jsx("div",{style:{maxHeight:E?320:0,opacity:E?1:0,transition:"max-height 0.35s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.25s ease",overflow:"hidden"},children:ho.jsx("div",{style:{borderTop:"1px solid rgba(255,255,255,0.08)",maxHeight:320,overflowY:"auto"},children:ho.jsx(xn,{events:Ut},c??"__compose__")})})]})}),Be==="error"&&ho.jsxs("div",{style:{padding:"20px 16px",textAlign:"center"},children:[ho.jsx("div",{style:{width:36,height:36,backgroundColor:"#fef2f2",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 10px auto"},children:ho.jsx(lucideReact.X,{style:{width:18,height:18,color:"#ef4444"}})}),ho.jsx("p",{style:{fontSize:12,color:"#6b7280",marginBottom:10,maxWidth:260,margin:"0 auto 10px auto"},children:lo??n}),ho.jsxs("button",{onClick:()=>{let a=ir?.prompt||Nt.current;a&&w(a,ut);},onMouseEnter:()=>k(true),onMouseLeave:()=>k(false),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,color:"#111827",backgroundColor:L?"#e5e7eb":"#f3f4f6",border:"none",cursor:"pointer",transition:"background-color 0.15s",fontFamily:"inherit"},children:[ho.jsx(lucideReact.RotateCcw,{style:{width:12,height:12}})," Try Again"]})]})]}),!(c?Be==="running":b&&e==="running")&&ho.jsx("div",{style:{padding:"8px 12px 12px 12px",borderTop:"1px solid rgba(229, 231, 235, 0.6)",flexShrink:0},children:ho.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:[ho.jsx("textarea",{ref:Q,value:g,onChange:a=>{C(a.target.value),a.target.style.height="auto",a.target.style.height=Math.min(a.target.scrollHeight,160)+"px";},onKeyDown:a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),Xr()),a.key==="Escape"&&!P&&en();},placeholder:c?"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"}}),ho.jsx("button",{onClick:Xr,disabled:!g.trim(),onMouseEnter:()=>q(true),onMouseLeave:()=>q(false),style:{width:26,height:26,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:g.trim()?1:.25,transform:G&&g.trim()?"scale(1.1)":"scale(1)",background:g.trim()?"#111827":"rgba(0,0,0,0.12)",border:"none",cursor:g.trim()?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s",padding:0},children:ho.jsx(lucideReact.ArrowUp,{style:{width:13,height:13}})})]})})]})]});return P?ar:Ce&&Pe?mo.createPortal(ar,Pe.document.body):ho.jsx(Rs,{children:ar})}function $n(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 Rr(e){let{apiKey:t,userId:r,userHash:n,baseUrl:o,appId:s,adminContext:i,refreshModuleManifest:l,queueBoundaryAnimation:f,trackForkActivity:w,recordForkActivityEvent:h}=we(),[p,F]=kr.useState({}),[I,y]=kr.useState(null),[u,O]=kr.useState("idle"),[P,R]=kr.useState(false),[g,C]=kr.useState(null),_=kr.useRef(new Map),D=kr.useCallback((k,E)=>{F(x=>{let M=x[k]??{forkId:k,state:"running",fork:E.fork,events:[],error:null};return {...x,[k]:{...M,...E}}});},[]),U=kr.useCallback((k,E)=>{F(x=>{let d=x[k];return d?{...x,[k]:{...d,events:[...d.events,E]}}:x});},[]),T=kr.useCallback(k=>{let E=_.current.get(k);E&&(E.close(),_.current.delete(k));},[]),se=kr.useCallback(()=>{O("prompting"),C(null),R(false),y(null);},[]),W=kr.useCallback(()=>{O("idle"),R(false),C(null),y(null);for(let k of _.current.values())k.close();_.current.clear(),F({});},[]),A=kr.useCallback((k,E)=>{T(k.id);let x=new URLSearchParams({key:t});r&&x.set("userId",r),n&&x.set("userHash",n),i.isAdmin&&i.containerId&&x.set("containerId",i.containerId);let d=new EventSource(`${o}/api/v1/forks/${k.id}/events?${x.toString()}`);_.current.set(k.id,d),d.onmessage=M=>{try{let v=JSON.parse(M.data);if(h(k.id,v),U(k.id,v),v.type==="complete"){let j=v.data;f(E,k.id),l().catch(()=>{}).finally(()=>{let ne={...k,status:"complete",moduleUrl:j.moduleUrl,cssUrls:j.cssUrls,summary:j.summary,completedAt:new Date().toISOString()};D(k.id,{state:"complete",fork:ne}),T(k.id);});}else if(v.type==="error"){let j=v.data;D(k.id,{state:"error",error:j.error||"Unknown error"}),T(k.id);}}catch{}},d.onerror=()=>{let M={Authorization:`Bearer ${t}`,...ce()};r&&(M["X-Fork-User-Id"]=r),n&&(M["X-Fork-User-Hash"]=n),fetch(`${o}/api/v1/forks/${k.id}`,{headers:M}).then(v=>v.json()).then(v=>{v.status==="complete"?(f(E,v.id),l().catch(()=>{}),D(k.id,{state:"complete",fork:v})):v.status==="error"?D(k.id,{state:"error",fork:v,error:v.error||"Fork generation failed"}):D(k.id,{fork:v});}).catch(()=>{D(k.id,{state:"error",error:"Connection lost"});}),T(k.id);};},[i.containerId,i.isAdmin,t,U,o,T,f,h,l,D,n,r]),S=kr.useCallback(async(k,E,x)=>{try{if(!s)throw new Error("ForkProvider requires appId for module boundary prompts.");R(!0),C(null),y(null);let d;if(x?.forkId){let M={prompt:k};r&&(M.userId=r),n&&(M.userHash=n);let v=await fetch(`${o}/api/v1/forks/${encodeURIComponent(x.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...ce()},body:JSON.stringify(M)});if(!v.ok){let j=await v.json().catch(()=>({}));throw new Error(j.error||`API error: ${v.status}`)}d=await v.json();}else {let M={userId:r,prompt:k,boundaryId:e,appId:s};E?M.containerId=E:i.isAdmin&&i.containerId&&(M.containerId=i.containerId),n&&(M.userHash=n),x?.forceNew&&(M.force_new=!0);let v=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...ce()},body:JSON.stringify(M)});if(!v.ok){let j=await v.json().catch(()=>({}));throw new Error(j.error||`API error: ${v.status}`)}d=await v.json();}F(M=>({...M,[d.id]:{forkId:d.id,state:"running",fork:d,events:[],error:null}})),y(d.id),R(!1),w(d,{targetKind:"module",targetId:e}),A(d,d.boundaryId??e);}catch(d){C(d.message),R(false);}},[i.containerId,i.isAdmin,t,s,o,e,A,w,n,r]),N=kr.useCallback(async k=>{try{let E={Authorization:`Bearer ${t}`,...ce()};r&&(E["X-Fork-User-Id"]=r),n&&(E["X-Fork-User-Hash"]=n);let x=await fetch(`${o}/api/v1/forks/${k}`,{headers:E});if(!x.ok)return;let d=await x.json(),M=d.boundaryId??e;if(w(d,{targetKind:"module",targetId:M}),d.status==="complete"){F(v=>({...v,[d.id]:{forkId:d.id,state:"complete",fork:d,events:[],error:null}})),y(d.id);return}if(d.status==="error"){F(v=>({...v,[d.id]:{forkId:d.id,state:"error",fork:d,events:[],error:d.error||"Fork generation failed"}})),y(d.id);return}if(d.status!=="pending"&&d.status!=="running"&&d.status!=="building")return;F(v=>({...v,[d.id]:{forkId:d.id,state:"running",fork:d,events:[],error:null}})),y(d.id),A(d,M);}catch{}},[t,o,e,A,w,n,r]),B=kr.useCallback(async()=>{try{if(!s)throw new Error("ForkProvider requires appId for boundary undo.");let k={userId:r,boundaryId:e,appId:s};n&&(k.userHash=n);let E=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(k)});if(!E.ok){let d=await E.json().catch(()=>({}));throw new Error(d.error||`API error: ${E.status}`)}let x=await E.json();if(await l().catch(()=>{}),x.removed)F(d=>{let M={};for(let[v,j]of Object.entries(d))(j.fork.boundaryId??e)!==e&&(M[v]=j);return M}),y(null),O("prompting");else if(x.fork){let d=x.fork;D(d.id,{state:"complete",fork:d}),y(d.id);}return x}catch(k){throw C(k.message),k}},[t,s,o,e,l,D,n,r]),K=I?p[I]??null:null,X=P?"running":g?"error":K?K.state:u,G=K?.fork??null,q=K?.events??[],L=g??K?.error??null;return {state:X,fork:G,events:q,error:L,runs:p,open:se,close:W,startFork:S,undoFork:B,adoptRunningFork:N}}var $s=0;function Pn(e){let{state:t,fork:r,events:n,error:o,runs:s,open:i,close:l,startFork:f,undoFork:w,adoptRunningFork:h}=Rr(e),[p,F]=kr.useState(false),I=kr.useRef(null),y=kr.useRef(t),u=kr.useCallback(()=>{I.current!==null&&(clearTimeout(I.current),I.current=null);},[]),O=kr.useCallback(()=>{u(),F(true),i();},[u,i]),P=kr.useCallback(()=>{u(),F(false),l();},[u,l]),R=kr.useCallback(async C=>{u(),F(true),await h(C);},[h,u]),g=Object.values(s).filter(C=>C.state==="running").length;return kr.useEffect(()=>{let C=y.current;y.current=t,t==="complete"&&C==="running"&&p&&g===0&&(u(),I.current=setTimeout(()=>{I.current=null,F(false),l();},$s)),(t==="running"||t==="prompting")&&u();},[t,p,g,u,l]),kr.useEffect(()=>u,[u]),{state:t,fork:r,events:n,error:o,runs:s,isOpen:p,open:O,close:P,submit:f,undo:w,adoptRunningFork:R}}function Cr(){let{apiKey:e,userId:t,userHash:r,baseUrl:n,adminContext:o,setSlotFork:s,clearSlotFork:i,skipAnimationForSlot:l,trackForkActivity:f,recordForkActivityEvent:w}=we(),[h,p]=kr.useState({}),[F,I]=kr.useState(null),[y,u]=kr.useState("idle"),[O,P]=kr.useState(false),[R,g]=kr.useState(null),C=kr.useRef(new Map),_=kr.useCallback((L,k)=>{p(E=>{let d=E[L]??{forkId:L,state:"running",fork:k.fork,events:[],error:null};return {...E,[L]:{...d,...k}}});},[]),D=kr.useCallback((L,k)=>{p(E=>{let x=E[L];return x?{...E,[L]:{...x,events:[...x.events,k]}}:E});},[]),U=kr.useCallback(L=>{let k=C.current.get(L);k&&(k.close(),C.current.delete(L));},[]),T=kr.useCallback(()=>{u("prompting"),g(null),P(false),I(null);},[]),se=kr.useCallback(()=>{u("idle"),P(false),g(null),I(null);for(let L of C.current.values())L.close();C.current.clear(),p({});},[]),W=kr.useCallback((L,k)=>{U(L.id);let E=new URLSearchParams({key:e});t&&E.set("userId",t),r&&E.set("userHash",r),o.isAdmin&&o.containerId&&E.set("containerId",o.containerId);let x=new EventSource(`${n}/api/v1/forks/${L.id}/events?${E.toString()}`);C.current.set(L.id,x),x.onmessage=d=>{try{let M=JSON.parse(d.data);if(w(L.id,M),D(L.id,M),M.type==="complete"){let v=M.data,j={...L,status:"complete",bundleUrl:v.bundleUrl,summary:v.summary,revealPending:!0,completedAt:new Date().toISOString()};_(L.id,{state:"complete",fork:j});let ne=k??L.slotId;ne&&v.bundleUrl&&s(ne,j),U(L.id);}else if(M.type==="error"){let v=M.data;_(L.id,{state:"error",error:v.error||"Unknown error"}),U(L.id);}}catch{}},x.onerror=()=>{let d={Authorization:`Bearer ${e}`,...ce()};t&&(d["X-Fork-User-Id"]=t),r&&(d["X-Fork-User-Hash"]=r),fetch(`${n}/api/v1/forks/${L.id}`,{headers:d}).then(M=>M.json()).then(M=>{if(M.status==="complete"){_(L.id,{state:"complete",fork:{...M,revealPending:true}});let v=k??M.slotId;v&&M.bundleUrl&&s(v,{...M,revealPending:true});}else M.status==="error"?_(L.id,{state:"error",fork:M,error:M.error||"Fork generation failed"}):_(L.id,{fork:M});}).catch(()=>{_(L.id,{state:"error",error:"Connection lost"});}),U(L.id);};},[o.containerId,o.isAdmin,e,D,n,U,w,s,_,r,t]),A=kr.useCallback(async(L,k,E,x)=>{try{P(!0),g(null),I(null);let d;if(x?.forkId){let v={prompt:L};t&&(v.userId=t),r&&(v.userHash=r);let j=await fetch(`${n}/api/v1/forks/${encodeURIComponent(x.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...ce()},body:JSON.stringify(v)});if(!j.ok){let ne=await j.json().catch(()=>({}));throw new Error(ne.error||`API error: ${j.status}`)}d=await j.json();}else {let v={userId:t,prompt:L};k&&(v.slotId=k),E?v.containerId=E:o.isAdmin&&o.containerId&&(v.containerId=o.containerId),r&&(v.userHash=r),x?.forceNew&&(v.force_new=!0);let j=await fetch(`${n}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...ce()},body:JSON.stringify(v)});if(!j.ok){let ne=await j.json().catch(()=>({}));throw new Error(ne.error||`API error: ${j.status}`)}d=await j.json();}p(v=>({...v,[d.id]:{forkId:d.id,state:"running",fork:d,events:[],error:null}})),I(d.id),P(!1);let M=k??d.slotId;M&&f(d,{targetKind:"slot",targetId:M}),W(d,k);}catch(d){g(d.message),P(false);}},[o.containerId,o.isAdmin,e,n,W,f,r,t]),S=kr.useCallback(async L=>{try{let k={Authorization:`Bearer ${e}`,...ce()};t&&(k["X-Fork-User-Id"]=t),r&&(k["X-Fork-User-Hash"]=r);let E=await fetch(`${n}/api/v1/forks/${L}`,{headers:k});if(!E.ok)return;let x=await E.json();if(x.slotId&&f(x,{targetKind:"slot",targetId:x.slotId}),x.status==="complete"){p(d=>({...d,[x.id]:{forkId:x.id,state:"complete",fork:x,events:[],error:null}})),I(x.id);return}if(x.status==="error"){p(d=>({...d,[x.id]:{forkId:x.id,state:"error",fork:x,events:[],error:x.error||"Fork generation failed"}})),I(x.id);return}if(x.status!=="pending"&&x.status!=="running"&&x.status!=="building")return;p(d=>({...d,[x.id]:{forkId:x.id,state:"running",fork:x,events:[],error:null}})),I(x.id),W(x,x.slotId);}catch{}},[e,n,W,f,r,t]),N=kr.useCallback(async L=>{try{let k={userId:t,slotId:L};r&&(k.userHash=r);let E=await fetch(`${n}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(k)});if(!E.ok){let d=await E.json().catch(()=>({}));throw new Error(d.error||`API error: ${E.status}`)}let x=await E.json();if(l(L),x.removed)i(L),p(d=>{let M={};for(let[v,j]of Object.entries(d))j.fork.slotId!==L&&(M[v]=j);return M}),I(null),u("prompting");else if(x.fork){s(L,x.fork);let d=x.fork;_(d.id,{state:"complete",fork:d});}return x}catch(k){throw g(k.message),k}},[e,t,r,n,i,s,l,_]),B=F?h[F]??null:null,K=O?"running":R?"error":B?B.state:y,X=B?.fork??null,G=B?.events??[],q=R??B?.error??null;return {state:K,fork:X,events:G,error:q,runs:h,open:T,close:se,startFork:A,undoFork:N,adoptRunningFork:S}}var Ps=0;function Hn(){let{state:e,fork:t,events:r,error:n,runs:o,open:s,close:i,startFork:l,undoFork:f,adoptRunningFork:w}=Cr(),[h,p]=kr.useState(false),F=kr.useRef(null),I=kr.useRef(e),y=kr.useCallback(()=>{F.current!==null&&(clearTimeout(F.current),F.current=null);},[]),u=kr.useCallback(()=>{y(),p(true),s();},[y,s]),O=kr.useCallback(()=>{y(),p(false),i();},[y,i]),P=kr.useCallback(async g=>{y(),p(true),await w(g);},[w,y]),R=Object.values(o).filter(g=>g.state==="running").length;return kr.useEffect(()=>{let g=I.current;I.current=e,e==="complete"&&g==="running"&&h&&R===0&&(y(),F.current=setTimeout(()=>{F.current=null,p(false),i();},Ps)),(e==="running"||e==="prompting")&&y();},[e,h,R,y,i]),kr.useEffect(()=>y,[y]),{state:e,fork:t,events:r,error:n,runs:o,isOpen:h,open:u,close:O,submit:l,undo:f,adoptRunningFork:P}}var _s=new Set(["pending","running","building"]);function $r(e){let t=$n(e),r=Hn(),n=Pn(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:s,userId:i,userHash:l,appId:f,activitySummary:w,forkActivities:h}=we(),p=t.type==="slot"?r:n,F=t.type==="slot"?"slot":"boundary",I=t.id,y=t.title,u=t.type==="slot"?"slot":"module",O=h.find(_=>_.targetKind===u&&_.targetId===t.id&&_s.has(_.status)),P=h.find(_=>_.targetKind===u&&_.targetId===t.id&&_.status==="complete"&&_.unread),R=kr.useCallback(()=>{let _=O??P;if(_){p.adoptRunningFork(_.id);return}p.open();},[p,O,P]),g=kr.useCallback((_,D,U,T)=>t.type==="slot"?r.submit(_,D??t.id,U,T):n.submit(_,U,T),[n,r,t]),C=kr.useCallback(_=>t.type==="slot"?r.undo(_??t.id):n.undo(),[n,r,t]);return {...p,open:R,target:t,targetId:I,targetLabel:y,historyMode:F,submit:g,undo:C,buttonProps:{onClick:R,hasNotification:w.unreadCompletedCount>0,activity:w},panelProps:{state:p.state,fork:p.fork,events:p.events,error:p.error,runs:p.runs,...t.type==="slot"?{slotId:I,targetLabel:y,historyMode:F}:{targetId:I,targetLabel:y,historyMode:F},onSubmit:g,onUndo:C,onClose:p.close,baseUrl:o,apiKey:s,userId:i,userHash:l,appId:f}}}function It(e){let{embedded:t,completeVariant:r}=e,n=$r(e);return t?ho.jsx(Yt,{...n.panelProps,embedded:true,completeVariant:r}):n.isOpen?ho.jsx(Yt,{...n.panelProps,completeVariant:r}):ho.jsx(Sr,{...n.buttonProps})}function Ls({boundaryId:e,title:t}){return ho.jsx(It,{boundaryId:e,title:t})}function Mr(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 On(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 Pr(e){let t=[],r=e.querySelectorAll("*");for(let n of r){if(!(n instanceof HTMLElement))continue;let o=n.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(n.tagName))continue;let 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 Nn(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 l=r[i];l.rect.top>=n.rect.top&&l.rect.left>=n.rect.left&&l.rect.right<=n.rect.right&&l.rect.bottom<=n.rect.bottom&&r.splice(i,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Un(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 l=r[i];l.rect.top>=n.rect.top&&l.rect.left>=n.rect.left&&l.rect.right<=n.rect.right&&l.rect.bottom<=n.rect.bottom&&r.splice(i,1);}r.push({rect:n.rect,borderRadius:n.borderRadius});}return r}function Bn(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 _r(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 h=0;h<e.length;h+=1){let{rect:p,borderRadius:F}=e[h],I=p.left-.5,y=p.top-.5,u=p.width+1,O=p.height+1,P=Math.min(F+.5,u/2,O/2),R=Bn(I,y,u,O,P),g=`__fork-glow-${h}`,C=document.createElementNS(t,"filter");C.setAttribute("id",g),C.setAttribute("x","-100%"),C.setAttribute("y","-100%"),C.setAttribute("width","300%"),C.setAttribute("height","300%");let _=document.createElementNS(t,"feGaussianBlur");_.setAttribute("in","SourceGraphic"),_.setAttribute("stdDeviation","8"),C.appendChild(_),o.appendChild(C);let D=`__fork-mask-${h}`,U=document.createElementNS(t,"mask");U.setAttribute("id",D),U.setAttribute("maskUnits","userSpaceOnUse"),U.setAttribute("x",String(I-200)),U.setAttribute("y",String(y-200)),U.setAttribute("width",String(u+400)),U.setAttribute("height",String(O+400));let T=document.createElementNS(t,"rect");T.setAttribute("x",String(I-200)),T.setAttribute("y",String(y-200)),T.setAttribute("width",String(u+400)),T.setAttribute("height",String(O+400)),T.setAttribute("fill","white"),U.appendChild(T);let se=document.createElementNS(t,"path");se.setAttribute("d",R),se.setAttribute("fill","black"),U.appendChild(se),o.appendChild(U);let W=document.createElementNS(t,"g");W.setAttribute("mask",`url(#${D})`),W.setAttribute("opacity","0");let A=document.createElementNS(t,"g");A.setAttribute("filter",`url(#${g})`);let S=document.createElementNS(t,"path");S.setAttribute("d",R),S.setAttribute("fill","none"),S.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),S.setAttribute("stroke-width","6"),S.setAttribute("stroke-linecap","round"),A.appendChild(S),W.appendChild(A),n.appendChild(W);let N=document.createElementNS(t,"path");N.setAttribute("d",R),N.setAttribute("fill","none"),N.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),N.setAttribute("stroke-width","2"),N.setAttribute("stroke-linecap","round"),N.setAttribute("opacity","0"),n.appendChild(N),s.push(S,N),S.__group=W;}r.appendChild(n),document.body.appendChild(r);let i=[];for(let h=0;h<s.length;h+=2){let p=s[h],F=s[h+1],I=p.__group;if(!I)continue;let y=F.getTotalLength(),u=p.getTotalLength();if(y<=0)continue;let O=y*.35;F.setAttribute("stroke-dasharray",`${O} ${y-O}`),F.setAttribute("stroke-dashoffset","0"),i.push(F.animate([{strokeDashoffset:0,opacity:0,offset:0},{strokeDashoffset:-0.2*y,opacity:.92,offset:.06},{strokeDashoffset:-2*y,opacity:.92,offset:.92},{strokeDashoffset:-2.25*y,opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));let P=u*.35;p.setAttribute("stroke-dasharray",`${P} ${u-P}`),p.setAttribute("stroke-dashoffset","0"),i.push(p.animate([{strokeDashoffset:0,offset:0},{strokeDashoffset:-0.2*u,offset:.06},{strokeDashoffset:-2*u,offset:.92},{strokeDashoffset:-2.25*u,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 l=false,f=()=>{if(l)return;l=true,clearTimeout(w);for(let p of i)try{p.cancel();}catch{}let h=r.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});h.onfinish=()=>r.remove(),window.removeEventListener("click",f);},w=setTimeout(f,14500);return setTimeout(()=>{l||window.addEventListener("click",f);},500),f}function Dn(e){let t="http://www.w3.org/2000/svg",r=document.createElement("div");r.setAttribute("data-fork-removed","true"),r.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let n=document.createElementNS(t,"svg");n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs"),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:l,borderRadius:f}of e){let w=document.createElementNS(t,"path");w.setAttribute("d",Bn(l.left,l.top,l.width,l.height,f)),w.setAttribute("fill","none"),w.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),w.setAttribute("stroke-width","1.5"),w.setAttribute("stroke-dasharray","8 4"),w.setAttribute("stroke-linecap","round"),w.setAttribute("filter","url(#__fork-removed-shadow)"),w.setAttribute("opacity","0"),n.appendChild(w),w.animate([{opacity:0,offset:0},{opacity:.6,offset:.08},{opacity:.05,offset:.45},{opacity:.6,offset:.85},{opacity:.05,offset:1}],{duration:5e3,easing:"ease-in-out",fill:"forwards"});}return r.appendChild(n),document.body.appendChild(r),r}function zn(e,t){if(Os(t.selector))return Kn(e,t);let n=Kn(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(jn(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=Hr(e,h=>h===s);if(i)return i;let l=s.toLowerCase(),f=Hr(e,h=>h.toLowerCase()===l);if(f)return f;let w=Hr(e,h=>h.toLowerCase().includes(l));if(w)return w}}let o=Ns(t.selector);if(o&&o!==t.selector&&jn(o))try{let s=e.querySelector(o);if(s instanceof HTMLElement&&s!==e)return s}catch{}return null}function jn(e){let t=e.split(/\s+|>|~|\+/),r=t[t.length-1]??"";return /[#\[]|:not\(|:nth-/.test(r)}function Kn(e,t){let r=Array.from(e.querySelectorAll("[data-fork-new]"));if(r.length===0)return null;let n=Lr(t.label),o=Lr(t.textHint);return r.find(i=>{let l=Lr(i.getAttribute("data-fork-new"));return !!l&&(l===n||l===o)})??null}function Os(e){return e.trim()==="[data-fork-new]"}function Lr(e){return e?.trim().replace(/\s+/g," ").toLowerCase()||null}function Ns(e){return e.replace(/\[class[\*~|^$]?=("[^"]*"|'[^']*'|[^\]]+)\]/g,"").replace(/\.[A-Za-z_][\w-]*/g,"").replace(/\s+/g," ").trim()}function Hr(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 l=s.getBoundingClientRect();if(l.width<4||l.height<4)continue;let f=l.width*l.height;f<n&&(r=s,n=f);}return r}var Or=2147483600,Us=1600,Bs=3e4,Ds=300,qe=10;function js(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 l=e.getBoundingClientRect(),f=Math.min(l.width,l.height);return Math.max(4,i/100*f)}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 Ks(e,t,r,n){let s=window.innerWidth,i=window.innerHeight,l=e;l==="top"&&t.top<n+qe+8?l="bottom":l==="bottom"&&i-t.bottom<n+qe+8?l="top":l==="left"&&t.left<r+qe+8?l="right":l==="right"&&s-t.right<r+qe+8&&(l="left");let f=0,w=0;return l==="top"?(f=t.top-n-qe,w=t.left+t.width/2-r/2):l==="bottom"?(f=t.bottom+qe,w=t.left+t.width/2-r/2):l==="left"?(f=t.top+t.height/2-n/2,w=t.left-r-qe):(f=t.top+t.height/2-n/2,w=t.right+qe),w=Math.max(8,Math.min(w,s-r-8)),f=Math.max(8,Math.min(f,i-n-8)),{top:f,left:w,placement:l}}function zs(e){let t=document.createElement("div");t.setAttribute("data-fork-highlight-outline","true"),t.style.cssText=["position:fixed","pointer-events:none",`z-index:${Or}`,"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:${Or-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:${Or+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 Ws(){if(document.getElementById("__fork-highlight-keyframes"))return;let e=document.createElement("style");e.id="__fork-highlight-keyframes",e.textContent=`
|
|
59
|
+
`}),ls.jsxs("div",{className:"__fork-panel",style:rs,children:[ls.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0 16px",height:54,boxSizing:"border-box",borderBottom:"1px solid rgba(229, 231, 235, 0.8)",flexShrink:0},children:[ls.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:[c||A?ls.jsxs(ls.Fragment,{children:[ls.jsx("button",{onClick:()=>{y(null),z(false),Q.current=false;},style:{width:30,height:30,borderRadius:9,background:"#ffffff",border:"1px solid #e5e7eb",color:"#111827",cursor:"pointer",display:"inline-flex",alignItems:"center",justifyContent:"center",padding:0,flexShrink:0,transition:"background 0.12s, border-color 0.12s"},onMouseEnter:a=>{a.currentTarget.style.background="#f9fafb",a.currentTarget.style.borderColor="#d1d5db";},onMouseLeave:a=>{a.currentTarget.style.background="#ffffff",a.currentTarget.style.borderColor="#e5e7eb";},title:"Back to all forks",children:ls.jsx(lucideReact.ChevronLeft,{style:{width:15,height:15}})}),(()=>{let a=c?o[c]:void 0,B=(a?a.events.find(G=>{let le=G.data;return G.type==="status"&&le.summary})?.data?.summary??a.fork.summary:void 0)||vn?.summary||"New Feature";return ls.jsx("span",{style:{fontSize:13.5,fontWeight:700,color:"#111827",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",minWidth:0},title:B,children:B})})()]}):ls.jsxs(ls.Fragment,{children:[ls.jsx("span",{onDoubleClick:async a=>{if(a.stopPropagation(),!re&&confirm("Kill all forks in this container?")){Ae(true);try{let T=await zo();`${T?.deleted??0}`,ft([]),y(null),z(!1),P("");}catch(T){console.error("[Fork] Reset failed:",T);}finally{Ae(false);}}},style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:4,margin:-4,cursor:"pointer",flexShrink:0},children:ls.jsx(nn,{style:{width:16,height:16,color:"#111827",pointerEvents:"none"}})}),De==="running"?ls.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:Qo}):Te.length===0&&!Vt?ls.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:"Fork"}):Vt?ls.jsxs("div",{ref:Yt,style:{position:"relative",minWidth:0,display:"inline-flex"},children:[ls.jsxs("button",{type:"button",onClick:()=>{ke(a=>!a);},onMouseEnter:()=>Bt(true),onMouseLeave:()=>Bt(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:hn||$e?"#f3f4f6":"transparent",fontSize:13,fontWeight:600,color:"#111827",fontFamily:"inherit",cursor:"pointer",maxWidth:180,minWidth:0,transition:"background-color 0.12s"},children:[ls.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:Mr}),ls.jsx(lucideReact.ChevronDown,{style:{width:12,height:12,color:"#6b7280",flexShrink:0,transform:$e?"rotate(180deg)":void 0,transition:"transform 0.15s"}})]}),$e&&ls.jsxs("div",{role:"menu",style:{position:"absolute",top:"calc(100% + 4px)",left:0,minWidth:200,maxWidth:260,background:"#ffffff",border:"1px solid #e5e7eb",borderRadius:8,boxShadow:"0 4px 12px rgba(0,0,0,0.08), 0 1px 3px rgba(0,0,0,0.06)",padding:4,zIndex:2147483001},children:[Te.map(a=>{let T=a.id===Se,B=yn===a.id,G=ge===a.id;return ls.jsxs("button",{type:"button",role:"menuitem",onMouseEnter:()=>Dt(a.id),onMouseLeave:()=>Dt(null),onClick:()=>{a.id!==Se&&ns(a.id);},disabled:!!ge,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:ge?"default":"pointer",textAlign:"left",fontWeight:T?600:400,opacity:ge&&!G?.55:1},children:[ls.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,color:"#111827",flexShrink:0},children:T&&ls.jsx(lucideReact.Check,{style:{width:12,height:12}})}),ls.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:G?"Switching...":a.name})]},a.id)}),ls.jsx("div",{style:{height:1,background:"#e5e7eb",margin:"4px 0"}}),bt?ls.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"4px 4px"},children:[ls.jsx("input",{ref:wt,type:"text",value:Be,placeholder:"Container name",disabled:ge==="__new__",onChange:a=>Xe(a.target.value),onKeyDown:a=>{a.key==="Enter"?(a.preventDefault(),Rr(Be)):a.key==="Escape"&&(a.preventDefault(),a.stopPropagation(),ut(false),Xe(""));},style:{flex:1,minWidth:0,padding:"5px 8px",border:"1px solid #d1d5db",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",background:"#ffffff",outline:"none"},onFocus:a=>{a.currentTarget.style.borderColor="#111827",a.currentTarget.style.boxShadow="0 0 0 2px rgba(17,24,39,0.15)";},onBlur:a=>{a.currentTarget.style.borderColor="#d1d5db",a.currentTarget.style.boxShadow="none";}}),ls.jsx("button",{type:"button",onClick:()=>{Rr(Be);},disabled:!Be.trim()||ge==="__new__",title:"Create",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:26,height:26,border:"none",borderRadius:4,background:!Be.trim()||ge==="__new__"?"#e5e7eb":"#111827",color:!Be.trim()||ge==="__new__"?"#9ca3af":"#ffffff",cursor:!Be.trim()||ge==="__new__"?"default":"pointer",flexShrink:0},children:ge==="__new__"?ls.jsx("span",{style:{width:10,height:10,border:"1.5px solid currentColor",borderTopColor:"transparent",borderRadius:"50%",animation:"__fork-spin 0.7s linear infinite"}}):ls.jsx(lucideReact.Check,{style:{width:12,height:12}})})]}):ls.jsx("button",{type:"button",role:"menuitem",onMouseEnter:()=>jt(true),onMouseLeave:()=>jt(false),onClick:()=>{ge||(Fe(null),Xe(""),ut(true));},disabled:!!ge,style:{display:"flex",alignItems:"center",width:"100%",padding:"6px 8px",border:"none",background:tt?"#f3f4f6":"transparent",borderRadius:4,fontSize:13,fontFamily:"inherit",color:"#111827",cursor:ge?"default":"pointer",textAlign:"left",opacity:ge&&ge!=="__new__"?.55:1},children:"+ New container"}),Kt&&ls.jsx("div",{style:{padding:"6px 8px",fontSize:11,lineHeight:1.35,color:"#b91c1c"},children:Kt})]})]}):ls.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:Mr})]}),De==="running"&&ls.jsx("span",{title:nt?`Estimated ~${nt} min`:"Estimating\u2026",style:{fontSize:10,fontWeight:600,color:nt?"#111827":"#9ca3af",backgroundColor:nt?"rgba(17, 24, 39, 0.08)":"rgba(156, 163, 175, 0.12)",padding:"1px 6px",borderRadius:999,flexShrink:0,fontVariantNumeric:"tabular-nums",animation:nt?void 0:"__fork-pulse 1.4s ease-in-out infinite",minWidth:28,textAlign:"center"},children:nt?`~${nt}m`:"~ m"})]}),ls.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[Vo&&ls.jsx("button",{type:"button",role:"switch","aria-checked":!mt,"aria-label":mt?"Turn Fork back on":"Turn Fork off",title:mt?"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:()=>{Jo(!mt);},onMouseEnter:()=>gr(true),onMouseLeave:()=>gr(false),style:{position:"relative",width:26,height:15,borderRadius:999,border:"none",padding:0,marginRight:6,flexShrink:0,cursor:"pointer",backgroundColor:mt?mr?"#9ca3af":"#d1d5db":mr?"#374151":"#111827",transition:"background-color 0.18s ease",outline:"none",boxSizing:"border-box"},children:ls.jsx("span",{"aria-hidden":true,style:{position:"absolute",top:2,left:mt?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)"}})}),!S&&ls.jsxs(ls.Fragment,{children:[yr&&ls.jsx("button",{onClick:Oe?qo:Xo,onMouseEnter:()=>V(true),onMouseLeave:()=>V(false),title:Oe?"Redock to sidebar":"Pop out into window",style:{padding:6,borderRadius:6,color:K?"#4b5563":"#9ca3af",backgroundColor:K?"#f3f4f6":"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.15s, color 0.15s"},children:Oe?ls.jsx(lucideReact.PictureInPicture,{style:{width:16,height:16}}):ls.jsx(lucideReact.PictureInPicture2,{style:{width:16,height:16}})}),ls.jsx("button",{onClick:Cr,onMouseEnter:()=>D(true),onMouseLeave:()=>D(false),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:ls.jsx(lucideReact.X,{style:{width:16,height:16}})})]})]})]}),ls.jsxs("div",{ref:ne,style:{flex:1,overflowY:"auto",minHeight:0,display:"flex",flexDirection:"column"},children:[!c&&!A&&ls.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[Ne.length===0&&ls.jsx("div",{style:{padding:"24px 20px",textAlign:"center",fontSize:13,color:"#6b7280"},children:"No forks yet. Describe a feature below to start one."}),Ne.length>0&&ls.jsx("div",{style:{display:"flex",flexDirection:"column"},children:Ne.map((a,T)=>{let B=o[a.id],le=(B?B.events.find(Ye=>{let ss=Ye.data;return Ye.type==="status"&&ss.summary})?.data?.summary??B.fork.summary:void 0)||a.summary||"Untitled fork",je=!!fr.find(Ye=>Ye.id===a.id)?.unread,Me=o[a.id]?.state??a.status,os=Me==="running"||Me==="building"||Me==="pending";return ls.jsxs(Pn.Fragment,{children:[ls.jsxs("button",{onClick:()=>{z(false),y(a.id);},style:{textAlign:"left",padding:"12px 16px",background:"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"flex-start",gap:8,width:"100%",transition:"background 0.12s",fontFamily:"inherit"},onMouseEnter:Ye=>{Ye.currentTarget.style.background="#fafafa";},onMouseLeave:Ye=>{Ye.currentTarget.style.background="transparent";},children:[je&&ls.jsx("span",{"aria-label":"Not viewed yet",title:"Not viewed yet",style:{width:7,height:7,borderRadius:"50%",backgroundColor:"#111827",flexShrink:0,marginTop:5}}),ls.jsxs("div",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:5,alignItems:"flex-start"},children:[ls.jsx("span",{style:{fontSize:13.5,fontWeight:600,color:"#111827",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:"100%"},children:le}),ls.jsx("span",{style:{fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, "Liberation Mono", "Courier New", monospace',fontSize:10,color:"#9ca3af",background:"#f8f9fa",borderRadius:5,padding:"1px 6px",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:"100%",boxSizing:"border-box"},children:a.targetId})]}),os&&ls.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:5,background:"#fff7ed",border:"1px solid #fed7aa",color:"#c2410c",borderRadius:999,padding:"2px 9px",fontSize:11,fontWeight:600,flexShrink:0},children:[ls.jsx("span",{style:{width:6,height:6,borderRadius:"50%",background:"#f59e0b",animation:"__fork-pulse 1.4s ease-in-out infinite"}}),"Running"]}),Me==="error"&&ls.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:5,background:"#fef2f2",border:"1px solid #fecaca",color:"#b91c1c",borderRadius:999,padding:"2px 9px",fontSize:11,fontWeight:600,flexShrink:0},children:"Failed"}),ls.jsx("span",{style:{fontSize:11.5,color:"#9ca3af",flexShrink:0,marginTop:2},children:Kn(a.updatedAt)})]}),T<Ne.length-1&&ls.jsx("div",{style:{height:1,background:"#f3f4f6",margin:"0 16px",flexShrink:0}})]},a.id)})})]}),c&&xt.length>0&&ls.jsx("div",{style:{margin:"16px 16px 0 16px"},children:xt.map((a,T)=>ls.jsx("div",{style:{marginBottom:T<xt.length-1?12:0},children:a.type==="user"?ls.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:ls.jsxs("div",{style:{backgroundColor:"#f3f4f6",borderRadius:12,padding:"10px 14px",fontSize:13,color:"#374151",lineHeight:1.5,maxWidth:"85%"},children:[a.attachments&&a.attachments.length>0&&ls.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginBottom:6},children:a.attachments.map((B,G)=>ls.jsx("img",{src:B.dataUrl,alt:"attachment",style:{maxWidth:150,maxHeight:110,borderRadius:8,border:"1px solid #e5e7eb",display:"block",objectFit:"cover"}},G))}),a.selectedElement&&ls.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:4,background:"#eef2ff",border:"1px solid #c7d2fe",color:"#4338ca",borderRadius:999,padding:"2px 8px",fontSize:10.5,fontWeight:500,marginBottom:5,marginRight:6,maxWidth:"100%"},children:[ls.jsx(lucideReact.MousePointer2,{style:{width:10,height:10,flexShrink:0}}),ls.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:a.selectedElement.label})]}),a.text]})}):I==="item"&&T===xt.length-1?ls.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:12,padding:12,borderRadius:8,border:"1px solid #e4e4e7",background:"#ffffff"},children:[ls.jsx("div",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,flexShrink:0,borderRadius:6,background:"#f4f4f5",color:"#0a0a0a"},children:ls.jsx(lucideReact.BadgeCheck,{style:{width:16,height:16}})}),ls.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,flex:1,minWidth:0},children:[ls.jsx("div",{style:{fontSize:13,fontWeight:500,color:"#0a0a0a",lineHeight:1.3},children:"Feature applied"}),ls.jsx("div",{style:{fontSize:13,color:"#71717a",lineHeight:1.4},children:a.text})]}),b&&De!=="running"&&ls.jsx("button",{onClick:B=>{B.stopPropagation(),Ir();},disabled:p,style:{padding:"4px 10px",fontSize:12,fontWeight:500,borderRadius:6,border:"1px solid #e4e4e7",background:"#ffffff",color:"#0a0a0a",cursor:p?"default":"pointer",opacity:p?.4:1,height:28,flexShrink:0},children:"Undo"})]}):ls.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:8,background:"#ffffff",border:"1px solid #e5e7eb",borderRadius:10,boxShadow:"0 1px 2px rgba(0, 0, 0, 0.03)",padding:"9px 12px",maxWidth:"90%",boxSizing:"border-box"},children:[ls.jsx("span",{style:{width:7,height:7,borderRadius:"50%",background:"#94a3b8",flexShrink:0}}),ls.jsx("span",{style:{fontSize:12.5,fontWeight:600,color:"#334155",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:a.text}),a.timestamp&&ls.jsx("span",{style:{fontSize:11,color:"#9ca3af",flexShrink:0},children:Kn(a.timestamp)}),b&&T===xt.length-1&&De!=="running"&&ls.jsxs("button",{onClick:B=>{B.stopPropagation(),Ir();},onMouseEnter:()=>q(T),onMouseLeave:()=>q(null),disabled:p,style:{position:"relative",padding:2,borderRadius:4,border:"none",background:x===T?"rgba(0,0,0,0.06)":"transparent",color:x===T?"#6b7280":"#d1d5db",cursor:p?"default":"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s, background 0.15s",opacity:p?.4:1,flexShrink:0},children:[ls.jsx(lucideReact.Undo2,{style:{width:12,height:12}}),x===T&&ls.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"})]})]})},T))}),De==="running"&&ls.jsx("div",{style:{margin:"12px 16px 0 16px"},children:ls.jsxs("div",{onClick:()=>w(!M),style:{background:"#ffffff",border:"1px solid #e5e7eb",borderRadius:10,boxShadow:"0 1px 2px rgba(0, 0, 0, 0.03)",overflow:"hidden",cursor:"pointer",transition:"all 0.3s cubic-bezier(0.22, 1, 0.36, 1)"},children:[ls.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"9px 12px"},children:[ls.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[ls.jsx("span",{style:{width:7,height:7,borderRadius:"50%",background:"#f59e0b",flexShrink:0,animation:"__fork-pulse 1.4s ease-in-out infinite"}}),ls.jsx(Ci,{events:ht},c??"__compose__")]}),ls.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,marginLeft:8},children:[ht[0]?.timestamp&&ls.jsx("span",{style:{fontSize:11,color:"#9ca3af"},children:Kn(ht[0].timestamp)}),ls.jsx("div",{style:{color:"#9ca3af",transition:"transform 0.2s ease",transform:M?"rotate(180deg)":"rotate(0deg)",display:"flex"},children:ls.jsx(lucideReact.ChevronDown,{style:{width:14,height:14}})})]})]}),ls.jsx("div",{style:{maxHeight:M?320:0,opacity:M?1:0,transition:"max-height 0.35s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.25s ease",overflow:"hidden"},children:ls.jsx("div",{style:{background:"#1a1a2e",borderTop:"1px solid #e5e7eb",maxHeight:320,overflowY:"auto"},children:ls.jsx(Zr,{events:ht},c??"__compose__")})})]})}),De==="error"&&ls.jsxs("div",{style:{padding:"20px 16px",textAlign:"center"},children:[ls.jsx("div",{style:{width:36,height:36,backgroundColor:"#fef2f2",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 10px auto"},children:ls.jsx(lucideReact.X,{style:{width:18,height:18,color:"#ef4444"}})}),ls.jsx("p",{style:{fontSize:12,color:"#6b7280",marginBottom:10,maxWidth:260,margin:"0 auto 10px auto"},children:Yo??r}),ls.jsxs("button",{onClick:()=>{let a=Sn?.prompt||qt.current;a&&h(a,vt);},onMouseEnter:()=>C(true),onMouseLeave:()=>C(false),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,color:"#111827",backgroundColor:U?"#e5e7eb":"#f3f4f6",border:"none",cursor:"pointer",transition:"background-color 0.15s",fontFamily:"inherit"},children:[ls.jsx(lucideReact.RotateCcw,{style:{width:12,height:12}})," Try Again"]})]})]}),!(c?De==="running":A&&e==="running")&&ls.jsxs("div",{style:{padding:"8px 12px 12px 12px",borderTop:"1px solid rgba(229, 231, 235, 0.6)",flexShrink:0,position:"relative"},children:[pt&&ls.jsx("div",{style:{position:"absolute",top:-42,left:"50%",transform:"translateX(-50%)",background:"#111827",color:"#ffffff",fontSize:12,fontWeight:500,padding:"7px 14px",borderRadius:999,boxShadow:"0 4px 16px rgba(0, 0, 0, 0.22)",whiteSpace:"nowrap",maxWidth:jn-32,overflow:"hidden",textOverflow:"ellipsis",pointerEvents:"none",zIndex:5},children:pt}),ls.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6,borderRadius:14,padding:"10px 10px 8px 12px",background:"#ffffff",border:"1px solid #e5e7eb",boxShadow:"0 1px 2px rgba(0, 0, 0, 0.04), 0 4px 14px -6px rgba(0, 0, 0, 0.08)"},children:[(ie.length>0||ce)&&ls.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6,alignItems:"center"},children:[ie.map(a=>ls.jsxs("div",{onMouseEnter:()=>ur(a.id),onMouseLeave:()=>ur(null),style:{position:"relative",width:44,height:44,borderRadius:8,overflow:"hidden",border:"1px solid #e5e7eb",flexShrink:0},children:[ls.jsx("img",{src:a.dataUrl,alt:"attachment",style:{width:"100%",height:"100%",objectFit:"cover",display:"block"}}),ls.jsx("button",{onClick:()=>be(T=>T.filter(B=>B.id!==a.id)),title:"Remove image",style:{position:"absolute",top:2,right:2,width:15,height:15,borderRadius:"50%",background:"rgba(17, 24, 39, 0.78)",color:"#ffffff",border:"none",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,opacity:Ko===a.id?1:.6,transition:"opacity 0.12s"},children:ls.jsx(lucideReact.X,{style:{width:9,height:9}})})]},a.id)),ce&&ls.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:5,background:"#eef2ff",border:"1px solid #c7d2fe",color:"#4338ca",borderRadius:999,padding:"4px 6px 4px 9px",fontSize:11,fontWeight:500,maxWidth:"100%",minWidth:0},children:[ls.jsx(lucideReact.MousePointer2,{style:{width:11,height:11,flexShrink:0}}),ls.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:an(ce)}),ls.jsx("button",{onClick:()=>me(null),title:"Remove element context",style:{width:14,height:14,borderRadius:"50%",background:"transparent",color:"#6366f1",border:"none",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,flexShrink:0},children:ls.jsx(lucideReact.X,{style:{width:10,height:10}})})]})]}),ls.jsx("textarea",{ref:Z,value:m,onChange:a=>P(a.target.value),onPaste:a=>{let T=eo(a.nativeEvent);T.length>0&&(a.preventDefault(),vr(T));},onKeyDown:a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),xr()),a.key==="Escape"&&!S&&Cr();},placeholder:c?"Iterate on this feature...":"Start building a new Fork...",rows:1,style:{width:"100%",backgroundColor:"transparent",fontSize:13,color:"#111827",border:"none",outline:"none",padding:0,fontFamily:"inherit",resize:"none",lineHeight:1.5,maxHeight:160,overflow:"auto",boxSizing:"border-box"}}),ls.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2},children:[ls.jsx("button",{onClick:()=>ir.current?.click(),onMouseEnter:()=>ar(true),onMouseLeave:()=>ar(false),title:"Attach an image",style:{width:28,height:28,borderRadius:8,display:"flex",alignItems:"center",justifyContent:"center",background:Bo?"rgba(0, 0, 0, 0.05)":"transparent",color:"#6b7280",border:"none",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.12s"},children:ls.jsx(lucideReact.ImagePlus,{style:{width:16,height:16}})}),ls.jsx("button",{onClick:es,onMouseEnter:()=>lr(true),onMouseLeave:()=>lr(false),title:ae?"Cancel element selection":"Select an element on the page",style:{width:28,height:28,borderRadius:8,display:"flex",alignItems:"center",justifyContent:"center",background:ae?"#eef2ff":Do?"rgba(0, 0, 0, 0.05)":"transparent",color:ae?"#4f46e5":"#6b7280",border:"none",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.12s, color 0.12s"},children:ls.jsx(lucideReact.MousePointer2,{style:{width:16,height:16}})}),ls.jsx("div",{style:{flex:1}}),ls.jsx("button",{onClick:ts,onMouseEnter:()=>cr(true),onMouseLeave:()=>cr(false),title:fe?"Stop voice input":"Voice input",style:{width:28,height:28,borderRadius:8,display:"flex",alignItems:"center",justifyContent:"center",background:fe?"#fef2f2":jo?"rgba(0, 0, 0, 0.05)":"transparent",color:fe?"#dc2626":"#6b7280",border:"none",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.12s, color 0.12s",animation:fe?"__fork-pulse 1.4s ease-in-out infinite":void 0},children:ls.jsx(lucideReact.Mic,{style:{width:16,height:16}})}),ls.jsx("button",{onClick:xr,disabled:!yt,onMouseEnter:()=>X(true),onMouseLeave:()=>X(false),title:"Send",style:{width:28,height:28,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",opacity:yt?1:.35,transform:W&&yt?"scale(1.08)":"scale(1)",background:yt?"#111827":"rgba(0, 0, 0, 0.12)",border:"none",cursor:yt?"pointer":"default",flexShrink:0,transition:"transform 0.15s, opacity 0.15s, background 0.15s",padding:0,marginLeft:4},children:ls.jsx(lucideReact.ArrowUp,{style:{width:14,height:14}})})]})]}),ls.jsx("input",{ref:ir,type:"file",accept:"image/*",multiple:true,style:{display:"none"},onChange:a=>{let T=Array.from(a.target.files??[]);a.target.value="",vr(T);}})]})]})]});return S?Fn:Oe&&Ie?as.createPortal(Fn,Ie.document.body):ls.jsx(Mi,{children:Fn})}function uo(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 zn(e){let{apiKey:t,userId:n,userHash:r,baseUrl:o,appId:s,adminContext:i,refreshModuleManifest:l,queueBoundaryAnimation:u,trackForkActivity:h,recordForkActivityEvent:b}=ve(),[d,k]=Pn.useState({}),[R,v]=Pn.useState(null),[f,g]=Pn.useState("idle"),[S,I]=Pn.useState(false),[m,P]=Pn.useState(null),L=Pn.useRef(new Map),j=Pn.useCallback((C,M)=>{k(w=>{let $=w[C]??{forkId:C,state:"running",fork:M.fork,events:[],error:null};return {...w,[C]:{...$,...M}}});},[]),O=Pn.useCallback((C,M)=>{k(w=>{let p=w[C];return p?{...w,[C]:{...p,events:[...p.events,M]}}:w});},[]),N=Pn.useCallback(C=>{let M=L.current.get(C);M&&(M.close(),L.current.delete(C));},[]),oe=Pn.useCallback(()=>{g("prompting"),P(null),I(false),v(null);},[]),Y=Pn.useCallback(()=>{g("idle"),I(false),P(null),v(null);for(let C of L.current.values())C.close();L.current.clear(),k({});},[]),_=Pn.useCallback((C,M)=>{N(C.id);let w=new URLSearchParams({key:t});n&&w.set("userId",n),r&&w.set("userHash",r),i.isAdmin&&i.containerId&&w.set("containerId",i.containerId);let p=new EventSource(`${o}/api/v1/forks/${C.id}/events?${w.toString()}`);L.current.set(C.id,p),p.onmessage=$=>{try{let x=JSON.parse($.data);if(b(C.id,x),O(C.id,x),x.type==="complete"){let q=x.data;u(M,C.id),l().catch(()=>{}).finally(()=>{let re={...C,status:"complete",moduleUrl:q.moduleUrl,cssUrls:q.cssUrls,summary:q.summary,completedAt:new Date().toISOString()};j(C.id,{state:"complete",fork:re}),N(C.id);});}else if(x.type==="error"){let q=x.data;j(C.id,{state:"error",error:q.error||"Unknown error"}),N(C.id);}}catch{}},p.onerror=()=>{let $={Authorization:`Bearer ${t}`,...pe()};n&&($["X-Fork-User-Id"]=n),r&&($["X-Fork-User-Hash"]=r),fetch(`${o}/api/v1/forks/${C.id}`,{headers:$}).then(x=>x.json()).then(x=>{x.status==="complete"?(u(M,x.id),l().catch(()=>{}),j(C.id,{state:"complete",fork:x})):x.status==="error"?j(C.id,{state:"error",fork:x,error:x.error||"Fork generation failed"}):j(C.id,{fork:x});}).catch(()=>{j(C.id,{state:"error",error:"Connection lost"});}),N(C.id);};},[i.containerId,i.isAdmin,t,O,o,N,u,b,l,j,r,n]),F=Pn.useCallback(async(C,M,w)=>{try{if(!s)throw new Error("ForkProvider requires appId for module boundary prompts.");I(!0),P(null),v(null);let p;if(w?.forkId){let $={prompt:C};n&&($.userId=n),r&&($.userHash=r),w?.attachments?.length&&($.attachments=w.attachments),w?.selectedElement&&($.selectedElement=w.selectedElement);let x=await fetch(`${o}/api/v1/forks/${encodeURIComponent(w.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...pe()},body:JSON.stringify($)});if(!x.ok){let q=await x.json().catch(()=>({}));throw new Error(q.error||`API error: ${x.status}`)}p=await x.json();}else {let $={userId:n,prompt:C,boundaryId:e,appId:s};M?$.containerId=M:i.isAdmin&&i.containerId&&($.containerId=i.containerId),r&&($.userHash=r),w?.forceNew&&($.force_new=!0),w?.attachments?.length&&($.attachments=w.attachments),w?.selectedElement&&($.selectedElement=w.selectedElement);let x=await fetch(`${o}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...pe()},body:JSON.stringify($)});if(!x.ok){let q=await x.json().catch(()=>({}));throw new Error(q.error||`API error: ${x.status}`)}p=await x.json();}k($=>({...$,[p.id]:{forkId:p.id,state:"running",fork:p,events:[],error:null}})),v(p.id),I(!1),h(p,{targetKind:"module",targetId:e}),_(p,p.boundaryId??e);}catch(p){P(p.message),I(false);}},[i.containerId,i.isAdmin,t,s,o,e,_,h,r,n]),H=Pn.useCallback(async C=>{try{let M={Authorization:`Bearer ${t}`,...pe()};n&&(M["X-Fork-User-Id"]=n),r&&(M["X-Fork-User-Hash"]=r);let w=await fetch(`${o}/api/v1/forks/${C}`,{headers:M});if(!w.ok)return;let p=await w.json(),$=p.boundaryId??e;if(h(p,{targetKind:"module",targetId:$}),p.status==="complete"){k(x=>({...x,[p.id]:{forkId:p.id,state:"complete",fork:p,events:[],error:null}})),v(p.id);return}if(p.status==="error"){k(x=>({...x,[p.id]:{forkId:p.id,state:"error",fork:p,events:[],error:p.error||"Fork generation failed"}})),v(p.id);return}if(p.status!=="pending"&&p.status!=="running"&&p.status!=="building")return;k(x=>({...x,[p.id]:{forkId:p.id,state:"running",fork:p,events:[],error:null}})),v(p.id),_(p,$);}catch{}},[t,o,e,_,h,r,n]),D=Pn.useCallback(async C=>{try{if(!s)throw new Error("ForkProvider requires appId for boundary undo.");let M={userId:n,boundaryId:e,appId:s};r&&(M.userHash=r),C&&(M.fork_id=C);let w=await fetch(`${o}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(M)});if(!w.ok){let $=await w.json().catch(()=>({}));throw new Error($.error||`API error: ${w.status}`)}let p=await w.json();if(await l().catch(()=>{}),p.removed)k($=>{let x={};for(let[q,re]of Object.entries($))(re.fork.boundaryId??e)!==e&&(x[q]=re);return x}),v(null),g("prompting");else if(p.fork){let $=p.fork;j($.id,{state:"complete",fork:$}),v($.id);}return p}catch(M){throw P(M.message),M}},[t,s,o,e,l,j,r,n]),K=R?d[R]??null:null,V=S?"running":m?"error":K?K.state:f,W=K?.fork??null,X=K?.events??[],U=m??K?.error??null;return {state:V,fork:W,events:X,error:U,runs:d,open:oe,close:Y,startFork:F,undoFork:D,adoptRunningFork:H}}var Pi=0;function mo(e){let{state:t,fork:n,events:r,error:o,runs:s,open:i,close:l,startFork:u,undoFork:h,adoptRunningFork:b}=zn(e),[d,k]=Pn.useState(false),R=Pn.useRef(null),v=Pn.useRef(t),f=Pn.useCallback(()=>{R.current!==null&&(clearTimeout(R.current),R.current=null);},[]),g=Pn.useCallback(()=>{f(),k(true),i();},[f,i]),S=Pn.useCallback(()=>{f(),k(false),l();},[f,l]),I=Pn.useCallback(async P=>{f(),k(true),await b(P);},[b,f]),m=Object.values(s).filter(P=>P.state==="running").length;return Pn.useEffect(()=>{let P=v.current;v.current=t,t==="complete"&&P==="running"&&d&&m===0&&(f(),R.current=setTimeout(()=>{R.current=null,k(false),l();},Pi)),(t==="running"||t==="prompting")&&f();},[t,d,m,f,l]),Pn.useEffect(()=>f,[f]),{state:t,fork:n,events:r,error:o,runs:s,isOpen:d,open:g,close:S,submit:u,undo:h,adoptRunningFork:I}}function Wn(){let{apiKey:e,userId:t,userHash:n,baseUrl:r,adminContext:o,setSlotFork:s,clearSlotFork:i,skipAnimationForSlot:l,trackForkActivity:u,recordForkActivityEvent:h}=ve(),[b,d]=Pn.useState({}),[k,R]=Pn.useState(null),[v,f]=Pn.useState("idle"),[g,S]=Pn.useState(false),[I,m]=Pn.useState(null),P=Pn.useRef(new Map),L=Pn.useCallback((U,C)=>{d(M=>{let p=M[U]??{forkId:U,state:"running",fork:C.fork,events:[],error:null};return {...M,[U]:{...p,...C}}});},[]),j=Pn.useCallback((U,C)=>{d(M=>{let w=M[U];return w?{...M,[U]:{...w,events:[...w.events,C]}}:M});},[]),O=Pn.useCallback(U=>{let C=P.current.get(U);C&&(C.close(),P.current.delete(U));},[]),N=Pn.useCallback(()=>{f("prompting"),m(null),S(false),R(null);},[]),oe=Pn.useCallback(()=>{f("idle"),S(false),m(null),R(null);for(let U of P.current.values())U.close();P.current.clear(),d({});},[]),Y=Pn.useCallback((U,C)=>{O(U.id);let M=new URLSearchParams({key:e});t&&M.set("userId",t),n&&M.set("userHash",n),o.isAdmin&&o.containerId&&M.set("containerId",o.containerId);let w=new EventSource(`${r}/api/v1/forks/${U.id}/events?${M.toString()}`);P.current.set(U.id,w),w.onmessage=p=>{try{let $=JSON.parse(p.data);if(h(U.id,$),j(U.id,$),$.type==="complete"){let x=$.data,q={...U,status:"complete",bundleUrl:x.bundleUrl,summary:x.summary,revealPending:!0,completedAt:new Date().toISOString()};L(U.id,{state:"complete",fork:q});let re=C??U.slotId;re&&x.bundleUrl&&s(re,q),O(U.id);}else if($.type==="error"){let x=$.data;L(U.id,{state:"error",error:x.error||"Unknown error"}),O(U.id);}}catch{}},w.onerror=()=>{let p={Authorization:`Bearer ${e}`,...pe()};t&&(p["X-Fork-User-Id"]=t),n&&(p["X-Fork-User-Hash"]=n),fetch(`${r}/api/v1/forks/${U.id}`,{headers:p}).then($=>$.json()).then($=>{if($.status==="complete"){L(U.id,{state:"complete",fork:{...$,revealPending:true}});let x=C??$.slotId;x&&$.bundleUrl&&s(x,{...$,revealPending:true});}else $.status==="error"?L(U.id,{state:"error",fork:$,error:$.error||"Fork generation failed"}):L(U.id,{fork:$});}).catch(()=>{L(U.id,{state:"error",error:"Connection lost"});}),O(U.id);};},[o.containerId,o.isAdmin,e,j,r,O,h,s,L,n,t]),_=Pn.useCallback(async(U,C,M,w)=>{try{S(!0),m(null),R(null);let p;if(w?.forkId){let x={prompt:U};t&&(x.userId=t),n&&(x.userHash=n),w?.attachments?.length&&(x.attachments=w.attachments),w?.selectedElement&&(x.selectedElement=w.selectedElement);let q=await fetch(`${r}/api/v1/forks/${encodeURIComponent(w.forkId)}/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...pe()},body:JSON.stringify(x)});if(!q.ok){let re=await q.json().catch(()=>({}));throw new Error(re.error||`API error: ${q.status}`)}p=await q.json();}else {let x={userId:t,prompt:U};C&&(x.slotId=C),M?x.containerId=M:o.isAdmin&&o.containerId&&(x.containerId=o.containerId),n&&(x.userHash=n),w?.forceNew&&(x.force_new=!0),w?.attachments?.length&&(x.attachments=w.attachments),w?.selectedElement&&(x.selectedElement=w.selectedElement);let q=await fetch(`${r}/api/v1/forks`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...pe()},body:JSON.stringify(x)});if(!q.ok){let re=await q.json().catch(()=>({}));throw new Error(re.error||`API error: ${q.status}`)}p=await q.json();}d(x=>({...x,[p.id]:{forkId:p.id,state:"running",fork:p,events:[],error:null}})),R(p.id),S(!1);let $=C??p.slotId;$&&u(p,{targetKind:"slot",targetId:$}),Y(p,C);}catch(p){m(p.message),S(false);}},[o.containerId,o.isAdmin,e,r,Y,u,n,t]),F=Pn.useCallback(async U=>{try{let C={Authorization:`Bearer ${e}`,...pe()};t&&(C["X-Fork-User-Id"]=t),n&&(C["X-Fork-User-Hash"]=n);let M=await fetch(`${r}/api/v1/forks/${U}`,{headers:C});if(!M.ok)return;let w=await M.json();if(w.slotId&&u(w,{targetKind:"slot",targetId:w.slotId}),w.status==="complete"){d(p=>({...p,[w.id]:{forkId:w.id,state:"complete",fork:w,events:[],error:null}})),R(w.id);return}if(w.status==="error"){d(p=>({...p,[w.id]:{forkId:w.id,state:"error",fork:w,events:[],error:w.error||"Fork generation failed"}})),R(w.id);return}if(w.status!=="pending"&&w.status!=="running"&&w.status!=="building")return;d(p=>({...p,[w.id]:{forkId:w.id,state:"running",fork:w,events:[],error:null}})),R(w.id),Y(w,w.slotId);}catch{}},[e,r,Y,u,n,t]),H=Pn.useCallback(async U=>{try{let C={userId:t,slotId:U};n&&(C.userHash=n);let M=await fetch(`${r}/api/v1/forks/undo`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(C)});if(!M.ok){let p=await M.json().catch(()=>({}));throw new Error(p.error||`API error: ${M.status}`)}let w=await M.json();if(l(U),w.removed)i(U),d(p=>{let $={};for(let[x,q]of Object.entries(p))q.fork.slotId!==U&&($[x]=q);return $}),R(null),f("prompting");else if(w.fork){s(U,w.fork);let p=w.fork;L(p.id,{state:"complete",fork:p});}return w}catch(C){throw m(C.message),C}},[e,t,n,r,i,s,l,L]),D=k?b[k]??null:null,K=g?"running":I?"error":D?D.state:v,V=D?.fork??null,W=D?.events??[],X=I??D?.error??null;return {state:K,fork:V,events:W,error:X,runs:b,open:N,close:oe,startFork:_,undoFork:H,adoptRunningFork:F}}var Hi=0;function yo(){let{state:e,fork:t,events:n,error:r,runs:o,open:s,close:i,startFork:l,undoFork:u,adoptRunningFork:h}=Wn(),[b,d]=Pn.useState(false),k=Pn.useRef(null),R=Pn.useRef(e),v=Pn.useCallback(()=>{k.current!==null&&(clearTimeout(k.current),k.current=null);},[]),f=Pn.useCallback(()=>{v(),d(true),s();},[v,s]),g=Pn.useCallback(()=>{v(),d(false),i();},[v,i]),S=Pn.useCallback(async m=>{v(),d(true),await h(m);},[h,v]),I=Object.values(o).filter(m=>m.state==="running").length;return Pn.useEffect(()=>{let m=R.current;R.current=e,e==="complete"&&m==="running"&&b&&I===0&&(v(),k.current=setTimeout(()=>{k.current=null,d(false),i();},Hi)),(e==="running"||e==="prompting")&&v();},[e,b,I,v,i]),Pn.useEffect(()=>v,[v]),{state:e,fork:t,events:n,error:r,runs:o,isOpen:b,open:f,close:g,submit:l,undo:u,adoptRunningFork:S}}var Oi=new Set(["pending","running","building"]);function Vn(e){let t=uo(e),n=yo(),r=mo(t.type==="boundary"?t.id:""),{baseUrl:o,apiKey:s,userId:i,userHash:l,appId:u,activitySummary:h,forkActivities:b}=ve(),d=t.type==="slot"?n:r,k=t.type==="slot"?"slot":"boundary",R=t.id,v=t.title,f=t.type==="slot"?"slot":"module",g=b.find(L=>L.targetKind===f&&L.targetId===t.id&&Oi.has(L.status)),S=b.find(L=>L.targetKind===f&&L.targetId===t.id&&L.status==="complete"&&L.unread),I=Pn.useCallback(()=>{let L=g??S;if(L){d.adoptRunningFork(L.id);return}d.open();},[d,g,S]),m=Pn.useCallback((L,j,O,N)=>t.type==="slot"?n.submit(L,j??t.id,O,N):r.submit(L,O,N),[r,n,t]),P=Pn.useCallback((L,j)=>t.type==="slot"?n.undo(L??t.id):r.undo(j),[r,n,t]);return {...d,open:I,target:t,targetId:R,targetLabel:v,historyMode:k,submit:m,undo:P,buttonProps:{onClick:I,hasNotification:h.unreadCompletedCount>0,activity:h},panelProps:{state:d.state,fork:d.fork,events:d.events,error:d.error,runs:d.runs,...t.type==="slot"?{slotId:R,targetLabel:v,historyMode:k}:{targetId:R,targetLabel:v,historyMode:k},onSubmit:m,onUndo:P,onClose:d.close,baseUrl:o,apiKey:s,userId:i,userHash:l,appId:u}}}function _t(e){let{embedded:t,completeVariant:n}=e,r=Vn(e);return t?ls.jsx(dn,{...r.panelProps,embedded:true,completeVariant:n}):r.isOpen?ls.jsx(dn,{...r.panelProps,completeVariant:n}):ls.jsx(Nn,{...r.buttonProps})}function Ni({boundaryId:e,title:t}){return ls.jsx(_t,{boundaryId:e,title:t})}function qn(e){let t=Array.from(e.children).filter(r=>r instanceof HTMLElement);return t.length===1?t[0]:getComputedStyle(e).display==="contents"?null:e}function ko(e){let t=e.getBoundingClientRect(),n=e.cloneNode(true);n.setAttribute("data-fork-clone-overlay","true"),n.style.position="fixed",n.style.top=`${t.top}px`,n.style.left=`${t.left}px`,n.style.width=`${t.width}px`,n.style.height=`${t.height}px`,n.style.flex="none",n.style.minHeight="auto",n.style.zIndex="9998",n.style.pointerEvents="none",n.style.overflow="hidden";let r=getComputedStyle(e).backgroundColor;n.style.backgroundColor=r&&r!=="rgba(0, 0, 0, 0)"&&r!=="transparent"?r:getComputedStyle(document.body).backgroundColor||"#ffffff",document.body.appendChild(n);let o=e.querySelectorAll("*"),s=n.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 n}function Gn(e){let t=[],n=e.querySelectorAll("*");for(let r of n){if(!(r instanceof HTMLElement))continue;let o=r.getBoundingClientRect();if(o.width<10||o.height<10||["SCRIPT","STYLE","META","LINK"].includes(r.tagName))continue;let s=getComputedStyle(r),i=parseFloat(s.borderTopLeftRadius)||0;t.push({tag:r.tagName,className:r.className||"",text:(r.textContent||"").slice(0,50).trim(),rect:o,borderRadius:i});}return t}function bo(e,t){let n=[];for(let r of t)if(!(e.find(i=>i.tag===r.tag&&i.className===r.className&&Math.abs(i.rect.top-r.rect.top)<20&&Math.abs(i.rect.left-r.rect.left)<20)||n.some(i=>r.rect.top>=i.rect.top&&r.rect.left>=i.rect.left&&r.rect.right<=i.rect.right&&r.rect.bottom<=i.rect.bottom))){for(let i=n.length-1;i>=0;i-=1){let l=n[i];l.rect.top>=r.rect.top&&l.rect.left>=r.rect.left&&l.rect.right<=r.rect.right&&l.rect.bottom<=r.rect.bottom&&n.splice(i,1);}n.push({rect:r.rect,borderRadius:r.borderRadius});}return n}function wo(e,t){let n=[];for(let r of e)if(!(t.find(i=>i.tag===r.tag&&i.className===r.className&&Math.abs(i.rect.top-r.rect.top)<20&&Math.abs(i.rect.left-r.rect.left)<20)||n.some(i=>r.rect.top>=i.rect.top&&r.rect.left>=i.rect.left&&r.rect.right<=i.rect.right&&r.rect.bottom<=i.rect.bottom))){for(let i=n.length-1;i>=0;i-=1){let l=n[i];l.rect.top>=r.rect.top&&l.rect.left>=r.rect.left&&l.rect.right<=r.rect.right&&l.rect.bottom<=r.rect.bottom&&n.splice(i,1);}n.push({rect:r.rect,borderRadius:r.borderRadius});}return n}function vo(e,t,n,r,o){let s=Math.max(0,Math.min(o,n/2,r/2));return s===0?`M ${e} ${t} L ${e+n} ${t} L ${e+n} ${t+r} L ${e} ${t+r} Z`:[`M ${e+s} ${t}`,`L ${e+n-s} ${t}`,`A ${s} ${s} 0 0 1 ${e+n} ${t+s}`,`L ${e+n} ${t+r-s}`,`A ${s} ${s} 0 0 1 ${e+n-s} ${t+r}`,`L ${e+s} ${t+r}`,`A ${s} ${s} 0 0 1 ${e} ${t+r-s}`,`L ${e} ${t+s}`,`A ${s} ${s} 0 0 1 ${e+s} ${t}`,"Z"].join(" ")}function Yn(e){let t="http://www.w3.org/2000/svg",n=document.createElement("div");n.setAttribute("data-fork-highlights","true"),n.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let r=document.createElementNS(t,"svg");r.setAttribute("width","100%"),r.setAttribute("height","100%"),r.style.cssText="position:absolute;top:0;left:0;overflow:visible;";let o=document.createElementNS(t,"defs");r.appendChild(o);let s=[];for(let b=0;b<e.length;b+=1){let{rect:d,borderRadius:k}=e[b],R=d.left-.5,v=d.top-.5,f=d.width+1,g=d.height+1,S=Math.min(k+.5,f/2,g/2),I=vo(R,v,f,g,S),m=`__fork-glow-${b}`,P=document.createElementNS(t,"filter");P.setAttribute("id",m),P.setAttribute("x","-100%"),P.setAttribute("y","-100%"),P.setAttribute("width","300%"),P.setAttribute("height","300%");let L=document.createElementNS(t,"feGaussianBlur");L.setAttribute("in","SourceGraphic"),L.setAttribute("stdDeviation","8"),P.appendChild(L),o.appendChild(P);let j=`__fork-mask-${b}`,O=document.createElementNS(t,"mask");O.setAttribute("id",j),O.setAttribute("maskUnits","userSpaceOnUse"),O.setAttribute("x",String(R-200)),O.setAttribute("y",String(v-200)),O.setAttribute("width",String(f+400)),O.setAttribute("height",String(g+400));let N=document.createElementNS(t,"rect");N.setAttribute("x",String(R-200)),N.setAttribute("y",String(v-200)),N.setAttribute("width",String(f+400)),N.setAttribute("height",String(g+400)),N.setAttribute("fill","white"),O.appendChild(N);let oe=document.createElementNS(t,"path");oe.setAttribute("d",I),oe.setAttribute("fill","black"),O.appendChild(oe),o.appendChild(O);let Y=document.createElementNS(t,"g");Y.setAttribute("mask",`url(#${j})`),Y.setAttribute("opacity","0");let _=document.createElementNS(t,"g");_.setAttribute("filter",`url(#${m})`);let F=document.createElementNS(t,"path");F.setAttribute("d",I),F.setAttribute("fill","none"),F.setAttribute("stroke","rgba(150, 185, 220, 0.6)"),F.setAttribute("stroke-width","6"),F.setAttribute("stroke-linecap","round"),_.appendChild(F),Y.appendChild(_),r.appendChild(Y);let H=document.createElementNS(t,"path");H.setAttribute("d",I),H.setAttribute("fill","none"),H.setAttribute("stroke","rgba(150, 185, 220, 0.35)"),H.setAttribute("stroke-width","2"),H.setAttribute("stroke-linecap","round"),H.setAttribute("opacity","0"),r.appendChild(H),s.push(F,H),F.__group=Y;}n.appendChild(r),document.body.appendChild(n);let i=[];for(let b=0;b<s.length;b+=2){let d=s[b],k=s[b+1],R=d.__group;if(!R)continue;let v=k.getTotalLength(),f=d.getTotalLength();if(v<=0)continue;let g=v*.35;k.setAttribute("stroke-dasharray",`${g} ${v-g}`),k.setAttribute("stroke-dashoffset","0"),i.push(k.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 S=f*.35;d.setAttribute("stroke-dasharray",`${S} ${f-S}`),d.setAttribute("stroke-dashoffset","0"),i.push(d.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(R.animate([{opacity:0,offset:0},{opacity:.92,offset:.06},{opacity:.92,offset:.92},{opacity:0,offset:1}],{duration:14e3,easing:"ease-in-out",fill:"forwards"}));}let l=false,u=()=>{if(l)return;l=true,clearTimeout(h);for(let d of i)try{d.cancel();}catch{}let b=n.animate([{opacity:1},{opacity:0}],{duration:400,fill:"forwards"});b.onfinish=()=>n.remove(),window.removeEventListener("click",u);},h=setTimeout(u,14500);return setTimeout(()=>{l||window.addEventListener("click",u);},500),u}function So(e){let t="http://www.w3.org/2000/svg",n=document.createElement("div");n.setAttribute("data-fork-removed","true"),n.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";let r=document.createElementNS(t,"svg");r.setAttribute("width","100%"),r.setAttribute("height","100%"),r.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),r.appendChild(o);for(let{rect:l,borderRadius:u}of e){let h=document.createElementNS(t,"path");h.setAttribute("d",vo(l.left,l.top,l.width,l.height,u)),h.setAttribute("fill","none"),h.setAttribute("stroke","rgba(120, 125, 135, 0.6)"),h.setAttribute("stroke-width","1.5"),h.setAttribute("stroke-dasharray","8 4"),h.setAttribute("stroke-linecap","round"),h.setAttribute("filter","url(#__fork-removed-shadow)"),h.setAttribute("opacity","0"),r.appendChild(h),h.animate([{opacity:0,offset:0},{opacity:.6,offset:.08},{opacity:.05,offset:.45},{opacity:.6,offset:.85},{opacity:.05,offset:1}],{duration:5e3,easing:"ease-in-out",fill:"forwards"});}return n.appendChild(r),document.body.appendChild(n),n}function Ao(e,t){if(Bi(t.selector))return xo(e,t);let r=xo(e,t);if(r)return r;try{let s=document.querySelector(t.selector);if(s instanceof HTMLElement&&s!==e&&e.contains(s))return s}catch{}if(Fo(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=Qn(e,b=>b===s);if(i)return i;let l=s.toLowerCase(),u=Qn(e,b=>b.toLowerCase()===l);if(u)return u;let h=Qn(e,b=>b.toLowerCase().includes(l));if(h)return h}}let o=Di(t.selector);if(o&&o!==t.selector&&Fo(o))try{let s=e.querySelector(o);if(s instanceof HTMLElement&&s!==e)return s}catch{}return null}function Fo(e){let t=e.split(/\s+|>|~|\+/),n=t[t.length-1]??"";return /[#\[]|:not\(|:nth-/.test(n)}function xo(e,t){let n=Array.from(e.querySelectorAll("[data-fork-new]"));if(n.length===0)return null;let r=Zn(t.label),o=Zn(t.textHint);return n.find(i=>{let l=Zn(i.getAttribute("data-fork-new"));return !!l&&(l===r||l===o)})??null}function Bi(e){return e.trim()==="[data-fork-new]"}function Zn(e){return e?.trim().replace(/\s+/g," ").toLowerCase()||null}function Di(e){return e.replace(/\[class[\*~|^$]?=("[^"]*"|'[^']*'|[^\]]+)\]/g,"").replace(/\.[A-Za-z_][\w-]*/g,"").replace(/\s+/g," ").trim()}function Qn(e,t){let n=null,r=1/0,o=e.querySelectorAll("*");for(let s of o){let i=s.textContent?.trim();if(!i||!t(i))continue;let l=s.getBoundingClientRect();if(l.width<4||l.height<4)continue;let u=l.width*l.height;u<r&&(n=s,r=u);}return n}var er=2147483600,ji=1600,Ki=3e4,zi=300,Qe=10;function Wi(e){let n=getComputedStyle(e).borderTopLeftRadius;if(!n)return 4;if(n.endsWith("%")){let i=parseFloat(n);if(!Number.isFinite(i)||i<=0)return 4;let l=e.getBoundingClientRect(),u=Math.min(l.width,l.height);return Math.max(4,i/100*u)}let r=parseFloat(n);if(!Number.isFinite(r)||r<=0)return 4;let o=e.getBoundingClientRect(),s=Math.min(o.width,o.height)/2;return r>=s?s:Math.min(r,16)}function Ji(e,t,n,r){let s=window.innerWidth,i=window.innerHeight,l=e;l==="top"&&t.top<r+Qe+8?l="bottom":l==="bottom"&&i-t.bottom<r+Qe+8?l="top":l==="left"&&t.left<n+Qe+8?l="right":l==="right"&&s-t.right<n+Qe+8&&(l="left");let u=0,h=0;return l==="top"?(u=t.top-r-Qe,h=t.left+t.width/2-n/2):l==="bottom"?(u=t.bottom+Qe,h=t.left+t.width/2-n/2):l==="left"?(u=t.top+t.height/2-r/2,h=t.left-n-Qe):(u=t.top+t.height/2-r/2,h=t.right+Qe),h=Math.max(8,Math.min(h,s-n-8)),u=Math.max(8,Math.min(u,i-r-8)),{top:u,left:h,placement:l}}function Vi(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 n=document.createElement("div");n.setAttribute("data-fork-highlight-glow","true"),n.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 r=document.createElement("div");return r.setAttribute("data-fork-highlight-tooltip","true"),r.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(";"),r.textContent=`New: ${e}`,{outline:t,glow:n,tooltip:r}}function Xi(){if(document.getElementById("__fork-highlight-keyframes"))return;let e=document.createElement("style");e.id="__fork-highlight-keyframes",e.textContent=`
|
|
59
60
|
@keyframes __fork-highlight-pulse {
|
|
60
61
|
0%, 100% { box-shadow: 0 0 0 3px rgba(59,130,246,0.11), 0 0 12px 1px rgba(59,130,246,0.22); }
|
|
61
62
|
50% { box-shadow: 0 0 0 6px rgba(59,130,246,0.25), 0 0 22px 4px rgba(59,130,246,0.49); }
|
|
62
63
|
}
|
|
63
|
-
`,document.head.appendChild(e);}function Wn(e,t,r="top"){Ws();let{outline:n,glow:o,tooltip:s}=zs(t),i=js(e);n.style.borderRadius=`${i}px`,o.style.borderRadius=`${i+1}px`,o.style.animation=`__fork-highlight-pulse ${Us}ms ease-in-out infinite`,document.body.append(o,n,s);let l=()=>{let u=e.getBoundingClientRect();if(u.width===0&&u.height===0)return;n.style.top=`${u.top}px`,n.style.left=`${u.left}px`,n.style.width=`${u.width}px`,n.style.height=`${u.height}px`,o.style.top=`${u.top-1}px`,o.style.left=`${u.left-1}px`,o.style.width=`${u.width+2}px`,o.style.height=`${u.height+2}px`;let O=s.getBoundingClientRect(),P=O.width||s.offsetWidth||80,R=O.height||s.offsetHeight||26,g=Ks(r,u,P,R);s.style.top=`${g.top}px`,s.style.left=`${g.left}px`;};l(),requestAnimationFrame(()=>{n.style.opacity="1",o.style.opacity="1",s.style.opacity="1",s.style.transform="translateY(0)",requestAnimationFrame(l);});let f=false,w=new ResizeObserver(l);w.observe(e);let h=()=>l(),p=()=>l();window.addEventListener("scroll",h,true),window.addEventListener("resize",p);let F=()=>{f||(f=true,clearTimeout(y),w.disconnect(),window.removeEventListener("scroll",h,true),window.removeEventListener("resize",p),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();},Ds));},I=()=>F();setTimeout(()=>{f||window.addEventListener("click",I,{once:true,capture:true});},250);let y=setTimeout(F,Bs);return F}var Vs="fork:highlight:v1:seen";function Vn(e){return `${Vs}:${e}`}function Jn(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 Js(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify([...t].slice(-200)));}catch{}}var qn=new Set;function Xn(e,t,r){return `${r}::${e}:${t}`}function Nr(e,t,r){let n=Xn(e,t,r);return qn.has(n)?true:Jn(Vn(r)).has(`${e}:${t}`)}function Gn(e,t,r){let n=Xn(e,t,r);qn.add(n);let o=Vn(r),s=`${e}:${t}`,i=Jn(o);i.has(s)||(i.add(s),Js(o,i));}var Et=new Map,$t=new Map,Ur=new Map;function Xs(e){for(let t of e)$t.set(t,($t.get(t)??0)+1);}function Gs(e){if(!(typeof document>"u"))for(let t of e){let r=($t.get(t)??0)-1;if(r>0){$t.set(t,r);continue}$t.delete(t),Et.delete(t);let n=document.querySelector(`link[data-fork-override-href="${CSS.escape(t)}"]`);n&&n.remove();}}function Ys(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function Qn(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 Zn(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 Qs(e){if(!e||typeof document>"u")return Promise.resolve();let t=Et.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 l=()=>{r.removeEventListener("load",l),r.removeEventListener("error",f),s();},f=()=>{r.removeEventListener("load",l),r.removeEventListener("error",f),i(new Error(`Failed to load boundary stylesheet: ${e}`));};r.addEventListener("load",l,{once:true}),r.addEventListener("error",f,{once:true});});return Et.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 Et.delete(e),o});return Et.set(e,n),n}var Ct=null;function Zs(){if(Ct)return Ct;try{Ct=new Function("u","return import(/*webpackIgnore:true*//*@vite-ignore*/u)");}catch{Ct=e=>import(/*webpackIgnore:true*//*@vite-ignore*/e);}return Ct}function ei(e){let t=Ur.get(e);if(t)return t;let r=Zs()(e).catch(n=>{throw Ur.delete(e),n});return Ur.set(e,r),r}async function ti(e,t,r){if(e)try{await Promise.all(e.cssUrls.map(s=>Qs(s)));let o=await ei(e.moduleUrl);return Zn(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 Zn(n,r)}function ri(e){function t(r){let{appId:n,moduleOverridesEnabled:o,moduleManifestReady:s,moduleManifestVersion:i,registerBoundary:l,getBoundaryOverride:f,consumeBoundaryAnimation:w,highlightScope:h}=we(),[p,F]=kr.useState(null),[I,y]=kr.useState(null),u=kr.useRef(null),O=kr.useRef(null),P=kr.useRef(null),R=kr.useRef(false),g=kr.useRef(null),C=kr.useRef(null),_=kr.useRef(null),D=kr.useRef(false),U=kr.useRef(false),T=f(e.id),se=T?`override:${T.id}`:"original",W=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if(kr.useEffect(()=>()=>{C.current&&(clearTimeout(C.current),C.current=null),g.current&&(g.current.remove(),g.current=null),_.current&&(_.current(),_.current=null);},[]),kr.useEffect(()=>{l({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[n,l,e.id,e.exportName,W]),kr.useEffect(()=>{let A=T?.cssUrls??[];if(A.length!==0)return Xs(A),()=>Gs(A)},[T?.cssUrls.join("|")]),kr.useEffect(()=>{if(o&&!s&&!p||O.current===se&&p)return;let A=false;return y(null),ti(T,e.original,e.exportName).then(S=>{if(A)return;let N=T?.id?w(e.id,T.id):false;if(D.current=N,N&&u.current){let B=Mr(u.current);if(B){let K=Pr(B);K.length>0&&(P.current=K,R.current=true,C.current&&(clearTimeout(C.current),C.current=null),g.current&&g.current.remove(),g.current=On(B));}}O.current=se,kr.startTransition(()=>{F(()=>S);});}).catch(S=>{A||y(Ys(S));}),()=>{A=true;}},[w,se,o,s,i,T?.id,T?.moduleUrl,T?.integrity,T?.cssUrls.join("|"),e.exportName,e.original,p]),kr.useEffect(()=>{if(!p||!u.current)return;let A=false,S=null,N=()=>{if(A||!u.current)return false;let B=T?.highlightHint,K=T?.id,X=T?.createdAt?String(T.createdAt):"";if(!B||!K||Nr(K,X,h))return false;let G=Array.from(u.current.querySelectorAll("[data-fork-new]"));G.length,G.map(L=>L.getAttribute("data-fork-new")),B.label,B.textHint,B.selector;let q=zn(u.current,B);return q?.tagName,q?.getAttribute("data-fork-new"),q?.getAttribute("aria-label"),q?.textContent?.trim().slice(0,60),!q||!Qn(q)?(q&&Qn(q),q?.getBoundingClientRect(),false):(Gn(K,X,h),g.current&&(g.current.remove(),g.current=null),_.current&&_.current(),_.current=Wn(q,B.label,B.position??"top"),true)};return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(A||!u.current)return;let B=D.current,K=!U.current;U.current=true;let X=B||K,G=X?N():false;if(X&&!G&&T?.highlightHint&&T?.id&&!Nr(T.id,String(T.createdAt??""),h)){let j=[150,400,800],ne=0,Ee=()=>{if(A||ne>=j.length)return;let Le=j[ne];ne+=1,S=setTimeout(()=>{if(N()){G=true;return}Ee();},Le);};Ee();}let q=R.current,L=!!T?.highlightHint,k=P.current;if(P.current=null,R.current=false,G||L||!q){g.current&&(g.current.remove(),g.current=null);return}let E=Mr(u.current);if(!k||!E){g.current&&(g.current.remove(),g.current=null);return}let x=Pr(E),d=Nn(k,x),M=Un(k,x),v=g.current;if(M.length>0&&v){let j=Dn(M);C.current=setTimeout(()=>{C.current=null;let ne=400;v.animate([{opacity:1},{opacity:0}],{duration:ne,fill:"forwards"}),j.animate([{opacity:1},{opacity:0}],{duration:ne,fill:"forwards"}),setTimeout(()=>{v.remove(),j.remove(),g.current===v&&(g.current=null),d.length>0&&_r(d);},ne);},3500);}else v&&(v.remove(),g.current===v&&(g.current=null)),d.length>0&&_r(d);});}),()=>{A=true,S!==null&&(clearTimeout(S),S=null);}},[p,T?.id,T?.createdAt,T?.highlightHint,h]),I)throw I;return p?ho.jsx("div",{ref:u,"data-fork-boundary":e.id,style:{display:"contents"},children:ho.jsx(p,{...r})}):ho.jsx(ho.Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function oi({slotId:e,title:t,slotLabel:r}){return ho.jsx(It,{slotId:e,title:t,slotLabel:r})}function ai(e){return e.replace(/\/+$/,"")}function li(e){return {namespace:e.namespace||"default",type:e.type,id:e.id}}function Tt(e,t="value"){let r=li(e);return `${r.namespace}:${r.type}:${r.id}:${t}`}function Dr(e){if(Array.isArray(e))return e.map(Dr);if(!e||typeof e!="object")return e;let t=e,r={};for(let n of Object.keys(t).sort())r[n]=Dr(t[n]);return r}function no(e){return JSON.stringify(Dr(e))}function eo(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 to(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 oo(e){let t=ai(e.baseUrl),r={appId:e.appId,containerId:e.containerId},n=async(s,i)=>{let l=i&&typeof i=="object"&&!Array.isArray(i)?i:{},f=await fetch(`${t}/api/v1/data${s}`,{method:"POST",headers:eo(e),body:JSON.stringify({...r,...l})});return to(f)},o=async(s,i)=>{let l=new URLSearchParams({appId:e.appId,containerId:e.containerId});for(let[w,h]of Object.entries(i))h&&l.set(w,h);let f=await fetch(`${t}/api/v1/data${s}?${l.toString()}`,{headers:eo(e)});return to(f)};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 tr(e){let{apiKey:t,appId:r,baseUrl:n,currentContainerId:o,userHash:s,userId:i}=we(),l=e||o;return kr.useMemo(()=>{if(!r||!l)return null;let f=ce();return oo({apiKey:t,appId:r,baseUrl:n,containerId:l,userId:i,userHash:s,extraHeaders:f})},[t,r,n,l,s,i])}function ui(e){let t=tr(e.containerId),[r,n]=kr.useState(null),[o,s]=kr.useState([]),[i,l]=kr.useState(false),[f,w]=kr.useState(null),h=no({featureId:e.featureId,featureKey:e.featureKey,entities:e.entities,valueKeys:e.valueKeys,enabled:e.enabled!==false}),p=kr.useCallback(async()=>{if(!(!t||e.enabled===false)&&!(!e.featureId&&!e.featureKey)){l(true);try{let y=await t.queryValues({featureId:e.featureId,featureKey:e.featureKey,entities:e.entities,valueKeys:e.valueKeys});n(y.feature),s(y.values),w(null);}catch(y){w(y instanceof Error?y:new Error(String(y)));}finally{l(false);}}},[t,h]);kr.useEffect(()=>{p();},[p]),kr.useEffect(()=>{if(!e.pollMs||e.pollMs<=0)return;let y=setInterval(()=>{p();},e.pollMs);return ()=>clearInterval(y)},[e.pollMs,p]);let F=kr.useMemo(()=>new Map(o.map(y=>[Tt(y.entity,y.valueKey),y])),[o]),I=kr.useCallback((y,u="value")=>F.get(Tt(y,u))??null,[F]);return {feature:r,values:o,byKey:F,getValue:I,loading:i,error:f,refresh:p}}function ci(e){let t=tr(e),r=kr.useCallback(async s=>{if(!t)throw new Error("Fork data is unavailable until appId and containerId are resolved");return t.ensureFeature(s)},[t]),n=kr.useCallback(async s=>{if(!t)throw new Error("Fork data is unavailable until appId and containerId are resolved");return t.setValues(s)},[t]),o=kr.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 ro(e){return e.some(t=>t.status==="queued"||t.status==="running")}function di(e){let t=tr(e.containerId),[r,n]=kr.useState(null),[o,s]=kr.useState([]),[i,l]=kr.useState([]),[f,w]=kr.useState(false),[h,p]=kr.useState(null),F=kr.useRef(""),I=no({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}),y=kr.useCallback(async()=>{if(!(!t||e.enabled===false)&&!(!e.featureId&&!e.featureKey)&&!(!e.jobs||e.jobs.length===0)){w(true);try{let R=await t.ensureLlmJobs(e);F.current=I,n(R.feature),s(R.jobs),l(R.values),p(null);}catch(R){p(R instanceof Error?R:new Error(String(R)));}finally{w(false);}}},[t,I]),u=kr.useCallback(async()=>{if(!t)return;let R=o.map(g=>g.id);try{if(R.length>0){let g=await t.queryLlmJobs({jobIds:R});s(g.jobs);}if(e.featureId||e.featureKey){let g=await t.queryValues({featureId:e.featureId,featureKey:e.featureKey,entities:e.jobs.map(C=>C.entity),valueKeys:Array.from(new Set(e.jobs.map(C=>C.valueKey||"value")))});n(g.feature),l(g.values);}p(null);}catch(g){p(g instanceof Error?g:new Error(String(g)));}},[t,o,I]);kr.useEffect(()=>{F.current!==I&&y();},[y,I]),kr.useEffect(()=>{let R=e.pollMs??3e3;if(R<=0||!ro(o))return;let g=setInterval(()=>{u();},R);return ()=>clearInterval(g)},[e.pollMs,o,u]);let O=kr.useMemo(()=>new Map(i.map(R=>[Tt(R.entity,R.valueKey),R])),[i]),P=kr.useCallback((R,g="value")=>O.get(Tt(R,g))??null,[O]);return {feature:r,jobs:o,values:i,byKey:O,getValue:P,loading:f,error:h,ensure:y,refresh:u,running:ro(o)}}exports.ForkBoundaryUI=Ls;exports.ForkButton=Sr;exports.ForkChatInterface=It;exports.ForkPanel=Yt;exports.ForkProvider=Ho;exports.ForkSlot=Xo;exports.ForkUI=oi;exports.clearCachedManifest=vo;exports.createForkDataClient=oo;exports.forkEntityValueKey=Tt;exports.forkable=ri;exports.loadManifest=pr;exports.manifestDiffers=Fo;exports.readCachedManifest=bo;exports.registerForkShared=cr;exports.useBoundaryFork=Rr;exports.useFork=Cr;exports.useForkChatPanel=$r;exports.useForkDataClient=tr;exports.useForkDataMutation=ci;exports.useForkFeatureValues=ui;exports.useForkLlmJobs=di;exports.writeCachedManifest=wo;
|
|
64
|
+
`,document.head.appendChild(e);}function Eo(e,t,n="top"){Xi();let{outline:r,glow:o,tooltip:s}=Vi(t),i=Wi(e);r.style.borderRadius=`${i}px`,o.style.borderRadius=`${i+1}px`,o.style.animation=`__fork-highlight-pulse ${ji}ms ease-in-out infinite`,document.body.append(o,r,s);let l=()=>{let f=e.getBoundingClientRect();if(f.width===0&&f.height===0)return;r.style.top=`${f.top}px`,r.style.left=`${f.left}px`,r.style.width=`${f.width}px`,r.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 g=s.getBoundingClientRect(),S=g.width||s.offsetWidth||80,I=g.height||s.offsetHeight||26,m=Ji(n,f,S,I);s.style.top=`${m.top}px`,s.style.left=`${m.left}px`;};l(),requestAnimationFrame(()=>{r.style.opacity="1",o.style.opacity="1",s.style.opacity="1",s.style.transform="translateY(0)",requestAnimationFrame(l);});let u=false,h=new ResizeObserver(l);h.observe(e);let b=()=>l(),d=()=>l();window.addEventListener("scroll",b,true),window.addEventListener("resize",d);let k=()=>{u||(u=true,clearTimeout(v),h.disconnect(),window.removeEventListener("scroll",b,true),window.removeEventListener("resize",d),window.removeEventListener("click",R,true),r.style.opacity="0",o.style.opacity="0",s.style.opacity="0",s.style.transform="translateY(-2px)",setTimeout(()=>{r.remove(),o.remove(),s.remove();},zi));},R=()=>k();setTimeout(()=>{u||window.addEventListener("click",R,{once:true,capture:true});},250);let v=setTimeout(k,Ki);return k}var qi="fork:highlight:v1:seen";function Ro(e){return `${qi}:${e}`}function Io(e){if(typeof window>"u")return new Set;try{let t=window.localStorage.getItem(e);if(!t)return new Set;let n=JSON.parse(t);return Array.isArray(n)?new Set(n.filter(r=>typeof r=="string")):new Set}catch{return new Set}}function Gi(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify([...t].slice(-200)));}catch{}}var Co=new Set;function Mo(e,t,n){return `${n}::${e}:${t}`}function tr(e,t,n){let r=Mo(e,t,n);return Co.has(r)?true:Io(Ro(n)).has(`${e}:${t}`)}function To(e,t,n){let r=Mo(e,t,n);Co.add(r);let o=Ro(n),s=`${e}:${t}`,i=Io(o);i.has(s)||(i.add(s),Gi(o,i));}var Ot=new Map,Nt=new Map,nr=new Map;function Zi(e){for(let t of e)Nt.set(t,(Nt.get(t)??0)+1);}function Qi(e){if(!(typeof document>"u"))for(let t of e){let n=(Nt.get(t)??0)-1;if(n>0){Nt.set(t,n);continue}Nt.delete(t),Ot.delete(t);let r=document.querySelector(`link[data-fork-override-href="${CSS.escape(t)}"]`);r&&r.remove();}}function ea(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown module override error")}function Po(e){let t=e.getBoundingClientRect();if(t.width<=0||t.height<=0)return false;let n=window.innerWidth||document.documentElement.clientWidth,r=window.innerHeight||document.documentElement.clientHeight;return t.bottom>0&&t.right>0&&t.top<r&&t.left<n}function _o(e,t){let n=(t?e[t]:void 0)??e.default;if(typeof n!="function"){let r=t||"default";throw new Error(`Fork boundary module is missing a React component export: ${r}`)}return n}function ta(e){if(!e||typeof document>"u")return Promise.resolve();let t=Ot.get(e);if(t)return t;let n=document.querySelector(`link[data-fork-override-href="${e}"]`);if(n instanceof HTMLLinkElement){let o=n.sheet?Promise.resolve():new Promise((s,i)=>{let l=()=>{n.removeEventListener("load",l),n.removeEventListener("error",u),s();},u=()=>{n.removeEventListener("load",l),n.removeEventListener("error",u),i(new Error(`Failed to load boundary stylesheet: ${e}`));};n.addEventListener("load",l,{once:true}),n.addEventListener("error",u,{once:true});});return Ot.set(e,o),o}let r=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 Ot.delete(e),o});return Ot.set(e,r),r}var Ht=null;function na(){if(Ht)return Ht;try{Ht=new Function("u","return import(/*webpackIgnore:true*//*@vite-ignore*/u)");}catch{Ht=e=>import(/*webpackIgnore:true*//*@vite-ignore*/e);}return Ht}function ra(e){let t=nr.get(e);if(t)return t;let n=na()(e).catch(r=>{throw nr.delete(e),r});return nr.set(e,n),n}async function oa(e,t,n){if(e)try{await Promise.all(e.cssUrls.map(s=>ta(s)));let o=await ra(e.moduleUrl);return _o(o,n)}catch(o){console.error(`[Fork] Failed to load override for boundary "${e.boundaryId}", falling back to original module.`,o);}let r=await t();return _o(r,n)}function sa(e){function t(n){let{appId:r,moduleOverridesEnabled:o,moduleManifestReady:s,moduleManifestVersion:i,registerBoundary:l,getBoundaryOverride:u,consumeBoundaryAnimation:h,highlightScope:b}=ve(),[d,k]=Pn.useState(null),[R,v]=Pn.useState(null),f=Pn.useRef(null),g=Pn.useRef(null),S=Pn.useRef(null),I=Pn.useRef(false),m=Pn.useRef(null),P=Pn.useRef(null),L=Pn.useRef(null),j=Pn.useRef(false),O=Pn.useRef(false),N=u(e.id),oe=N?`override:${N.id}`:"original",Y=e.editorMetadata?JSON.stringify(e.editorMetadata):void 0;if(Pn.useEffect(()=>()=>{P.current&&(clearTimeout(P.current),P.current=null),m.current&&(m.current.remove(),m.current=null),L.current&&(L.current(),L.current=null);},[]),Pn.useEffect(()=>{l({id:e.id,exportName:e.exportName,editorMetadata:e.editorMetadata});},[r,l,e.id,e.exportName,Y]),Pn.useEffect(()=>{let _=N?.cssUrls??[];if(_.length!==0)return Zi(_),()=>Qi(_)},[N?.cssUrls.join("|")]),Pn.useEffect(()=>{if(o&&!s&&!d||g.current===oe&&d)return;let _=false;return v(null),oa(N,e.original,e.exportName).then(F=>{if(_)return;let H=N?.id?h(e.id,N.id):false;if(j.current=H,H&&f.current){let D=qn(f.current);if(D){let K=Gn(D);K.length>0&&(S.current=K,I.current=true,P.current&&(clearTimeout(P.current),P.current=null),m.current&&m.current.remove(),m.current=ko(D));}}g.current=oe,Pn.startTransition(()=>{k(()=>F);});}).catch(F=>{_||v(ea(F));}),()=>{_=true;}},[h,oe,o,s,i,N?.id,N?.moduleUrl,N?.integrity,N?.cssUrls.join("|"),e.exportName,e.original,d]),Pn.useEffect(()=>{if(!d||!f.current)return;let _=false,F=null,H=()=>{if(_||!f.current)return false;let D=N?.highlightHint,K=N?.id,V=N?.createdAt?String(N.createdAt):"";if(!D||!K||tr(K,V,b))return false;let W=Array.from(f.current.querySelectorAll("[data-fork-new]"));W.length,W.map(U=>U.getAttribute("data-fork-new")),D.label,D.textHint,D.selector;let X=Ao(f.current,D);return X?.tagName,X?.getAttribute("data-fork-new"),X?.getAttribute("aria-label"),X?.textContent?.trim().slice(0,60),!X||!Po(X)?(X&&Po(X),X?.getBoundingClientRect(),false):(To(K,V,b),m.current&&(m.current.remove(),m.current=null),L.current&&L.current(),L.current=Eo(X,D.label,D.position??"top"),true)};return requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(_||!f.current)return;let D=j.current,K=!O.current;O.current=true;let V=D||K,W=V?H():false;if(V&&!W&&N?.highlightHint&&N?.id&&!tr(N.id,String(N.createdAt??""),b)){let q=[150,400,800],re=0,Ae=()=>{if(_||re>=q.length)return;let Te=q[re];re+=1,F=setTimeout(()=>{if(H()){W=true;return}Ae();},Te);};Ae();}let X=I.current,U=!!N?.highlightHint,C=S.current;if(S.current=null,I.current=false,W||U||!X){m.current&&(m.current.remove(),m.current=null);return}let M=qn(f.current);if(!C||!M){m.current&&(m.current.remove(),m.current=null);return}let w=Gn(M),p=bo(C,w),$=wo(C,w),x=m.current;if($.length>0&&x){let q=So($);P.current=setTimeout(()=>{P.current=null;let re=400;x.animate([{opacity:1},{opacity:0}],{duration:re,fill:"forwards"}),q.animate([{opacity:1},{opacity:0}],{duration:re,fill:"forwards"}),setTimeout(()=>{x.remove(),q.remove(),m.current===x&&(m.current=null),p.length>0&&Yn(p);},re);},3500);}else x&&(x.remove(),m.current===x&&(m.current=null)),p.length>0&&Yn(p);});}),()=>{_=true,F!==null&&(clearTimeout(F),F=null);}},[d,N?.id,N?.createdAt,N?.highlightHint,b]),R)throw R;return d?ls.jsx("div",{ref:f,"data-fork-boundary":e.id,style:{display:"contents"},children:ls.jsx(d,{...n})}):ls.jsx(ls.Fragment,{children:e.loading??null})}return t.displayName=`ForkBoundary(${e.id})`,t}function aa({slotId:e,title:t,slotLabel:n}){return ls.jsx(_t,{slotId:e,title:t,slotLabel:n})}function ua(e){return e.replace(/\/+$/,"")}function da(e){return {namespace:e.namespace||"default",type:e.type,id:e.id}}function Ut(e,t="value"){let n=da(e);return `${n.namespace}:${n.type}:${n.id}:${t}`}function or(e){if(Array.isArray(e))return e.map(or);if(!e||typeof e!="object")return e;let t=e,n={};for(let r of Object.keys(t).sort())n[r]=or(t[r]);return n}function No(e){return JSON.stringify(or(e))}function Lo(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 Ho(e){let t=await e.json().catch(()=>({}));if(!e.ok){let n=typeof t.error=="string"?t.error:`Fork data API ${e.status}`;throw new Error(n)}return t}function Uo(e){let t=ua(e.baseUrl),n={appId:e.appId,containerId:e.containerId},r=async(s,i)=>{let l=i&&typeof i=="object"&&!Array.isArray(i)?i:{},u=await fetch(`${t}/api/v1/data${s}`,{method:"POST",headers:Lo(e),body:JSON.stringify({...n,...l})});return Ho(u)},o=async(s,i)=>{let l=new URLSearchParams({appId:e.appId,containerId:e.containerId});for(let[h,b]of Object.entries(i))b&&l.set(h,b);let u=await fetch(`${t}/api/v1/data${s}?${l.toString()}`,{headers:Lo(e)});return Ho(u)};return {listFeatures(){return o("/features",{})},ensureFeature(s){return r("/features",s)},queryValues(s){return r("/values/query",s)},setValues(s){return r("/values",s)},listOptions(s){return o("/options",{featureId:s.featureId,featureKey:s.featureKey,includeArchived:s.includeArchived?"true":void 0})},setOptions(s){return r("/options",s)},ensureLlmJobs(s){return r("/llm/ensure",s)},queryLlmJobs(s){return r("/llm/jobs/query",s)}}}function gn(e){let{apiKey:t,appId:n,baseUrl:r,currentContainerId:o,userHash:s,userId:i}=ve(),l=e||o;return Pn.useMemo(()=>{if(!n||!l)return null;let u=pe();return Uo({apiKey:t,appId:n,baseUrl:r,containerId:l,userId:i,userHash:s,extraHeaders:u})},[t,n,r,l,s,i])}function fa(e){let t=gn(e.containerId),[n,r]=Pn.useState(null),[o,s]=Pn.useState([]),[i,l]=Pn.useState(false),[u,h]=Pn.useState(null),b=No({featureId:e.featureId,featureKey:e.featureKey,entities:e.entities,valueKeys:e.valueKeys,enabled:e.enabled!==false}),d=Pn.useCallback(async()=>{if(!(!t||e.enabled===false)&&!(!e.featureId&&!e.featureKey)){l(true);try{let v=await t.queryValues({featureId:e.featureId,featureKey:e.featureKey,entities:e.entities,valueKeys:e.valueKeys});r(v.feature),s(v.values),h(null);}catch(v){h(v instanceof Error?v:new Error(String(v)));}finally{l(false);}}},[t,b]);Pn.useEffect(()=>{d();},[d]),Pn.useEffect(()=>{if(!e.pollMs||e.pollMs<=0)return;let v=setInterval(()=>{d();},e.pollMs);return ()=>clearInterval(v)},[e.pollMs,d]);let k=Pn.useMemo(()=>new Map(o.map(v=>[Ut(v.entity,v.valueKey),v])),[o]),R=Pn.useCallback((v,f="value")=>k.get(Ut(v,f))??null,[k]);return {feature:n,values:o,byKey:k,getValue:R,loading:i,error:u,refresh:d}}function pa(e){let t=gn(e),n=Pn.useCallback(async s=>{if(!t)throw new Error("Fork data is unavailable until appId and containerId are resolved");return t.ensureFeature(s)},[t]),r=Pn.useCallback(async s=>{if(!t)throw new Error("Fork data is unavailable until appId and containerId are resolved");return t.setValues(s)},[t]),o=Pn.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:n,setValues:r,setOptions:o}}function Oo(e){return e.some(t=>t.status==="queued"||t.status==="running")}function ma(e){let t=gn(e.containerId),[n,r]=Pn.useState(null),[o,s]=Pn.useState([]),[i,l]=Pn.useState([]),[u,h]=Pn.useState(false),[b,d]=Pn.useState(null),k=Pn.useRef(""),R=No({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=Pn.useCallback(async()=>{if(!(!t||e.enabled===false)&&!(!e.featureId&&!e.featureKey)&&!(!e.jobs||e.jobs.length===0)){h(true);try{let I=await t.ensureLlmJobs(e);k.current=R,r(I.feature),s(I.jobs),l(I.values),d(null);}catch(I){d(I instanceof Error?I:new Error(String(I)));}finally{h(false);}}},[t,R]),f=Pn.useCallback(async()=>{if(!t)return;let I=o.map(m=>m.id);try{if(I.length>0){let m=await t.queryLlmJobs({jobIds:I});s(m.jobs);}if(e.featureId||e.featureKey){let m=await t.queryValues({featureId:e.featureId,featureKey:e.featureKey,entities:e.jobs.map(P=>P.entity),valueKeys:Array.from(new Set(e.jobs.map(P=>P.valueKey||"value")))});r(m.feature),l(m.values);}d(null);}catch(m){d(m instanceof Error?m:new Error(String(m)));}},[t,o,R]);Pn.useEffect(()=>{k.current!==R&&v();},[v,R]),Pn.useEffect(()=>{let I=e.pollMs??3e3;if(I<=0||!Oo(o))return;let m=setInterval(()=>{f();},I);return ()=>clearInterval(m)},[e.pollMs,o,f]);let g=Pn.useMemo(()=>new Map(i.map(I=>[Ut(I.entity,I.valueKey),I])),[i]),S=Pn.useCallback((I,m="value")=>g.get(Ut(I,m))??null,[g]);return {feature:n,jobs:o,values:i,byKey:g,getValue:S,loading:u,error:b,ensure:v,refresh:f,running:Oo(o)}}exports.ForkBoundaryUI=Ni;exports.ForkButton=Nn;exports.ForkChatInterface=_t;exports.ForkPanel=dn;exports.ForkProvider=Is;exports.ForkSlot=Ds;exports.ForkUI=aa;exports.clearCachedManifest=ps;exports.createForkDataClient=Uo;exports.forkEntityValueKey=Ut;exports.forkable=sa;exports.loadManifest=In;exports.manifestDiffers=ms;exports.readCachedManifest=ds;exports.registerForkShared=An;exports.useBoundaryFork=zn;exports.useFork=Wn;exports.useForkChatPanel=Vn;exports.useForkDataClient=gn;exports.useForkDataMutation=pa;exports.useForkFeatureValues=fa;exports.useForkLlmJobs=ma;exports.writeCachedManifest=fs;
|